Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
A API Payment Card Recognition do Google possibilita o uso de uma câmera
para reconhecer as informações dos cartões de pagamento. A API é compatível com o
reconhecimento do número da conta principal (PAN, na sigla em inglês) e da data de validade de um cartão de crédito ou débito
por meio do reconhecimento óptico de caracteres (OCR). A API delega a tarefa de
verificação do cartão para os serviços do Google Play. Portanto, seu app não precisa
solicitar a permissão da câmera e recebe apenas os resultados da verificação. Todo o processamento
de imagens ocorre no dispositivo, e o Google não armazena os resultados nem compartilha os dados das imagens.
Para garantir a melhor funcionalidade e experiência do usuário, a API tem as seguintes restrições:
O dispositivo precisa estar disponível em países específicos (AU, BR, CA, CH, CZ,
DK, ES, FI, FR, GB, HK, IE, JP, KR, NL, NO, NZ, PL, RU, SE, SG, TW, UA, US)
O dispositivo deve ter pelo menos 1 GB de RAM.
O dispositivo deve ter uma câmera traseira.
O dispositivo deve ser compatível com a orientação PORTRAIT.
Criar uma solicitação
Crie uma instância
PaymentsClient
no método onCreate em Activity. Use
PaymentsClient para interagir com a API Google Pay.
Depois de criar a resposta, é possível enviar uma solicitação assíncrona para um PendingIntent,
que pode ser usado para iniciar a atividade de reconhecimento do cartão de pagamento.
Não se esqueça de que a solicitação nem sempre dá certo. Se a API não for ativada, a solicitação
vai apresentar problemas. Recomendamos que você ajuste o comportamento do app de acordo com a
resposta à solicitação. No app de exemplo, o botão aparece somente após o
recebimento de uma resposta bem-sucedida.
Kotlin
privatefunpossiblyShowPaymentCardOcrButton(){// The request can be used to configure the type of the payment card recognition. Currently// the only supported type is card OCR, so it is sufficient to call the getDefaultInstance()// method.valrequest=PaymentCardRecognitionIntentRequest.getDefaultInstance()paymentsClient.getPaymentCardRecognitionIntent(request).addOnSuccessListener{intentResponse->
cardRecognitionPendingIntent=intentResponse.paymentCardRecognitionPendingIntentpaymentCardOcrButton.visibility=View.VISIBLE}.addOnFailureListener{e->
// The API is not available either because the feature is not enabled on the device// or because your app is not registered.Log.e(TAG,"Payment card ocr not available.",e)}}
publicvoidpossiblyShowPaymentCardOcrButton(){// The request can be used to configure the type of the payment card recognition. Currently the// only supported type is card OCR, so it is sufficient to call the getDefaultInstance() method.PaymentCardRecognitionIntentRequestrequest=PaymentCardRecognitionIntentRequest.getDefaultInstance();paymentsClient.getPaymentCardRecognitionIntent(request).addOnSuccessListener(intentResponse->{cardRecognitionPendingIntent=intentResponse.getPaymentCardRecognitionPendingIntent();paymentCardOcrButton.setVisibility(View.VISIBLE);}).addOnFailureListener(e->{// The API is not available either because the feature is not enabled on the device// or because your app is not registered.Log.e(TAG,"Payment card ocr not available.",e);});}
Durante o processo de reconhecimento, nosso algoritmo tenta reconhecer o
cartão de pagamento. Se ele reconhecer um resultado, a API vai dar um retorno como
PaymentCardRecognitionResult. O resultado sempre contém um número de cartão. O algoritmo não vai detectar
uma data de validade, caso ela não esteja presente ou se
já tiver passado do vencimento. Por vários motivos, um cartão pode não ser
reconhecível. Isso geralmente acontece quando um usuário cancela um fluxo e a API
retorna o código Activity.RESULT_CANCELLED.
[null,null,["Última atualização 2024-10-16 UTC."],[[["\u003cp\u003eThe Google Pay payment card recognition API enables apps to scan credit and debit cards using the device's camera to extract PAN and expiration date information through OCR.\u003c/p\u003e\n"],["\u003cp\u003eThe API delegates scanning to Google Play services, eliminating the need for camera permissions within your app and ensuring data privacy as images are processed on-device and not stored by Google.\u003c/p\u003e\n"],["\u003cp\u003eCertain device constraints, such as having a Google account, minimum RAM, a back-facing camera, latest Google Play services, and portrait orientation support, must be met for the API to function.\u003c/p\u003e\n"],["\u003cp\u003eTo use the API, you need to create a \u003ccode\u003ePaymentsClient\u003c/code\u003e instance, request a \u003ccode\u003ePendingIntent\u003c/code\u003e, and handle the \u003ccode\u003ePaymentCardRecognitionResult\u003c/code\u003e to retrieve card information while acknowledging potential inaccuracies and the need for card network verification.\u003c/p\u003e\n"]]],["The Google payment card recognition API uses a device's camera to scan credit/debit card data (PAN and expiration date) via OCR. It requires production access to the Google Pay API for Android. Key actions include: creating a `PaymentsClient` instance, requesting a `PendingIntent`, and initiating card recognition. The API returns a `PaymentCardRecognitionResult` with the card number and, if available, the expiration date. Device constraints include having a Google account, RAM of 1GB or more, a back facing camera, and the latest Google Play Services.\n"],null,["# Debit and credit card recognition\n\n| **Important:** The payment card recognition API requires production access to [Google Pay API\n| for Android](https://developers.google.com/pay/api/android/overview).\n\n\nThe Google payment card recognition API provides the ability to use a camera\nto recognize information from payment cards. The API supports\nrecognition of the primary account number (PAN) and the expiration date from a credit card or a debit card\nthrough optical character recognition (OCR). The API delegates the task of\nscanning the card to Google Play services. Therefore, your app doesn't need\nto request camera permission and only receives the scan results. All image\nprocessing occurs on the device and Google doesn't store the results or share the image data.\n\n\nTo ensure the optimal user experience and functionality, the API has the following constraints:\n\n- The device has a Google account logged in.\n- The device has at least 1 GB of RAM.\n- The device has a back facing camera.\n- The device has the latest Google Play services version.\n- The device supports `PORTRAIT` orientation.\n\n| **Note:** In scenarios where these constraints aren't met, Google Play services disables the API. Google Play services automatically handle the enablement and disablement of the API with Google Play.\n\nCreate a request\n----------------\n\n\nCreate a\n[PaymentsClient](/android/reference/com/google/android/gms/wallet/PaymentsClient)\ninstance in the `onCreate` method in your `Activity`. You can use\n`PaymentsClient` to interact with the Google Pay API. \n\n### Kotlin\n\n```kotlin\n fun createPaymentsClient(activity: Activity): PaymentsClient {\n val walletOptions = Wallet.WalletOptions.Builder()\n .setEnvironment(Constants.PAYMENTS_ENVIRONMENT)\n .build()\n\n return Wallet.getPaymentsClient(activity, walletOptions)\n }https://github.com/google-pay/android-quickstart/blob/bdb0fd8e8d09a2e4f08faa428e852f748a233a3a/kotlin/app/src/main/java/com/google/android/gms/samples/wallet/PaymentsUtil.kt\n```\n\n### Java\n\n```java\n public static PaymentsClient createPaymentsClient(Activity activity) {\n Wallet.WalletOptions walletOptions =\n new Wallet.WalletOptions.Builder().setEnvironment(Constants.PAYMENTS_ENVIRONMENT).build();\n return Wallet.getPaymentsClient(activity, walletOptions);\n }https://github.com/google-pay/android-quickstart/blob/bdb0fd8e8d09a2e4f08faa428e852f748a233a3a/java/app/src/main/java/com/google/android/gms/samples/wallet/util/PaymentsUtil.java\n```\n| **Note:** When using `WalletConstants.ENVIRONMENT_TEST`, the API always returns a stub result if it recognizes the card.\n\n\nAfter you create the response, you can then send an asynchronous request for a `PendingIntent`,\nwhich you can use to start the payment card recognition activity.\n\n\nKeep in mind that the request doesn't always succeed. If there is no API enablement, the request\nfails. We suggest that you adjust your app's behavior according to the\nresponse to the request. In the sample app, we display the button only after\nwe receive a successful response. \n\n### Kotlin\n\n```kotlin\n private fun possiblyShowPaymentCardOcrButton() {\n // The request can be used to configure the type of the payment card recognition. Currently\n // the only supported type is card OCR, so it is sufficient to call the getDefaultInstance()\n // method.\n val request = PaymentCardRecognitionIntentRequest.getDefaultInstance()\n paymentsClient\n .getPaymentCardRecognitionIntent(request)\n .addOnSuccessListener { intentResponse -\u003e\n cardRecognitionPendingIntent = intentResponse.paymentCardRecognitionPendingIntent\n paymentCardOcrButton.visibility = View.VISIBLE\n }\n .addOnFailureListener { e -\u003e\n // The API is not available either because the feature is not enabled on the device\n // or because your app is not registered.\n Log.e(TAG, \"Payment card ocr not available.\", e)\n }\n }https://github.com/google-pay/android-quickstart/blob/bdb0fd8e8d09a2e4f08faa428e852f748a233a3a/kotlin/app/src/main/java/com/google/android/gms/samples/wallet/CheckoutActivity.kt\n```\n\n### Java\n\n```java\n public void possiblyShowPaymentCardOcrButton() {\n // The request can be used to configure the type of the payment card recognition. Currently the\n // only supported type is card OCR, so it is sufficient to call the getDefaultInstance() method.\n PaymentCardRecognitionIntentRequest request =\n PaymentCardRecognitionIntentRequest.getDefaultInstance();\n paymentsClient\n .getPaymentCardRecognitionIntent(request)\n .addOnSuccessListener(intentResponse -\u003e {\n cardRecognitionPendingIntent = intentResponse.getPaymentCardRecognitionPendingIntent();\n paymentCardOcrButton.setVisibility(View.VISIBLE);\n })\n .addOnFailureListener(e -\u003e {\n // The API is not available either because the feature is not enabled on the device\n // or because your app is not registered.\n Log.e(TAG, \"Payment card ocr not available.\", e);\n });\n }https://github.com/google-pay/android-quickstart/blob/bdb0fd8e8d09a2e4f08faa428e852f748a233a3a/java/app/src/main/java/com/google/android/gms/samples/wallet/activity/CheckoutActivity.java\n```\n\n\nTo start the payment card recognition activity, use the following code sample: \n\n### Kotlin\n\n```kotlin\n private fun startPaymentCardOcr() {\n try {\n ActivityCompat.startIntentSenderForResult(\n this@CheckoutActivity,\n cardRecognitionPendingIntent.intentSender,\n PAYMENT_CARD_RECOGNITION_REQUEST_CODE,\n null, 0, 0, 0, null\n )\n } catch (e: SendIntentException) {\n throw RuntimeException(\"Failed to start payment card recognition.\", e)\n }\n }https://github.com/google-pay/android-quickstart/blob/bdb0fd8e8d09a2e4f08faa428e852f748a233a3a/kotlin/app/src/main/java/com/google/android/gms/samples/wallet/CheckoutActivity.kt\n```\n\n### Java\n\n```java\n public void startPaymentCardOcr(View view) {\n try {\n ActivityCompat.startIntentSenderForResult(\n CheckoutActivity.this, cardRecognitionPendingIntent.getIntentSender(),\n PAYMENT_CARD_RECOGNITION_REQUEST_CODE,\n null, 0, 0, 0, null);\n } catch (SendIntentException e) {\n throw new RuntimeException(\"Failed to start payment card recognition.\", e);\n }\n }https://github.com/google-pay/android-quickstart/blob/bdb0fd8e8d09a2e4f08faa428e852f748a233a3a/java/app/src/main/java/com/google/android/gms/samples/wallet/activity/CheckoutActivity.java\n```\n\nInterpret the result\n--------------------\n\n\nDuring the recognition process, our algorithm attempts to recognize the\npayment card. If it successfully recognizes a result, then the API returns the result as a\n[PaymentCardRecognitionResult](/android/reference/com/google/android/gms/wallet/PaymentCardRecognitionResult). The result always contains a card number. The expiration date might\nnot be present if the algorithm fails to detect one, or if the date\nshows that the card is past its expiration date. For various reasons, a card might not be\nrecognizable. This usually results when a user cancels a flow and the API\nreturns `Activity.RESULT_CANCELLED`.\n**Caution:** On rare occasions, the results might be incorrect. It's your responsibility to verify the card information through the corresponding card network. \n\n### Kotlin\n\n```kotlin\n private fun handlePaymentCardRecognitionSuccess(\n cardRecognitionResult: PaymentCardRecognitionResult\n ) {\n val creditCardExpirationDate = cardRecognitionResult.creditCardExpirationDate\n val expirationDate = creditCardExpirationDate?.let { \"%02d/%d\".format(it.month, it.year) }\n val cardResultText = \"PAN: ${cardRecognitionResult.pan}\\nExpiration date: $expirationDate\"\n Toast.makeText(this, cardResultText, Toast.LENGTH_LONG).show()\n }https://github.com/google-pay/android-quickstart/blob/bdb0fd8e8d09a2e4f08faa428e852f748a233a3a/kotlin/app/src/main/java/com/google/android/gms/samples/wallet/CheckoutActivity.kt\n```\n\n### Java\n\n```java\n private void handleCardRecognitionSuccess(PaymentCardRecognitionResult cardResult) {\n\n String expirationDate = null;\n Locale locale = Locale.getDefault();\n CreditCardExpirationDate cardExpirationDate = cardResult.getCreditCardExpirationDate();\n if(cardExpirationDate != null) {\n expirationDate = String.format(locale,\n \"%02d/%d\", cardExpirationDate.getMonth(), cardExpirationDate.getYear());\n }\n\n String cardResultString = String.format(locale,\n \"PAN: %s\\nExpiration date: %s\", cardResult.getPan(), expirationDate);\n Toast.makeText(this, cardResultString, Toast.LENGTH_LONG).show();\n }https://github.com/google-pay/android-quickstart/blob/bdb0fd8e8d09a2e4f08faa428e852f748a233a3a/java/app/src/main/java/com/google/android/gms/samples/wallet/activity/CheckoutActivity.java\n```"]]