diff --git a/CHANGELOG.md b/CHANGELOG.md index 5550067f..9d61825e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ All notable changes to this project are documented in this file. ### Added +- **Google Pay `DIRECT` tokenization.** `PaymentRequest` and `usePaymentCheckout` add + `googlePayTokenization`. `{ type: 'direct', publicKey }` has Google encrypt the token with your + own EC public key (`protocolVersion: "ECv2"`), for a PCI DSS compliant server that decrypts it; + it needs Google's approval. A missing `publicKey` fails with `'CONFIGURATION'` in every + environment, and `PRODUCTION` then needs no gateway values. Omitted or `{ type: 'gateway' }` + sends the same request as before. See + [Direct tokenization](https://gmi-software.github.io/react-native-pay/docs/setup/android-google-pay#direct-tokenization) + ([#89](https://github.com/gmi-software/react-native-pay/issues/89)). - **ISO 3166-2 region codes in Google Pay addresses.** `CNPostalAddress` adds `isoAdministrativeArea`, the region as an ISO 3166-2 code such as `'US-CA'`, for tax and shipping systems that need a code rather than the free-text `state`. Android now requests full billing diff --git a/README.md b/README.md index 1072074e..7021bd81 100644 --- a/README.md +++ b/README.md @@ -363,6 +363,7 @@ interface UsePaymentCheckoutConfig { googlePayEnvironment?: "TEST" | "PRODUCTION"; googlePayGateway?: string; googlePayGatewayMerchantId?: string; + googlePayTokenization?: GooglePayTokenization; // Default: gateway. { type: "direct", publicKey } to decrypt yourself googlePayAllowedAuthMethods?: GooglePayAuthMethod[]; // Default: ['PAN_ONLY', 'CRYPTOGRAM_3DS'] googlePayAllowPrepaidCards?: boolean; // false leaves prepaid cards out. Default: true googlePayCheckoutOption?: GooglePayCheckoutOption; // Sheet button label. Default: Google Pay picks @@ -807,6 +808,7 @@ interface PaymentRequest { googlePayEnvironment?: "TEST" | "PRODUCTION"; googlePayGateway?: string; googlePayGatewayMerchantId?: string; + googlePayTokenization?: GooglePayTokenization; // who encrypts the token googlePayAllowedAuthMethods?: string[]; // GooglePayAuthMethod values googlePayAllowPrepaidCards?: boolean; // false leaves prepaid cards out googlePayCheckoutOption?: GooglePayCheckoutOption; // the sheet's button label @@ -906,6 +908,14 @@ type GooglePayCheckoutOption = | "completeImmediatePurchase" | "continueToReview"; +// Who encrypts the Google Pay token (Android). 'direct' needs Google's approval, +// PCI DSS compliance and your base64 EC public key; your server decrypts the token. +type GooglePayTokenizationType = "gateway" | "direct"; +interface GooglePayTokenization { + type: GooglePayTokenizationType; + publicKey?: string; // required for 'direct' +} + // Payment Method Type type PaymentMethodType = "unknown" | "debit" | "credit" | "prepaid" | "store"; diff --git a/docs/docs/api/types.md b/docs/docs/api/types.md index bc670446..963828f0 100644 --- a/docs/docs/api/types.md +++ b/docs/docs/api/types.md @@ -90,6 +90,7 @@ interface PaymentRequest { googlePayEnvironment?: 'TEST' | 'PRODUCTION' googlePayGateway?: string googlePayGatewayMerchantId?: string + googlePayTokenization?: GooglePayTokenization // default: gateway googlePayAllowedAuthMethods?: string[] // GooglePayAuthMethod values googlePayAllowPrepaidCards?: boolean // default: true googlePayCheckoutOption?: GooglePayCheckoutOption // the sheet's button label @@ -108,6 +109,8 @@ Without `googlePayEnvironment`, Android uses `'TEST'`. When it is omitted, an An `supportedNetworks` takes [`PaymentNetwork`](#paymentnetwork) names, matched ignoring case, and limits the cards the payer can choose on both platforms. A name that is not a `PaymentNetwork` fails the payment with `code: 'CONFIGURATION'` and an `error` that contains `Unknown payment network "". Use a PaymentNetwork value such as "visa" or "mastercard"`. A network the platform does not offer is left out, so one cross-platform list works: Android drops `cartesBancaires`, for example. The payment fails when no network is left. +`googlePayTokenization` sets who encrypts the Google Pay token: your gateway, from `googlePayGateway` and `googlePayGatewayMerchantId`, or your own server with `'direct'`. See [`GooglePayTokenization`](#googlepaytokenization). Omitted, it is `'gateway'`. Android only. + `googlePayAllowedAuthMethods` takes [`GooglePayAuthMethod`](#googlepayauthmethod) values and defaults to both. Android only. `googlePayAllowPrepaidCards: false` leaves prepaid cards out of the Google Pay sheet, for a gateway or risk policy that refuses them. Sent as Google Pay's `allowPrepaidCards`. Omitted or `true`, prepaid cards are accepted. Android only: Apple Pay cannot leave prepaid cards out. @@ -449,6 +452,26 @@ Any other value fails the payment on both platforms with `code: 'CONFIGURATION'` --- +## GooglePayTokenization + +Who encrypts the Google Pay token, used in `googlePayTokenization` (Android only). Sent as the card's `tokenizationSpecification`. + +```ts +type GooglePayTokenizationType = 'gateway' | 'direct' + +interface GooglePayTokenization { + type: GooglePayTokenizationType + publicKey?: string // required for 'direct' +} +``` + +- `'gateway'` — Google encrypts the token for your payment gateway, named by `googlePayGateway` and `googlePayGatewayMerchantId`. Google Pay calls it `PAYMENT_GATEWAY`. The same request as leaving `googlePayTokenization` out; `publicKey` is ignored. +- `'direct'` — Google encrypts the token with your own public key, and your server decrypts it. Sent as `{"type":"DIRECT","parameters":{"protocolVersion":"ECv2","publicKey":""}}`; the gateway fields are ignored. It needs Google's approval and PCI DSS compliance. See [Decrypt the token yourself](/docs/guides/server-processing#decrypt-the-token-yourself-google-pay-direct). + +With `'direct'`, a missing or blank `publicKey` fails the payment with `code: 'CONFIGURATION'` and an `error` that contains `googlePayTokenization.publicKey is required for 'direct' tokenization`, in `TEST` too: unlike the gateway, there is no example key to fall back to. In `PRODUCTION`, `'direct'` still needs `googlePayMerchantId`, but not `googlePayGateway` or `googlePayGatewayMerchantId`. Another `type` fails the payment on both platforms with `code: 'CONFIGURATION'`. iOS ignores the rest. + +--- + ## MerchantCapability Merchant capabilities, used in `merchantCapabilities`. They come from Apple Pay; Android only reads `'Credit'` and `'Debit'`. diff --git a/docs/docs/api/use-payment-checkout.md b/docs/docs/api/use-payment-checkout.md index bcd803ac..e0240d30 100644 --- a/docs/docs/api/use-payment-checkout.md +++ b/docs/docs/api/use-payment-checkout.md @@ -28,6 +28,7 @@ interface UsePaymentCheckoutConfig { googlePayEnvironment?: 'TEST' | 'PRODUCTION' googlePayGateway?: string googlePayGatewayMerchantId?: string + googlePayTokenization?: GooglePayTokenization // default: gateway googlePayAllowedAuthMethods?: GooglePayAuthMethod[] // default: both googlePayAllowPrepaidCards?: boolean // default: true googlePayCheckoutOption?: GooglePayCheckoutOption // the sheet's button label @@ -53,6 +54,7 @@ interface UsePaymentCheckoutConfig { - **merchantName** — The business name shown to the payer. On iOS, Apple Pay labels the total with it, so the sheet reads "Pay *merchantName*". On Android, it is the merchant name on the Google Pay sheet. Without it, iOS uses your app's display name (`CFBundleDisplayName`) and Android uses the app's label. Set it on both platforms. - **totalLabel** — Android only. The label of the total in the Google Pay sheet, such as `'Razem'`. Defaults to `'Total'`. iOS labels the total with `merchantName`. See [PaymentRequest](/docs/api/types#paymentrequest). - **supportedNetworks** — The card networks the payer can choose, as [PaymentNetwork](/docs/api/types#paymentnetwork) names. Both platforms honour it. A network the platform does not offer is left out, and an unknown name fails the payment. Pass the same list to [`GooglePayButton`](/docs/api/components#googlepaybutton-android-only). +- **googlePayTokenization** — Android only. Who encrypts the Google Pay token. Omitted or `{ type: 'gateway' }`, your gateway does, from `googlePayGateway` and `googlePayGatewayMerchantId`. `{ type: 'direct', publicKey }` has Google encrypt it with your own key, for a PCI DSS compliant server that decrypts it; it needs Google's approval. A missing `publicKey` fails with a `'CONFIGURATION'` error. See [GooglePayTokenization](/docs/api/types#googlepaytokenization). - **googlePayAllowedAuthMethods** — Android only. Which Google Pay cards to accept: `'PAN_ONLY'` (saved to the Google account), `'CRYPTOGRAM_3DS'` (tokenized on the device), or both, the default. See [GooglePayAuthMethod](/docs/api/types#googlepayauthmethod). - **googlePayAllowPrepaidCards** — Android only. `false` leaves prepaid cards out of the Google Pay sheet, for a gateway or risk policy that refuses them; without it, the payer learns only when the charge fails. Defaults to `true`. Pass the same value to [`GooglePayButton`](/docs/api/components#googlepaybutton-android-only). - **googlePayCheckoutOption** — Android only. The label of the Google Pay sheet's button: `'default'` ("Continue" or "Pay", as when it is omitted), `'completeImmediatePurchase'` ("Pay now") or `'continueToReview'` ("Review Order"). `'completeImmediatePurchase'` needs a final total: with a `'pending'` item, `startPayment()` fails with a `'CONFIGURATION'` error before the sheet opens. See [GooglePayCheckoutOption](/docs/api/types#googlepaycheckoutoption). diff --git a/docs/docs/compatibility.md b/docs/docs/compatibility.md index cc679396..f7a66203 100644 --- a/docs/docs/compatibility.md +++ b/docs/docs/compatibility.md @@ -65,7 +65,7 @@ No. The library works in bare React Native too. The Expo plugin only simplifies Yes. Omit `enableGooglePay` for iOS-only (`false` removes an entry another plugin added); omit plugin `merchantIdentifier` for Android-only. In code, only render the button for the platform you support. **Which gateways are supported for Google Pay?** -Any gateway that supports the [Google Pay API](https://developers.google.com/pay/api/android) and the gateway token format. Commonly used: Stripe, Braintree, Square, Adyen, Authorize.net, Checkout.com. Set `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId` accordingly. +Any gateway that supports the [Google Pay API](https://developers.google.com/pay/api/android) and the gateway token format. Commonly used: Stripe, Braintree, Square, Adyen, Authorize.net, Checkout.com. Set `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId` accordingly. A PCI DSS compliant merchant that decrypts tokens itself can use [`'direct'` tokenization](/docs/setup/android-google-pay#direct-tokenization) instead. **Where do I report issues?** [GitHub Issues](https://github.com/gmi-software/react-native-pay/issues). diff --git a/docs/docs/guides/server-processing.md b/docs/docs/guides/server-processing.md index 3feb747d..f3896645 100644 --- a/docs/docs/guides/server-processing.md +++ b/docs/docs/guides/server-processing.md @@ -171,6 +171,16 @@ app.post('/process-payment', async (req, res) => { - Handling failures and refunds. - Provider-specific walkthroughs in [Przelewy24 Apple Pay + Google Pay cookbook](/docs/integrations/przelewy24). +## Decrypt the token yourself (Google Pay `DIRECT`) + +With [`googlePayTokenization: { type: 'direct', publicKey }`](/docs/setup/android-google-pay#direct-tokenization), no gateway decrypts the Google Pay token: your server does. `token.paymentData` is then Google's `ECv2` payment method token, a JSON string with `protocolVersion`, `signature`, `intermediateSigningKey` and `signedMessage`. + +- Verify the token before you decrypt it. Check the `intermediateSigningKey` signatures against Google's root signing keys, check that the intermediate key has not expired, and check `signature` with the intermediate signing key. That signature covers a length-prefixed string of the sender ID (`Google`), your recipient ID, the protocol version and `signedMessage`, not `signedMessage` alone. Reject the token if any check fails. Tink does this for you; on another stack, follow the verification steps in Google's guide. +- Decrypt it with the private key that matches `publicKey`. Google recommends Tink's [`apps-paymentmethodtoken`](https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#using-tink) library (Java), with `protocolVersion("ECv2")`. For `PRODUCTION` tokens, the recipient ID is `merchant:` and the signing keys are Google's production keys. `TEST` tokens use Google's test signing keys; the library sends no merchant ID in `TEST`, so take the recipient ID for them from Google's guide. +- Check `messageExpiration` before you charge. +- The decrypted message holds the card number and, for `CRYPTOGRAM_3DS` cards, a cryptogram. It is card data: your servers must be PCI DSS compliant. +- Rotate the key every year. Google encrypts with the key in the request, so serve `publicKey` from your server. Keep the old private key for at least eight days after you remove the old public key from the Google Pay & Wallet Console, so it can decrypt tokens made with the old key. See Google's [key rotation](https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#key-rotation) section for the full steps. + ## Security - Use **HTTPS** and authenticate the client (e.g. session or API key). diff --git a/docs/docs/guides/testing.md b/docs/docs/guides/testing.md index f0100d5f..03b94695 100644 --- a/docs/docs/guides/testing.md +++ b/docs/docs/guides/testing.md @@ -85,7 +85,7 @@ Some gateways, such as Stripe, Braintree, and Adyen, show their own test cards i - **Availability.** With `existingPaymentMethodRequired`, `isReadyToPay` [always returns `true` in `TEST`](https://developers.google.com/pay/api/android/reference/request-objects#IsReadyToPayRequest), so `hasActiveCard` is `true` even with no card. An emulator with no Google account signed in answers `false` instead. You can't test the "no card" path of a signed-in user in `TEST`. - **A live charge.** `TEST` tokens never carry real card data. With your gateway's test values, its test environment can process them, but nothing is charged. -- **Your production request.** The library sends `googlePayMerchantId` and requires `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId` only in `PRODUCTION`. A missing value fails with, for example, `googlePayMerchantId is required in PRODUCTION`, which you only see in a `PRODUCTION` build. +- **Your production request.** The library sends `googlePayMerchantId` and requires `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId` only in `PRODUCTION`; with [`'direct'` tokenization](/docs/setup/android-google-pay#direct-tokenization) it requires `googlePayMerchantId` and no gateway values. A missing value fails with, for example, `googlePayMerchantId is required in PRODUCTION`, which you only see in a `PRODUCTION` build. ### Production access @@ -94,9 +94,9 @@ Google Pay only works in `PRODUCTION` after Google approves your app. Google's [ 1. In the [Google Pay & Wallet Console](https://pay.google.com/business/console), choose the **Merchant** business type and complete your business profile. 2. Open **Google Pay API**, then **Get started**, and accept the Google Pay API Terms of Service and Acceptable Use Policy. Your Google Pay merchant ID then appears in the Console. Pass it as `googlePayMerchantId`. 3. Go through the [integration checklist](https://developers.google.com/pay/api/android/guides/test-and-deploy/integration-checklist) against your `TEST` build. -4. Under **Google Pay API → Integrations → Integrate with your Android app**, pick your app and the **Gateway** integration type. The Console only lists apps published on Google Play under the same Google account. +4. Under **Google Pay API → Integrations → Integrate with your Android app**, pick your app and the integration type: **Gateway** if a payment service provider decrypts the token, or **Direct** with [`'direct'` tokenization](/docs/setup/android-google-pay#direct-tokenization), where you register your public key. The Console only lists apps published on Google Play under the same Google account. 5. Upload screenshots of your `TEST` integration, and submit the app for approval. -6. Once approved, set `googlePayEnvironment: 'PRODUCTION'` and your production gateway values, sign the app with your release key, and publish it on Google Play. Google says the debug key doesn't work in `PRODUCTION`. +6. Once approved, set `googlePayEnvironment: 'PRODUCTION'` and your production gateway values (or your production `publicKey` with `'direct'`), sign the app with your release key, and publish it on Google Play. Google says the debug key doesn't work in `PRODUCTION`. Until your app has production access, the sheet shows an "Unrecognized App" error. To find out why a `PRODUCTION` request fails, read the merchant error log: diff --git a/docs/docs/payment-flow.md b/docs/docs/payment-flow.md index b8010712..29b9cb68 100644 --- a/docs/docs/payment-flow.md +++ b/docs/docs/payment-flow.md @@ -85,7 +85,7 @@ function describeOutcome(result: PaymentResult): string | null { | --- | --- | --- | --- | | `'CANCELLED'` | The sheet closed before the user authorized. | iOS: the sheet closed without an authorization. PassKit doesn't say why, so a sheet that closes by itself also reports a cancel. Debug builds log a warning when the sheet closes within 1 second of appearing (see [Troubleshooting](/docs/troubleshooting#the-apple-pay-sheet-closes-right-away)). Android: the sheet returned `RESULT_CANCELED`, also when the user dismisses Google's sign-in prompt, or a Google Pay error has `CANCELED` / `ERROR_CODE_USER_CANCELLED`. | Nothing. Don't show an error. | | `'IN_PROGRESS'` | Another payment is still in flight. No sheet was shown. | Both: `startPayment` called while a payment hasn't settled (see [`isPaymentInProgress()`](/docs/api/hybrid-payment-handler#ispaymentinprogress)). | Ignore it. The payment in flight settles normally. | -| `'CONFIGURATION'` | The request or the app's setup is invalid. Retrying won't help. | Both: an invalid amount, a negative total, a `currencyCode` or `countryCode` that isn't an upper-case ISO code, an unknown merchant capability, invalid `shippingMethods`, and `supportedNetworks` that is empty, has an unknown name or has no network the platform offers. iOS: no Apple Pay merchant ID, an unknown `shippingType` or `applePayLaterAvailability`, an `applePayMerchantCategoryCode` that isn't a whole number from 0 to 9999. Android: more than two decimal places, an unknown `googlePayAllowedAuthMethods` value, `googlePayCheckoutOption: 'completeImmediatePurchase'` with a `'pending'` item, `PRODUCTION` without `googlePayMerchantId`, `googlePayGateway` or `googlePayGatewayMerchantId`, and a Google Pay error with `DEVELOPER_ERROR`, `ERROR_CODE_INVALID_PARAMETERS`, `ERROR_CODE_MERCHANT_ACCOUNT_ERROR` or `ERROR_CODE_UNSUPPORTED_API_VERSION`. | Fix the request or the setup; `error` says what is wrong. Show the user a generic error. | +| `'CONFIGURATION'` | The request or the app's setup is invalid. Retrying won't help. | Both: an invalid amount, a negative total, a `currencyCode` or `countryCode` that isn't an upper-case ISO code, an unknown merchant capability, invalid `shippingMethods`, and `supportedNetworks` that is empty, has an unknown name or has no network the platform offers. iOS: no Apple Pay merchant ID, an unknown `shippingType` or `applePayLaterAvailability`, an `applePayMerchantCategoryCode` that isn't a whole number from 0 to 9999. Android: more than two decimal places, an unknown `googlePayAllowedAuthMethods` value, `googlePayCheckoutOption: 'completeImmediatePurchase'` with a `'pending'` item, `googlePayTokenization: { type: 'direct' }` without a `publicKey`, `PRODUCTION` without `googlePayMerchantId`, `PRODUCTION` with gateway tokenization but without `googlePayGateway` or `googlePayGatewayMerchantId`, and a Google Pay error with `DEVELOPER_ERROR`, `ERROR_CODE_INVALID_PARAMETERS`, `ERROR_CODE_MERCHANT_ACCOUNT_ERROR` or `ERROR_CODE_UNSUPPORTED_API_VERSION`. | Fix the request or the setup; `error` says what is wrong. Show the user a generic error. | | `'NOT_AVAILABLE'` | The device can't show the payment sheet right now. | iOS: PassKit can't create the sheet, which Apple documents for a user who can't pay with any of the request's networks, or can't show it (see [Troubleshooting](/docs/troubleshooting#unable-to-present-payment-authorization)). Android: no current activity, the Google Pay sheet fails to start, and a Google Pay error with `SIGN_IN_REQUIRED`, `API_NOT_CONNECTED`, `ERROR_CODE_BUYER_ACCOUNT_ERROR` or `ERROR_CODE_AUTHENTICATION_FAILURE`. | Offer another payment method. Show the pay button only as [Check availability](/docs/guides/availability#show-the-right-button) describes, from `isSupported` and `hasActiveCard`. | | `'PROVIDER_ERROR'` | Apple Pay, Google Pay or your `onAuthorize` reported a failure. | Both: [`onAuthorize`](/docs/guides/server-processing#charge-before-the-sheet-closes) resolved with `'failure'`, rejected, or didn't settle within 25 seconds. Android: any other Google Pay error, such as a network or internal error, and payment data that is missing or can't be read. | Let the user retry or choose another payment method. After a timeout, your server may still have charged: reconcile the order. | | `'UNKNOWN'` | Anything else. | iOS: an unexpected error while starting the payment. Android: an unexpected result code or exception, or a Google Pay error without a status. | Show a generic error and log `error`. | diff --git a/docs/docs/setup/android-google-pay.md b/docs/docs/setup/android-google-pay.md index 10595c66..261b967f 100644 --- a/docs/docs/setup/android-google-pay.md +++ b/docs/docs/setup/android-google-pay.md @@ -49,6 +49,37 @@ If you omit `googlePayEnvironment`, Google Pay runs in `TEST`, in release builds Supported gateways include: `stripe`, `braintree`, `square`, `adyen`, `authorizenet`, `checkoutltd`. See [Google Pay Gateway Tokens](https://developers.google.com/pay/api/android/reference/request-objects#gateway) for the full list and exact identifiers. +### Direct tokenization + +With a gateway, Google encrypts the token for your gateway, which decrypts it. With `'direct'`, Google encrypts it with your own public key, and your server decrypts it and gets the card data. Use it only when you process card data yourself: + +- Your servers must be PCI DSS compliant, and Google must approve the direct integration. Each year you send Google updated PCI documentation and rotate the key. +- Register the public key in the [Google Pay & Wallet Console](https://pay.google.com/business/console), under **Google Pay API** > **Direct integration**. + +Generate a key pair on the NIST P-256 curve, and the public key as base64 of its uncompressed point, with the commands in Google's [payment data cryptography guide](https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography): + +```bash +openssl ecparam -name prime256v1 -genkey -noout -out key.pem +openssl ec -in key.pem -pubout -text -noout 2> /dev/null | grep "pub:" -A5 | sed 1d | xxd -r -p | base64 | paste -sd "\0" - | tr -d '\n\r ' > publicKey.txt +``` + +Keep `key.pem` on your server. Pass the public key as `googlePayTokenization`: + +```ts +import { usePaymentCheckout } from '@gmisoftware/react-native-pay' + +// From your server, so you can rotate it without an app release. +declare const publicKey: string + +usePaymentCheckout({ + googlePayMerchantId: 'your_google_pay_merchant_id', + googlePayEnvironment: 'PRODUCTION', + googlePayTokenization: { type: 'direct', publicKey }, +}) +``` + +The library sends `{"type":"DIRECT","parameters":{"protocolVersion":"ECv2","publicKey":"…"}}` and ignores `googlePayGateway` and `googlePayGatewayMerchantId`. Without a `publicKey`, the payment fails with `code: 'CONFIGURATION'`, in `TEST` too, since there is no example key like the `example` gateway. To decrypt the token, see [Decrypt the token yourself](/docs/guides/server-processing#decrypt-the-token-yourself-google-pay-direct). + ## 4. Prebuild and run ```bash diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 9c5706c6..49ab7e7e 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -94,7 +94,7 @@ Use only supported Apple button values: - Add at least one card in Google Pay on the device. - Use `googlePayEnvironment: 'TEST'` for test flows. -- Verify `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId`. +- Verify `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId`, or with `'direct'` tokenization, `googlePayTokenization.publicKey` and the key registered in the Google Pay & Wallet Console. ### `hasActiveCard` is `true` without a card diff --git a/package/android/src/main/java/com/margelo/nitro/pay/Constants.kt b/package/android/src/main/java/com/margelo/nitro/pay/Constants.kt index 478c097b..30a6afae 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/Constants.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/Constants.kt @@ -25,6 +25,8 @@ object PaymentConstants { // Tokenization const val TOKENIZATION_PAYMENT_GATEWAY = "PAYMENT_GATEWAY" + const val TOKENIZATION_DIRECT = "DIRECT" + const val DIRECT_PROTOCOL_VERSION = "ECv2" const val DEFAULT_GATEWAY = "example" const val DEFAULT_GATEWAY_MERCHANT_ID = "exampleGatewayMerchantId" diff --git a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayRequestBuilder.kt b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayRequestBuilder.kt index 6bba666e..a091bdf3 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayRequestBuilder.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayRequestBuilder.kt @@ -204,12 +204,23 @@ object GooglePayRequestBuilder { } /** - * Creates tokenization specification + * Creates tokenization specification: `PAYMENT_GATEWAY`, or `DIRECT` + * for [GooglePayTokenizationType.DIRECT] */ private fun createTokenizationSpec( request: PaymentRequest, environment: Int ): JSONObject { + if (request.googlePayTokenization?.type == GooglePayTokenizationType.DIRECT) { + return JSONObject().apply { + put("type", PaymentConstants.TOKENIZATION_DIRECT) + put("parameters", JSONObject().apply { + put("protocolVersion", PaymentConstants.DIRECT_PROTOCOL_VERSION) + put("publicKey", request.googlePayTokenization.publicKey!!.trim()) + }) + } + } + val isProduction = environment == WalletConstants.ENVIRONMENT_PRODUCTION val gateway = if (isProduction) { request.googlePayGateway!!.trim() @@ -234,11 +245,17 @@ object GooglePayRequestBuilder { } private fun validatePaymentRequest(request: PaymentRequest, environment: Int) { + // No fallback key in TEST, unlike the example gateway. + val isDirect = request.googlePayTokenization?.type == GooglePayTokenizationType.DIRECT + require(!isDirect || !request.googlePayTokenization?.publicKey.isNullOrBlank()) { + "googlePayTokenization.publicKey is required for 'direct' tokenization" + } if (environment != WalletConstants.ENVIRONMENT_PRODUCTION) return require(!request.googlePayMerchantId.isNullOrBlank()) { "googlePayMerchantId is required in PRODUCTION" } + if (isDirect) return require(!request.googlePayGateway.isNullOrBlank()) { "googlePayGateway is required in PRODUCTION" } diff --git a/package/android/src/test/java/com/margelo/nitro/pay/GooglePayRequestBuilderTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/GooglePayRequestBuilderTest.kt index 1e3b1974..a3570cd1 100644 --- a/package/android/src/test/java/com/margelo/nitro/pay/GooglePayRequestBuilderTest.kt +++ b/package/android/src/test/java/com/margelo/nitro/pay/GooglePayRequestBuilderTest.kt @@ -340,6 +340,130 @@ class GooglePayRequestBuilderTest { assertTrue(error.message!!.contains("googlePayMerchantId")) } + // Tokenization + + private fun JSONObject.tokenizationSpec(): JSONObject = + getJSONArray("allowedPaymentMethods").getJSONObject(0) + .getJSONObject("tokenizationSpecification") + + private val publicKey = + "BOdoXP+9Aq473SnGwg3JU1aiNpsd9vH2ognq4PtDtlLGa3Kj8TPf+jaQNPyDSkh3JUhiS0KyrrlWhAgNZKHYF2Y=" + + private fun gatewaySpec(gateway: String, gatewayMerchantId: String) = + """{"type":"PAYMENT_GATEWAY","parameters":{"gateway":"$gateway","gatewayMerchantId":"$gatewayMerchantId"}}""" + + // org.json's JVM build doesn't keep key order, so compare as maps. + private fun JSONObject.toMap(): Map = keys().asSequence().associateWith { key -> + get(key).let { if (it is JSONObject) it.toMap() else it } + } + + private fun assertJsonEquals(expected: String, actual: JSONObject) { + assertEquals(JSONObject(expected).toMap(), actual.toMap()) + } + + @Test + fun tokenization_defaultsToExampleGatewayInTest() { + val json = build(paymentRequest(coffee)) + + assertJsonEquals(gatewaySpec("example", "exampleGatewayMerchantId"), json.tokenizationSpec()) + } + + @Test + fun tokenization_gatewayTypeSendsTheSameJsonAsOmitted() { + val gateway = GooglePayTokenization(GooglePayTokenizationType.GATEWAY, publicKey) + listOf(WalletConstants.ENVIRONMENT_TEST, WalletConstants.ENVIRONMENT_PRODUCTION).forEach { env -> + fun request(tokenization: GooglePayTokenization?) = paymentRequest( + coffee, + googlePayMerchantId = "BCR2DN4T000000", + googlePayGateway = " stripe ", + googlePayGatewayMerchantId = "acct_123", + googlePayTokenization = tokenization + ) + + val omitted = build(request(null), environment = env) + val explicit = build(request(gateway), environment = env) + + assertEquals(omitted.toString(), explicit.toString()) + assertJsonEquals(gatewaySpec("stripe", "acct_123"), explicit.tokenizationSpec()) + } + } + + @Test + fun tokenization_directSendsPublicKey() { + val json = build( + paymentRequest( + coffee, + googlePayGateway = "stripe", + googlePayGatewayMerchantId = "acct_123", + googlePayTokenization = GooglePayTokenization( + GooglePayTokenizationType.DIRECT, + " $publicKey\n" + ) + ) + ) + + assertJsonEquals( + """{"type":"DIRECT","parameters":{"protocolVersion":"ECv2","publicKey":"$publicKey"}}""", + json.tokenizationSpec() + ) + } + + @Test + fun tokenization_directInProductionNeedsNoGateway() { + val json = build( + paymentRequest( + coffee, + googlePayMerchantId = "BCR2DN4T000000", + googlePayTokenization = GooglePayTokenization(GooglePayTokenizationType.DIRECT, publicKey) + ), + environment = WalletConstants.ENVIRONMENT_PRODUCTION + ) + + assertEquals("DIRECT", json.tokenizationSpec().getString("type")) + assertEquals("BCR2DN4T000000", json.merchantInfo().getString("merchantId")) + } + + @Test + fun tokenization_directInProductionStillRequiresMerchantId() { + val error = assertThrows(IllegalArgumentException::class.java) { + build( + paymentRequest( + coffee, + googlePayTokenization = GooglePayTokenization(GooglePayTokenizationType.DIRECT, publicKey) + ), + environment = WalletConstants.ENVIRONMENT_PRODUCTION + ) + } + + assertTrue(error.message!!.contains("googlePayMerchantId")) + } + + @Test + fun tokenization_directRequiresPublicKeyInEveryEnvironment() { + listOf(WalletConstants.ENVIRONMENT_TEST, WalletConstants.ENVIRONMENT_PRODUCTION).forEach { env -> + listOf(null, "", " ").forEach { key -> + val error = assertThrows(IllegalArgumentException::class.java) { + build( + paymentRequest( + coffee, + googlePayMerchantId = "BCR2DN4T000000", + googlePayTokenization = GooglePayTokenization( + GooglePayTokenizationType.DIRECT, + key + ) + ), + environment = env + ) + } + + assertEquals( + "googlePayTokenization.publicKey is required for 'direct' tokenization", + error.message + ) + } + } + } + // Contact details private fun JSONObject.cardParameters(): JSONObject = diff --git a/package/android/src/test/java/com/margelo/nitro/pay/TestFixtures.kt b/package/android/src/test/java/com/margelo/nitro/pay/TestFixtures.kt index 354bcd9b..de34d8fd 100644 --- a/package/android/src/test/java/com/margelo/nitro/pay/TestFixtures.kt +++ b/package/android/src/test/java/com/margelo/nitro/pay/TestFixtures.kt @@ -25,6 +25,7 @@ internal fun paymentRequest( googlePayMerchantId: String? = null, googlePayGateway: String? = null, googlePayGatewayMerchantId: String? = null, + googlePayTokenization: GooglePayTokenization? = null, billingContactRequired: Boolean? = null, shippingContactRequired: Boolean? = null, emailRequired: Boolean? = null, @@ -64,6 +65,7 @@ internal fun paymentRequest( googlePayEnvironment = environment, googlePayGateway = googlePayGateway, googlePayGatewayMerchantId = googlePayGatewayMerchantId, + googlePayTokenization = googlePayTokenization, googlePayAllowedAuthMethods = googlePayAllowedAuthMethods, googlePayAllowPrepaidCards = googlePayAllowPrepaidCards, googlePayCheckoutOption = googlePayCheckoutOption diff --git a/package/ios/Tests/PaymentSheetSessionTests.swift b/package/ios/Tests/PaymentSheetSessionTests.swift index 2595e44d..a7160c7e 100644 --- a/package/ios/Tests/PaymentSheetSessionTests.swift +++ b/package/ios/Tests/PaymentSheetSessionTests.swift @@ -82,6 +82,7 @@ final class PaymentSheetSessionTests: XCTestCase { googlePayEnvironment: nil, googlePayGateway: nil, googlePayGatewayMerchantId: nil, + googlePayTokenization: nil, googlePayAllowedAuthMethods: nil, googlePayAllowPrepaidCards: nil, googlePayCheckoutOption: nil diff --git a/package/ios/Tests/TestFixtures.swift b/package/ios/Tests/TestFixtures.swift index 2028731c..b9b5d76b 100644 --- a/package/ios/Tests/TestFixtures.swift +++ b/package/ios/Tests/TestFixtures.swift @@ -62,6 +62,7 @@ func paymentRequest( googlePayEnvironment: nil, googlePayGateway: nil, googlePayGatewayMerchantId: nil, + googlePayTokenization: nil, googlePayAllowedAuthMethods: nil, googlePayAllowPrepaidCards: nil, googlePayCheckoutOption: nil diff --git a/package/nitrogen/generated/android/c++/JGooglePayTokenization.hpp b/package/nitrogen/generated/android/c++/JGooglePayTokenization.hpp new file mode 100644 index 00000000..7c5c1b05 --- /dev/null +++ b/package/nitrogen/generated/android/c++/JGooglePayTokenization.hpp @@ -0,0 +1,64 @@ +/// +/// JGooglePayTokenization.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include "GooglePayTokenization.hpp" + +#include "GooglePayTokenizationType.hpp" +#include "JGooglePayTokenizationType.hpp" +#include +#include + +namespace margelo::nitro::pay { + + using namespace facebook; + + /** + * The C++ JNI bridge between the C++ struct "GooglePayTokenization" and the Kotlin data class "GooglePayTokenization". + */ + struct JGooglePayTokenization final: public jni::JavaClass { + public: + static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/pay/GooglePayTokenization;"; + + public: + /** + * Convert this Java/Kotlin-based struct to the C++ struct GooglePayTokenization by copying all values to C++. + */ + [[maybe_unused]] + [[nodiscard]] + GooglePayTokenization toCpp() const { + static const auto clazz = javaClassStatic(); + static const auto fieldType = clazz->getField("type"); + jni::local_ref type = this->getFieldValue(fieldType); + static const auto fieldPublicKey = clazz->getField("publicKey"); + jni::local_ref publicKey = this->getFieldValue(fieldPublicKey); + return GooglePayTokenization( + type->toCpp(), + publicKey != nullptr ? std::make_optional(publicKey->toStdString()) : std::nullopt + ); + } + + public: + /** + * Create a Java/Kotlin-based struct by copying all values from the given C++ struct to Java. + */ + [[maybe_unused]] + static jni::local_ref fromCpp(const GooglePayTokenization& value) { + using JSignature = JGooglePayTokenization(jni::alias_ref, jni::alias_ref); + static const auto clazz = javaClassStatic(); + static const auto create = clazz->getStaticMethod("fromCpp"); + return create( + clazz, + JGooglePayTokenizationType::fromCpp(value.type), + value.publicKey.has_value() ? jni::make_jstring(value.publicKey.value()) : nullptr + ); + } + }; + +} // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/c++/JGooglePayTokenizationType.hpp b/package/nitrogen/generated/android/c++/JGooglePayTokenizationType.hpp new file mode 100644 index 00000000..e6a348c1 --- /dev/null +++ b/package/nitrogen/generated/android/c++/JGooglePayTokenizationType.hpp @@ -0,0 +1,58 @@ +/// +/// JGooglePayTokenizationType.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include "GooglePayTokenizationType.hpp" + +namespace margelo::nitro::pay { + + using namespace facebook; + + /** + * The C++ JNI bridge between the C++ enum "GooglePayTokenizationType" and the Kotlin enum "GooglePayTokenizationType". + */ + struct JGooglePayTokenizationType final: public jni::JavaClass { + public: + static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/pay/GooglePayTokenizationType;"; + + public: + /** + * Convert this Java/Kotlin-based enum to the C++ enum GooglePayTokenizationType. + */ + [[maybe_unused]] + [[nodiscard]] + GooglePayTokenizationType toCpp() const { + static const auto clazz = javaClassStatic(); + static const auto fieldOrdinal = clazz->getField("value"); + int ordinal = this->getFieldValue(fieldOrdinal); + return static_cast(ordinal); + } + + public: + /** + * Create a Java/Kotlin-based enum with the given C++ enum's value. + */ + [[maybe_unused]] + static jni::alias_ref fromCpp(GooglePayTokenizationType value) { + static const auto clazz = javaClassStatic(); + switch (value) { + case GooglePayTokenizationType::GATEWAY: + static const auto fieldGATEWAY = clazz->getStaticField("GATEWAY"); + return clazz->getStaticFieldValue(fieldGATEWAY); + case GooglePayTokenizationType::DIRECT: + static const auto fieldDIRECT = clazz->getStaticField("DIRECT"); + return clazz->getStaticFieldValue(fieldDIRECT); + default: + std::string stringValue = std::to_string(static_cast(value)); + throw std::invalid_argument("Invalid enum value (" + stringValue + "!"); + } + } + }; + +} // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp index 5c65a98f..f99f3618 100644 --- a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp +++ b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp @@ -75,6 +75,10 @@ namespace margelo::nitro::pay { struct AutomaticReloadPaymentRequest; } namespace margelo::nitro::pay { struct AutomaticReloadBillingItem; } // Forward declaration of `PaymentTokenContext` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentTokenContext; } +// Forward declaration of `GooglePayTokenization` to properly resolve imports. +namespace margelo::nitro::pay { struct GooglePayTokenization; } +// Forward declaration of `GooglePayTokenizationType` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayTokenizationType; } // Forward declaration of `GooglePayCheckoutOption` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayCheckoutOption; } // Forward declaration of `StartPaymentOptions` to properly resolve imports. @@ -175,6 +179,10 @@ namespace margelo::nitro::pay { struct PaymentSheetCard; } #include "JAutomaticReloadBillingItem.hpp" #include "PaymentTokenContext.hpp" #include "JPaymentTokenContext.hpp" +#include "GooglePayTokenization.hpp" +#include "JGooglePayTokenization.hpp" +#include "GooglePayTokenizationType.hpp" +#include "JGooglePayTokenizationType.hpp" #include "GooglePayCheckoutOption.hpp" #include "JGooglePayCheckoutOption.hpp" #include "StartPaymentOptions.hpp" diff --git a/package/nitrogen/generated/android/c++/JPaymentRequest.hpp b/package/nitrogen/generated/android/c++/JPaymentRequest.hpp index 6258e2be..4c9c4e79 100644 --- a/package/nitrogen/generated/android/c++/JPaymentRequest.hpp +++ b/package/nitrogen/generated/android/c++/JPaymentRequest.hpp @@ -17,6 +17,8 @@ #include "FreeCancellation.hpp" #include "GooglePayCheckoutOption.hpp" #include "GooglePayEnvironment.hpp" +#include "GooglePayTokenization.hpp" +#include "GooglePayTokenizationType.hpp" #include "JAutomaticReloadBillingItem.hpp" #include "JAutomaticReloadPaymentRequest.hpp" #include "JDeferredBillingItem.hpp" @@ -24,6 +26,8 @@ #include "JFreeCancellation.hpp" #include "JGooglePayCheckoutOption.hpp" #include "JGooglePayEnvironment.hpp" +#include "JGooglePayTokenization.hpp" +#include "JGooglePayTokenizationType.hpp" #include "JPaymentAmount.hpp" #include "JPaymentItem.hpp" #include "JPaymentItemKind.hpp" @@ -117,6 +121,8 @@ namespace margelo::nitro::pay { jni::local_ref googlePayGateway = this->getFieldValue(fieldGooglePayGateway); static const auto fieldGooglePayGatewayMerchantId = clazz->getField("googlePayGatewayMerchantId"); jni::local_ref googlePayGatewayMerchantId = this->getFieldValue(fieldGooglePayGatewayMerchantId); + static const auto fieldGooglePayTokenization = clazz->getField("googlePayTokenization"); + jni::local_ref googlePayTokenization = this->getFieldValue(fieldGooglePayTokenization); static const auto fieldGooglePayAllowedAuthMethods = clazz->getField>("googlePayAllowedAuthMethods"); jni::local_ref> googlePayAllowedAuthMethods = this->getFieldValue(fieldGooglePayAllowedAuthMethods); static const auto fieldGooglePayAllowPrepaidCards = clazz->getField("googlePayAllowPrepaidCards"); @@ -194,6 +200,7 @@ namespace margelo::nitro::pay { googlePayEnvironment != nullptr ? std::make_optional(googlePayEnvironment->toCpp()) : std::nullopt, googlePayGateway != nullptr ? std::make_optional(googlePayGateway->toStdString()) : std::nullopt, googlePayGatewayMerchantId != nullptr ? std::make_optional(googlePayGatewayMerchantId->toStdString()) : std::nullopt, + googlePayTokenization != nullptr ? std::make_optional(googlePayTokenization->toCpp()) : std::nullopt, googlePayAllowedAuthMethods != nullptr ? std::make_optional([&](auto&& __input) { size_t __size = __input->size(); std::vector __vector; @@ -215,7 +222,7 @@ namespace margelo::nitro::pay { */ [[maybe_unused]] static jni::local_ref fromCpp(const PaymentRequest& value) { - using JSignature = JPaymentRequest(jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref>, jni::alias_ref>, jni::alias_ref>, jni::alias_ref, jni::alias_ref>, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref>, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref>, jni::alias_ref, jni::alias_ref); + using JSignature = JPaymentRequest(jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref>, jni::alias_ref>, jni::alias_ref>, jni::alias_ref, jni::alias_ref>, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref>, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref>, jni::alias_ref, jni::alias_ref); static const auto clazz = javaClassStatic(); static const auto create = clazz->getStaticMethod("fromCpp"); return create( @@ -290,6 +297,7 @@ namespace margelo::nitro::pay { value.googlePayEnvironment.has_value() ? JGooglePayEnvironment::fromCpp(value.googlePayEnvironment.value()) : nullptr, value.googlePayGateway.has_value() ? jni::make_jstring(value.googlePayGateway.value()) : nullptr, value.googlePayGatewayMerchantId.has_value() ? jni::make_jstring(value.googlePayGatewayMerchantId.value()) : nullptr, + value.googlePayTokenization.has_value() ? JGooglePayTokenization::fromCpp(value.googlePayTokenization.value()) : nullptr, value.googlePayAllowedAuthMethods.has_value() ? [&](auto&& __input) { size_t __size = __input.size(); jni::local_ref> __array = jni::JArrayClass::newArray(__size); diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/GooglePayTokenization.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/GooglePayTokenization.kt new file mode 100644 index 00000000..283bc092 --- /dev/null +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/GooglePayTokenization.kt @@ -0,0 +1,56 @@ +/// +/// GooglePayTokenization.kt +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +package com.margelo.nitro.pay + +import androidx.annotation.Keep +import com.facebook.proguard.annotations.DoNotStrip +import java.util.Objects + + +/** + * Represents the JavaScript object/struct "GooglePayTokenization". + */ +@DoNotStrip +@Keep +data class GooglePayTokenization( + @DoNotStrip + @Keep + val type: GooglePayTokenizationType, + @DoNotStrip + @Keep + val publicKey: String? +) { + /* primary constructor */ + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is GooglePayTokenization) return false + return Objects.deepEquals(this.type, other.type) + && Objects.deepEquals(this.publicKey, other.publicKey) + } + + override fun hashCode(): Int { + return arrayOf( + type, + publicKey + ).contentDeepHashCode() + } + + companion object { + /** + * Constructor called from C++ + */ + @DoNotStrip + @Keep + @Suppress("unused") + @JvmStatic + private fun fromCpp(type: GooglePayTokenizationType, publicKey: String?): GooglePayTokenization { + return GooglePayTokenization(type, publicKey) + } + } +} diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/GooglePayTokenizationType.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/GooglePayTokenizationType.kt new file mode 100644 index 00000000..c894af37 --- /dev/null +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/GooglePayTokenizationType.kt @@ -0,0 +1,23 @@ +/// +/// GooglePayTokenizationType.kt +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +package com.margelo.nitro.pay + +import androidx.annotation.Keep +import com.facebook.proguard.annotations.DoNotStrip + +/** + * Represents the JavaScript enum/union "GooglePayTokenizationType". + */ +@DoNotStrip +@Keep +enum class GooglePayTokenizationType(@DoNotStrip @Keep val value: Int) { + GATEWAY(0), + DIRECT(1); + + companion object +} diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentRequest.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentRequest.kt index c5eaafac..42c17907 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentRequest.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentRequest.kt @@ -95,6 +95,9 @@ data class PaymentRequest( val googlePayGatewayMerchantId: String?, @DoNotStrip @Keep + val googlePayTokenization: GooglePayTokenization?, + @DoNotStrip + @Keep val googlePayAllowedAuthMethods: Array?, @DoNotStrip @Keep @@ -133,6 +136,7 @@ data class PaymentRequest( && Objects.deepEquals(this.googlePayEnvironment, other.googlePayEnvironment) && Objects.deepEquals(this.googlePayGateway, other.googlePayGateway) && Objects.deepEquals(this.googlePayGatewayMerchantId, other.googlePayGatewayMerchantId) + && Objects.deepEquals(this.googlePayTokenization, other.googlePayTokenization) && Objects.deepEquals(this.googlePayAllowedAuthMethods, other.googlePayAllowedAuthMethods) && Objects.deepEquals(this.googlePayAllowPrepaidCards, other.googlePayAllowPrepaidCards) && Objects.deepEquals(this.googlePayCheckoutOption, other.googlePayCheckoutOption) @@ -165,6 +169,7 @@ data class PaymentRequest( googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, + googlePayTokenization, googlePayAllowedAuthMethods, googlePayAllowPrepaidCards, googlePayCheckoutOption @@ -179,8 +184,8 @@ data class PaymentRequest( @Keep @Suppress("unused") @JvmStatic - private fun fromCpp(applePayMerchantIdentifier: String?, merchantName: String?, totalLabel: String?, countryCode: String, currencyCode: String, paymentItems: Array, merchantCapabilities: Array, supportedNetworks: Array, shippingType: String?, shippingMethods: Array?, billingContactRequired: Boolean?, shippingContactRequired: Boolean?, emailRequired: Boolean?, phoneNumberRequired: Boolean?, recurring: RecurringPaymentRequest?, deferred: DeferredPaymentRequest?, automaticReload: AutomaticReloadPaymentRequest?, applePayMultiTokenContexts: Array?, couponCode: String?, applePayMerchantCategoryCode: Double?, applePayLaterAvailability: String?, googlePayMerchantId: String?, googlePayEnvironment: GooglePayEnvironment?, googlePayGateway: String?, googlePayGatewayMerchantId: String?, googlePayAllowedAuthMethods: Array?, googlePayAllowPrepaidCards: Boolean?, googlePayCheckoutOption: GooglePayCheckoutOption?): PaymentRequest { - return PaymentRequest(applePayMerchantIdentifier, merchantName, totalLabel, countryCode, currencyCode, paymentItems, merchantCapabilities, supportedNetworks, shippingType, shippingMethods, billingContactRequired, shippingContactRequired, emailRequired, phoneNumberRequired, recurring, deferred, automaticReload, applePayMultiTokenContexts, couponCode, applePayMerchantCategoryCode, applePayLaterAvailability, googlePayMerchantId, googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, googlePayAllowedAuthMethods, googlePayAllowPrepaidCards, googlePayCheckoutOption) + private fun fromCpp(applePayMerchantIdentifier: String?, merchantName: String?, totalLabel: String?, countryCode: String, currencyCode: String, paymentItems: Array, merchantCapabilities: Array, supportedNetworks: Array, shippingType: String?, shippingMethods: Array?, billingContactRequired: Boolean?, shippingContactRequired: Boolean?, emailRequired: Boolean?, phoneNumberRequired: Boolean?, recurring: RecurringPaymentRequest?, deferred: DeferredPaymentRequest?, automaticReload: AutomaticReloadPaymentRequest?, applePayMultiTokenContexts: Array?, couponCode: String?, applePayMerchantCategoryCode: Double?, applePayLaterAvailability: String?, googlePayMerchantId: String?, googlePayEnvironment: GooglePayEnvironment?, googlePayGateway: String?, googlePayGatewayMerchantId: String?, googlePayTokenization: GooglePayTokenization?, googlePayAllowedAuthMethods: Array?, googlePayAllowPrepaidCards: Boolean?, googlePayCheckoutOption: GooglePayCheckoutOption?): PaymentRequest { + return PaymentRequest(applePayMerchantIdentifier, merchantName, totalLabel, countryCode, currencyCode, paymentItems, merchantCapabilities, supportedNetworks, shippingType, shippingMethods, billingContactRequired, shippingContactRequired, emailRequired, phoneNumberRequired, recurring, deferred, automaticReload, applePayMultiTokenContexts, couponCode, applePayMerchantCategoryCode, applePayLaterAvailability, googlePayMerchantId, googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, googlePayTokenization, googlePayAllowedAuthMethods, googlePayAllowPrepaidCards, googlePayCheckoutOption) } } } diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp index 73bb319f..2e82bf66 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp @@ -36,6 +36,10 @@ namespace margelo::nitro::pay { struct FreeCancellation; } namespace margelo::nitro::pay { enum class GooglePayCheckoutOption; } // Forward declaration of `GooglePayEnvironment` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayEnvironment; } +// Forward declaration of `GooglePayTokenizationType` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayTokenizationType; } +// Forward declaration of `GooglePayTokenization` to properly resolve imports. +namespace margelo::nitro::pay { struct GooglePayTokenization; } // Forward declaration of `HybridApplePayButtonSpec` to properly resolve imports. namespace margelo::nitro::pay { class HybridApplePayButtonSpec; } // Forward declaration of `HybridPaymentHandlerSpec` to properly resolve imports. @@ -122,6 +126,8 @@ namespace NitroPay { class HybridPaymentHandlerSpec_cxx; } #include "FreeCancellation.hpp" #include "GooglePayCheckoutOption.hpp" #include "GooglePayEnvironment.hpp" +#include "GooglePayTokenization.hpp" +#include "GooglePayTokenizationType.hpp" #include "HybridApplePayButtonSpec.hpp" #include "HybridPaymentHandlerSpec.hpp" #include "PKSecureElementPass.hpp" @@ -762,6 +768,21 @@ namespace margelo::nitro::pay::bridge::swift { return optional.value(); } + // pragma MARK: std::optional + /** + * Specialized version of `std::optional`. + */ + using std__optional_GooglePayTokenization_ = std::optional; + inline std::optional create_std__optional_GooglePayTokenization_(const GooglePayTokenization& value) noexcept { + return std::optional(value); + } + inline bool has_value_std__optional_GooglePayTokenization_(const std::optional& optional) noexcept { + return optional.has_value(); + } + inline GooglePayTokenization get_std__optional_GooglePayTokenization_(const std::optional& optional) noexcept { + return optional.value(); + } + // pragma MARK: std::optional /** * Specialized version of `std::optional`. diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp index 3fd0103e..4829db16 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp @@ -40,6 +40,10 @@ namespace margelo::nitro::pay { struct FreeCancellation; } namespace margelo::nitro::pay { enum class GooglePayCheckoutOption; } // Forward declaration of `GooglePayEnvironment` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayEnvironment; } +// Forward declaration of `GooglePayTokenizationType` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayTokenizationType; } +// Forward declaration of `GooglePayTokenization` to properly resolve imports. +namespace margelo::nitro::pay { struct GooglePayTokenization; } // Forward declaration of `HybridApplePayButtonSpec` to properly resolve imports. namespace margelo::nitro::pay { class HybridApplePayButtonSpec; } // Forward declaration of `HybridPaymentHandlerSpec` to properly resolve imports. @@ -124,6 +128,8 @@ namespace margelo::nitro::pay { struct StartPaymentOptions; } #include "FreeCancellation.hpp" #include "GooglePayCheckoutOption.hpp" #include "GooglePayEnvironment.hpp" +#include "GooglePayTokenization.hpp" +#include "GooglePayTokenizationType.hpp" #include "HybridApplePayButtonSpec.hpp" #include "HybridPaymentHandlerSpec.hpp" #include "PKSecureElementPass.hpp" diff --git a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp index 1c4941be..c4711076 100644 --- a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp +++ b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp @@ -80,6 +80,10 @@ namespace margelo::nitro::pay { struct AutomaticReloadPaymentRequest; } namespace margelo::nitro::pay { struct AutomaticReloadBillingItem; } // Forward declaration of `PaymentTokenContext` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentTokenContext; } +// Forward declaration of `GooglePayTokenization` to properly resolve imports. +namespace margelo::nitro::pay { struct GooglePayTokenization; } +// Forward declaration of `GooglePayTokenizationType` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayTokenizationType; } // Forward declaration of `GooglePayCheckoutOption` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayCheckoutOption; } // Forward declaration of `StartPaymentOptions` to properly resolve imports. @@ -143,6 +147,8 @@ namespace margelo::nitro::pay { struct PaymentSheetCard; } #include "AutomaticReloadPaymentRequest.hpp" #include "AutomaticReloadBillingItem.hpp" #include "PaymentTokenContext.hpp" +#include "GooglePayTokenization.hpp" +#include "GooglePayTokenizationType.hpp" #include "GooglePayCheckoutOption.hpp" #include "StartPaymentOptions.hpp" #include "PaymentAuthorizationResult.hpp" diff --git a/package/nitrogen/generated/ios/swift/GooglePayTokenization.swift b/package/nitrogen/generated/ios/swift/GooglePayTokenization.swift new file mode 100644 index 00000000..4969eb94 --- /dev/null +++ b/package/nitrogen/generated/ios/swift/GooglePayTokenization.swift @@ -0,0 +1,47 @@ +/// +/// GooglePayTokenization.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +import NitroModules + +/** + * Represents an instance of `GooglePayTokenization`, backed by a C++ struct. + */ +public typealias GooglePayTokenization = margelo.nitro.pay.GooglePayTokenization + +public extension GooglePayTokenization { + private typealias bridge = margelo.nitro.pay.bridge.swift + + /** + * Create a new instance of `GooglePayTokenization`. + */ + init(type: GooglePayTokenizationType, publicKey: String?) { + self.init(type, { () -> bridge.std__optional_std__string_ in + if let __unwrappedValue = publicKey { + return bridge.create_std__optional_std__string_(std.string(__unwrappedValue)) + } else { + return .init() + } + }()) + } + + @inline(__always) + var type: GooglePayTokenizationType { + return self.__type + } + + @inline(__always) + var publicKey: String? { + return { () -> String? in + if bridge.has_value_std__optional_std__string_(self.__publicKey) { + let __unwrapped = bridge.get_std__optional_std__string_(self.__publicKey) + return String(__unwrapped) + } else { + return nil + } + }() + } +} diff --git a/package/nitrogen/generated/ios/swift/GooglePayTokenizationType.swift b/package/nitrogen/generated/ios/swift/GooglePayTokenizationType.swift new file mode 100644 index 00000000..b38de9a4 --- /dev/null +++ b/package/nitrogen/generated/ios/swift/GooglePayTokenizationType.swift @@ -0,0 +1,40 @@ +/// +/// GooglePayTokenizationType.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +/** + * Represents the JS union `GooglePayTokenizationType`, backed by a C++ enum. + */ +public typealias GooglePayTokenizationType = margelo.nitro.pay.GooglePayTokenizationType + +public extension GooglePayTokenizationType { + /** + * Get a GooglePayTokenizationType for the given String value, or + * return `nil` if the given value was invalid/unknown. + */ + init?(fromString string: String) { + switch string { + case "gateway": + self = .gateway + case "direct": + self = .direct + default: + return nil + } + } + + /** + * Get the String value this GooglePayTokenizationType represents. + */ + var stringValue: String { + switch self { + case .gateway: + return "gateway" + case .direct: + return "direct" + } + } +} diff --git a/package/nitrogen/generated/ios/swift/PaymentRequest.swift b/package/nitrogen/generated/ios/swift/PaymentRequest.swift index 49b9ccb8..74dafbda 100644 --- a/package/nitrogen/generated/ios/swift/PaymentRequest.swift +++ b/package/nitrogen/generated/ios/swift/PaymentRequest.swift @@ -18,7 +18,7 @@ public extension PaymentRequest { /** * Create a new instance of `PaymentRequest`. */ - init(applePayMerchantIdentifier: String?, merchantName: String?, totalLabel: String?, countryCode: String, currencyCode: String, paymentItems: [PaymentItem], merchantCapabilities: [String], supportedNetworks: [String], shippingType: String?, shippingMethods: [ShippingMethod]?, billingContactRequired: Bool?, shippingContactRequired: Bool?, emailRequired: Bool?, phoneNumberRequired: Bool?, recurring: RecurringPaymentRequest?, deferred: DeferredPaymentRequest?, automaticReload: AutomaticReloadPaymentRequest?, applePayMultiTokenContexts: [PaymentTokenContext]?, couponCode: String?, applePayMerchantCategoryCode: Double?, applePayLaterAvailability: String?, googlePayMerchantId: String?, googlePayEnvironment: GooglePayEnvironment?, googlePayGateway: String?, googlePayGatewayMerchantId: String?, googlePayAllowedAuthMethods: [String]?, googlePayAllowPrepaidCards: Bool?, googlePayCheckoutOption: GooglePayCheckoutOption?) { + init(applePayMerchantIdentifier: String?, merchantName: String?, totalLabel: String?, countryCode: String, currencyCode: String, paymentItems: [PaymentItem], merchantCapabilities: [String], supportedNetworks: [String], shippingType: String?, shippingMethods: [ShippingMethod]?, billingContactRequired: Bool?, shippingContactRequired: Bool?, emailRequired: Bool?, phoneNumberRequired: Bool?, recurring: RecurringPaymentRequest?, deferred: DeferredPaymentRequest?, automaticReload: AutomaticReloadPaymentRequest?, applePayMultiTokenContexts: [PaymentTokenContext]?, couponCode: String?, applePayMerchantCategoryCode: Double?, applePayLaterAvailability: String?, googlePayMerchantId: String?, googlePayEnvironment: GooglePayEnvironment?, googlePayGateway: String?, googlePayGatewayMerchantId: String?, googlePayTokenization: GooglePayTokenization?, googlePayAllowedAuthMethods: [String]?, googlePayAllowPrepaidCards: Bool?, googlePayCheckoutOption: GooglePayCheckoutOption?) { self.init({ () -> bridge.std__optional_std__string_ in if let __unwrappedValue = applePayMerchantIdentifier { return bridge.create_std__optional_std__string_(std.string(__unwrappedValue)) @@ -169,6 +169,12 @@ public extension PaymentRequest { } else { return .init() } + }(), { () -> bridge.std__optional_GooglePayTokenization_ in + if let __unwrappedValue = googlePayTokenization { + return bridge.create_std__optional_GooglePayTokenization_(__unwrappedValue) + } else { + return .init() + } }(), { () -> bridge.std__optional_std__vector_std__string__ in if let __unwrappedValue = googlePayAllowedAuthMethods { return bridge.create_std__optional_std__vector_std__string__({ () -> bridge.std__vector_std__string_ in @@ -433,6 +439,11 @@ public extension PaymentRequest { }() } + @inline(__always) + var googlePayTokenization: GooglePayTokenization? { + return self.__googlePayTokenization.value + } + @inline(__always) var googlePayAllowedAuthMethods: [String]? { return { () -> [String]? in diff --git a/package/nitrogen/generated/shared/c++/GooglePayTokenization.hpp b/package/nitrogen/generated/shared/c++/GooglePayTokenization.hpp new file mode 100644 index 00000000..a6cb1511 --- /dev/null +++ b/package/nitrogen/generated/shared/c++/GooglePayTokenization.hpp @@ -0,0 +1,90 @@ +/// +/// GooglePayTokenization.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +// Forward declaration of `GooglePayTokenizationType` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayTokenizationType; } + +#include "GooglePayTokenizationType.hpp" +#include +#include + +namespace margelo::nitro::pay { + + /** + * A struct which can be represented as a JavaScript object (GooglePayTokenization). + */ + struct GooglePayTokenization final { + public: + GooglePayTokenizationType type SWIFT_PRIVATE; + std::optional publicKey SWIFT_PRIVATE; + + public: + GooglePayTokenization() = default; + explicit GooglePayTokenization(GooglePayTokenizationType type, std::optional publicKey): type(type), publicKey(publicKey) {} + + public: + friend bool operator==(const GooglePayTokenization& lhs, const GooglePayTokenization& rhs) = default; + }; + +} // namespace margelo::nitro::pay + +namespace margelo::nitro { + + // C++ GooglePayTokenization <> JS GooglePayTokenization (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::pay::GooglePayTokenization fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::pay::GooglePayTokenization( + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "type"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "publicKey"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::GooglePayTokenization& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "type"), JSIConverter::toJSI(runtime, arg.type)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "publicKey"), JSIConverter>::toJSI(runtime, arg.publicKey)); + return obj; + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "type")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "publicKey")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/package/nitrogen/generated/shared/c++/GooglePayTokenizationType.hpp b/package/nitrogen/generated/shared/c++/GooglePayTokenizationType.hpp new file mode 100644 index 00000000..8fad8e8d --- /dev/null +++ b/package/nitrogen/generated/shared/c++/GooglePayTokenizationType.hpp @@ -0,0 +1,76 @@ +/// +/// GooglePayTokenizationType.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +namespace margelo::nitro::pay { + + /** + * An enum which can be represented as a JavaScript union (GooglePayTokenizationType). + */ + enum class GooglePayTokenizationType { + GATEWAY SWIFT_NAME(gateway) = 0, + DIRECT SWIFT_NAME(direct) = 1, + } CLOSED_ENUM; + +} // namespace margelo::nitro::pay + +namespace margelo::nitro { + + // C++ GooglePayTokenizationType <> JS GooglePayTokenizationType (union) + template <> + struct JSIConverter final { + static inline margelo::nitro::pay::GooglePayTokenizationType fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + std::string unionValue = JSIConverter::fromJSI(runtime, arg); + switch (hashString(unionValue.c_str(), unionValue.size())) { + case hashString("gateway"): return margelo::nitro::pay::GooglePayTokenizationType::GATEWAY; + case hashString("direct"): return margelo::nitro::pay::GooglePayTokenizationType::DIRECT; + default: [[unlikely]] + throw std::invalid_argument("Cannot convert \"" + unionValue + "\" to enum GooglePayTokenizationType - invalid value!"); + } + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, margelo::nitro::pay::GooglePayTokenizationType arg) { + switch (arg) { + case margelo::nitro::pay::GooglePayTokenizationType::GATEWAY: return JSIConverter::toJSI(runtime, "gateway"); + case margelo::nitro::pay::GooglePayTokenizationType::DIRECT: return JSIConverter::toJSI(runtime, "direct"); + default: [[unlikely]] + throw std::invalid_argument("Cannot convert GooglePayTokenizationType to JS - invalid value: " + + std::to_string(static_cast(arg)) + "!"); + } + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isString()) { + return false; + } + std::string unionValue = JSIConverter::fromJSI(runtime, value); + switch (hashString(unionValue.c_str(), unionValue.size())) { + case hashString("gateway"): + case hashString("direct"): + return true; + default: + return false; + } + } + }; + +} // namespace margelo::nitro diff --git a/package/nitrogen/generated/shared/c++/PaymentRequest.hpp b/package/nitrogen/generated/shared/c++/PaymentRequest.hpp index 03b22dbf..7b0e4e36 100644 --- a/package/nitrogen/generated/shared/c++/PaymentRequest.hpp +++ b/package/nitrogen/generated/shared/c++/PaymentRequest.hpp @@ -42,6 +42,8 @@ namespace margelo::nitro::pay { struct AutomaticReloadPaymentRequest; } namespace margelo::nitro::pay { struct PaymentTokenContext; } // Forward declaration of `GooglePayEnvironment` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayEnvironment; } +// Forward declaration of `GooglePayTokenization` to properly resolve imports. +namespace margelo::nitro::pay { struct GooglePayTokenization; } // Forward declaration of `GooglePayCheckoutOption` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayCheckoutOption; } @@ -55,6 +57,7 @@ namespace margelo::nitro::pay { enum class GooglePayCheckoutOption; } #include "AutomaticReloadPaymentRequest.hpp" #include "PaymentTokenContext.hpp" #include "GooglePayEnvironment.hpp" +#include "GooglePayTokenization.hpp" #include "GooglePayCheckoutOption.hpp" namespace margelo::nitro::pay { @@ -89,13 +92,14 @@ namespace margelo::nitro::pay { std::optional googlePayEnvironment SWIFT_PRIVATE; std::optional googlePayGateway SWIFT_PRIVATE; std::optional googlePayGatewayMerchantId SWIFT_PRIVATE; + std::optional googlePayTokenization SWIFT_PRIVATE; std::optional> googlePayAllowedAuthMethods SWIFT_PRIVATE; std::optional googlePayAllowPrepaidCards SWIFT_PRIVATE; std::optional googlePayCheckoutOption SWIFT_PRIVATE; public: PaymentRequest() = default; - explicit PaymentRequest(std::optional applePayMerchantIdentifier, std::optional merchantName, std::optional totalLabel, std::string countryCode, std::string currencyCode, std::vector paymentItems, std::vector merchantCapabilities, std::vector supportedNetworks, std::optional shippingType, std::optional> shippingMethods, std::optional billingContactRequired, std::optional shippingContactRequired, std::optional emailRequired, std::optional phoneNumberRequired, std::optional recurring, std::optional deferred, std::optional automaticReload, std::optional> applePayMultiTokenContexts, std::optional couponCode, std::optional applePayMerchantCategoryCode, std::optional applePayLaterAvailability, std::optional googlePayMerchantId, std::optional googlePayEnvironment, std::optional googlePayGateway, std::optional googlePayGatewayMerchantId, std::optional> googlePayAllowedAuthMethods, std::optional googlePayAllowPrepaidCards, std::optional googlePayCheckoutOption): applePayMerchantIdentifier(applePayMerchantIdentifier), merchantName(merchantName), totalLabel(totalLabel), countryCode(countryCode), currencyCode(currencyCode), paymentItems(paymentItems), merchantCapabilities(merchantCapabilities), supportedNetworks(supportedNetworks), shippingType(shippingType), shippingMethods(shippingMethods), billingContactRequired(billingContactRequired), shippingContactRequired(shippingContactRequired), emailRequired(emailRequired), phoneNumberRequired(phoneNumberRequired), recurring(recurring), deferred(deferred), automaticReload(automaticReload), applePayMultiTokenContexts(applePayMultiTokenContexts), couponCode(couponCode), applePayMerchantCategoryCode(applePayMerchantCategoryCode), applePayLaterAvailability(applePayLaterAvailability), googlePayMerchantId(googlePayMerchantId), googlePayEnvironment(googlePayEnvironment), googlePayGateway(googlePayGateway), googlePayGatewayMerchantId(googlePayGatewayMerchantId), googlePayAllowedAuthMethods(googlePayAllowedAuthMethods), googlePayAllowPrepaidCards(googlePayAllowPrepaidCards), googlePayCheckoutOption(googlePayCheckoutOption) {} + explicit PaymentRequest(std::optional applePayMerchantIdentifier, std::optional merchantName, std::optional totalLabel, std::string countryCode, std::string currencyCode, std::vector paymentItems, std::vector merchantCapabilities, std::vector supportedNetworks, std::optional shippingType, std::optional> shippingMethods, std::optional billingContactRequired, std::optional shippingContactRequired, std::optional emailRequired, std::optional phoneNumberRequired, std::optional recurring, std::optional deferred, std::optional automaticReload, std::optional> applePayMultiTokenContexts, std::optional couponCode, std::optional applePayMerchantCategoryCode, std::optional applePayLaterAvailability, std::optional googlePayMerchantId, std::optional googlePayEnvironment, std::optional googlePayGateway, std::optional googlePayGatewayMerchantId, std::optional googlePayTokenization, std::optional> googlePayAllowedAuthMethods, std::optional googlePayAllowPrepaidCards, std::optional googlePayCheckoutOption): applePayMerchantIdentifier(applePayMerchantIdentifier), merchantName(merchantName), totalLabel(totalLabel), countryCode(countryCode), currencyCode(currencyCode), paymentItems(paymentItems), merchantCapabilities(merchantCapabilities), supportedNetworks(supportedNetworks), shippingType(shippingType), shippingMethods(shippingMethods), billingContactRequired(billingContactRequired), shippingContactRequired(shippingContactRequired), emailRequired(emailRequired), phoneNumberRequired(phoneNumberRequired), recurring(recurring), deferred(deferred), automaticReload(automaticReload), applePayMultiTokenContexts(applePayMultiTokenContexts), couponCode(couponCode), applePayMerchantCategoryCode(applePayMerchantCategoryCode), applePayLaterAvailability(applePayLaterAvailability), googlePayMerchantId(googlePayMerchantId), googlePayEnvironment(googlePayEnvironment), googlePayGateway(googlePayGateway), googlePayGatewayMerchantId(googlePayGatewayMerchantId), googlePayTokenization(googlePayTokenization), googlePayAllowedAuthMethods(googlePayAllowedAuthMethods), googlePayAllowPrepaidCards(googlePayAllowPrepaidCards), googlePayCheckoutOption(googlePayCheckoutOption) {} public: friend bool operator==(const PaymentRequest& lhs, const PaymentRequest& rhs) = default; @@ -136,6 +140,7 @@ namespace margelo::nitro { JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayGateway"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayGatewayMerchantId"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayTokenization"))), JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowPrepaidCards"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayCheckoutOption"))) @@ -168,6 +173,7 @@ namespace margelo::nitro { obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"), JSIConverter>::toJSI(runtime, arg.googlePayEnvironment)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayGateway"), JSIConverter>::toJSI(runtime, arg.googlePayGateway)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayGatewayMerchantId"), JSIConverter>::toJSI(runtime, arg.googlePayGatewayMerchantId)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayTokenization"), JSIConverter>::toJSI(runtime, arg.googlePayTokenization)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"), JSIConverter>>::toJSI(runtime, arg.googlePayAllowedAuthMethods)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowPrepaidCards"), JSIConverter>::toJSI(runtime, arg.googlePayAllowPrepaidCards)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayCheckoutOption"), JSIConverter>::toJSI(runtime, arg.googlePayCheckoutOption)); @@ -206,6 +212,7 @@ namespace margelo::nitro { if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayGateway")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayGatewayMerchantId")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayTokenization")))) return false; if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowPrepaidCards")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayCheckoutOption")))) return false; diff --git a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts index a0d5191e..5fb32016 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts @@ -533,6 +533,30 @@ describe('usePaymentCheckout integration', () => { expect(request.googlePayCheckoutOption).toBe('continueToReview') }) + it('sends the Google Pay tokenization', async () => { + mockStartPayment.mockResolvedValueOnce({ success: true }) + + const { result } = renderHook(() => + usePaymentCheckout({ + googlePayTokenization: { type: 'direct', publicKey: 'key' }, + }) + ) + + act(() => { + result.current.addItem('Coffee', 10) + }) + + await act(async () => { + await result.current.startPayment() + }) + + const [request] = mockStartPayment.mock.calls[0] + expect(request.googlePayTokenization).toEqual({ + type: 'direct', + publicKey: 'key', + }) + }) + it('leaves the Google Pay checkout option out when not set', async () => { mockStartPayment.mockResolvedValueOnce({ success: true }) @@ -614,6 +638,14 @@ describe('usePaymentCheckout integration', () => { googlePayEnvironment: ['TEST', 'PRODUCTION'], googlePayGateway: ['stripe', 'adyen'], googlePayGatewayMerchantId: ['gateway-a', 'gateway-b'], + googlePayTokenization: [ + { type: 'gateway' }, + { + type: 'direct', + publicKey: + 'BOdoXP+9Aq473SnGwg3JU1aiNpsd9vH2ognq4PtDtlLGa3Kj8TPf+jaQNPyDSkh3JUhiS0KyrrlWhAgNZKHYF2Y=', + }, + ], googlePayAllowedAuthMethods: [ ['PAN_ONLY', 'CRYPTOGRAM_3DS'], ['CRYPTOGRAM_3DS'], @@ -646,6 +678,20 @@ describe('usePaymentCheckout integration', () => { } ) + it('ignores the key order of googlePayTokenization', () => { + const { result, rerender } = renderWithConfig({ + googlePayTokenization: { type: 'direct', publicKey: 'key' }, + }) + const initial = result.current + + rerender({ googlePayTokenization: { publicKey: 'key', type: 'direct' } }) + expect(result.current.paymentRequest).toBe(initial.paymentRequest) + expect(result.current.paymentRequest.googlePayTokenization).toEqual({ + type: 'direct', + publicKey: 'key', + }) + }) + it('starts the payment with the config from the latest render', async () => { mockStartPayment.mockResolvedValueOnce({ success: true }) const { result, rerender } = renderWithConfig({ diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index d023ce9d..01c7155e 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -21,6 +21,7 @@ import type { GooglePayAuthMethod, GooglePayCheckoutOption, GooglePayEnvironment, + GooglePayTokenization, MerchantCapability, PayServiceStatusOptions, PaymentToken, @@ -40,7 +41,23 @@ import { // Values that survive a JSON round trip unchanged: functions are dropped, and // NaN and Infinity become null. No objects: a `JSON.stringify` key list would // filter their keys too. -type JsonValue = string | boolean | null | undefined | readonly JsonValue[] +type JsonValue = + | string + | boolean + | null + | undefined + | readonly JsonValue[] + | GooglePayTokenization + +// A `JSON.stringify` replacer that writes the keys of every object in +// sorted order, so the same config always gives the same string. +function sortObjectKeys(_key: string, value: unknown): unknown { + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + return value + } + const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1)) + return Object.fromEntries(entries) +} // Wraps what a call threw, keeping its message and the original as `cause`. function toPaymentError( @@ -142,6 +159,14 @@ export interface UsePaymentCheckoutConfig */ googlePayGatewayMerchantId?: string + /** + * Who encrypts the Google Pay token. Omitted, it is `'gateway'`, which + * uses `googlePayGateway` and `googlePayGatewayMerchantId`. Pass + * `{ type: 'direct', publicKey }` to decrypt the token on your own server. + * Android only. See `PaymentRequest.googlePayTokenization`. + */ + googlePayTokenization?: GooglePayTokenization + /** * How Google Pay may authenticate the card. Defaults to both * `'PAN_ONLY'` and `'CRYPTOGRAM_3DS'`; pass `['CRYPTOGRAM_3DS']` to accept @@ -358,11 +383,12 @@ export function usePaymentCheckout( } = config // Apps usually pass an inline config, which is new on every render, so - // compare the rest of it by value, with its keys sorted. A callback added to - // the config fails `satisfies` here: pull it out above, like `onAuthorize`. + // compare the rest of it by value, with the keys of every object sorted. A + // callback added to the config fails `satisfies` here: pull it out above, + // like `onAuthorize`. const requestConfigKey = JSON.stringify( requestConfig satisfies { readonly [key: string]: JsonValue }, - Object.keys(requestConfig).sort() + sortObjectKeys ) const stableRequestConfig = useMemo( () => JSON.parse(requestConfigKey), @@ -410,6 +436,7 @@ export function usePaymentCheckout( googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, + googlePayTokenization, googlePayAllowedAuthMethods, googlePayAllowPrepaidCards, googlePayCheckoutOption, @@ -434,6 +461,7 @@ export function usePaymentCheckout( googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, + googlePayTokenization, googlePayAllowedAuthMethods, googlePayAllowPrepaidCards, googlePayCheckoutOption, diff --git a/package/src/types/Payment.ts b/package/src/types/Payment.ts index 3ff32508..2cc9be5f 100644 --- a/package/src/types/Payment.ts +++ b/package/src/types/Payment.ts @@ -108,6 +108,33 @@ export type GooglePayCheckoutOption = | 'completeImmediatePurchase' | 'continueToReview' +/** + * Who encrypts the Google Pay token. Android only. + * + * - `'gateway'`: Google encrypts it for your payment gateway, set with + * `googlePayGateway` and `googlePayGatewayMerchantId`. Google Pay calls it + * `PAYMENT_GATEWAY`. + * - `'direct'`: Google encrypts it with your own public key, and your server + * decrypts it. Google Pay calls it `DIRECT`. Needs Google's approval and + * PCI DSS compliance. + */ +export type GooglePayTokenizationType = 'gateway' | 'direct' + +/** + * How Google Pay tokenizes the card, sent as the card's + * `tokenizationSpecification`. Android only. + */ +export interface GooglePayTokenization { + type: GooglePayTokenizationType + /** + * Your base64-encoded uncompressed EC public key on the NIST P-256 curve, + * the one your server decrypts the `ECv2` token with. Required for + * `'direct'` in every environment, ignored for `'gateway'`. A missing or + * blank key fails the payment with `'CONFIGURATION'`. + */ + publicKey?: string +} + /** * Merchant capability. `'3DS'` and `'EMV'` are Apple Pay payment protocols * (EMV only covers China UnionPay); `'Credit'` and `'Debit'` limit the @@ -466,8 +493,19 @@ export interface PaymentRequest { // Google Pay specific configuration (Android only) googlePayMerchantId?: string googlePayEnvironment?: GooglePayEnvironment + /** + * The gateway for `'gateway'` tokenization, such as `'stripe'`. Required + * in PRODUCTION for `'gateway'`. + */ googlePayGateway?: string + /** Your merchant ID at the gateway. Required in PRODUCTION for `'gateway'`. */ googlePayGatewayMerchantId?: string + /** + * Who encrypts the token. Omitted, it is `'gateway'`, which uses + * `googlePayGateway` and `googlePayGatewayMerchantId`. `'direct'` needs + * `publicKey` and ignores the gateway fields. Android only. + */ + googlePayTokenization?: GooglePayTokenization /** * `GooglePayAuthMethod` values, matched ignoring case. Defaults to both. * Android only. An unknown value fails the payment. Not typed as diff --git a/package/src/utils/__tests__/paymentRequest.test.ts b/package/src/utils/__tests__/paymentRequest.test.ts index 0be8fb30..108ee476 100644 --- a/package/src/utils/__tests__/paymentRequest.test.ts +++ b/package/src/utils/__tests__/paymentRequest.test.ts @@ -113,6 +113,45 @@ describe('normalizePaymentRequest', () => { } ) + it.each([{ type: 'gateway' }, { type: 'direct', publicKey: 'key' }] as const)( + 'keeps the Google Pay tokenization %p', + (googlePayTokenization) => { + const normalized = normalizePaymentRequest({ + ...request([{ label: 'Coffee', amount: 1, type: 'final' }]), + googlePayTokenization, + }) + + expect(normalized.googlePayTokenization).toEqual(googlePayTokenization) + } + ) + + // Android checks the key, since iOS ignores the field. + it('keeps a direct tokenization without a key for native to check', () => { + const normalized = normalizePaymentRequest({ + ...request([{ label: 'Coffee', amount: 1, type: 'final' }]), + googlePayTokenization: { type: 'direct' }, + }) + + expect(normalized.googlePayTokenization).toEqual({ type: 'direct' }) + }) + + it.each([ + [{ type: 'DIRECT' }, '"DIRECT"'], + [{ type: 'PAYMENT_GATEWAY' }, '"PAYMENT_GATEWAY"'], + [{}, 'undefined'], + [null, 'undefined'], + ['direct', 'undefined'], + ])('rejects the Google Pay tokenization %p', (tokenization, got) => { + expect(() => + normalizePaymentRequest({ + ...request([{ label: 'Coffee', amount: 1, type: 'final' }]), + googlePayTokenization: tokenization as { type: 'direct' }, + }) + ).toThrow( + `googlePayTokenization.type must be one of "gateway", "direct", got ${got}` + ) + }) + // Google Pay's rule: iOS has no such button, so a pending item is fine here. it('keeps completeImmediatePurchase with a pending item for native to check', () => { const normalized = normalizePaymentRequest({ diff --git a/package/src/utils/paymentRequest.ts b/package/src/utils/paymentRequest.ts index 79293489..9bb2658e 100644 --- a/package/src/utils/paymentRequest.ts +++ b/package/src/utils/paymentRequest.ts @@ -6,6 +6,7 @@ import type { GooglePayCheckoutOption, + GooglePayTokenizationType, PaymentItem, PaymentItemKind, PaymentRequest, @@ -35,6 +36,10 @@ const GOOGLE_PAY_CHECKOUT_OPTIONS: readonly GooglePayCheckoutOption[] = [ 'completeImmediatePurchase', 'continueToReview', ] +const GOOGLE_PAY_TOKENIZATION_TYPES: readonly GooglePayTokenizationType[] = [ + 'gateway', + 'direct', +] function checkCode( field: string, @@ -84,6 +89,23 @@ function checkGooglePayCheckoutOption(option: unknown) { } } +// Native code would reject an unknown type without naming the field. Android +// checks the public key: iOS ignores the field. +function checkGooglePayTokenization(tokenization: unknown) { + if (tokenization === undefined) return + const type = + typeof tokenization === 'object' && tokenization !== null + ? (tokenization as { type?: unknown }).type + : undefined + if ( + !GOOGLE_PAY_TOKENIZATION_TYPES.includes(type as GooglePayTokenizationType) + ) { + throw new Error( + `googlePayTokenization.type must be one of ${GOOGLE_PAY_TOKENIZATION_TYPES.map((t) => `"${t}"`).join(', ')}, got ${JSON.stringify(type)}` + ) + } +} + /** * Validates a payment request and returns a copy whose amounts are exact * decimal strings. `createPaymentRequest`, `usePaymentCheckout` and @@ -94,7 +116,8 @@ function checkGooglePayCheckoutOption(option: unknown) { * ISO 3166-1 alpha-2 code (`'US'`), both upper case. Line items may be * negative (discounts), but the total may not. An item's `kind` must be a * `PaymentItemKind`, `googlePayCheckoutOption` a `GooglePayCheckoutOption`, - * and `totalLabel` must not be blank. An Android release build warns once if + * `googlePayTokenization.type` a `GooglePayTokenizationType`, and + * `totalLabel` must not be blank. An Android release build warns once if * `googlePayEnvironment` is omitted. * * `recurring`, `deferred` and `automaticReload` follow the stricter of Apple @@ -106,8 +129,8 @@ function checkGooglePayCheckoutOption(option: unknown) { * shipping methods must then all cost the same. On Android the field is * removed without being checked. * - * @throws Error if a code, an amount, a `kind`, `totalLabel` or - * `googlePayCheckoutOption` is invalid, + * @throws Error if a code, an amount, a `kind`, `totalLabel`, + * `googlePayCheckoutOption` or `googlePayTokenization.type` is invalid, * the total is negative, a recurring, deferred or automatic reload request * is invalid, or `applePayMultiTokenContexts` is invalid. */ @@ -120,6 +143,7 @@ export function normalizePaymentRequest( checkCode('countryCode', request.countryCode, COUNTRY_CODE_PATTERN, 'US') checkTotalLabel(request.totalLabel) checkGooglePayCheckoutOption(request.googlePayCheckoutOption) + checkGooglePayTokenization(request.googlePayTokenization) const paymentItems = normalizePaymentItems(request.paymentItems, currencyCode) const total = sumExactly(paymentItems.map((item) => item.amount))