From a6531bc542b3036faef1f0c7b50a4835f771283e Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 16:59:55 +0100 Subject: [PATCH 1/8] fix: honour supportedNetworks on Android and report unknown networks as 'unknown' Android ignored PaymentRequest.supportedNetworks and always sent Visa, Mastercard, Amex and Discover with both auth methods, to the payment request, the PayButton and isReadyToPay. Both platforms reported any network they could not name as Visa. - Map supportedNetworks to Google Pay networks; add jcb, interac and the Brazilian combo networks. An unknown name fails on both platforms, a network the platform lacks is left out, and none left fails. - Add googlePayAllowedAuthMethods ('PAN_ONLY' | 'CRYPTOGRAM_3DS'). - Use one GooglePayCardParameters for the request, the button (new supportedNetworks / allowedAuthMethods props) and payServiceStatus (new optional PayServiceStatusOptions, passed by usePaymentCheckout). - Add 'unknown' and the remaining PassKit networks up to iOS 26.0 to PaymentNetwork; one table per platform maps both directions. - Android displayName uses paymentMethodData.description, as Google Pay asks, falling back to " ". Closes #13 --- CHANGELOG.md | 31 ++++ README.md | 54 +++++-- docs/docs/api/components.md | 5 + docs/docs/api/hybrid-payment-handler.md | 10 +- docs/docs/api/types.md | 53 ++++++- docs/docs/api/use-payment-checkout.md | 7 +- docs/docs/api/utils.md | 1 + example/app/(tabs)/index.tsx | 4 + .../java/com/margelo/nitro/pay/Constants.kt | 9 -- .../nitro/pay/GooglePayButtonFactory.kt | 32 +---- .../nitro/pay/GooglePayCardParameters.kt | 104 ++++++++++++++ .../nitro/pay/GooglePayRequestBuilder.kt | 62 ++++---- .../nitro/pay/HybridGooglePayButton.kt | 14 +- .../margelo/nitro/pay/HybridPaymentHandler.kt | 20 ++- .../com/margelo/nitro/pay/PaymentMapper.kt | 21 +-- .../nitro/pay/GooglePayRequestBuilderTest.kt | 136 +++++++++++++++++- .../margelo/nitro/pay/PaymentMapperTest.kt | 55 ++++++- package/ios/HybridPaymentHandler.swift | 52 ++++++- package/ios/PassKitTypeMapper.swift | 124 ++++++++++------ .../ios/Tests/PassKitTypeMapperTests.swift | 39 +++-- .../Tests/PaymentRequestBuilderTests.swift | 47 +++++- .../c++/JHybridGooglePayButtonSpec.cpp | 56 ++++++++ .../c++/JHybridGooglePayButtonSpec.hpp | 4 + .../android/c++/JHybridPaymentHandlerSpec.cpp | 10 +- .../android/c++/JHybridPaymentHandlerSpec.hpp | 2 +- .../android/c++/JPayServiceStatusOptions.hpp | 99 +++++++++++++ .../generated/android/c++/JPaymentNetwork.hpp | 69 +++++++++ .../generated/android/c++/JPaymentRequest.hpp | 28 +++- .../JHybridGooglePayButtonStateUpdater.cpp | 8 ++ .../nitro/pay/HybridGooglePayButtonSpec.kt | 12 ++ .../nitro/pay/HybridPaymentHandlerSpec.kt | 2 +- .../nitro/pay/PayServiceStatusOptions.kt | 56 ++++++++ .../com/margelo/nitro/pay/PaymentNetwork.kt | 25 +++- .../com/margelo/nitro/pay/PaymentRequest.kt | 13 +- .../ios/NitroPay-Swift-Cxx-Bridge.hpp | 55 +++++-- .../ios/NitroPay-Swift-Cxx-Umbrella.hpp | 3 + .../ios/c++/HybridPaymentHandlerSpecSwift.hpp | 13 +- .../ios/swift/HybridPaymentHandlerSpec.swift | 2 +- .../swift/HybridPaymentHandlerSpec_cxx.swift | 4 +- .../ios/swift/PayServiceStatusOptions.swift | 72 ++++++++++ .../generated/ios/swift/PaymentNetwork.swift | 92 ++++++++++++ .../generated/ios/swift/PaymentRequest.swift | 26 +++- .../shared/c++/HybridGooglePayButtonSpec.cpp | 4 + .../shared/c++/HybridGooglePayButtonSpec.hpp | 6 + .../shared/c++/HybridPaymentHandlerSpec.hpp | 7 +- .../shared/c++/PayServiceStatusOptions.hpp | 89 ++++++++++++ .../generated/shared/c++/PaymentNetwork.hpp | 92 ++++++++++++ .../generated/shared/c++/PaymentRequest.hpp | 8 +- .../views/HybridGooglePayButtonComponent.cpp | 22 +++ .../views/HybridGooglePayButtonComponent.hpp | 4 + .../shared/json/GooglePayButtonConfig.json | 2 + .../usePaymentCheckout.integration.test.ts | 50 ++++++- package/src/hooks/usePaymentCheckout.ts | 34 ++++- package/src/specs/GooglePayButton.nitro.ts | 7 + package/src/specs/PaymentHandler.nitro.ts | 3 +- package/src/types/Payment.ts | 72 ++++++++++ .../utils/__tests__/paymentHelpers.test.ts | 2 + package/src/utils/paymentHelpers.ts | 23 +++ 58 files changed, 1733 insertions(+), 223 deletions(-) create mode 100644 package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt create mode 100644 package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp create mode 100644 package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt create mode 100644 package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift create mode 100644 package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c7cafa..11da424 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,9 +22,35 @@ All notable changes to this project are documented in this file. iOS the payer picks one, and the first is selected by default. Google Pay cannot offer a choice yet, so Android charges the first method. An empty or repeated `identifier`, a negative `amount`, or `paymentItems` that total less than zero without shipping fail the payment. +- **`googlePayAllowedAuthMethods`** in `PaymentRequest` and the `usePaymentCheckout` config + (`GooglePayAuthMethod[]`: `'PAN_ONLY'`, `'CRYPTOGRAM_3DS'`) limits which Google Pay cards are + accepted, for example device tokens only under SCA. Both by default, as before. +- **More card networks.** `PaymentNetwork` gains `cartesBancaires`, `chinaUnionPay`, `dankort`, + `eftpos`, `girocard`, `mada`, `mir`, `quicPay`, `suica`, `vPay`, `waon`, `nanaco`, `bancontact`, + `postFinance`, `pagoBancomat`, `tmoney`, `meeza`, `napas`, `bankAxept`, `himyan`, `jaywan` and + `myDebit`, which Apple Pay accepts in `supportedNetworks` and reports in results. Android + accepts `jcb` and `interac`, and `electron`, `maestro` and `elo` for Brazilian combo cards. +- **`GooglePayButton` takes `supportedNetworks` and `allowedAuthMethods`,** and + **`HybridPaymentHandler.payServiceStatus(options?)`** takes the same two values + (`PayServiceStatusOptions`). Give them the values of your request, so the button and the Android + readiness check use the same cards as the payment. `usePaymentCheckout` passes its config to + `payServiceStatus` and checks again when they change. ### Changed +- **`PaymentNetwork` has a new `'unknown'` value,** reported for a card on a network the library + cannot name. Both platforms used to report such cards as `'visa'`. Code that switches over + `token.paymentMethod.network` needs a case for it. +- **An unknown name in `supportedNetworks` fails the payment** on both platforms, with an `error` + that contains `Unknown payment network "". Use a PaymentNetwork value such as "visa" or + "mastercard"`. iOS used to drop it silently. Names now match ignoring case, so `'Visa'` works, and a network the + platform does not offer is left out; the payment fails when none is left. `canMakePayments` and + `payServiceStatus` throw for an unknown name, and `canMakePayments` returns `false` when the + platform offers none of the networks. +- **Android: `PaymentMethod.displayName` is the wallet's description of the card** (Google Pay's + `paymentMethodData.description`, for example "Visa •••• 1234") instead of `"VISA 1234"`. Google + Pay asks apps not to show `cardNetwork` to the payer. Use `network` for logic. + - **`PaymentRequest.shippingMethods` is `ShippingMethod[]`, not `PaymentItem[]`.** Neither platform ever read the old field, so only the type changes: give each method an `identifier` and drop `type`. @@ -53,6 +79,11 @@ All notable changes to this project are documented in this file. ### Fixed +- **Android: `supportedNetworks` limits the cards the payer can choose.** Android ignored it and + always offered Visa, Mastercard, Amex and Discover, so a merchant whose gateway refuses Amex + still received Amex tokens, and JCB or Interac could not be enabled. The payment request, the + `GooglePayButton` and the readiness check behind `payServiceStatus` now use the same networks + and auth methods. - **Requested contact details are no longer lost.** iOS asked for the billing and shipping address but never returned them, and Android ignored `billingContactRequired` and `shippingContactRequired`. See Added. diff --git a/README.md b/README.md index 72e7801..ca3515b 100644 --- a/README.md +++ b/README.md @@ -367,7 +367,7 @@ interface UsePaymentCheckoutConfig { merchantName?: string; // "Pay " on Apple Pay; defaults to the app name countryCode?: string; // Default: 'US' currencyCode?: string; // Default: 'USD' - supportedNetworks?: string[]; // Default: ['visa', 'mastercard', 'amex', 'discover'] + supportedNetworks?: string[]; // PaymentNetwork names. Default: ['visa', 'mastercard', 'amex', 'discover'] merchantCapabilities?: MerchantCapability[]; // Default: ['3DS'] applePayMerchantIdentifier?: string; // Optional iOS override // Google Pay specific (Android) @@ -375,6 +375,7 @@ interface UsePaymentCheckoutConfig { googlePayEnvironment?: "TEST" | "PRODUCTION"; googlePayGateway?: string; googlePayGatewayMerchantId?: string; + googlePayAllowedAuthMethods?: GooglePayAuthMethod[]; // Default: ['PAN_ONLY', 'CRYPTOGRAM_3DS'] // Contact details, returned in the result (see "Shipping and contact details") billingContactRequired?: boolean; shippingContactRequired?: boolean; @@ -455,14 +456,16 @@ Low-level payment handler for direct control. #### Methods -##### `payServiceStatus(): PayServiceStatus` +##### `payServiceStatus(options?: PayServiceStatusOptions): PayServiceStatus` -Check payment service availability. +Check payment service availability. On Android, `options` names the cards to ask Google Pay about: pass the `supportedNetworks` and `googlePayAllowedAuthMethods` of your request. iOS only checks the network names. ```typescript import { HybridPaymentHandler } from "@gmisoftware/react-native-pay"; -const status = HybridPaymentHandler.payServiceStatus(); +const status = HybridPaymentHandler.payServiceStatus({ + supportedNetworks: ["visa", "mastercard"], +}); console.log("Can make payments:", status.canMakePayments); console.log("Can setup cards:", status.canSetupCards); ``` @@ -629,6 +632,10 @@ interface GooglePayButtonProps { radius?: number; // Corner radius in dp + // The cards your payment accepts, so the button never shows another card. + supportedNetworks?: string[]; // as PaymentRequest.supportedNetworks + allowedAuthMethods?: string[]; // as PaymentRequest.googlePayAllowedAuthMethods + onPress?: () => void; // wrap with callback() from react-native-nitro-modules style?: ViewStyle; } @@ -754,7 +761,7 @@ interface PaymentRequest { currencyCode: string; paymentItems: PaymentItem[]; merchantCapabilities: string[]; // MerchantCapability values - supportedNetworks: string[]; + supportedNetworks: string[]; // PaymentNetwork names; unknown names fail shippingType?: string; // ShippingType value, iOS only shippingMethods?: ShippingMethod[]; // → PaymentResult.shippingMethod billingContactRequired?: boolean; // → PaymentResult.billingContact @@ -766,6 +773,7 @@ interface PaymentRequest { googlePayEnvironment?: "TEST" | "PRODUCTION"; googlePayGateway?: string; googlePayGatewayMerchantId?: string; + googlePayAllowedAuthMethods?: string[]; // GooglePayAuthMethod values } // Payment Result @@ -785,14 +793,16 @@ interface PaymentToken { // Payment Method interface PaymentMethod { - displayName?: string; - network?: PaymentNetwork; + displayName?: string; // for the payer, e.g. "Visa •••• 1234"; don't parse it + network?: PaymentNetwork; // "unknown" when the library cannot name it type: PaymentMethodType; secureElementPass?: PKSecureElementPass; billingAddress?: CNContact; } -// Payment Networks +// Payment Networks. Google Pay offers visa, mastercard, amex, discover, jcb +// and interac, plus electron, maestro and elo for Brazilian combo cards. +// Apple Pay offers all of them; each platform leaves out the ones it lacks. type PaymentNetwork = | "visa" | "mastercard" @@ -804,7 +814,33 @@ type PaymentNetwork = | "elo" | "idcredit" | "interac" - | "privateLabel"; + | "privateLabel" + | "cartesBancaires" + | "chinaUnionPay" + | "dankort" + | "eftpos" + | "girocard" + | "mada" + | "mir" + | "quicPay" + | "suica" + | "vPay" + | "waon" + | "nanaco" + | "bancontact" + | "postFinance" + | "pagoBancomat" + | "tmoney" + | "meeza" + | "napas" + | "bankAxept" + | "himyan" + | "jaywan" + | "myDebit" + | "unknown"; // results only + +// Google Pay auth methods (Android) +type GooglePayAuthMethod = "PAN_ONLY" | "CRYPTOGRAM_3DS"; // Payment Method Type type PaymentMethodType = "unknown" | "debit" | "credit" | "prepaid" | "store"; diff --git a/docs/docs/api/components.md b/docs/docs/api/components.md index 2f2a6dd..3cdb682 100644 --- a/docs/docs/api/components.md +++ b/docs/docs/api/components.md @@ -56,9 +56,13 @@ Renders the Google Pay button. Only available on Android. | `buttonType` | `GooglePayButtonType` | Yes | Button label type. | | `theme` | `'dark' \| 'light'` | Yes | Button theme. | | `radius` | `number` | No | Corner radius in dp. | +| `supportedNetworks` | `string[]` | No | The card networks your payment accepts, as in `PaymentRequest.supportedNetworks`. Default: `visa`, `mastercard`, `amex`, `discover`. | +| `allowedAuthMethods` | `string[]` | No | As in `PaymentRequest.googlePayAllowedAuthMethods`. Default: both. | | `onPress` | `() => void`, wrapped with `callback()` | No | Called when the user taps the button. Must be wrapped, see [Nitro and onPress](#nitro-and-onpress). | | `style` | `ViewStyle` | No | Layout/style (e.g. width, height). | +The button can show the payer's card, so give it the same `supportedNetworks` and `allowedAuthMethods` as the payment. Otherwise it may show a card the payment then refuses. With `usePaymentCheckout`, pass `paymentRequest.supportedNetworks` and `paymentRequest.googlePayAllowedAuthMethods`. With an unknown network or auth method, the button keeps its previous configuration, or does not appear on the first render, and logs an error in debug builds. + **GooglePayButtonType:** `'buy'` | `'book'` | `'checkout'` | `'donate'` | `'order'` | `'pay'` | `'subscribe'` | `'plain'` @@ -76,6 +80,7 @@ const handlePayment = async () => { buttonType="buy" theme="dark" radius={8} + supportedNetworks={['visa', 'mastercard']} onPress={callback(handlePayment)} style={{ width: '100%', height: 48 }} /> diff --git a/docs/docs/api/hybrid-payment-handler.md b/docs/docs/api/hybrid-payment-handler.md index 0ec12d7..d975e8e 100644 --- a/docs/docs/api/hybrid-payment-handler.md +++ b/docs/docs/api/hybrid-payment-handler.md @@ -10,20 +10,24 @@ import { HybridPaymentHandler, createPaymentRequest } from '@gmisoftware/react-n ## Methods -### payServiceStatus() +### payServiceStatus(options?) Synchronously returns whether the payment service is available on the device. ```ts import { HybridPaymentHandler } from '@gmisoftware/react-native-pay' -const status = HybridPaymentHandler.payServiceStatus() +const status = HybridPaymentHandler.payServiceStatus({ + supportedNetworks: ['visa', 'mastercard'], +}) // status: { canMakePayments: boolean, canSetupCards: boolean } ``` - **canMakePayments** — User can complete a payment (has a valid card, etc.). - **canSetupCards** — User can add or manage cards (e.g. Wallet settings). +`options` ([`PayServiceStatusOptions`](/docs/api/types#payservicestatusoptions)) names the cards your payment accepts: pass the `supportedNetworks` and `googlePayAllowedAuthMethods` of your `PaymentRequest`. Android asks Google Pay about those cards; without `options` it asks about `visa`, `mastercard`, `amex` and `discover`. iOS does not use them yet. On both platforms an unknown network name throws. + --- ### startPayment(request, options?) @@ -111,6 +115,8 @@ import { HybridPaymentHandler } from '@gmisoftware/react-native-pay' const canPay = HybridPaymentHandler.canMakePayments(['visa', 'mastercard']) ``` +It returns `false` when the platform offers none of the networks, and throws for a name that is not a [`PaymentNetwork`](/docs/api/types#paymentnetwork). On Android it only checks that Google Pay offers one of the networks; it does not ask about the payer's cards. + ## When to use - Custom checkout flow without the hook’s cart. diff --git a/docs/docs/api/types.md b/docs/docs/api/types.md index 1ba8d57..da5d1b2 100644 --- a/docs/docs/api/types.md +++ b/docs/docs/api/types.md @@ -68,6 +68,7 @@ interface PaymentRequest { googlePayEnvironment?: 'TEST' | 'PRODUCTION' googlePayGateway?: string googlePayGatewayMerchantId?: string + googlePayAllowedAuthMethods?: string[] // GooglePayAuthMethod values } ``` @@ -77,6 +78,10 @@ On iOS, `applePayMerchantIdentifier` is optional and only needed when you want t `merchantCapabilities` takes [`MerchantCapability`](#merchantcapability) values. +`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 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. + +`googlePayAllowedAuthMethods` takes [`GooglePayAuthMethod`](#googlepayauthmethod) values and defaults to both. Android only. + `billingContactRequired`, `shippingContactRequired`, `emailRequired` and `phoneNumberRequired` ask the payer for contact details, which come back in the result as [`PaymentDetails`](#paymentdetails). On Android, a phone number is collected with an address. See [Shipping and contact details](/docs/guides/contact-details). `shippingType` takes a [`ShippingType`](#shippingtype) value. `shippingMethods` takes [`ShippingMethod`](#shippingmethod) values; the selected one is added to the total. The first is selected by default on iOS and is always the one charged on Android. @@ -162,19 +167,35 @@ type PaymentMethodType = 'unknown' | 'debit' | 'credit' | 'prepaid' | 'store' `PaymentMethodType` is exported separately for direct typing. +- **displayName** — Describes the card to the payer, as the wallet words it: `PKPaymentMethod.displayName` on iOS, `paymentMethodData.description` on Android (for example "Visa •••• 1234"). Show it as is; don't parse it. +- **network** — The card's [`PaymentNetwork`](#paymentnetwork), or `'unknown'` for a network the library cannot name. Use `network` rather than `displayName` for logic. + --- ## PaymentNetwork -Supported card networks. +Card networks. Use these names in `supportedNetworks`; results report one of them in `token.paymentMethod.network`. ```ts type PaymentNetwork = | 'visa' | 'mastercard' | 'amex' | 'discover' | 'jcb' | 'maestro' | 'electron' | 'elo' | 'idcredit' | 'interac' | 'privateLabel' + | 'cartesBancaires' | 'chinaUnionPay' | 'dankort' | 'eftpos' + | 'girocard' | 'mada' | 'mir' | 'quicPay' | 'suica' | 'vPay' + | 'waon' | 'nanaco' | 'bancontact' | 'postFinance' | 'pagoBancomat' + | 'tmoney' | 'meeza' | 'napas' | 'bankAxept' | 'himyan' | 'jaywan' + | 'myDebit' + | 'unknown' // results only ``` +| Platform | Offers | +|----------|--------| +| Google Pay | `visa`, `mastercard`, `amex`, `discover`, `jcb`, `interac`, and `electron`, `maestro` and `elo` for Brazilian combo cards | +| Apple Pay | Every network but `unknown`. Some need a newer iOS: `bancontact` 16, `postFinance` 16.4, `pagoBancomat` and `tmoney` 17, `meeza` 17.4, `napas` and `bankAxept` 17.5, `himyan` and `jaywan` 18.4, `myDebit` 26 | + +`'unknown'` is never a valid request value. A result reports it for a card on a network that is not listed here, instead of guessing. + --- ## PayServiceStatus @@ -190,6 +211,21 @@ interface PayServiceStatus { --- +## PayServiceStatusOptions + +The cards `HybridPaymentHandler.payServiceStatus(options)` asks about. Pass the values of your `PaymentRequest`, so the check matches the payment. + +```ts +interface PayServiceStatusOptions { + supportedNetworks?: string[] // default: ['visa', 'mastercard', 'amex', 'discover'] + googlePayAllowedAuthMethods?: string[] // default: both +} +``` + +Android asks Google Pay whether the payer can pay with these cards. iOS only checks the network names. + +--- + ## GooglePayEnvironment Used in config and `PaymentRequest` for Android. @@ -202,6 +238,21 @@ Use `'TEST'` for development/sandbox; `'PRODUCTION'` for live charges. Android u --- +## GooglePayAuthMethod + +How Google Pay may authenticate the card, used in `googlePayAllowedAuthMethods` (Android only). + +```ts +type GooglePayAuthMethod = 'PAN_ONLY' | 'CRYPTOGRAM_3DS' +``` + +- `'PAN_ONLY'` — Cards saved to the payer's Google account. The token holds the card number. +- `'CRYPTOGRAM_3DS'` — Cards tokenized on the device. The token holds a 3-D Secure cryptogram. Google Pay does not offer `jcb` or `discover` with it. + +The default is both. Pass `['CRYPTOGRAM_3DS']` when your gateway or Strong Customer Authentication requires device tokens. Android matches the values ignoring case, and any other value fails the payment, with an `error` that contains `Unknown Google Pay auth method "". Use "PAN_ONLY" or "CRYPTOGRAM_3DS"`. They are separate from `merchantCapabilities`: every Apple Pay card is a device token, so iOS has nothing like `'PAN_ONLY'`. + +--- + ## MerchantCapability Apple Pay merchant capabilities, used in `merchantCapabilities` (iOS only; Android ignores the field). diff --git a/docs/docs/api/use-payment-checkout.md b/docs/docs/api/use-payment-checkout.md index 4765fa4..924311c 100644 --- a/docs/docs/api/use-payment-checkout.md +++ b/docs/docs/api/use-payment-checkout.md @@ -27,6 +27,7 @@ interface UsePaymentCheckoutConfig { googlePayEnvironment?: 'TEST' | 'PRODUCTION' googlePayGateway?: string googlePayGatewayMerchantId?: string + googlePayAllowedAuthMethods?: GooglePayAuthMethod[] // default: both // Contact details, returned in the result billingContactRequired?: boolean shippingContactRequired?: boolean @@ -41,6 +42,8 @@ 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. +- **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. On Android the hook checks `canMakePayments` for these networks too. Pass the same list to [`GooglePayButton`](/docs/api/components#googlepaybutton-android-only). +- **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). - **merchantCapabilities** — Apple Pay only. iOS adds `'3DS'` when neither `'3DS'` nor `'EMV'` is given, and fails the payment for an unknown value. See [MerchantCapability](/docs/api/types#merchantcapability). - **billingContactRequired**, **shippingContactRequired**, **emailRequired**, **phoneNumberRequired** — Ask the payer for a billing address, a shipping address, an email address or a phone number. They come back as `result.billingContact`, `result.shippingContact`, `result.emailAddress` and `result.phoneNumber`. See [Shipping and contact details](/docs/guides/contact-details). - **onAuthorize** — Called with the token and the requested contact details after the user authorizes the payment. Charge it on your server and resolve with `{ status: 'success' }` or `{ status: 'failure', error }`. See [Charge before the sheet closes](/docs/guides/server-processing#charge-before-the-sheet-closes). An inline function is fine: `startPayment()` uses the one from the latest render, and a payment keeps that function until it settles, even if the config changes meanwhile. @@ -77,7 +80,7 @@ interface UsePaymentCheckoutReturn { - **canMakePayments** — Whether the user can pay with Apple Pay / Google Pay on this device. - **canSetupCards** — Whether the user can add or manage cards (e.g. in Wallet). -- **isCheckingStatus** — `true` while availability is being checked on mount. +- **isCheckingStatus** — `true` while availability is being checked on mount. The hook checks again when `supportedNetworks` or `googlePayAllowedAuthMethods` change. - **items** / **total** — Current cart and its exact decimal total, as a number (`NaN` if an amount is invalid). Amounts are `number | string` ([`PaymentAmount`](/docs/api/types#paymentamount)); use `formatAmount(item.amount, currencyCode)` to display them. - **startPayment()** — Opens the native sheet. Returns `Promise`. - Returns `null` and sets `error` when the cart is empty. @@ -86,7 +89,7 @@ interface UsePaymentCheckoutReturn { - Returns `null` if an exception is thrown while starting/processing the payment. - With `onAuthorize`, resolves after your callback settles. A `'failure'` result becomes `{ success: false, error }` and sets `error`. - Returns `{ success: false, error: 'A payment is already in progress' }` without opening a second sheet if a payment is still in flight, whether this hook, another `usePaymentCheckout` or [`HybridPaymentHandler`](/docs/api/hybrid-payment-handler) started it. `isProcessing`, `result` and `error` stay as they were. This check comes first, so it also applies when the cart is empty. -- **paymentRequest** / **startPayment** — Keep their identity until a config value or the cart changes. The hook compares the config by value (`supportedNetworks` and `merchantCapabilities` by content), so an inline config object is fine, and both are safe as hook dependencies and props of memoized components. +- **paymentRequest** / **startPayment** — Keep their identity until a config value or the cart changes. The hook compares the config by value (arrays such as `supportedNetworks` by content), so an inline config object is fine, and both are safe as hook dependencies and props of memoized components. - **reset()** — Clears `result` and `error` (does not clear cart). It does not clear `isProcessing` while a payment is in flight; `isProcessing` becomes `false` when that payment settles. ## Example diff --git a/docs/docs/api/utils.md b/docs/docs/api/utils.md index 629ddb5..cfe35e1 100644 --- a/docs/docs/api/utils.md +++ b/docs/docs/api/utils.md @@ -152,6 +152,7 @@ import { formatNetworkName } from '@gmisoftware/react-native-pay' formatNetworkName('visa') // "Visa" formatNetworkName('amex') // "American Express" formatNetworkName('mastercard') // "Mastercard" +formatNetworkName('unknown') // "Unknown" ``` --- diff --git a/example/app/(tabs)/index.tsx b/example/app/(tabs)/index.tsx index cd177c7..6f9f28f 100644 --- a/example/app/(tabs)/index.tsx +++ b/example/app/(tabs)/index.tsx @@ -42,6 +42,7 @@ export default function TabOneScreen() { result, error, reset, + paymentRequest, } = usePaymentCheckout({ merchantName: "React Native Pay Demo", countryCode: "US", @@ -294,6 +295,9 @@ export default function TabOneScreen() { buttonType="buy" theme="dark" radius={8} + // The cards the request accepts, so the button shows one of them. + supportedNetworks={paymentRequest.supportedNetworks} + allowedAuthMethods={paymentRequest.googlePayAllowedAuthMethods} onPress={callback(handlePayment)} style={styles.payButton} /> 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 09c3bf1..6ddc80c 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 @@ -22,12 +22,6 @@ object PaymentConstants { const val BILLING_ADDRESS_FORMAT_MIN = "MIN" const val BILLING_ADDRESS_FORMAT_FULL = "FULL" - // Card networks - const val NETWORK_VISA = "VISA" - const val NETWORK_MASTERCARD = "MASTERCARD" - const val NETWORK_AMEX = "AMEX" - const val NETWORK_DISCOVER = "DISCOVER" - // Tokenization const val TOKENIZATION_PAYMENT_GATEWAY = "PAYMENT_GATEWAY" const val DEFAULT_GATEWAY = "example" @@ -46,9 +40,6 @@ object PaymentConstants { const val ERROR_AUTHORIZATION_FAILED = "Payment authorization failed" const val ERROR_AUTHORIZATION_TIMED_OUT = "Payment authorization timed out" - // Supported networks (lowercase for comparison) - val SUPPORTED_NETWORKS = listOf("visa", "mastercard", "amex", "discover") - // Errors (keep in sync with iOS `ErrorMessage`) const val ERROR_PAYMENT_IN_PROGRESS = "A payment is already in progress" const val ERROR_NO_ACTIVITY = "No activity available to show payment UI" diff --git a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt index 7dbd6bb..d48c3e7 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt @@ -1,7 +1,6 @@ package com.margelo.nitro.pay import android.content.Context -import android.util.Log import com.google.android.gms.wallet.button.ButtonConstants import com.google.android.gms.wallet.button.ButtonOptions import com.google.android.gms.wallet.button.PayButton @@ -12,21 +11,22 @@ import com.google.android.gms.wallet.button.PayButton object GooglePayButtonFactory { /** - * Creates a configured PayButton + * Creates a configured PayButton that shows the cards in [cardParameters] */ - fun createButton( + internal fun createButton( context: Context, buttonType: GooglePayButtonType, theme: GooglePayButtonTheme, radius: Double?, + cardParameters: GooglePayCardParameters, onPress: (() -> Unit)? ): PayButton { - val allowedPaymentMethods = GooglePayRequestBuilder.createAllowedCardNetworks() + val allowedPaymentMethods = GooglePayRequestBuilder.createButtonPaymentMethods(cardParameters) val buttonOptions = ButtonOptions.newBuilder() .setButtonType(mapButtonType(buttonType)) .setButtonTheme(mapTheme(theme)) - .setAllowedPaymentMethods(createAllowedPaymentMethodsJson(allowedPaymentMethods)) + .setAllowedPaymentMethods(allowedPaymentMethods.toString()) .apply { radius?.let { r -> if (r >= 0) { @@ -70,26 +70,4 @@ object GooglePayButtonFactory { GooglePayButtonTheme.LIGHT -> ButtonConstants.ButtonTheme.LIGHT } } - - /** - * Creates allowed payment methods JSON for button configuration - */ - private fun createAllowedPaymentMethodsJson( - allowedNetworks: org.json.JSONArray - ): String { - return org.json.JSONArray().apply { - put(org.json.JSONObject().apply { - put("type", PaymentConstants.PAYMENT_METHOD_CARD) - put("parameters", org.json.JSONObject().apply { - put("allowedAuthMethods", org.json.JSONArray().apply { - put(PaymentConstants.AUTH_PAN_ONLY) - put(PaymentConstants.AUTH_CRYPTOGRAM_3DS) - }) - put("allowedCardNetworks", allowedNetworks) - }) - }) - }.toString() - } } - - diff --git a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt new file mode 100644 index 0000000..8f1d922 --- /dev/null +++ b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt @@ -0,0 +1,104 @@ +package com.margelo.nitro.pay + +import org.json.JSONArray +import org.json.JSONObject + +/** + * [PaymentNetwork] values and the Google Pay card networks they stand for + */ +internal object GooglePayNetworks { + // ELECTRON, MAESTRO and ELO only work for Brazilian combo cards. + private val googlePayNetworks = mapOf( + PaymentNetwork.VISA to "VISA", + PaymentNetwork.MASTERCARD to "MASTERCARD", + PaymentNetwork.AMEX to "AMEX", + PaymentNetwork.DISCOVER to "DISCOVER", + PaymentNetwork.JCB to "JCB", + PaymentNetwork.INTERAC to "INTERAC", + PaymentNetwork.ELECTRON to "ELECTRON", + PaymentNetwork.MAESTRO to "MAESTRO", + PaymentNetwork.ELO to "ELO" + ) + + /** + * The network named [name], ignoring case. Same message as iOS. + * + * @throws IllegalArgumentException for a name that is not a [PaymentNetwork] value + */ + fun parse(name: String): PaymentNetwork { + // Nitro names each entry after its JS value in upper case. + return PaymentNetwork.entries.firstOrNull { + it != PaymentNetwork.UNKNOWN && it.name.equals(name, ignoreCase = true) + } ?: throw IllegalArgumentException( + "Unknown payment network \"$name\". Use a PaymentNetwork value such as \"visa\" or \"mastercard\"" + ) + } + + /** The Google Pay card network, or null when Google Pay does not offer [network] */ + fun toGooglePay(network: PaymentNetwork): String? = googlePayNetworks[network] + + /** The network of a Google Pay `cardNetwork` value, or UNKNOWN */ + fun fromGooglePay(cardNetwork: String): PaymentNetwork { + return googlePayNetworks.entries + .firstOrNull { it.value.equals(cardNetwork, ignoreCase = true) } + ?.key + ?: PaymentNetwork.UNKNOWN + } +} + +/** + * The cards a Google Pay request accepts. The payment request, the readiness + * check and the button send the same values, so they offer the same cards. + */ +internal data class GooglePayCardParameters( + val cardNetworks: List, + val authMethods: List +) { + /** The `parameters` of a CARD payment method, before any billing address */ + fun toJson(): JSONObject = JSONObject().apply { + put("allowedAuthMethods", JSONArray(authMethods)) + put("allowedCardNetworks", JSONArray(cardNetworks)) + } + + companion object { + val DEFAULT_NETWORKS = arrayOf("visa", "mastercard", "amex", "discover") + private val AUTH_METHODS = listOf( + PaymentConstants.AUTH_PAN_ONLY, + PaymentConstants.AUTH_CRYPTOGRAM_3DS + ) + + /** + * Reads `supportedNetworks` and the allowed auth methods; null uses the + * defaults. A network Google Pay does not offer is left out. + * + * @throws IllegalArgumentException for an unknown value, or when no + * network or no auth method is left + */ + fun from( + supportedNetworks: Array?, + authMethods: Array? + ): GooglePayCardParameters { + val networkNames = supportedNetworks ?: DEFAULT_NETWORKS + require(networkNames.isNotEmpty()) { "supportedNetworks needs at least one network" } + val cardNetworks = networkNames + .map { GooglePayNetworks.parse(it) } + .mapNotNull { GooglePayNetworks.toGooglePay(it) } + .distinct() + require(cardNetworks.isNotEmpty()) { + "Google Pay offers none of these networks: ${networkNames.joinToString()}" + } + + val methods = (authMethods?.toList() ?: AUTH_METHODS).map { method -> + AUTH_METHODS.firstOrNull { it.equals(method, ignoreCase = true) } + ?: throw IllegalArgumentException( + "Unknown Google Pay auth method \"$method\". Use \"PAN_ONLY\" or \"CRYPTOGRAM_3DS\"" + ) + }.distinct() + require(methods.isNotEmpty()) { + "Google Pay needs at least one auth method: \"PAN_ONLY\" or \"CRYPTOGRAM_3DS\"" + } + + return GooglePayCardParameters(cardNetworks, methods) + } + } +} 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 2d924db..09e9d1b 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 @@ -12,20 +12,30 @@ import java.math.RoundingMode object GooglePayRequestBuilder { /** - * Creates an IsReadyToPay request + * Creates an IsReadyToPay request for the cards in [cardParameters] */ - fun createIsReadyToPayRequest(existingPaymentMethodRequired: Boolean? = null): JSONObject { + internal fun createIsReadyToPayRequest( + existingPaymentMethodRequired: Boolean? = null, + cardParameters: GooglePayCardParameters = GooglePayCardParameters.from(null, null) + ): JSONObject { return JSONObject().apply { put("apiVersion", PaymentConstants.API_VERSION) put("apiVersionMinor", PaymentConstants.API_VERSION_MINOR) - put("allowedPaymentMethods", JSONArray().apply { - put(createBaseCardPaymentMethod()) - }) + put("allowedPaymentMethods", createButtonPaymentMethods(cardParameters)) existingPaymentMethodRequired?.let { put("existingPaymentMethodRequired", it) } } } + + /** + * The `allowedPaymentMethods` of a PayButton: the cards in [cardParameters] + */ + internal fun createButtonPaymentMethods(cardParameters: GooglePayCardParameters): JSONArray { + return JSONArray().apply { + put(createBaseCardPaymentMethod(cardParameters)) + } + } /** * Creates a complete payment data request @@ -41,13 +51,17 @@ object GooglePayRequestBuilder { validatePaymentRequest(request, environment) validateShippingMethods(request) val requested = RequestedDetails.from(request) + val cardParameters = GooglePayCardParameters.from( + request.supportedNetworks, + request.googlePayAllowedAuthMethods + ) return JSONObject().apply { put("apiVersion", PaymentConstants.API_VERSION) put("apiVersionMinor", PaymentConstants.API_VERSION_MINOR) put("merchantInfo", createMerchantInfo(request, environment, fallbackMerchantName)) put("allowedPaymentMethods", JSONArray().apply { - put(createCardPaymentMethod(request, environment, requested)) + put(createCardPaymentMethod(request, environment, requested, cardParameters)) }) put("transactionInfo", createTransactionInfo(request, requested.shippingMethod)) if (requested.email) { @@ -85,13 +99,10 @@ object GooglePayRequestBuilder { /** * Creates base card payment method (no tokenization) */ - private fun createBaseCardPaymentMethod(): JSONObject { + private fun createBaseCardPaymentMethod(cardParameters: GooglePayCardParameters): JSONObject { return JSONObject().apply { put("type", PaymentConstants.PAYMENT_METHOD_CARD) - put("parameters", JSONObject().apply { - put("allowedAuthMethods", createAllowedAuthMethods()) - put("allowedCardNetworks", createAllowedCardNetworks()) - }) + put("parameters", cardParameters.toJson()) } } @@ -101,9 +112,10 @@ object GooglePayRequestBuilder { private fun createCardPaymentMethod( request: PaymentRequest, environment: Int, - requested: RequestedDetails + requested: RequestedDetails, + cardParameters: GooglePayCardParameters ): JSONObject { - val baseMethod = createBaseCardPaymentMethod() + val baseMethod = createBaseCardPaymentMethod(cardParameters) if (requested.billingAddressRequired) { baseMethod.getJSONObject("parameters").apply { put("billingAddressRequired", true) @@ -270,28 +282,4 @@ object GooglePayRequestBuilder { ) } } - - /** - * Creates allowed auth methods - */ - private fun createAllowedAuthMethods(): JSONArray { - return JSONArray().apply { - put(PaymentConstants.AUTH_PAN_ONLY) - put(PaymentConstants.AUTH_CRYPTOGRAM_3DS) - } - } - - /** - * Creates allowed card networks - */ - fun createAllowedCardNetworks(): JSONArray { - return JSONArray().apply { - put(PaymentConstants.NETWORK_VISA) - put(PaymentConstants.NETWORK_MASTERCARD) - put(PaymentConstants.NETWORK_AMEX) - put(PaymentConstants.NETWORK_DISCOVER) - } - } } - - diff --git a/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt b/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt index c4d0069..2541bda 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt @@ -19,11 +19,15 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton private var currentButtonType: GooglePayButtonType? = null private var currentTheme: GooglePayButtonTheme? = null private var currentRadius: Double? = null + private var currentSupportedNetworks: Array? = null + private var currentAllowedAuthMethods: Array? = null // Props override var buttonType: GooglePayButtonType = GooglePayButtonType.BUY override var theme: GooglePayButtonTheme = GooglePayButtonTheme.DARK override var radius: Double? = null + override var supportedNetworks: Array? = null + override var allowedAuthMethods: Array? = null override var onPress: (() -> Unit)? = null override var view: View = container @@ -64,7 +68,9 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton val hasButton = payButton != null && payButton?.parent == container val propsUnchanged = currentButtonType == buttonType && currentTheme == theme && - currentRadius == radius + currentRadius == radius && + currentSupportedNetworks contentEquals supportedNetworks && + currentAllowedAuthMethods contentEquals allowedAuthMethods return hasButton && propsUnchanged } @@ -87,6 +93,9 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton "Recreating button - type: $buttonType, theme: $theme, radius: $radius" ) + // Before removing the button: invalid networks keep the existing one. + val cardParameters = GooglePayCardParameters.from(supportedNetworks, allowedAuthMethods) + // Remove existing button container.removeAllViews() @@ -96,6 +105,7 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton buttonType, theme, radius, + cardParameters, onPress ) @@ -104,6 +114,8 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton currentButtonType = buttonType currentTheme = theme currentRadius = radius + currentSupportedNetworks = supportedNetworks + currentAllowedAuthMethods = allowedAuthMethods // Add to container val layoutParams = FrameLayout.LayoutParams( diff --git a/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt b/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt index 24f3b5b..a91cd1a 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt @@ -63,19 +63,27 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { // MARK: - Public API - override fun payServiceStatus(): PayServiceStatus { + override fun payServiceStatus(options: PayServiceStatusOptions?): PayServiceStatus { + // Outside the try, so a configuration error reaches JS instead of + // reading as "unavailable". + val cardParameters = GooglePayCardParameters.from( + options?.supportedNetworks, + options?.googlePayAllowedAuthMethods + ) return try { val client = createPaymentsClient(currentEnvironment) val canSetupCards = isReadyToPay( client = client, requestJson = GooglePayRequestBuilder.createIsReadyToPayRequest( - existingPaymentMethodRequired = false + existingPaymentMethodRequired = false, + cardParameters = cardParameters ) ) val canMakePayments = isReadyToPay( client = client, requestJson = GooglePayRequestBuilder.createIsReadyToPayRequest( - existingPaymentMethodRequired = true + existingPaymentMethodRequired = true, + cardParameters = cardParameters ) ) PayServiceStatus( @@ -89,9 +97,9 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { } override fun canMakePayments(usingNetworks: Array): Boolean { - return usingNetworks.any { network -> - PaymentConstants.SUPPORTED_NETWORKS.contains(network.lowercase()) - } + return usingNetworks + .map { GooglePayNetworks.parse(it) } + .any { GooglePayNetworks.toGooglePay(it) != null } } override fun isPaymentInProgress(): Boolean { diff --git a/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt b/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt index 35d8fbd..be555fe 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt @@ -31,9 +31,11 @@ object PaymentMapper { val cardNetwork = info.optString("cardNetwork", "unknown") val cardDetails = info.optString("cardDetails", "****") - // Create payment method + // Create payment method. Google Pay asks to show `description` + // to the payer, not `cardNetwork`. val paymentMethod = PaymentMethod( - displayName = "$cardNetwork $cardDetails", + displayName = paymentMethodData.optNonEmpty("description") + ?: "$cardNetwork $cardDetails", network = mapCardNetwork(cardNetwork), type = PaymentMethodType.UNKNOWN, secureElementPass = null, @@ -134,21 +136,10 @@ object PaymentMapper { } /** - * Maps card network string to PaymentNetwork enum + * Maps a Google Pay `cardNetwork` value to PaymentNetwork, or UNKNOWN */ fun mapCardNetwork(network: String): PaymentNetwork { - return when (network.uppercase()) { - "VISA" -> PaymentNetwork.VISA - "MASTERCARD" -> PaymentNetwork.MASTERCARD - "AMEX" -> PaymentNetwork.AMEX - "DISCOVER" -> PaymentNetwork.DISCOVER - "JCB" -> PaymentNetwork.JCB - "MAESTRO" -> PaymentNetwork.MAESTRO - "ELECTRON" -> PaymentNetwork.ELECTRON - "ELO" -> PaymentNetwork.ELO - "INTERAC" -> PaymentNetwork.INTERAC - else -> PaymentNetwork.VISA // Default fallback - } + return GooglePayNetworks.fromGooglePay(network) } /** 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 de74737..15b09fd 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 @@ -28,7 +28,9 @@ class GooglePayRequestBuilderTest { shippingContactRequired: Boolean? = null, emailRequired: Boolean? = null, phoneNumberRequired: Boolean? = null, - shippingMethods: Array? = null + shippingMethods: Array? = null, + supportedNetworks: Array = arrayOf("visa"), + googlePayAllowedAuthMethods: Array? = null ) = PaymentRequest( applePayMerchantIdentifier = null, merchantName = merchantName, @@ -36,7 +38,7 @@ class GooglePayRequestBuilderTest { currencyCode = currencyCode, paymentItems = items, merchantCapabilities = arrayOf("3DS"), - supportedNetworks = arrayOf("visa"), + supportedNetworks = supportedNetworks, shippingType = null, shippingMethods = shippingMethods, billingContactRequired = billingContactRequired, @@ -46,7 +48,8 @@ class GooglePayRequestBuilderTest { googlePayMerchantId = googlePayMerchantId, googlePayEnvironment = environment, googlePayGateway = googlePayGateway, - googlePayGatewayMerchantId = googlePayGatewayMerchantId + googlePayGatewayMerchantId = googlePayGatewayMerchantId, + googlePayAllowedAuthMethods = googlePayAllowedAuthMethods ) private fun build( @@ -420,9 +423,132 @@ class GooglePayRequestBuilderTest { @Test fun isReadyToPayRequest_neverAsksForContacts() { - val parameters = GooglePayRequestBuilder.createIsReadyToPayRequest() - .getJSONArray("allowedPaymentMethods").getJSONObject(0).getJSONObject("parameters") + val parameters = GooglePayRequestBuilder.createIsReadyToPayRequest().cardParameters() assertFalse(parameters.has("billingAddressRequired")) } + + // Card networks and auth methods + + private fun JSONObject.strings(key: String): List { + val array = getJSONArray(key) + return (0 until array.length()).map { array.getString(it) } + } + + private fun cardParametersOf( + networks: Array?, + authMethods: Array? = null + ) = GooglePayCardParameters.from(networks, authMethods) + + @Test + fun supportedNetworks_areTheOnlyNetworksInTheRequestTheReadinessCheckAndTheButton() { + val request = build(paymentRequest(coffee, supportedNetworks = arrayOf("visa", "mastercard"))) + val parameters = cardParametersOf(arrayOf("visa", "mastercard")) + val readiness = GooglePayRequestBuilder.createIsReadyToPayRequest(true, parameters) + val button = GooglePayRequestBuilder.createButtonPaymentMethods(parameters) + + val expected = listOf("VISA", "MASTERCARD") + assertEquals(expected, request.cardParameters().strings("allowedCardNetworks")) + assertEquals(expected, readiness.cardParameters().strings("allowedCardNetworks")) + assertEquals( + expected, + button.getJSONObject(0).getJSONObject("parameters").strings("allowedCardNetworks") + ) + assertEquals( + readiness.getJSONArray("allowedPaymentMethods").toString(), + button.toString() + ) + } + + @Test + fun supportedNetworks_mapEveryGooglePayNetworkIgnoringCase() { + val parameters = cardParametersOf( + arrayOf("VISA", "MasterCard", "amex", "discover", "jcb", "interac", "electron", "maestro", "elo") + ) + + assertEquals( + listOf("VISA", "MASTERCARD", "AMEX", "DISCOVER", "JCB", "INTERAC", "ELECTRON", "MAESTRO", "ELO"), + parameters.cardNetworks + ) + } + + @Test + fun supportedNetworks_leaveOutNetworksGooglePayDoesNotOffer() { + val parameters = cardParametersOf(arrayOf("cartesBancaires", "visa", "mada", "VISA")) + + assertEquals(listOf("VISA"), parameters.cardNetworks) + } + + @Test + fun supportedNetworks_defaultToTheFourCommonNetworks() { + val parameters = GooglePayRequestBuilder.createIsReadyToPayRequest().cardParameters() + + assertEquals( + listOf("VISA", "MASTERCARD", "AMEX", "DISCOVER"), + parameters.strings("allowedCardNetworks") + ) + assertEquals(listOf("PAN_ONLY", "CRYPTOGRAM_3DS"), parameters.strings("allowedAuthMethods")) + } + + @Test + fun supportedNetworks_rejectUnknownNames() { + for (name in listOf("vsa", "unknown", "")) { + val error = assertThrows(IllegalArgumentException::class.java) { + build(paymentRequest(coffee, supportedNetworks = arrayOf("visa", name))) + } + + assertEquals( + "Unknown payment network \"$name\". Use a PaymentNetwork value such as \"visa\" or \"mastercard\"", + error.message + ) + } + } + + @Test + fun supportedNetworks_rejectAListWithoutAGooglePayNetwork() { + val empty = assertThrows(IllegalArgumentException::class.java) { + build(paymentRequest(coffee, supportedNetworks = emptyArray())) + } + val iosOnly = assertThrows(IllegalArgumentException::class.java) { + build(paymentRequest(coffee, supportedNetworks = arrayOf("cartesBancaires", "mada"))) + } + + assertEquals("supportedNetworks needs at least one network", empty.message) + assertEquals("Google Pay offers none of these networks: cartesBancaires, mada", iosOnly.message) + } + + @Test + fun authMethods_canBeRestrictedToCryptogram3ds() { + val request = build( + paymentRequest(coffee, googlePayAllowedAuthMethods = arrayOf("cryptogram_3ds")) + ) + + assertEquals(listOf("CRYPTOGRAM_3DS"), request.cardParameters().strings("allowedAuthMethods")) + } + + @Test + fun authMethods_keepTheGivenOrderWithoutDuplicates() { + val parameters = cardParametersOf(null, arrayOf("CRYPTOGRAM_3DS", "PAN_ONLY", "pan_only")) + + assertEquals(listOf("CRYPTOGRAM_3DS", "PAN_ONLY"), parameters.authMethods) + } + + @Test + fun authMethods_rejectUnknownAndEmptyLists() { + val unknown = assertThrows(IllegalArgumentException::class.java) { + build(paymentRequest(coffee, googlePayAllowedAuthMethods = arrayOf("3DS"))) + } + val empty = assertThrows(IllegalArgumentException::class.java) { + build(paymentRequest(coffee, googlePayAllowedAuthMethods = emptyArray())) + } + + assertEquals( + "Unknown Google Pay auth method \"3DS\". Use \"PAN_ONLY\" or \"CRYPTOGRAM_3DS\"", + unknown.message + ) + assertEquals( + "Google Pay needs at least one auth method: \"PAN_ONLY\" or \"CRYPTOGRAM_3DS\"", + empty.message + ) + } } diff --git a/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt index ef73c31..9e2e6dc 100644 --- a/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt +++ b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt @@ -98,6 +98,43 @@ class PaymentMapperTest { assertTrue(result.success) assertEquals("unknown ****", result.token!!.paymentMethod.displayName) + assertEquals(PaymentNetwork.UNKNOWN, result.token!!.paymentMethod.network) + } + + @Test + fun mapPaymentDataToResult_showsTheDescriptionToThePayer() { + val result = PaymentMapper.mapPaymentDataToResult( + paymentData( + """ + { + "type": "CARD", + "description": "Visa •••• 4242", + "info": {"cardNetwork": "VISA", "cardDetails": "4242"}, + "tokenizationData": {"type": "PAYMENT_GATEWAY", "token": "gateway-token"} + } + """ + ) + ) + + assertEquals("Visa •••• 4242", result.token!!.paymentMethod.displayName) + assertEquals(PaymentNetwork.VISA, result.token!!.paymentMethod.network) + } + + @Test + fun mapPaymentDataToResult_fallsBackToNetworkAndDetailsForABlankDescription() { + val result = PaymentMapper.mapPaymentDataToResult( + paymentData( + """ + { + "description": " ", + "info": {"cardNetwork": "AMEX", "cardDetails": "0005"}, + "tokenizationData": {"token": "gateway-token"} + } + """ + ) + ) + + assertEquals("AMEX 0005", result.token!!.paymentMethod.displayName) } @Test @@ -244,7 +281,8 @@ class PaymentMapperTest { supportedNetworks = emptyArray(), shippingType = null, shippingMethods = methods, billingContactRequired = null, shippingContactRequired = null, emailRequired = null, phoneNumberRequired = null, googlePayMerchantId = null, googlePayEnvironment = null, - googlePayGateway = null, googlePayGatewayMerchantId = null + googlePayGateway = null, googlePayGatewayMerchantId = null, + googlePayAllowedAuthMethods = null ) val standard = ShippingMethod("standard", "Standard", PaymentAmount.create("4.50"), null) val express = ShippingMethod("express", "Express", PaymentAmount.create("9.00"), null) @@ -283,9 +321,18 @@ class PaymentMapperTest { } @Test - fun mapCardNetwork_reportsUnknownNetworksAsVisa() { - // Current behavior, tracked in #13. - assertEquals(PaymentNetwork.VISA, PaymentMapper.mapCardNetwork("unknown")) + fun mapCardNetwork_reportsUnrecognizedNetworksAsUnknown() { + assertEquals(PaymentNetwork.UNKNOWN, PaymentMapper.mapCardNetwork("unknown")) + assertEquals(PaymentNetwork.UNKNOWN, PaymentMapper.mapCardNetwork("ELO_DEBIT")) + assertEquals(PaymentNetwork.UNKNOWN, PaymentMapper.mapCardNetwork("")) + } + + @Test + fun mapCardNetwork_readsBackEveryNetworkTheRequestSends() { + for (network in PaymentNetwork.entries) { + val cardNetwork = GooglePayNetworks.toGooglePay(network) ?: continue + assertEquals(network, PaymentMapper.mapCardNetwork(cardNetwork)) + } } @Test diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index f18d793..7b22065 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -35,6 +35,16 @@ private enum ErrorMessage { return "Amount for \"\(label)\" must not be negative" } + static let missingSupportedNetwork = "supportedNetworks needs at least one network" + + static func unknownNetwork(_ network: String) -> String { + return "Unknown payment network \"\(network)\". Use a PaymentNetwork value such as \"visa\" or \"mastercard\"" + } + + static func unavailableNetworks(_ networks: [String]) -> String { + return "Apple Pay on this iOS version offers none of these networks: \(networks.joined(separator: ", "))" + } + static func unknownShippingType(_ shippingType: String) -> String { return "Unknown shipping type \"\(shippingType)\". Use \"shipping\", \"delivery\", \"storePickup\" or \"servicePickup\"" } @@ -83,7 +93,7 @@ struct PaymentRequestBuilder { selectedShippingMethodIdentifier: shippingMethods.first?.identifier ) paymentRequest.merchantCapabilities = try buildMerchantCapabilities(request.merchantCapabilities) - paymentRequest.supportedNetworks = buildSupportedNetworks(request.supportedNetworks) + paymentRequest.supportedNetworks = try buildSupportedNetworks(request.supportedNetworks) if let shippingType = request.shippingType { paymentRequest.shippingType = try convertShippingType(shippingType) @@ -229,8 +239,33 @@ struct PaymentRequestBuilder { return merchantCapabilities } - private static func buildSupportedNetworks(_ networks: [String]) -> [PKPaymentNetwork] { - return networks.compactMap { PassKitTypeMapper.convertToPKPaymentNetwork($0) } + /// Same rules and messages as Android: an unknown name fails, a network + /// this iOS version lacks is left out, and at least one must be left. + static func buildSupportedNetworks(_ names: [String]) throws -> [PKPaymentNetwork] { + guard !names.isEmpty else { + throw PaymentRequestError(message: ErrorMessage.missingSupportedNetwork) + } + let networks = try convertNetworks(names) + guard !networks.isEmpty else { + throw PaymentRequestError(message: ErrorMessage.unavailableNetworks(names)) + } + return networks + } + + /// The PassKit networks for these names that this iOS version has, + /// without duplicates. Fails for a name that is not a `PaymentNetwork`. + static func convertNetworks(_ names: [String]) throws -> [PKPaymentNetwork] { + var networks: [PKPaymentNetwork] = [] + for name in names { + guard let network = PassKitTypeMapper.paymentNetwork(named: name) else { + throw PaymentRequestError(message: ErrorMessage.unknownNetwork(name)) + } + if let pkNetwork = PassKitTypeMapper.convertToPKPaymentNetwork(network), + !networks.contains(pkNetwork) { + networks.append(pkNetwork) + } + } + return networks } private static func convertShippingType(_ type: String) throws -> PKShippingType { @@ -506,14 +541,21 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec { // MARK: - Public Methods - func payServiceStatus() throws -> PayServiceStatus { + func payServiceStatus(options: PayServiceStatusOptions?) throws -> PayServiceStatus { + // Rejects unknown names like Android. The status itself does not + // depend on the networks on iOS. + if let networks = options?.supportedNetworks { + _ = try PaymentRequestBuilder.convertNetworks(networks) + } let canMakePayments = PKPaymentAuthorizationViewController.canMakePayments() let canSetupCards = PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: []) return PayServiceStatus.init(canMakePayments, canSetupCards) } func canMakePayments(usingNetworks: [String]) throws -> Bool { - let networks = usingNetworks.compactMap { PassKitTypeMapper.convertToPKPaymentNetwork($0) } + let networks = try PaymentRequestBuilder.convertNetworks(usingNetworks) + // As on Android. PassKit may answer true for an empty list. + guard !networks.isEmpty else { return false } return PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: networks) } diff --git a/package/ios/PassKitTypeMapper.swift b/package/ios/PassKitTypeMapper.swift index e2615d4..4d6da29 100644 --- a/package/ios/PassKitTypeMapper.swift +++ b/package/ios/PassKitTypeMapper.swift @@ -2,22 +2,6 @@ import PassKit import Contacts import NitroModules -// MARK: - Constants - -private enum PaymentNetworkString { - static let visa = "visa" - static let mastercard = "mastercard" - static let amex = "amex" - static let discover = "discover" - static let jcb = "jcb" - static let maestro = "maestro" - static let electron = "electron" - static let elo = "elo" - static let idcredit = "idcredit" - static let interac = "interac" - static let privateLabel = "privateLabel" -} - // MARK: - Type Converter /// Converts Apple PassKit and Contacts types to Nitro-generated types @@ -25,21 +9,9 @@ enum PassKitTypeMapper { // MARK: - Enum Conversions + /// The network a payer paid with, or `.unknown` for one this library cannot name static func convert(_ network: PKPaymentNetwork) -> PaymentNetwork { - switch network { - case .visa: return .visa - case .masterCard: return .mastercard - case .amex: return .amex - case .discover: return .discover - case .JCB: return .jcb - case .maestro: return .maestro - case .electron: return .electron - case .elo: return .elo - case .idCredit: return .idcredit - case .interac: return .interac - case .privateLabel: return .privatelabel - default: return .visa - } + return paymentNetworks.first { convertToPKPaymentNetwork($0) == network } ?? .unknown } static func convert(_ type: PKPaymentMethodType) -> PaymentMethodType { @@ -62,22 +34,82 @@ enum PassKitTypeMapper { } } - // MARK: - String to Enum Conversions - - static func convertToPKPaymentNetwork(_ string: String) -> PKPaymentNetwork? { - switch string { - case PaymentNetworkString.visa: return .visa - case PaymentNetworkString.mastercard: return .masterCard - case PaymentNetworkString.amex: return .amex - case PaymentNetworkString.discover: return .discover - case PaymentNetworkString.jcb: return .JCB - case PaymentNetworkString.maestro: return .maestro - case PaymentNetworkString.electron: return .electron - case PaymentNetworkString.elo: return .elo - case PaymentNetworkString.idcredit: return .idCredit - case PaymentNetworkString.interac: return .interac - case PaymentNetworkString.privateLabel: return .privateLabel - default: return nil + // MARK: - Payment Networks + + /// Every `PaymentNetwork` but `.unknown` + private static let paymentNetworks: [PaymentNetwork] = [ + .visa, .mastercard, .amex, .discover, .jcb, .maestro, .electron, .elo, + .idcredit, .interac, .privatelabel, .cartesbancaires, .chinaunionpay, + .dankort, .eftpos, .girocard, .mada, .mir, .quicpay, .suica, .vpay, + .waon, .nanaco, .bancontact, .postfinance, .pagobancomat, .tmoney, + .meeza, .napas, .bankaxept, .himyan, .jaywan, .mydebit, + ] + + /// The network with this name, ignoring case, or nil for a name that is + /// not a `PaymentNetwork` value + static func paymentNetwork(named name: String) -> PaymentNetwork? { + return paymentNetworks.first { + $0.stringValue.caseInsensitiveCompare(name) == .orderedSame + } + } + + /// The PassKit network, or nil when this iOS version doesn't have it + static func convertToPKPaymentNetwork(_ network: PaymentNetwork) -> PKPaymentNetwork? { + switch network { + case .visa: return .visa + case .mastercard: return .masterCard + case .amex: return .amex + case .discover: return .discover + case .jcb: return .JCB + case .maestro: return .maestro + case .electron: return .electron + case .elo: return .elo + case .idcredit: return .idCredit + case .interac: return .interac + case .privatelabel: return .privateLabel + case .cartesbancaires: return .cartesBancaires + case .chinaunionpay: return .chinaUnionPay + case .dankort: return .dankort + case .eftpos: return .eftpos + case .girocard: return .girocard + case .mada: return .mada + case .mir: return .mir + case .quicpay: return .quicPay + case .suica: return .suica + case .vpay: return .vPay + case .waon: return .waon + case .nanaco: return .nanaco + case .bancontact: + guard #available(iOS 16.0, *) else { return nil } + return .bancontact + case .postfinance: + guard #available(iOS 16.4, *) else { return nil } + return .postFinance + case .pagobancomat: + guard #available(iOS 17.0, *) else { return nil } + return .pagoBancomat + case .tmoney: + guard #available(iOS 17.0, *) else { return nil } + return .tmoney + case .meeza: + guard #available(iOS 17.4, *) else { return nil } + return .meeza + case .napas: + guard #available(iOS 17.5, *) else { return nil } + return .NAPAS + case .bankaxept: + guard #available(iOS 17.5, *) else { return nil } + return .bankAxept + case .himyan: + guard #available(iOS 18.4, *) else { return nil } + return .himyan + case .jaywan: + guard #available(iOS 18.4, *) else { return nil } + return .jaywan + case .mydebit: + guard #available(iOS 26.0, *) else { return nil } + return .myDebit + case .unknown: return nil } } diff --git a/package/ios/Tests/PassKitTypeMapperTests.swift b/package/ios/Tests/PassKitTypeMapperTests.swift index 76abe86..91962af 100644 --- a/package/ios/Tests/PassKitTypeMapperTests.swift +++ b/package/ios/Tests/PassKitTypeMapperTests.swift @@ -5,9 +5,14 @@ import XCTest final class PassKitTypeMapperTests: XCTestCase { + // Every PaymentNetwork in src/types/Payment.ts but "unknown" private let networkNames = [ "visa", "mastercard", "amex", "discover", "jcb", "maestro", "electron", "elo", "idcredit", "interac", "privateLabel", + "cartesBancaires", "chinaUnionPay", "dankort", "eftpos", "girocard", + "mada", "mir", "quicPay", "suica", "vPay", "waon", "nanaco", + "bancontact", "postFinance", "pagoBancomat", "tmoney", "meeza", + "napas", "bankAxept", "himyan", "jaywan", "myDebit", ] // Swift drops this `convert` overload when it is looked up before the @@ -17,23 +22,41 @@ final class PassKitTypeMapperTests: XCTestCase { return PassKitTypeMapper.convert(network) } + private func pkNetwork(named name: String) -> PKPaymentNetwork? { + let network: PaymentNetwork? = PassKitTypeMapper.paymentNetwork(named: name) + return network.flatMap { PassKitTypeMapper.convertToPKPaymentNetwork($0) } + } + func testConvertsEveryNetworkNameToPassKitAndBack() throws { for name in networkNames { - let pkNetwork = try XCTUnwrap(PassKitTypeMapper.convertToPKPaymentNetwork(name), name) + let network = try XCTUnwrap(PassKitTypeMapper.paymentNetwork(named: name), name) + XCTAssertEqual(network.stringValue, name) + guard let pkNetwork = pkNetwork(named: name) else { + // Only a network newer than the simulator's iOS has none. + if #available(iOS 26.0, *) { XCTFail("No PassKit network for \(name)") } + continue + } XCTAssertEqual(convert(pkNetwork), PaymentNetwork(fromString: name), name) } - XCTAssertEqual(PassKitTypeMapper.convertToPKPaymentNetwork("mastercard"), .masterCard) - XCTAssertEqual(PassKitTypeMapper.convertToPKPaymentNetwork("idcredit"), .idCredit) + XCTAssertEqual(pkNetwork(named: "mastercard"), .masterCard) + XCTAssertEqual(pkNetwork(named: "idcredit"), .idCredit) + XCTAssertEqual(pkNetwork(named: "cartesBancaires"), .cartesBancaires) + } + + func testMatchesNetworkNamesIgnoringCase() { + XCTAssertEqual(pkNetwork(named: "Visa"), .visa) + XCTAssertEqual(pkNetwork(named: "PRIVATELABEL"), .privateLabel) } func testIgnoresUnknownNetworkNames() { - XCTAssertNil(PassKitTypeMapper.convertToPKPaymentNetwork("unknown")) - XCTAssertNil(PassKitTypeMapper.convertToPKPaymentNetwork("Visa")) + XCTAssertNil(PassKitTypeMapper.paymentNetwork(named: "unknown")) + XCTAssertNil(PassKitTypeMapper.paymentNetwork(named: "vsa")) + XCTAssertNil(PassKitTypeMapper.paymentNetwork(named: "")) } - func testReportsUnsupportedPassKitNetworksAsVisa() { - // Current behavior: PaymentNetwork has no "other" case. - XCTAssertEqual(convert(.girocard), .visa) + func testReportsUnrecognizedPassKitNetworksAsUnknown() { + XCTAssertEqual(convert(.barcode), .unknown) + XCTAssertEqual(convert(PKPaymentNetwork(rawValue: "NotANetwork")), .unknown) } func testConvertsPaymentMethodTypes() { diff --git a/package/ios/Tests/PaymentRequestBuilderTests.swift b/package/ios/Tests/PaymentRequestBuilderTests.swift index 69e9ab0..333e477 100644 --- a/package/ios/Tests/PaymentRequestBuilderTests.swift +++ b/package/ios/Tests/PaymentRequestBuilderTests.swift @@ -47,7 +47,8 @@ final class PaymentRequestBuilderTests: XCTestCase { googlePayMerchantId: nil, googlePayEnvironment: nil, googlePayGateway: nil, - googlePayGatewayMerchantId: nil + googlePayGatewayMerchantId: nil, + googlePayAllowedAuthMethods: nil ) } @@ -67,7 +68,7 @@ final class PaymentRequestBuilderTests: XCTestCase { items: [item("Coffee", "4.99")], merchantIdentifier: " merchant.com.example\n", merchantCapabilities: ["3DS", "Debit"], - supportedNetworks: ["visa", "amex", "unknown"], + supportedNetworks: ["visa", "amex"], shippingType: "delivery" )) @@ -79,6 +80,48 @@ final class PaymentRequestBuilderTests: XCTestCase { XCTAssertEqual(request.shippingType, .delivery) } + func testMatchesNetworksCaseInsensitivelyWithoutDuplicates() throws { + let request = try PaymentRequestBuilder.build(from: paymentRequest( + items: [item("Coffee", "4.99")], + supportedNetworks: ["VISA", "MasterCard", "cartesBancaires", "visa"] + )) + + XCTAssertEqual(request.supportedNetworks, [.visa, .masterCard, .cartesBancaires]) + } + + func testRejectsUnknownNetworks() { + for name in ["vsa", "unknown", ""] { + assertBuildFails( + paymentRequest(items: [item("Coffee", "4.99")], supportedNetworks: ["visa", name]), + with: "Unknown payment network \"\(name)\". Use a PaymentNetwork value such as \"visa\" or \"mastercard\"" + ) + } + } + + func testRejectsAnEmptyNetworkList() { + assertBuildFails( + paymentRequest(items: [item("Coffee", "4.99")], supportedNetworks: []), + with: "supportedNetworks needs at least one network" + ) + } + + func testLeavesOutNetworksThisIOSVersionLacks() throws { + let names = ["visa", "myDebit"] + if #available(iOS 26.0, *) { + let request = try PaymentRequestBuilder.build(from: paymentRequest( + items: [item("Coffee", "4.99")], + supportedNetworks: names + )) + XCTAssertEqual(request.supportedNetworks, [.visa, .myDebit]) + } else { + XCTAssertEqual(try PaymentRequestBuilder.convertNetworks(names), [.visa]) + assertBuildFails( + paymentRequest(items: [item("Coffee", "4.99")], supportedNetworks: ["myDebit"]), + with: "Apple Pay on this iOS version offers none of these networks: myDebit" + ) + } + } + func testMatchesMerchantCapabilitiesCaseInsensitively() throws { let request = try PaymentRequestBuilder.build(from: paymentRequest( items: [item("Coffee", "4.99")], diff --git a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp index 3b6741a..ca50b0e 100644 --- a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp +++ b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp @@ -17,6 +17,8 @@ namespace margelo::nitro::pay { enum class GooglePayButtonTheme; } #include "GooglePayButtonTheme.hpp" #include "JGooglePayButtonTheme.hpp" #include +#include +#include #include #include "JFunc_void.hpp" #include @@ -78,6 +80,60 @@ namespace margelo::nitro::pay { static const auto method = _javaPart->javaClassStatic()->getMethod /* radius */)>("setRadius"); method(_javaPart, radius.has_value() ? jni::JDouble::valueOf(radius.value()) : nullptr); } + std::optional> JHybridGooglePayButtonSpec::getSupportedNetworks() { + static const auto method = _javaPart->javaClassStatic()->getMethod>()>("getSupportedNetworks"); + auto __result = method(_javaPart); + return __result != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(__result)) : std::nullopt; + } + void JHybridGooglePayButtonSpec::setSupportedNetworks(const std::optional>& supportedNetworks) { + static const auto method = _javaPart->javaClassStatic()->getMethod> /* supportedNetworks */)>("setSupportedNetworks"); + method(_javaPart, supportedNetworks.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(supportedNetworks.value()) : nullptr); + } + std::optional> JHybridGooglePayButtonSpec::getAllowedAuthMethods() { + static const auto method = _javaPart->javaClassStatic()->getMethod>()>("getAllowedAuthMethods"); + auto __result = method(_javaPart); + return __result != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(__result)) : std::nullopt; + } + void JHybridGooglePayButtonSpec::setAllowedAuthMethods(const std::optional>& allowedAuthMethods) { + static const auto method = _javaPart->javaClassStatic()->getMethod> /* allowedAuthMethods */)>("setAllowedAuthMethods"); + method(_javaPart, allowedAuthMethods.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(allowedAuthMethods.value()) : nullptr); + } std::optional> JHybridGooglePayButtonSpec::getOnPress() { static const auto method = _javaPart->javaClassStatic()->getMethod()>("getOnPress_cxx"); auto __result = method(_javaPart); diff --git a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp index 0655777..8497ac1 100644 --- a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp +++ b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp @@ -56,6 +56,10 @@ namespace margelo::nitro::pay { void setTheme(GooglePayButtonTheme theme) override; std::optional getRadius() override; void setRadius(std::optional radius) override; + std::optional> getSupportedNetworks() override; + void setSupportedNetworks(const std::optional>& supportedNetworks) override; + std::optional> getAllowedAuthMethods() override; + void setAllowedAuthMethods(const std::optional>& allowedAuthMethods) override; std::optional> getOnPress() override; void setOnPress(const std::optional>& onPress) override; diff --git a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp index 3d94e2f..cc77492 100644 --- a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp +++ b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp @@ -41,6 +41,8 @@ namespace margelo::nitro::pay { struct CNPostalAddress; } namespace margelo::nitro::pay { struct PaymentContact; } // Forward declaration of `ShippingMethod` to properly resolve imports. namespace margelo::nitro::pay { struct ShippingMethod; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } // Forward declaration of `PaymentRequest` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentRequest; } // Forward declaration of `PaymentItem` to properly resolve imports. @@ -99,6 +101,8 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include "JShippingMethod.hpp" #include #include "JPaymentAmount.hpp" +#include "PayServiceStatusOptions.hpp" +#include "JPayServiceStatusOptions.hpp" #include "PaymentRequest.hpp" #include "JPaymentRequest.hpp" #include "PaymentItem.hpp" @@ -152,9 +156,9 @@ namespace margelo::nitro::pay { // Methods - PayServiceStatus JHybridPaymentHandlerSpec::payServiceStatus() { - static const auto method = _javaPart->javaClassStatic()->getMethod()>("payServiceStatus"); - auto __result = method(_javaPart); + PayServiceStatus JHybridPaymentHandlerSpec::payServiceStatus(const std::optional& options) { + static const auto method = _javaPart->javaClassStatic()->getMethod(jni::alias_ref /* options */)>("payServiceStatus"); + auto __result = method(_javaPart, options.has_value() ? JPayServiceStatusOptions::fromCpp(options.value()) : nullptr); return __result->toCpp(); } std::shared_ptr> JHybridPaymentHandlerSpec::startPayment(const PaymentRequest& request, const std::optional& options) { diff --git a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp index b29d19f..db80ec0 100644 --- a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp +++ b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp @@ -54,7 +54,7 @@ namespace margelo::nitro::pay { public: // Methods - PayServiceStatus payServiceStatus() override; + PayServiceStatus payServiceStatus(const std::optional& options) override; std::shared_ptr> startPayment(const PaymentRequest& request, const std::optional& options) override; bool canMakePayments(const std::vector& usingNetworks) override; bool isPaymentInProgress() override; diff --git a/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp b/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp new file mode 100644 index 0000000..8eb6b26 --- /dev/null +++ b/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp @@ -0,0 +1,99 @@ +/// +/// JPayServiceStatusOptions.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 "PayServiceStatusOptions.hpp" + +#include +#include +#include + +namespace margelo::nitro::pay { + + using namespace facebook; + + /** + * The C++ JNI bridge between the C++ struct "PayServiceStatusOptions" and the Kotlin data class "PayServiceStatusOptions". + */ + struct JPayServiceStatusOptions final: public jni::JavaClass { + public: + static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/pay/PayServiceStatusOptions;"; + + public: + /** + * Convert this Java/Kotlin-based struct to the C++ struct PayServiceStatusOptions by copying all values to C++. + */ + [[maybe_unused]] + [[nodiscard]] + PayServiceStatusOptions toCpp() const { + static const auto clazz = javaClassStatic(); + static const auto fieldSupportedNetworks = clazz->getField>("supportedNetworks"); + jni::local_ref> supportedNetworks = this->getFieldValue(fieldSupportedNetworks); + static const auto fieldGooglePayAllowedAuthMethods = clazz->getField>("googlePayAllowedAuthMethods"); + jni::local_ref> googlePayAllowedAuthMethods = this->getFieldValue(fieldGooglePayAllowedAuthMethods); + return PayServiceStatusOptions( + supportedNetworks != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(supportedNetworks)) : std::nullopt, + googlePayAllowedAuthMethods != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(googlePayAllowedAuthMethods)) : 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 PayServiceStatusOptions& value) { + using JSignature = JPayServiceStatusOptions(jni::alias_ref>, jni::alias_ref>); + static const auto clazz = javaClassStatic(); + static const auto create = clazz->getStaticMethod("fromCpp"); + return create( + clazz, + value.supportedNetworks.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(value.supportedNetworks.value()) : nullptr, + value.googlePayAllowedAuthMethods.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(value.googlePayAllowedAuthMethods.value()) : nullptr + ); + } + }; + +} // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/c++/JPaymentNetwork.hpp b/package/nitrogen/generated/android/c++/JPaymentNetwork.hpp index f61fff2..3dd0c5a 100644 --- a/package/nitrogen/generated/android/c++/JPaymentNetwork.hpp +++ b/package/nitrogen/generated/android/c++/JPaymentNetwork.hpp @@ -75,6 +75,75 @@ namespace margelo::nitro::pay { case PaymentNetwork::PRIVATELABEL: static const auto fieldPRIVATELABEL = clazz->getStaticField("PRIVATELABEL"); return clazz->getStaticFieldValue(fieldPRIVATELABEL); + case PaymentNetwork::CARTESBANCAIRES: + static const auto fieldCARTESBANCAIRES = clazz->getStaticField("CARTESBANCAIRES"); + return clazz->getStaticFieldValue(fieldCARTESBANCAIRES); + case PaymentNetwork::CHINAUNIONPAY: + static const auto fieldCHINAUNIONPAY = clazz->getStaticField("CHINAUNIONPAY"); + return clazz->getStaticFieldValue(fieldCHINAUNIONPAY); + case PaymentNetwork::DANKORT: + static const auto fieldDANKORT = clazz->getStaticField("DANKORT"); + return clazz->getStaticFieldValue(fieldDANKORT); + case PaymentNetwork::EFTPOS: + static const auto fieldEFTPOS = clazz->getStaticField("EFTPOS"); + return clazz->getStaticFieldValue(fieldEFTPOS); + case PaymentNetwork::GIROCARD: + static const auto fieldGIROCARD = clazz->getStaticField("GIROCARD"); + return clazz->getStaticFieldValue(fieldGIROCARD); + case PaymentNetwork::MADA: + static const auto fieldMADA = clazz->getStaticField("MADA"); + return clazz->getStaticFieldValue(fieldMADA); + case PaymentNetwork::MIR: + static const auto fieldMIR = clazz->getStaticField("MIR"); + return clazz->getStaticFieldValue(fieldMIR); + case PaymentNetwork::QUICPAY: + static const auto fieldQUICPAY = clazz->getStaticField("QUICPAY"); + return clazz->getStaticFieldValue(fieldQUICPAY); + case PaymentNetwork::SUICA: + static const auto fieldSUICA = clazz->getStaticField("SUICA"); + return clazz->getStaticFieldValue(fieldSUICA); + case PaymentNetwork::VPAY: + static const auto fieldVPAY = clazz->getStaticField("VPAY"); + return clazz->getStaticFieldValue(fieldVPAY); + case PaymentNetwork::WAON: + static const auto fieldWAON = clazz->getStaticField("WAON"); + return clazz->getStaticFieldValue(fieldWAON); + case PaymentNetwork::NANACO: + static const auto fieldNANACO = clazz->getStaticField("NANACO"); + return clazz->getStaticFieldValue(fieldNANACO); + case PaymentNetwork::BANCONTACT: + static const auto fieldBANCONTACT = clazz->getStaticField("BANCONTACT"); + return clazz->getStaticFieldValue(fieldBANCONTACT); + case PaymentNetwork::POSTFINANCE: + static const auto fieldPOSTFINANCE = clazz->getStaticField("POSTFINANCE"); + return clazz->getStaticFieldValue(fieldPOSTFINANCE); + case PaymentNetwork::PAGOBANCOMAT: + static const auto fieldPAGOBANCOMAT = clazz->getStaticField("PAGOBANCOMAT"); + return clazz->getStaticFieldValue(fieldPAGOBANCOMAT); + case PaymentNetwork::TMONEY: + static const auto fieldTMONEY = clazz->getStaticField("TMONEY"); + return clazz->getStaticFieldValue(fieldTMONEY); + case PaymentNetwork::MEEZA: + static const auto fieldMEEZA = clazz->getStaticField("MEEZA"); + return clazz->getStaticFieldValue(fieldMEEZA); + case PaymentNetwork::NAPAS: + static const auto fieldNAPAS = clazz->getStaticField("NAPAS"); + return clazz->getStaticFieldValue(fieldNAPAS); + case PaymentNetwork::BANKAXEPT: + static const auto fieldBANKAXEPT = clazz->getStaticField("BANKAXEPT"); + return clazz->getStaticFieldValue(fieldBANKAXEPT); + case PaymentNetwork::HIMYAN: + static const auto fieldHIMYAN = clazz->getStaticField("HIMYAN"); + return clazz->getStaticFieldValue(fieldHIMYAN); + case PaymentNetwork::JAYWAN: + static const auto fieldJAYWAN = clazz->getStaticField("JAYWAN"); + return clazz->getStaticFieldValue(fieldJAYWAN); + case PaymentNetwork::MYDEBIT: + static const auto fieldMYDEBIT = clazz->getStaticField("MYDEBIT"); + return clazz->getStaticFieldValue(fieldMYDEBIT); + case PaymentNetwork::UNKNOWN: + static const auto fieldUNKNOWN = clazz->getStaticField("UNKNOWN"); + return clazz->getStaticFieldValue(fieldUNKNOWN); default: std::string stringValue = std::to_string(static_cast(value)); throw std::invalid_argument("Invalid enum value (" + stringValue + "!"); diff --git a/package/nitrogen/generated/android/c++/JPaymentRequest.hpp b/package/nitrogen/generated/android/c++/JPaymentRequest.hpp index aeafaf0..4e53800 100644 --- a/package/nitrogen/generated/android/c++/JPaymentRequest.hpp +++ b/package/nitrogen/generated/android/c++/JPaymentRequest.hpp @@ -77,6 +77,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 fieldGooglePayAllowedAuthMethods = clazz->getField>("googlePayAllowedAuthMethods"); + jni::local_ref> googlePayAllowedAuthMethods = this->getFieldValue(fieldGooglePayAllowedAuthMethods); return PaymentRequest( applePayMerchantIdentifier != nullptr ? std::make_optional(applePayMerchantIdentifier->toStdString()) : std::nullopt, merchantName != nullptr ? std::make_optional(merchantName->toStdString()) : std::nullopt, @@ -130,7 +132,17 @@ namespace margelo::nitro::pay { googlePayMerchantId != nullptr ? std::make_optional(googlePayMerchantId->toStdString()) : std::nullopt, 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 + googlePayGatewayMerchantId != nullptr ? std::make_optional(googlePayGatewayMerchantId->toStdString()) : std::nullopt, + googlePayAllowedAuthMethods != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(googlePayAllowedAuthMethods)) : std::nullopt ); } @@ -140,7 +152,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); + 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>); static const auto clazz = javaClassStatic(); static const auto create = clazz->getStaticMethod("fromCpp"); return create( @@ -197,7 +209,17 @@ namespace margelo::nitro::pay { value.googlePayMerchantId.has_value() ? jni::make_jstring(value.googlePayMerchantId.value()) : nullptr, 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.googlePayGatewayMerchantId.has_value() ? jni::make_jstring(value.googlePayGatewayMerchantId.value()) : nullptr, + value.googlePayAllowedAuthMethods.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(value.googlePayAllowedAuthMethods.value()) : nullptr ); } }; diff --git a/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp b/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp index c1f6a52..a9d881a 100644 --- a/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp +++ b/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp @@ -49,6 +49,14 @@ void JHybridGooglePayButtonStateUpdater::updateViewProps(jni::alias_refsetRadius(props->radius.value); props->radius.isDirty = false; } + if (props->supportedNetworks.isDirty) { + hybridView->setSupportedNetworks(props->supportedNetworks.value); + props->supportedNetworks.isDirty = false; + } + if (props->allowedAuthMethods.isDirty) { + hybridView->setAllowedAuthMethods(props->allowedAuthMethods.value); + props->allowedAuthMethods.isDirty = false; + } if (props->onPress.isDirty) { hybridView->setOnPress(props->onPress.value); props->onPress.isDirty = false; diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt index 44560ad..6911b3d 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt @@ -44,6 +44,18 @@ abstract class HybridGooglePayButtonSpec: HybridView() { @set:Keep abstract var radius: Double? + @get:DoNotStrip + @get:Keep + @set:DoNotStrip + @set:Keep + abstract var supportedNetworks: Array? + + @get:DoNotStrip + @get:Keep + @set:DoNotStrip + @set:Keep + abstract var allowedAuthMethods: Array? + abstract var onPress: (() -> Unit)? private var onPress_cxx: Func_void? diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt index b265f1b..d067ea8 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt @@ -31,7 +31,7 @@ abstract class HybridPaymentHandlerSpec: HybridObject() { // Methods @DoNotStrip @Keep - abstract fun payServiceStatus(): PayServiceStatus + abstract fun payServiceStatus(options: PayServiceStatusOptions?): PayServiceStatus @DoNotStrip @Keep diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt new file mode 100644 index 0000000..37a343e --- /dev/null +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt @@ -0,0 +1,56 @@ +/// +/// PayServiceStatusOptions.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 "PayServiceStatusOptions". + */ +@DoNotStrip +@Keep +data class PayServiceStatusOptions( + @DoNotStrip + @Keep + val supportedNetworks: Array?, + @DoNotStrip + @Keep + val googlePayAllowedAuthMethods: Array? +) { + /* primary constructor */ + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is PayServiceStatusOptions) return false + return Objects.deepEquals(this.supportedNetworks, other.supportedNetworks) + && Objects.deepEquals(this.googlePayAllowedAuthMethods, other.googlePayAllowedAuthMethods) + } + + override fun hashCode(): Int { + return arrayOf( + supportedNetworks, + googlePayAllowedAuthMethods + ).contentDeepHashCode() + } + + companion object { + /** + * Constructor called from C++ + */ + @DoNotStrip + @Keep + @Suppress("unused") + @JvmStatic + private fun fromCpp(supportedNetworks: Array?, googlePayAllowedAuthMethods: Array?): PayServiceStatusOptions { + return PayServiceStatusOptions(supportedNetworks, googlePayAllowedAuthMethods) + } + } +} diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentNetwork.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentNetwork.kt index 9688c03..f3486f8 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentNetwork.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentNetwork.kt @@ -26,7 +26,30 @@ enum class PaymentNetwork(@DoNotStrip @Keep val value: Int) { ELO(7), IDCREDIT(8), INTERAC(9), - PRIVATELABEL(10); + PRIVATELABEL(10), + CARTESBANCAIRES(11), + CHINAUNIONPAY(12), + DANKORT(13), + EFTPOS(14), + GIROCARD(15), + MADA(16), + MIR(17), + QUICPAY(18), + SUICA(19), + VPAY(20), + WAON(21), + NANACO(22), + BANCONTACT(23), + POSTFINANCE(24), + PAGOBANCOMAT(25), + TMONEY(26), + MEEZA(27), + NAPAS(28), + BANKAXEPT(29), + HIMYAN(30), + JAYWAN(31), + MYDEBIT(32), + UNKNOWN(33); 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 5156579..bb49c98 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 @@ -68,7 +68,10 @@ data class PaymentRequest( val googlePayGateway: String?, @DoNotStrip @Keep - val googlePayGatewayMerchantId: String? + val googlePayGatewayMerchantId: String?, + @DoNotStrip + @Keep + val googlePayAllowedAuthMethods: Array? ) { /* primary constructor */ @@ -92,6 +95,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.googlePayAllowedAuthMethods, other.googlePayAllowedAuthMethods) } override fun hashCode(): Int { @@ -112,7 +116,8 @@ data class PaymentRequest( googlePayMerchantId, googlePayEnvironment, googlePayGateway, - googlePayGatewayMerchantId + googlePayGatewayMerchantId, + googlePayAllowedAuthMethods ).contentDeepHashCode() } @@ -124,8 +129,8 @@ data class PaymentRequest( @Keep @Suppress("unused") @JvmStatic - private fun fromCpp(applePayMerchantIdentifier: String?, merchantName: String?, countryCode: String, currencyCode: String, paymentItems: Array, merchantCapabilities: Array, supportedNetworks: Array, shippingType: String?, shippingMethods: Array?, billingContactRequired: Boolean?, shippingContactRequired: Boolean?, emailRequired: Boolean?, phoneNumberRequired: Boolean?, googlePayMerchantId: String?, googlePayEnvironment: GooglePayEnvironment?, googlePayGateway: String?, googlePayGatewayMerchantId: String?): PaymentRequest { - return PaymentRequest(applePayMerchantIdentifier, merchantName, countryCode, currencyCode, paymentItems, merchantCapabilities, supportedNetworks, shippingType, shippingMethods, billingContactRequired, shippingContactRequired, emailRequired, phoneNumberRequired, googlePayMerchantId, googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId) + private fun fromCpp(applePayMerchantIdentifier: String?, merchantName: String?, countryCode: String, currencyCode: String, paymentItems: Array, merchantCapabilities: Array, supportedNetworks: Array, shippingType: String?, shippingMethods: Array?, billingContactRequired: Boolean?, shippingContactRequired: Boolean?, emailRequired: Boolean?, phoneNumberRequired: Boolean?, googlePayMerchantId: String?, googlePayEnvironment: GooglePayEnvironment?, googlePayGateway: String?, googlePayGatewayMerchantId: String?, googlePayAllowedAuthMethods: Array?): PaymentRequest { + return PaymentRequest(applePayMerchantIdentifier, merchantName, countryCode, currencyCode, paymentItems, merchantCapabilities, supportedNetworks, shippingType, shippingMethods, billingContactRequired, shippingContactRequired, emailRequired, phoneNumberRequired, googlePayMerchantId, googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, googlePayAllowedAuthMethods) } } } diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp index 5c44955..f0e242c 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp @@ -32,6 +32,8 @@ namespace margelo::nitro::pay { class HybridPaymentHandlerSpec; } namespace margelo::nitro::pay { struct PKSecureElementPass; } // Forward declaration of `PassActivationState` to properly resolve imports. namespace margelo::nitro::pay { enum class PassActivationState; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } // Forward declaration of `PayServiceStatus` to properly resolve imports. namespace margelo::nitro::pay { struct PayServiceStatus; } // Forward declaration of `PaymentAuthorizationResult` to properly resolve imports. @@ -81,6 +83,7 @@ namespace NitroPay { class HybridPaymentHandlerSpec_cxx; } #include "PKSecureElementPass.hpp" #include "PassActivationState.hpp" #include "PayServiceStatus.hpp" +#include "PayServiceStatusOptions.hpp" #include "PaymentAuthorizationResult.hpp" #include "PaymentAuthorizationStatus.hpp" #include "PaymentContact.hpp" @@ -160,6 +163,47 @@ namespace margelo::nitro::pay::bridge::swift { using std__weak_ptr_HybridApplePayButtonSpec_ = std::weak_ptr; inline std__weak_ptr_HybridApplePayButtonSpec_ weakify_std__shared_ptr_HybridApplePayButtonSpec_(const std::shared_ptr& strong) noexcept { return strong; } + // pragma MARK: std::vector + /** + * Specialized version of `std::vector`. + */ + using std__vector_std__string_ = std::vector; + inline std::vector create_std__vector_std__string_(size_t size) noexcept { + std::vector vector; + vector.reserve(size); + return vector; + } + + // pragma MARK: std::optional> + /** + * Specialized version of `std::optional>`. + */ + using std__optional_std__vector_std__string__ = std::optional>; + inline std::optional> create_std__optional_std__vector_std__string__(const std::vector& value) noexcept { + return std::optional>(value); + } + inline bool has_value_std__optional_std__vector_std__string__(const std::optional>& optional) noexcept { + return optional.has_value(); + } + inline std::vector get_std__optional_std__vector_std__string__(const std::optional>& optional) noexcept { + return optional.value(); + } + + // pragma MARK: std::optional + /** + * Specialized version of `std::optional`. + */ + using std__optional_PayServiceStatusOptions_ = std::optional; + inline std::optional create_std__optional_PayServiceStatusOptions_(const PayServiceStatusOptions& value) noexcept { + return std::optional(value); + } + inline bool has_value_std__optional_PayServiceStatusOptions_(const std::optional& optional) noexcept { + return optional.has_value(); + } + inline PayServiceStatusOptions get_std__optional_PayServiceStatusOptions_(const std::optional& optional) noexcept { + return optional.value(); + } + // pragma MARK: std::optional /** * Specialized version of `std::optional`. @@ -424,17 +468,6 @@ namespace margelo::nitro::pay::bridge::swift { return vector; } - // pragma MARK: std::vector - /** - * Specialized version of `std::vector`. - */ - using std__vector_std__string_ = std::vector; - inline std::vector create_std__vector_std__string_(size_t size) noexcept { - std::vector vector; - vector.reserve(size); - return vector; - } - // pragma MARK: std::vector /** * Specialized version of `std::vector`. diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp index 120c346..16f2fc4 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp @@ -36,6 +36,8 @@ namespace margelo::nitro::pay { class HybridPaymentHandlerSpec; } namespace margelo::nitro::pay { struct PKSecureElementPass; } // Forward declaration of `PassActivationState` to properly resolve imports. namespace margelo::nitro::pay { enum class PassActivationState; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } // Forward declaration of `PayServiceStatus` to properly resolve imports. namespace margelo::nitro::pay { struct PayServiceStatus; } // Forward declaration of `PaymentAuthorizationResult` to properly resolve imports. @@ -83,6 +85,7 @@ namespace margelo::nitro::pay { struct StartPaymentOptions; } #include "PKSecureElementPass.hpp" #include "PassActivationState.hpp" #include "PayServiceStatus.hpp" +#include "PayServiceStatusOptions.hpp" #include "PaymentAuthorizationResult.hpp" #include "PaymentAuthorizationStatus.hpp" #include "PaymentContact.hpp" diff --git a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp index dc10f54..7f6decc 100644 --- a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp +++ b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp @@ -14,6 +14,8 @@ namespace NitroPay { class HybridPaymentHandlerSpec_cxx; } // Forward declaration of `PayServiceStatus` to properly resolve imports. namespace margelo::nitro::pay { struct PayServiceStatus; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } // Forward declaration of `PaymentResult` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentResult; } // Forward declaration of `PaymentToken` to properly resolve imports. @@ -64,10 +66,12 @@ namespace margelo::nitro::pay { struct PaymentDetails; } namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include "PayServiceStatus.hpp" +#include "PayServiceStatusOptions.hpp" +#include +#include +#include #include "PaymentResult.hpp" #include -#include -#include #include "PaymentToken.hpp" #include "PaymentMethod.hpp" #include "PaymentNetwork.hpp" @@ -77,7 +81,6 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include "CNContact.hpp" #include "CNContactType.hpp" #include "CNLabeledPhoneNumber.hpp" -#include #include "CNPhoneNumber.hpp" #include "CNLabeledEmailAddress.hpp" #include "CNLabeledPostalAddress.hpp" @@ -145,8 +148,8 @@ namespace margelo::nitro::pay { public: // Methods - inline PayServiceStatus payServiceStatus() override { - auto __result = _swiftPart.payServiceStatus(); + inline PayServiceStatus payServiceStatus(const std::optional& options) override { + auto __result = _swiftPart.payServiceStatus(options); if (__result.hasError()) [[unlikely]] { std::rethrow_exception(__result.error()); } diff --git a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift index 68d9884..70510aa 100644 --- a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift +++ b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift @@ -13,7 +13,7 @@ public protocol HybridPaymentHandlerSpec_protocol: HybridObject { // Methods - func payServiceStatus() throws -> PayServiceStatus + func payServiceStatus(options: PayServiceStatusOptions?) throws -> PayServiceStatus func startPayment(request: PaymentRequest, options: StartPaymentOptions?) throws -> Promise func canMakePayments(usingNetworks: [String]) throws -> Bool func isPaymentInProgress() throws -> Bool diff --git a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift index bb4876d..0663d3e 100644 --- a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift +++ b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift @@ -125,9 +125,9 @@ open class HybridPaymentHandlerSpec_cxx { // Methods @inline(__always) - public final func payServiceStatus() -> bridge.Result_PayServiceStatus_ { + public final func payServiceStatus(options: bridge.std__optional_PayServiceStatusOptions_) -> bridge.Result_PayServiceStatus_ { do { - let __result = try self.__implementation.payServiceStatus() + let __result = try self.__implementation.payServiceStatus(options: options.value) let __resultCpp = __result return bridge.create_Result_PayServiceStatus_(__resultCpp) } catch (let __error) { diff --git a/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift b/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift new file mode 100644 index 0000000..5d45704 --- /dev/null +++ b/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift @@ -0,0 +1,72 @@ +/// +/// PayServiceStatusOptions.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 `PayServiceStatusOptions`, backed by a C++ struct. + */ +public typealias PayServiceStatusOptions = margelo.nitro.pay.PayServiceStatusOptions + +public extension PayServiceStatusOptions { + private typealias bridge = margelo.nitro.pay.bridge.swift + + /** + * Create a new instance of `PayServiceStatusOptions`. + */ + init(supportedNetworks: [String]?, googlePayAllowedAuthMethods: [String]?) { + self.init({ () -> bridge.std__optional_std__vector_std__string__ in + if let __unwrappedValue = supportedNetworks { + return bridge.create_std__optional_std__vector_std__string__({ () -> bridge.std__vector_std__string_ in + var __vector = bridge.create_std__vector_std__string_(__unwrappedValue.count) + for __item in __unwrappedValue { + __vector.push_back(std.string(__item)) + } + return __vector + }()) + } 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 + var __vector = bridge.create_std__vector_std__string_(__unwrappedValue.count) + for __item in __unwrappedValue { + __vector.push_back(std.string(__item)) + } + return __vector + }()) + } else { + return .init() + } + }()) + } + + @inline(__always) + var supportedNetworks: [String]? { + return { () -> [String]? in + if bridge.has_value_std__optional_std__vector_std__string__(self.__supportedNetworks) { + let __unwrapped = bridge.get_std__optional_std__vector_std__string__(self.__supportedNetworks) + return __unwrapped.map({ __item in String(__item) }) + } else { + return nil + } + }() + } + + @inline(__always) + var googlePayAllowedAuthMethods: [String]? { + return { () -> [String]? in + if bridge.has_value_std__optional_std__vector_std__string__(self.__googlePayAllowedAuthMethods) { + let __unwrapped = bridge.get_std__optional_std__vector_std__string__(self.__googlePayAllowedAuthMethods) + return __unwrapped.map({ __item in String(__item) }) + } else { + return nil + } + }() + } +} diff --git a/package/nitrogen/generated/ios/swift/PaymentNetwork.swift b/package/nitrogen/generated/ios/swift/PaymentNetwork.swift index ef2c76e..1477de8 100644 --- a/package/nitrogen/generated/ios/swift/PaymentNetwork.swift +++ b/package/nitrogen/generated/ios/swift/PaymentNetwork.swift @@ -39,6 +39,52 @@ public extension PaymentNetwork { self = .interac case "privateLabel": self = .privatelabel + case "cartesBancaires": + self = .cartesbancaires + case "chinaUnionPay": + self = .chinaunionpay + case "dankort": + self = .dankort + case "eftpos": + self = .eftpos + case "girocard": + self = .girocard + case "mada": + self = .mada + case "mir": + self = .mir + case "quicPay": + self = .quicpay + case "suica": + self = .suica + case "vPay": + self = .vpay + case "waon": + self = .waon + case "nanaco": + self = .nanaco + case "bancontact": + self = .bancontact + case "postFinance": + self = .postfinance + case "pagoBancomat": + self = .pagobancomat + case "tmoney": + self = .tmoney + case "meeza": + self = .meeza + case "napas": + self = .napas + case "bankAxept": + self = .bankaxept + case "himyan": + self = .himyan + case "jaywan": + self = .jaywan + case "myDebit": + self = .mydebit + case "unknown": + self = .unknown default: return nil } @@ -71,6 +117,52 @@ public extension PaymentNetwork { return "interac" case .privatelabel: return "privateLabel" + case .cartesbancaires: + return "cartesBancaires" + case .chinaunionpay: + return "chinaUnionPay" + case .dankort: + return "dankort" + case .eftpos: + return "eftpos" + case .girocard: + return "girocard" + case .mada: + return "mada" + case .mir: + return "mir" + case .quicpay: + return "quicPay" + case .suica: + return "suica" + case .vpay: + return "vPay" + case .waon: + return "waon" + case .nanaco: + return "nanaco" + case .bancontact: + return "bancontact" + case .postfinance: + return "postFinance" + case .pagobancomat: + return "pagoBancomat" + case .tmoney: + return "tmoney" + case .meeza: + return "meeza" + case .napas: + return "napas" + case .bankaxept: + return "bankAxept" + case .himyan: + return "himyan" + case .jaywan: + return "jaywan" + case .mydebit: + return "myDebit" + case .unknown: + return "unknown" } } } diff --git a/package/nitrogen/generated/ios/swift/PaymentRequest.swift b/package/nitrogen/generated/ios/swift/PaymentRequest.swift index 7df29ad..691761a 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?, countryCode: String, currencyCode: String, paymentItems: [PaymentItem], merchantCapabilities: [String], supportedNetworks: [String], shippingType: String?, shippingMethods: [ShippingMethod]?, billingContactRequired: Bool?, shippingContactRequired: Bool?, emailRequired: Bool?, phoneNumberRequired: Bool?, googlePayMerchantId: String?, googlePayEnvironment: GooglePayEnvironment?, googlePayGateway: String?, googlePayGatewayMerchantId: String?) { + init(applePayMerchantIdentifier: String?, merchantName: String?, countryCode: String, currencyCode: String, paymentItems: [PaymentItem], merchantCapabilities: [String], supportedNetworks: [String], shippingType: String?, shippingMethods: [ShippingMethod]?, billingContactRequired: Bool?, shippingContactRequired: Bool?, emailRequired: Bool?, phoneNumberRequired: Bool?, googlePayMerchantId: String?, googlePayEnvironment: GooglePayEnvironment?, googlePayGateway: String?, googlePayGatewayMerchantId: String?, googlePayAllowedAuthMethods: [String]?) { self.init({ () -> bridge.std__optional_std__string_ in if let __unwrappedValue = applePayMerchantIdentifier { return bridge.create_std__optional_std__string_(std.string(__unwrappedValue)) @@ -115,6 +115,18 @@ public extension PaymentRequest { } 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 + var __vector = bridge.create_std__vector_std__string_(__unwrappedValue.count) + for __item in __unwrappedValue { + __vector.push_back(std.string(__item)) + } + return __vector + }()) + } else { + return .init() + } }()) } @@ -279,4 +291,16 @@ public extension PaymentRequest { } }() } + + @inline(__always) + var googlePayAllowedAuthMethods: [String]? { + return { () -> [String]? in + if bridge.has_value_std__optional_std__vector_std__string__(self.__googlePayAllowedAuthMethods) { + let __unwrapped = bridge.get_std__optional_std__vector_std__string__(self.__googlePayAllowedAuthMethods) + return __unwrapped.map({ __item in String(__item) }) + } else { + return nil + } + }() + } } diff --git a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp index bab6775..b2f6949 100644 --- a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp +++ b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp @@ -20,6 +20,10 @@ namespace margelo::nitro::pay { prototype.registerHybridSetter("theme", &HybridGooglePayButtonSpec::setTheme); prototype.registerHybridGetter("radius", &HybridGooglePayButtonSpec::getRadius); prototype.registerHybridSetter("radius", &HybridGooglePayButtonSpec::setRadius); + prototype.registerHybridGetter("supportedNetworks", &HybridGooglePayButtonSpec::getSupportedNetworks); + prototype.registerHybridSetter("supportedNetworks", &HybridGooglePayButtonSpec::setSupportedNetworks); + prototype.registerHybridGetter("allowedAuthMethods", &HybridGooglePayButtonSpec::getAllowedAuthMethods); + prototype.registerHybridSetter("allowedAuthMethods", &HybridGooglePayButtonSpec::setAllowedAuthMethods); prototype.registerHybridGetter("onPress", &HybridGooglePayButtonSpec::getOnPress); prototype.registerHybridSetter("onPress", &HybridGooglePayButtonSpec::setOnPress); }); diff --git a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp index 1efb4bb..d93bbc4 100644 --- a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp +++ b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp @@ -21,6 +21,8 @@ namespace margelo::nitro::pay { enum class GooglePayButtonTheme; } #include "GooglePayButtonType.hpp" #include "GooglePayButtonTheme.hpp" #include +#include +#include #include namespace margelo::nitro::pay { @@ -56,6 +58,10 @@ namespace margelo::nitro::pay { virtual void setTheme(GooglePayButtonTheme theme) = 0; virtual std::optional getRadius() = 0; virtual void setRadius(std::optional radius) = 0; + virtual std::optional> getSupportedNetworks() = 0; + virtual void setSupportedNetworks(const std::optional>& supportedNetworks) = 0; + virtual std::optional> getAllowedAuthMethods() = 0; + virtual void setAllowedAuthMethods(const std::optional>& allowedAuthMethods) = 0; virtual std::optional> getOnPress() = 0; virtual void setOnPress(const std::optional>& onPress) = 0; diff --git a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp index f92e5c5..8b385b6 100644 --- a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp +++ b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp @@ -15,6 +15,8 @@ // Forward declaration of `PayServiceStatus` to properly resolve imports. namespace margelo::nitro::pay { struct PayServiceStatus; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } // Forward declaration of `PaymentResult` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentResult; } // Forward declaration of `PaymentRequest` to properly resolve imports. @@ -23,11 +25,12 @@ namespace margelo::nitro::pay { struct PaymentRequest; } namespace margelo::nitro::pay { struct StartPaymentOptions; } #include "PayServiceStatus.hpp" +#include "PayServiceStatusOptions.hpp" +#include #include "PaymentResult.hpp" #include #include "PaymentRequest.hpp" #include "StartPaymentOptions.hpp" -#include #include #include @@ -62,7 +65,7 @@ namespace margelo::nitro::pay { public: // Methods - virtual PayServiceStatus payServiceStatus() = 0; + virtual PayServiceStatus payServiceStatus(const std::optional& options) = 0; virtual std::shared_ptr> startPayment(const PaymentRequest& request, const std::optional& options) = 0; virtual bool canMakePayments(const std::vector& usingNetworks) = 0; virtual bool isPaymentInProgress() = 0; diff --git a/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp b/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp new file mode 100644 index 0000000..8b9fce5 --- /dev/null +++ b/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp @@ -0,0 +1,89 @@ +/// +/// PayServiceStatusOptions.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 + + + +#include +#include +#include + +namespace margelo::nitro::pay { + + /** + * A struct which can be represented as a JavaScript object (PayServiceStatusOptions). + */ + struct PayServiceStatusOptions final { + public: + std::optional> supportedNetworks SWIFT_PRIVATE; + std::optional> googlePayAllowedAuthMethods SWIFT_PRIVATE; + + public: + PayServiceStatusOptions() = default; + explicit PayServiceStatusOptions(std::optional> supportedNetworks, std::optional> googlePayAllowedAuthMethods): supportedNetworks(supportedNetworks), googlePayAllowedAuthMethods(googlePayAllowedAuthMethods) {} + + public: + friend bool operator==(const PayServiceStatusOptions& lhs, const PayServiceStatusOptions& rhs) = default; + }; + +} // namespace margelo::nitro::pay + +namespace margelo::nitro { + + // C++ PayServiceStatusOptions <> JS PayServiceStatusOptions (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::pay::PayServiceStatusOptions fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::pay::PayServiceStatusOptions( + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks"))), + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::PayServiceStatusOptions& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks"), JSIConverter>>::toJSI(runtime, arg.supportedNetworks)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"), JSIConverter>>::toJSI(runtime, arg.googlePayAllowedAuthMethods)); + 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, "supportedNetworks")))) return false; + if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/package/nitrogen/generated/shared/c++/PaymentNetwork.hpp b/package/nitrogen/generated/shared/c++/PaymentNetwork.hpp index 1e27dde..071b8b0 100644 --- a/package/nitrogen/generated/shared/c++/PaymentNetwork.hpp +++ b/package/nitrogen/generated/shared/c++/PaymentNetwork.hpp @@ -40,6 +40,29 @@ namespace margelo::nitro::pay { IDCREDIT SWIFT_NAME(idcredit) = 8, INTERAC SWIFT_NAME(interac) = 9, PRIVATELABEL SWIFT_NAME(privatelabel) = 10, + CARTESBANCAIRES SWIFT_NAME(cartesbancaires) = 11, + CHINAUNIONPAY SWIFT_NAME(chinaunionpay) = 12, + DANKORT SWIFT_NAME(dankort) = 13, + EFTPOS SWIFT_NAME(eftpos) = 14, + GIROCARD SWIFT_NAME(girocard) = 15, + MADA SWIFT_NAME(mada) = 16, + MIR SWIFT_NAME(mir) = 17, + QUICPAY SWIFT_NAME(quicpay) = 18, + SUICA SWIFT_NAME(suica) = 19, + VPAY SWIFT_NAME(vpay) = 20, + WAON SWIFT_NAME(waon) = 21, + NANACO SWIFT_NAME(nanaco) = 22, + BANCONTACT SWIFT_NAME(bancontact) = 23, + POSTFINANCE SWIFT_NAME(postfinance) = 24, + PAGOBANCOMAT SWIFT_NAME(pagobancomat) = 25, + TMONEY SWIFT_NAME(tmoney) = 26, + MEEZA SWIFT_NAME(meeza) = 27, + NAPAS SWIFT_NAME(napas) = 28, + BANKAXEPT SWIFT_NAME(bankaxept) = 29, + HIMYAN SWIFT_NAME(himyan) = 30, + JAYWAN SWIFT_NAME(jaywan) = 31, + MYDEBIT SWIFT_NAME(mydebit) = 32, + UNKNOWN SWIFT_NAME(unknown) = 33, } CLOSED_ENUM; } // namespace margelo::nitro::pay @@ -63,6 +86,29 @@ namespace margelo::nitro { case hashString("idcredit"): return margelo::nitro::pay::PaymentNetwork::IDCREDIT; case hashString("interac"): return margelo::nitro::pay::PaymentNetwork::INTERAC; case hashString("privateLabel"): return margelo::nitro::pay::PaymentNetwork::PRIVATELABEL; + case hashString("cartesBancaires"): return margelo::nitro::pay::PaymentNetwork::CARTESBANCAIRES; + case hashString("chinaUnionPay"): return margelo::nitro::pay::PaymentNetwork::CHINAUNIONPAY; + case hashString("dankort"): return margelo::nitro::pay::PaymentNetwork::DANKORT; + case hashString("eftpos"): return margelo::nitro::pay::PaymentNetwork::EFTPOS; + case hashString("girocard"): return margelo::nitro::pay::PaymentNetwork::GIROCARD; + case hashString("mada"): return margelo::nitro::pay::PaymentNetwork::MADA; + case hashString("mir"): return margelo::nitro::pay::PaymentNetwork::MIR; + case hashString("quicPay"): return margelo::nitro::pay::PaymentNetwork::QUICPAY; + case hashString("suica"): return margelo::nitro::pay::PaymentNetwork::SUICA; + case hashString("vPay"): return margelo::nitro::pay::PaymentNetwork::VPAY; + case hashString("waon"): return margelo::nitro::pay::PaymentNetwork::WAON; + case hashString("nanaco"): return margelo::nitro::pay::PaymentNetwork::NANACO; + case hashString("bancontact"): return margelo::nitro::pay::PaymentNetwork::BANCONTACT; + case hashString("postFinance"): return margelo::nitro::pay::PaymentNetwork::POSTFINANCE; + case hashString("pagoBancomat"): return margelo::nitro::pay::PaymentNetwork::PAGOBANCOMAT; + case hashString("tmoney"): return margelo::nitro::pay::PaymentNetwork::TMONEY; + case hashString("meeza"): return margelo::nitro::pay::PaymentNetwork::MEEZA; + case hashString("napas"): return margelo::nitro::pay::PaymentNetwork::NAPAS; + case hashString("bankAxept"): return margelo::nitro::pay::PaymentNetwork::BANKAXEPT; + case hashString("himyan"): return margelo::nitro::pay::PaymentNetwork::HIMYAN; + case hashString("jaywan"): return margelo::nitro::pay::PaymentNetwork::JAYWAN; + case hashString("myDebit"): return margelo::nitro::pay::PaymentNetwork::MYDEBIT; + case hashString("unknown"): return margelo::nitro::pay::PaymentNetwork::UNKNOWN; default: [[unlikely]] throw std::invalid_argument("Cannot convert \"" + unionValue + "\" to enum PaymentNetwork - invalid value!"); } @@ -80,6 +126,29 @@ namespace margelo::nitro { case margelo::nitro::pay::PaymentNetwork::IDCREDIT: return JSIConverter::toJSI(runtime, "idcredit"); case margelo::nitro::pay::PaymentNetwork::INTERAC: return JSIConverter::toJSI(runtime, "interac"); case margelo::nitro::pay::PaymentNetwork::PRIVATELABEL: return JSIConverter::toJSI(runtime, "privateLabel"); + case margelo::nitro::pay::PaymentNetwork::CARTESBANCAIRES: return JSIConverter::toJSI(runtime, "cartesBancaires"); + case margelo::nitro::pay::PaymentNetwork::CHINAUNIONPAY: return JSIConverter::toJSI(runtime, "chinaUnionPay"); + case margelo::nitro::pay::PaymentNetwork::DANKORT: return JSIConverter::toJSI(runtime, "dankort"); + case margelo::nitro::pay::PaymentNetwork::EFTPOS: return JSIConverter::toJSI(runtime, "eftpos"); + case margelo::nitro::pay::PaymentNetwork::GIROCARD: return JSIConverter::toJSI(runtime, "girocard"); + case margelo::nitro::pay::PaymentNetwork::MADA: return JSIConverter::toJSI(runtime, "mada"); + case margelo::nitro::pay::PaymentNetwork::MIR: return JSIConverter::toJSI(runtime, "mir"); + case margelo::nitro::pay::PaymentNetwork::QUICPAY: return JSIConverter::toJSI(runtime, "quicPay"); + case margelo::nitro::pay::PaymentNetwork::SUICA: return JSIConverter::toJSI(runtime, "suica"); + case margelo::nitro::pay::PaymentNetwork::VPAY: return JSIConverter::toJSI(runtime, "vPay"); + case margelo::nitro::pay::PaymentNetwork::WAON: return JSIConverter::toJSI(runtime, "waon"); + case margelo::nitro::pay::PaymentNetwork::NANACO: return JSIConverter::toJSI(runtime, "nanaco"); + case margelo::nitro::pay::PaymentNetwork::BANCONTACT: return JSIConverter::toJSI(runtime, "bancontact"); + case margelo::nitro::pay::PaymentNetwork::POSTFINANCE: return JSIConverter::toJSI(runtime, "postFinance"); + case margelo::nitro::pay::PaymentNetwork::PAGOBANCOMAT: return JSIConverter::toJSI(runtime, "pagoBancomat"); + case margelo::nitro::pay::PaymentNetwork::TMONEY: return JSIConverter::toJSI(runtime, "tmoney"); + case margelo::nitro::pay::PaymentNetwork::MEEZA: return JSIConverter::toJSI(runtime, "meeza"); + case margelo::nitro::pay::PaymentNetwork::NAPAS: return JSIConverter::toJSI(runtime, "napas"); + case margelo::nitro::pay::PaymentNetwork::BANKAXEPT: return JSIConverter::toJSI(runtime, "bankAxept"); + case margelo::nitro::pay::PaymentNetwork::HIMYAN: return JSIConverter::toJSI(runtime, "himyan"); + case margelo::nitro::pay::PaymentNetwork::JAYWAN: return JSIConverter::toJSI(runtime, "jaywan"); + case margelo::nitro::pay::PaymentNetwork::MYDEBIT: return JSIConverter::toJSI(runtime, "myDebit"); + case margelo::nitro::pay::PaymentNetwork::UNKNOWN: return JSIConverter::toJSI(runtime, "unknown"); default: [[unlikely]] throw std::invalid_argument("Cannot convert PaymentNetwork to JS - invalid value: " + std::to_string(static_cast(arg)) + "!"); @@ -102,6 +171,29 @@ namespace margelo::nitro { case hashString("idcredit"): case hashString("interac"): case hashString("privateLabel"): + case hashString("cartesBancaires"): + case hashString("chinaUnionPay"): + case hashString("dankort"): + case hashString("eftpos"): + case hashString("girocard"): + case hashString("mada"): + case hashString("mir"): + case hashString("quicPay"): + case hashString("suica"): + case hashString("vPay"): + case hashString("waon"): + case hashString("nanaco"): + case hashString("bancontact"): + case hashString("postFinance"): + case hashString("pagoBancomat"): + case hashString("tmoney"): + case hashString("meeza"): + case hashString("napas"): + case hashString("bankAxept"): + case hashString("himyan"): + case hashString("jaywan"): + case hashString("myDebit"): + case hashString("unknown"): return true; default: return false; diff --git a/package/nitrogen/generated/shared/c++/PaymentRequest.hpp b/package/nitrogen/generated/shared/c++/PaymentRequest.hpp index 736d3df..fd3b8d5 100644 --- a/package/nitrogen/generated/shared/c++/PaymentRequest.hpp +++ b/package/nitrogen/generated/shared/c++/PaymentRequest.hpp @@ -66,10 +66,11 @@ namespace margelo::nitro::pay { std::optional googlePayEnvironment SWIFT_PRIVATE; std::optional googlePayGateway SWIFT_PRIVATE; std::optional googlePayGatewayMerchantId SWIFT_PRIVATE; + std::optional> googlePayAllowedAuthMethods SWIFT_PRIVATE; public: PaymentRequest() = default; - explicit PaymentRequest(std::optional applePayMerchantIdentifier, std::optional merchantName, 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 googlePayMerchantId, std::optional googlePayEnvironment, std::optional googlePayGateway, std::optional googlePayGatewayMerchantId): applePayMerchantIdentifier(applePayMerchantIdentifier), merchantName(merchantName), countryCode(countryCode), currencyCode(currencyCode), paymentItems(paymentItems), merchantCapabilities(merchantCapabilities), supportedNetworks(supportedNetworks), shippingType(shippingType), shippingMethods(shippingMethods), billingContactRequired(billingContactRequired), shippingContactRequired(shippingContactRequired), emailRequired(emailRequired), phoneNumberRequired(phoneNumberRequired), googlePayMerchantId(googlePayMerchantId), googlePayEnvironment(googlePayEnvironment), googlePayGateway(googlePayGateway), googlePayGatewayMerchantId(googlePayGatewayMerchantId) {} + explicit PaymentRequest(std::optional applePayMerchantIdentifier, std::optional merchantName, 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 googlePayMerchantId, std::optional googlePayEnvironment, std::optional googlePayGateway, std::optional googlePayGatewayMerchantId, std::optional> googlePayAllowedAuthMethods): applePayMerchantIdentifier(applePayMerchantIdentifier), merchantName(merchantName), countryCode(countryCode), currencyCode(currencyCode), paymentItems(paymentItems), merchantCapabilities(merchantCapabilities), supportedNetworks(supportedNetworks), shippingType(shippingType), shippingMethods(shippingMethods), billingContactRequired(billingContactRequired), shippingContactRequired(shippingContactRequired), emailRequired(emailRequired), phoneNumberRequired(phoneNumberRequired), googlePayMerchantId(googlePayMerchantId), googlePayEnvironment(googlePayEnvironment), googlePayGateway(googlePayGateway), googlePayGatewayMerchantId(googlePayGatewayMerchantId), googlePayAllowedAuthMethods(googlePayAllowedAuthMethods) {} public: friend bool operator==(const PaymentRequest& lhs, const PaymentRequest& rhs) = default; @@ -101,7 +102,8 @@ namespace margelo::nitro { JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayMerchantId"))), 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, "googlePayGatewayMerchantId"))), + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::PaymentRequest& arg) { @@ -123,6 +125,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, "googlePayAllowedAuthMethods"), JSIConverter>>::toJSI(runtime, arg.googlePayAllowedAuthMethods)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -150,6 +153,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, "googlePayAllowedAuthMethods")))) return false; return true; } }; diff --git a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp index 10f49f9..899713f 100644 --- a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp +++ b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp @@ -56,6 +56,26 @@ namespace margelo::nitro::pay::views { throw std::runtime_error(std::string("GooglePayButton.radius: ") + exc.what()); } }()), + supportedNetworks([&]() -> CachedProp>> { + try { + const react::RawValue* rawValue = rawProps.at("supportedNetworks", nullptr, nullptr); + if (rawValue == nullptr) return sourceProps.supportedNetworks; + const auto& [runtime, value] = (std::pair)*rawValue; + return CachedProp>>::fromRawValue(*runtime, value, sourceProps.supportedNetworks); + } catch (const std::exception& exc) { + throw std::runtime_error(std::string("GooglePayButton.supportedNetworks: ") + exc.what()); + } + }()), + allowedAuthMethods([&]() -> CachedProp>> { + try { + const react::RawValue* rawValue = rawProps.at("allowedAuthMethods", nullptr, nullptr); + if (rawValue == nullptr) return sourceProps.allowedAuthMethods; + const auto& [runtime, value] = (std::pair)*rawValue; + return CachedProp>>::fromRawValue(*runtime, value, sourceProps.allowedAuthMethods); + } catch (const std::exception& exc) { + throw std::runtime_error(std::string("GooglePayButton.allowedAuthMethods: ") + exc.what()); + } + }()), onPress([&]() -> CachedProp>> { try { const react::RawValue* rawValue = rawProps.at("onPress", nullptr, nullptr); @@ -82,6 +102,8 @@ namespace margelo::nitro::pay::views { case hashString("buttonType"): return true; case hashString("theme"): return true; case hashString("radius"): return true; + case hashString("supportedNetworks"): return true; + case hashString("allowedAuthMethods"): return true; case hashString("onPress"): return true; case hashString("hybridRef"): return true; default: return false; diff --git a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp index fd0a79d..cdce648 100644 --- a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp +++ b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp @@ -19,6 +19,8 @@ #include "GooglePayButtonType.hpp" #include "GooglePayButtonTheme.hpp" #include +#include +#include #include #include #include "HybridGooglePayButtonSpec.hpp" @@ -46,6 +48,8 @@ namespace margelo::nitro::pay::views { CachedProp buttonType; CachedProp theme; CachedProp> radius; + CachedProp>> supportedNetworks; + CachedProp>> allowedAuthMethods; CachedProp>> onPress; CachedProp& /* ref */)>>> hybridRef; diff --git a/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json b/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json index 56110b6..eab66c9 100644 --- a/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json +++ b/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json @@ -7,6 +7,8 @@ "buttonType": true, "theme": true, "radius": true, + "supportedNetworks": true, + "allowedAuthMethods": true, "onPress": true, "hybridRef": true } diff --git a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts index a3ffa11..12ffd31 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts @@ -34,7 +34,7 @@ function createDeferred() { describe('usePaymentCheckout integration', () => { beforeEach(() => { - mockPayServiceStatus.mockReturnValue({ + mockPayServiceStatus.mockReset().mockReturnValue({ canMakePayments: true, canSetupCards: true, }) @@ -62,6 +62,50 @@ describe('usePaymentCheckout integration', () => { expect(result.current.canSetupCards).toBe(true) }) + it('checks the status for the default cards', async () => { + const { result } = renderCheckout() + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) + expect(mockPayServiceStatus).toHaveBeenCalledWith({ + supportedNetworks: ['visa', 'mastercard', 'amex', 'discover'], + }) + }) + + it('checks the status for the configured cards, again only when they change', async () => { + const config: UsePaymentCheckoutConfig = { + merchantName: 'Store A', + supportedNetworks: ['visa', 'mastercard'], + googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + } + const { result, rerender } = renderWithConfig(config) + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + expect(mockPayServiceStatus).toHaveBeenCalledWith({ + supportedNetworks: ['visa', 'mastercard'], + googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + }) + expect(result.current.paymentRequest).toMatchObject({ + supportedNetworks: ['visa', 'mastercard'], + googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + }) + + rerender({ ...config, merchantName: 'Store B' }) + expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) + + rerender({ ...config, supportedNetworks: ['visa'] }) + expect(mockPayServiceStatus).toHaveBeenCalledTimes(2) + expect(mockPayServiceStatus).toHaveBeenLastCalledWith({ + supportedNetworks: ['visa'], + googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + }) + }) + it('falls back to unavailable status when status check fails', async () => { mockPayServiceStatus.mockImplementationOnce(() => { throw new Error('Native status failure') @@ -441,6 +485,10 @@ describe('usePaymentCheckout integration', () => { googlePayEnvironment: ['TEST', 'PRODUCTION'], googlePayGateway: ['stripe', 'adyen'], googlePayGatewayMerchantId: ['gateway-a', 'gateway-b'], + googlePayAllowedAuthMethods: [ + ['PAN_ONLY', 'CRYPTOGRAM_3DS'], + ['CRYPTOGRAM_3DS'], + ], billingContactRequired: [false, true], shippingContactRequired: [false, true], emailRequired: [false, true], diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index 96f89d4..5b96aaf 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -13,8 +13,10 @@ import type { PaymentResult, PaymentItem, PayServiceStatus, + GooglePayAuthMethod, GooglePayEnvironment, MerchantCapability, + PayServiceStatusOptions, PaymentToken, PaymentAuthorizationResult, PaymentDetails, @@ -26,6 +28,8 @@ import { sanitizePaymentRequest, } from '../utils' +const DEFAULT_SUPPORTED_NETWORKS = ['visa', 'mastercard', 'amex', 'discover'] + // 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. @@ -57,8 +61,10 @@ export interface UsePaymentCheckoutConfig { currencyCode?: string /** - * Supported card networks for the payment sheet. - * Defaults to `['visa', 'mastercard', 'amex', 'discover']`. + * Card networks the payer can pay with, as `PaymentNetwork` values. + * Defaults to `['visa', 'mastercard', 'amex', 'discover']`. On Android, + * `canMakePayments` is checked for these networks too. See + * `PaymentRequest.supportedNetworks`. */ supportedNetworks?: string[] @@ -97,6 +103,13 @@ export interface UsePaymentCheckoutConfig { */ googlePayGatewayMerchantId?: string + /** + * How Google Pay may authenticate the card. Defaults to both + * `'PAN_ONLY'` and `'CRYPTOGRAM_3DS'`; pass `['CRYPTOGRAM_3DS']` to accept + * device tokens only. Android only. + */ + googlePayAllowedAuthMethods?: GooglePayAuthMethod[] + /** * Ask for the billing name and postal address, returned as * `result.billingContact`. See `PaymentRequest.billingContactRequired`. @@ -282,9 +295,18 @@ export function usePaymentCheckout( // Set synchronously, so two calls in the same frame still see each other. const isPaymentInFlight = useRef(false) + // Checked again when the accepted cards change, not on other config changes. + const statusOptionsKey = JSON.stringify({ + supportedNetworks: + stableRequestConfig.supportedNetworks ?? DEFAULT_SUPPORTED_NETWORKS, + googlePayAllowedAuthMethods: + stableRequestConfig.googlePayAllowedAuthMethods, + } satisfies PayServiceStatusOptions) + useEffect(() => { try { - const paymentStatus = getPaymentHandler().payServiceStatus() + const options: PayServiceStatusOptions = JSON.parse(statusOptionsKey) + const paymentStatus = getPaymentHandler().payServiceStatus(options) setStatus(paymentStatus) } catch (err) { console.error('Failed to check payment status:', err) @@ -292,7 +314,7 @@ export function usePaymentCheckout( } finally { setIsCheckingStatus(false) } - }, []) + }, [statusOptionsKey]) const total = useMemo(() => calculateTotal(items), [items]) @@ -301,13 +323,14 @@ export function usePaymentCheckout( merchantName, countryCode = 'US', currencyCode = 'USD', - supportedNetworks = ['visa', 'mastercard', 'amex', 'discover'], + supportedNetworks = DEFAULT_SUPPORTED_NETWORKS, merchantCapabilities = ['3DS'], applePayMerchantIdentifier, googlePayMerchantId, googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, + googlePayAllowedAuthMethods, billingContactRequired, shippingContactRequired, emailRequired, @@ -327,6 +350,7 @@ export function usePaymentCheckout( googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, + googlePayAllowedAuthMethods, billingContactRequired, shippingContactRequired, emailRequired, diff --git a/package/src/specs/GooglePayButton.nitro.ts b/package/src/specs/GooglePayButton.nitro.ts index 5dbe3f3..15a19dc 100644 --- a/package/src/specs/GooglePayButton.nitro.ts +++ b/package/src/specs/GooglePayButton.nitro.ts @@ -20,6 +20,13 @@ export interface GooglePayButtonProps extends HybridViewProps { buttonType: GooglePayButtonType theme: GooglePayButtonTheme radius?: number + /** + * As `PaymentRequest.supportedNetworks`. Pass the same values as the + * request, so the button shows a card the payer can use. + */ + supportedNetworks?: string[] + /** As `PaymentRequest.googlePayAllowedAuthMethods`. Defaults to both. */ + allowedAuthMethods?: string[] onPress?: () => void } diff --git a/package/src/specs/PaymentHandler.nitro.ts b/package/src/specs/PaymentHandler.nitro.ts index b0230d3..b00506a 100644 --- a/package/src/specs/PaymentHandler.nitro.ts +++ b/package/src/specs/PaymentHandler.nitro.ts @@ -1,6 +1,7 @@ import type { HybridObject } from 'react-native-nitro-modules' import type { PayServiceStatus, + PayServiceStatusOptions, PaymentRequest, PaymentResult, StartPaymentOptions, @@ -8,7 +9,7 @@ import type { export interface PaymentHandler extends HybridObject<{ ios: 'swift'; android: 'kotlin' }> { - payServiceStatus(): PayServiceStatus + payServiceStatus(options?: PayServiceStatusOptions): PayServiceStatus startPayment( request: PaymentRequest, options?: StartPaymentOptions diff --git a/package/src/types/Payment.ts b/package/src/types/Payment.ts index f5cbfbc..64233a8 100644 --- a/package/src/types/Payment.ts +++ b/package/src/types/Payment.ts @@ -14,6 +14,15 @@ export type PaymentMethodType = | 'prepaid' | 'store' +/** + * A card network. Use these names in `PaymentRequest.supportedNetworks`. + * + * Google Pay offers `visa`, `mastercard`, `amex`, `discover`, `jcb` and + * `interac`, plus `electron`, `maestro` and `elo` for Brazilian combo cards. + * Apple Pay offers all of them, some only on newer iOS versions. + * + * `'unknown'` only appears in results, for a network this library cannot name. + */ export type PaymentNetwork = | 'visa' | 'mastercard' @@ -26,6 +35,29 @@ export type PaymentNetwork = | 'idcredit' | 'interac' | 'privateLabel' + | 'cartesBancaires' + | 'chinaUnionPay' + | 'dankort' + | 'eftpos' + | 'girocard' + | 'mada' + | 'mir' + | 'quicPay' + | 'suica' + | 'vPay' + | 'waon' + | 'nanaco' + | 'bancontact' + | 'postFinance' + | 'pagoBancomat' + | 'tmoney' + | 'meeza' + | 'napas' + | 'bankAxept' + | 'himyan' + | 'jaywan' + | 'myDebit' + | 'unknown' export type PassActivationState = | 'activated' @@ -36,6 +68,14 @@ export type PassActivationState = export type GooglePayEnvironment = 'TEST' | 'PRODUCTION' +/** + * How Google Pay may authenticate a card. `'PAN_ONLY'` covers cards saved + * to the Google account and returns the card number; `'CRYPTOGRAM_3DS'` + * covers cards tokenized on the device and returns a 3-D Secure cryptogram. + * Google Pay does not offer `jcb` or `discover` with `'CRYPTOGRAM_3DS'`. + */ +export type GooglePayAuthMethod = 'PAN_ONLY' | 'CRYPTOGRAM_3DS' + /** * Apple Pay merchant capability. `'3DS'` and `'EMV'` are payment protocols * (EMV only covers China UnionPay); `'Credit'` and `'Debit'` limit the @@ -103,7 +143,12 @@ export interface ShippingMethod { } export interface PaymentMethod { + /** + * Describes the card to the payer, for example `'Visa 1234'`. Comes from + * the wallet; don't parse it. + */ displayName?: string + /** `'unknown'` for a network this library cannot name. */ network?: PaymentNetwork type: PaymentMethodType secureElementPass?: PKSecureElementPass // Available from iOS 13.4+ @@ -128,6 +173,12 @@ export interface PaymentRequest { // `MerchantCapability` values. Not typed as such: Nitro would generate a // native enum that rejects `'3ds'` or unknown values without a message. merchantCapabilities: string[] + /** + * `PaymentNetwork` values, matched ignoring case. An unknown name fails the + * payment. A network the platform does not offer is left out, and the + * payment fails when none is left: Google Pay has no `cartesBancaires`, + * for example, and Apple Pay has no `bancontact` before iOS 16. + */ supportedNetworks: string[] /** * A `ShippingType` value. iOS only; Android ignores it. An unknown value @@ -168,6 +219,12 @@ export interface PaymentRequest { googlePayEnvironment?: GooglePayEnvironment googlePayGateway?: string googlePayGatewayMerchantId?: string + /** + * `GooglePayAuthMethod` values, matched ignoring case. Defaults to both. + * Android only. An unknown value fails the payment. Not typed as + * `GooglePayAuthMethod` for the same reason as `merchantCapabilities`. + */ + googlePayAllowedAuthMethods?: string[] } /** @@ -236,5 +293,20 @@ export interface PayServiceStatus { canSetupCards: boolean } +/** + * The cards `payServiceStatus` asks about. Pass the values of your + * `PaymentRequest`, so the check matches the payment. Android asks Google + * Pay about these cards; iOS only rejects unknown network names. + */ +export interface PayServiceStatusOptions { + /** + * As `PaymentRequest.supportedNetworks`. Defaults to `visa`, `mastercard`, + * `amex` and `discover`. + */ + supportedNetworks?: string[] + /** As `PaymentRequest.googlePayAllowedAuthMethods`. Defaults to both. */ + googlePayAllowedAuthMethods?: string[] +} + // Backward compatibility alias export type ApplePayStatus = PayServiceStatus diff --git a/package/src/utils/__tests__/paymentHelpers.test.ts b/package/src/utils/__tests__/paymentHelpers.test.ts index c0bb636..8241ce3 100644 --- a/package/src/utils/__tests__/paymentHelpers.test.ts +++ b/package/src/utils/__tests__/paymentHelpers.test.ts @@ -182,5 +182,7 @@ describe('paymentHelpers', () => { expect(formatNetworkName('visa')).toBe('Visa') expect(formatNetworkName('amex')).toBe('American Express') expect(formatNetworkName('privateLabel')).toBe('Private Label') + expect(formatNetworkName('cartesBancaires')).toBe('Cartes Bancaires') + expect(formatNetworkName('unknown')).toBe('Unknown') }) }) diff --git a/package/src/utils/paymentHelpers.ts b/package/src/utils/paymentHelpers.ts index d95952d..9379f42 100644 --- a/package/src/utils/paymentHelpers.ts +++ b/package/src/utils/paymentHelpers.ts @@ -250,6 +250,29 @@ export function formatNetworkName(network: PaymentNetwork): string { idcredit: 'iD Credit', interac: 'Interac', privateLabel: 'Private Label', + cartesBancaires: 'Cartes Bancaires', + chinaUnionPay: 'China UnionPay', + dankort: 'Dankort', + eftpos: 'eftpos', + girocard: 'girocard', + mada: 'mada', + mir: 'Mir', + quicPay: 'QUICPay', + suica: 'Suica', + vPay: 'V PAY', + waon: 'WAON', + nanaco: 'nanaco', + bancontact: 'Bancontact', + postFinance: 'PostFinance', + pagoBancomat: 'PagoBANCOMAT', + tmoney: 'T-money', + meeza: 'Meeza', + napas: 'NAPAS', + bankAxept: 'BankAxept', + himyan: 'Himyan', + jaywan: 'Jaywan', + myDebit: 'MyDebit', + unknown: 'Unknown', } return networkNames[network] || network } From b5760ee5c80ecbf690c6f42757b20fa7f5e8cc21 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 23:22:31 +0100 Subject: [PATCH 2/8] refactor(android): name the shared allowedPaymentMethods helper for both callers --- .../java/com/margelo/nitro/pay/GooglePayButtonFactory.kt | 2 +- .../java/com/margelo/nitro/pay/GooglePayCardParameters.kt | 2 +- .../java/com/margelo/nitro/pay/GooglePayRequestBuilder.kt | 7 ++++--- .../com/margelo/nitro/pay/GooglePayRequestBuilderTest.kt | 2 +- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt index d48c3e7..4e48a1a 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayButtonFactory.kt @@ -21,7 +21,7 @@ object GooglePayButtonFactory { cardParameters: GooglePayCardParameters, onPress: (() -> Unit)? ): PayButton { - val allowedPaymentMethods = GooglePayRequestBuilder.createButtonPaymentMethods(cardParameters) + val allowedPaymentMethods = GooglePayRequestBuilder.createAllowedPaymentMethods(cardParameters) val buttonOptions = ButtonOptions.newBuilder() .setButtonType(mapButtonType(buttonType)) diff --git a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt index 8f1d922..5a1c09a 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt @@ -61,7 +61,7 @@ internal data class GooglePayCardParameters( } companion object { - val DEFAULT_NETWORKS = arrayOf("visa", "mastercard", "amex", "discover") + private val DEFAULT_NETWORKS = arrayOf("visa", "mastercard", "amex", "discover") private val AUTH_METHODS = listOf( PaymentConstants.AUTH_PAN_ONLY, PaymentConstants.AUTH_CRYPTOGRAM_3DS 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 09e9d1b..8cf742b 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 @@ -21,7 +21,7 @@ object GooglePayRequestBuilder { return JSONObject().apply { put("apiVersion", PaymentConstants.API_VERSION) put("apiVersionMinor", PaymentConstants.API_VERSION_MINOR) - put("allowedPaymentMethods", createButtonPaymentMethods(cardParameters)) + put("allowedPaymentMethods", createAllowedPaymentMethods(cardParameters)) existingPaymentMethodRequired?.let { put("existingPaymentMethodRequired", it) } @@ -29,9 +29,10 @@ object GooglePayRequestBuilder { } /** - * The `allowedPaymentMethods` of a PayButton: the cards in [cardParameters] + * The `allowedPaymentMethods` of an IsReadyToPay request or a PayButton: + * the cards in [cardParameters] */ - internal fun createButtonPaymentMethods(cardParameters: GooglePayCardParameters): JSONArray { + internal fun createAllowedPaymentMethods(cardParameters: GooglePayCardParameters): JSONArray { return JSONArray().apply { put(createBaseCardPaymentMethod(cardParameters)) } 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 15b09fd..6c5f653 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 @@ -445,7 +445,7 @@ class GooglePayRequestBuilderTest { val request = build(paymentRequest(coffee, supportedNetworks = arrayOf("visa", "mastercard"))) val parameters = cardParametersOf(arrayOf("visa", "mastercard")) val readiness = GooglePayRequestBuilder.createIsReadyToPayRequest(true, parameters) - val button = GooglePayRequestBuilder.createButtonPaymentMethods(parameters) + val button = GooglePayRequestBuilder.createAllowedPaymentMethods(parameters) val expected = listOf("VISA", "MASTERCARD") assertEquals(expected, request.cardParameters().strings("allowedCardNetworks")) From 23f032fcb86ebf5d20c7ee102baed1fe84bc1a05 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 23:28:49 +0100 Subject: [PATCH 3/8] refactor: track the Google Pay button as one config, read status cards from the request --- .../nitro/pay/HybridGooglePayButton.kt | 64 ++++++++----------- .../com/margelo/nitro/pay/PaymentMapper.kt | 9 +-- .../margelo/nitro/pay/PaymentMapperTest.kt | 32 +++++----- package/src/hooks/usePaymentCheckout.ts | 44 ++++++------- 4 files changed, 62 insertions(+), 87 deletions(-) diff --git a/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt b/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt index 2541bda..2a1bb3d 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt @@ -11,16 +11,18 @@ import com.google.android.gms.wallet.button.PayButton */ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButtonSpec() { + /** What a PayButton is built from: a different value needs a new button */ + private data class ButtonConfig( + val buttonType: GooglePayButtonType, + val theme: GooglePayButtonTheme, + val radius: Double?, + val cardParameters: GooglePayCardParameters + ) + // View state private var payButton: PayButton? = null private val container: FrameLayout = FrameLayout(context) - - // Configuration tracking for change detection - private var currentButtonType: GooglePayButtonType? = null - private var currentTheme: GooglePayButtonTheme? = null - private var currentRadius: Double? = null - private var currentSupportedNetworks: Array? = null - private var currentAllowedAuthMethods: Array? = null + private var buttonConfig: ButtonConfig? = null // Props override var buttonType: GooglePayButtonType = GooglePayButtonType.BUY @@ -48,12 +50,19 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton val context = container.context ?: return try { - if (shouldReuseButton()) { + // Built first, so invalid networks keep the existing button. + val config = ButtonConfig( + buttonType, + theme, + radius, + GooglePayCardParameters.from(supportedNetworks, allowedAuthMethods) + ) + if (payButton?.parent == container && config == buttonConfig) { updateExistingButton() return } - recreateButton(context) + recreateButton(context, config) } catch (e: Exception) { PayLog.e(PaymentConstants.TAG_GOOGLE_PAY_BUTTON, "Error setting up button", e) @@ -61,19 +70,6 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton } } - /** - * Checks if the existing button can be reused - */ - private fun shouldReuseButton(): Boolean { - val hasButton = payButton != null && payButton?.parent == container - val propsUnchanged = currentButtonType == buttonType && - currentTheme == theme && - currentRadius == radius && - currentSupportedNetworks contentEquals supportedNetworks && - currentAllowedAuthMethods contentEquals allowedAuthMethods - return hasButton && propsUnchanged - } - /** * Updates the click listener on existing button */ @@ -87,14 +83,8 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton /** * Recreates the button with new configuration */ - private fun recreateButton(context: android.content.Context) { - PayLog.d( - PaymentConstants.TAG_GOOGLE_PAY_BUTTON, - "Recreating button - type: $buttonType, theme: $theme, radius: $radius" - ) - - // Before removing the button: invalid networks keep the existing one. - val cardParameters = GooglePayCardParameters.from(supportedNetworks, allowedAuthMethods) + private fun recreateButton(context: android.content.Context, config: ButtonConfig) { + PayLog.d(PaymentConstants.TAG_GOOGLE_PAY_BUTTON, "Recreating button - $config") // Remove existing button container.removeAllViews() @@ -102,20 +92,16 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton // Create new button val newButton = GooglePayButtonFactory.createButton( context, - buttonType, - theme, - radius, - cardParameters, + config.buttonType, + config.theme, + config.radius, + config.cardParameters, onPress ) // Update state payButton = newButton - currentButtonType = buttonType - currentTheme = theme - currentRadius = radius - currentSupportedNetworks = supportedNetworks - currentAllowedAuthMethods = allowedAuthMethods + buttonConfig = config // Add to container val layoutParams = FrameLayout.LayoutParams( diff --git a/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt b/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt index be555fe..35f4367 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt @@ -36,7 +36,7 @@ object PaymentMapper { val paymentMethod = PaymentMethod( displayName = paymentMethodData.optNonEmpty("description") ?: "$cardNetwork $cardDetails", - network = mapCardNetwork(cardNetwork), + network = GooglePayNetworks.fromGooglePay(cardNetwork), type = PaymentMethodType.UNKNOWN, secureElementPass = null, billingAddress = null @@ -135,13 +135,6 @@ object PaymentMapper { ) } - /** - * Maps a Google Pay `cardNetwork` value to PaymentNetwork, or UNKNOWN - */ - fun mapCardNetwork(network: String): PaymentNetwork { - return GooglePayNetworks.fromGooglePay(network) - } - /** * Applies the merchant's `onAuthorize` outcome to an authorized PaymentResult */ diff --git a/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt index 9e2e6dc..64fb4a5 100644 --- a/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt +++ b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt @@ -308,30 +308,30 @@ class PaymentMapperTest { } @Test - fun mapCardNetwork_mapsGooglePayNetworksIgnoringCase() { - assertEquals(PaymentNetwork.VISA, PaymentMapper.mapCardNetwork("VISA")) - assertEquals(PaymentNetwork.MASTERCARD, PaymentMapper.mapCardNetwork("MASTERCARD")) - assertEquals(PaymentNetwork.AMEX, PaymentMapper.mapCardNetwork("AMEX")) - assertEquals(PaymentNetwork.DISCOVER, PaymentMapper.mapCardNetwork("DISCOVER")) - assertEquals(PaymentNetwork.JCB, PaymentMapper.mapCardNetwork("JCB")) - assertEquals(PaymentNetwork.INTERAC, PaymentMapper.mapCardNetwork("INTERAC")) - assertEquals(PaymentNetwork.MAESTRO, PaymentMapper.mapCardNetwork("maestro")) - assertEquals(PaymentNetwork.ELECTRON, PaymentMapper.mapCardNetwork("Electron")) - assertEquals(PaymentNetwork.ELO, PaymentMapper.mapCardNetwork("elo")) + fun fromGooglePay_mapsGooglePayNetworksIgnoringCase() { + assertEquals(PaymentNetwork.VISA, GooglePayNetworks.fromGooglePay("VISA")) + assertEquals(PaymentNetwork.MASTERCARD, GooglePayNetworks.fromGooglePay("MASTERCARD")) + assertEquals(PaymentNetwork.AMEX, GooglePayNetworks.fromGooglePay("AMEX")) + assertEquals(PaymentNetwork.DISCOVER, GooglePayNetworks.fromGooglePay("DISCOVER")) + assertEquals(PaymentNetwork.JCB, GooglePayNetworks.fromGooglePay("JCB")) + assertEquals(PaymentNetwork.INTERAC, GooglePayNetworks.fromGooglePay("INTERAC")) + assertEquals(PaymentNetwork.MAESTRO, GooglePayNetworks.fromGooglePay("maestro")) + assertEquals(PaymentNetwork.ELECTRON, GooglePayNetworks.fromGooglePay("Electron")) + assertEquals(PaymentNetwork.ELO, GooglePayNetworks.fromGooglePay("elo")) } @Test - fun mapCardNetwork_reportsUnrecognizedNetworksAsUnknown() { - assertEquals(PaymentNetwork.UNKNOWN, PaymentMapper.mapCardNetwork("unknown")) - assertEquals(PaymentNetwork.UNKNOWN, PaymentMapper.mapCardNetwork("ELO_DEBIT")) - assertEquals(PaymentNetwork.UNKNOWN, PaymentMapper.mapCardNetwork("")) + fun fromGooglePay_reportsUnrecognizedNetworksAsUnknown() { + assertEquals(PaymentNetwork.UNKNOWN, GooglePayNetworks.fromGooglePay("unknown")) + assertEquals(PaymentNetwork.UNKNOWN, GooglePayNetworks.fromGooglePay("ELO_DEBIT")) + assertEquals(PaymentNetwork.UNKNOWN, GooglePayNetworks.fromGooglePay("")) } @Test - fun mapCardNetwork_readsBackEveryNetworkTheRequestSends() { + fun fromGooglePay_readsBackEveryNetworkTheRequestSends() { for (network in PaymentNetwork.entries) { val cardNetwork = GooglePayNetworks.toGooglePay(network) ?: continue - assertEquals(network, PaymentMapper.mapCardNetwork(cardNetwork)) + assertEquals(network, GooglePayNetworks.fromGooglePay(cardNetwork)) } } diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index 5b96aaf..a168d70 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -28,8 +28,6 @@ import { sanitizePaymentRequest, } from '../utils' -const DEFAULT_SUPPORTED_NETWORKS = ['visa', 'mastercard', 'amex', 'discover'] - // 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. @@ -295,27 +293,6 @@ export function usePaymentCheckout( // Set synchronously, so two calls in the same frame still see each other. const isPaymentInFlight = useRef(false) - // Checked again when the accepted cards change, not on other config changes. - const statusOptionsKey = JSON.stringify({ - supportedNetworks: - stableRequestConfig.supportedNetworks ?? DEFAULT_SUPPORTED_NETWORKS, - googlePayAllowedAuthMethods: - stableRequestConfig.googlePayAllowedAuthMethods, - } satisfies PayServiceStatusOptions) - - useEffect(() => { - try { - const options: PayServiceStatusOptions = JSON.parse(statusOptionsKey) - const paymentStatus = getPaymentHandler().payServiceStatus(options) - setStatus(paymentStatus) - } catch (err) { - console.error('Failed to check payment status:', err) - setStatus({ canMakePayments: false, canSetupCards: false }) - } finally { - setIsCheckingStatus(false) - } - }, [statusOptionsKey]) - const total = useMemo(() => calculateTotal(items), [items]) const paymentRequest = useMemo(() => { @@ -323,7 +300,7 @@ export function usePaymentCheckout( merchantName, countryCode = 'US', currencyCode = 'USD', - supportedNetworks = DEFAULT_SUPPORTED_NETWORKS, + supportedNetworks = ['visa', 'mastercard', 'amex', 'discover'], merchantCapabilities = ['3DS'], applePayMerchantIdentifier, googlePayMerchantId, @@ -358,6 +335,25 @@ export function usePaymentCheckout( }) }, [stableRequestConfig, items]) + // The request's cards, so the status is checked again only when they change. + const statusOptionsKey = JSON.stringify({ + supportedNetworks: paymentRequest.supportedNetworks, + googlePayAllowedAuthMethods: paymentRequest.googlePayAllowedAuthMethods, + } satisfies PayServiceStatusOptions) + + useEffect(() => { + try { + const options: PayServiceStatusOptions = JSON.parse(statusOptionsKey) + const paymentStatus = getPaymentHandler().payServiceStatus(options) + setStatus(paymentStatus) + } catch (err) { + console.error('Failed to check payment status:', err) + setStatus({ canMakePayments: false, canSetupCards: false }) + } finally { + setIsCheckingStatus(false) + } + }, [statusOptionsKey]) + // Cart operations const addItem = useCallback( ( From b117459d09653285529f282bbfeb896200ad6988 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 17:14:47 +0100 Subject: [PATCH 4/8] fix(android): report the card's funding source as PaymentMethod.type Android always set PaymentMethod.type to 'unknown', although Google Pay's CardInfo returns cardFundingSource (UNKNOWN, CREDIT, DEBIT or PREPAID). Map it, ignoring case, to 'credit', 'debit' or 'prepaid'; anything else or a missing value stays 'unknown'. 'store' remains iOS only. --- CHANGELOG.md | 4 ++ README.md | 2 +- docs/docs/api/types.md | 1 + .../com/margelo/nitro/pay/PaymentMapper.kt | 15 ++++- .../margelo/nitro/pay/PaymentMapperTest.kt | 62 ++++++++++++++++++- 5 files changed, 80 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11da424..46f0726 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,6 +84,10 @@ All notable changes to this project are documented in this file. still received Amex tokens, and JCB or Interac could not be enabled. The payment request, the `GooglePayButton` and the readiness check behind `payServiceStatus` now use the same networks and auth methods. +- **Android: `PaymentMethod.type` reports the card's funding source.** It was always + `'unknown'`. It now reads Google Pay's `cardFundingSource`, so a result reports `'credit'`, + `'debit'` or `'prepaid'`, and `'unknown'` only when Google Pay does not know. `'store'` stays + iOS only. - **Requested contact details are no longer lost.** iOS asked for the billing and shipping address but never returned them, and Android ignored `billingContactRequired` and `shippingContactRequired`. See Added. diff --git a/README.md b/README.md index ca3515b..cee46e0 100644 --- a/README.md +++ b/README.md @@ -795,7 +795,7 @@ interface PaymentToken { interface PaymentMethod { displayName?: string; // for the payer, e.g. "Visa •••• 1234"; don't parse it network?: PaymentNetwork; // "unknown" when the library cannot name it - type: PaymentMethodType; + type: PaymentMethodType; // funding source; "store" is iOS only secureElementPass?: PKSecureElementPass; billingAddress?: CNContact; } diff --git a/docs/docs/api/types.md b/docs/docs/api/types.md index da5d1b2..bd774dc 100644 --- a/docs/docs/api/types.md +++ b/docs/docs/api/types.md @@ -169,6 +169,7 @@ type PaymentMethodType = 'unknown' | 'debit' | 'credit' | 'prepaid' | 'store' - **displayName** — Describes the card to the payer, as the wallet words it: `PKPaymentMethod.displayName` on iOS, `paymentMethodData.description` on Android (for example "Visa •••• 1234"). Show it as is; don't parse it. - **network** — The card's [`PaymentNetwork`](#paymentnetwork), or `'unknown'` for a network the library cannot name. Use `network` rather than `displayName` for logic. +- **type** — How the card is funded: `PKPaymentMethod.type` on iOS, Google Pay's `cardFundingSource` on Android. Android reports `'credit'`, `'debit'` or `'prepaid'`, and `'unknown'` when Google Pay does not know; `'store'` (a store card) is iOS only. --- diff --git a/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt b/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt index 35f4367..568026f 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt @@ -30,6 +30,7 @@ object PaymentMapper { val info = paymentMethodData.getJSONObject("info") val cardNetwork = info.optString("cardNetwork", "unknown") val cardDetails = info.optString("cardDetails", "****") + val cardFundingSource = info.optNonEmpty("cardFundingSource") ?: "UNKNOWN" // Create payment method. Google Pay asks to show `description` // to the payer, not `cardNetwork`. @@ -37,7 +38,7 @@ object PaymentMapper { displayName = paymentMethodData.optNonEmpty("description") ?: "$cardNetwork $cardDetails", network = GooglePayNetworks.fromGooglePay(cardNetwork), - type = PaymentMethodType.UNKNOWN, + type = mapCardFundingSource(cardFundingSource), secureElementPass = null, billingAddress = null ) @@ -135,6 +136,18 @@ object PaymentMapper { ) } + /** + * Maps a Google Pay `cardFundingSource` value to PaymentMethodType, or UNKNOWN + */ + fun mapCardFundingSource(fundingSource: String): PaymentMethodType { + return when { + fundingSource.equals("CREDIT", ignoreCase = true) -> PaymentMethodType.CREDIT + fundingSource.equals("DEBIT", ignoreCase = true) -> PaymentMethodType.DEBIT + fundingSource.equals("PREPAID", ignoreCase = true) -> PaymentMethodType.PREPAID + else -> PaymentMethodType.UNKNOWN + } + } + /** * Applies the merchant's `onAuthorize` outcome to an authorized PaymentResult */ diff --git a/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt index 64fb4a5..15dd1e1 100644 --- a/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt +++ b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt @@ -72,7 +72,7 @@ class PaymentMapperTest { """ { "type": "CARD", - "info": {"cardNetwork": "MASTERCARD", "cardDetails": "4242"}, + "info": {"cardNetwork": "MASTERCARD", "cardDetails": "4242", "cardFundingSource": "CREDIT"}, "tokenizationData": {"type": "PAYMENT_GATEWAY", "token": "gateway-token"} } """ @@ -86,7 +86,7 @@ class PaymentMapperTest { assertEquals("gateway-token", token.paymentData) assertEquals("MASTERCARD 4242", token.paymentMethod.displayName) assertEquals(PaymentNetwork.MASTERCARD, token.paymentMethod.network) - assertEquals(PaymentMethodType.UNKNOWN, token.paymentMethod.type) + assertEquals(PaymentMethodType.CREDIT, token.paymentMethod.type) assertNull(token.paymentMethod.billingAddress) } @@ -99,6 +99,7 @@ class PaymentMapperTest { assertTrue(result.success) assertEquals("unknown ****", result.token!!.paymentMethod.displayName) assertEquals(PaymentNetwork.UNKNOWN, result.token!!.paymentMethod.network) + assertEquals(PaymentMethodType.UNKNOWN, result.token!!.paymentMethod.type) } @Test @@ -335,6 +336,63 @@ class PaymentMapperTest { } } + @Test + fun mapCardFundingSource_mapsGooglePayValuesIgnoringCase() { + assertEquals(PaymentMethodType.CREDIT, PaymentMapper.mapCardFundingSource("CREDIT")) + assertEquals(PaymentMethodType.DEBIT, PaymentMapper.mapCardFundingSource("DEBIT")) + assertEquals(PaymentMethodType.PREPAID, PaymentMapper.mapCardFundingSource("PREPAID")) + assertEquals(PaymentMethodType.DEBIT, PaymentMapper.mapCardFundingSource("debit")) + assertEquals(PaymentMethodType.PREPAID, PaymentMapper.mapCardFundingSource("Prepaid")) + } + + @Test + fun mapCardFundingSource_reportsUnrecognizedValuesAsUnknown() { + assertEquals(PaymentMethodType.UNKNOWN, PaymentMapper.mapCardFundingSource("UNKNOWN")) + assertEquals(PaymentMethodType.UNKNOWN, PaymentMapper.mapCardFundingSource("STORE")) + assertEquals(PaymentMethodType.UNKNOWN, PaymentMapper.mapCardFundingSource("")) + } + + @Test + fun mapPaymentDataToResult_readsEachFundingSource() { + val expected = mapOf( + "CREDIT" to PaymentMethodType.CREDIT, + "DEBIT" to PaymentMethodType.DEBIT, + "PREPAID" to PaymentMethodType.PREPAID, + "UNKNOWN" to PaymentMethodType.UNKNOWN + ) + + for ((fundingSource, type) in expected) { + val result = PaymentMapper.mapPaymentDataToResult( + paymentData( + """ + { + "info": {"cardNetwork": "VISA", "cardDetails": "1111", "cardFundingSource": "$fundingSource"}, + "tokenizationData": {"token": "gateway-token"} + } + """ + ) + ) + + assertEquals(fundingSource, type, result.token!!.paymentMethod.type) + } + } + + @Test + fun mapPaymentDataToResult_reportsANullFundingSourceAsUnknown() { + val result = PaymentMapper.mapPaymentDataToResult( + paymentData( + """ + { + "info": {"cardNetwork": "VISA", "cardDetails": "1111", "cardFundingSource": null}, + "tokenizationData": {"token": "gateway-token"} + } + """ + ) + ) + + assertEquals(PaymentMethodType.UNKNOWN, result.token!!.paymentMethod.type) + } + @Test fun applyAuthorization_keepsTheAuthorizedResultOnSuccess() { val authorized = authorizedResult() From d5782eab859631e00d655dabcfd0af54ce83809d Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 17:18:55 +0100 Subject: [PATCH 5/8] feat: honour a debit-only merchantCapabilities on Android Android ignored PaymentRequest.merchantCapabilities, so ['3DS', 'Debit'] meant debit cards only on iOS but still accepted credit cards on Android. - 'Debit' without 'Credit' sends allowCreditCards: false in the Google Pay CARD parameters, as UK gambling merchants must. Prepaid cards stay allowed. Google Pay cannot leave debit cards out, so 'Credit' alone still accepts every card type; '3DS' and 'EMV' have no effect. - An unknown capability fails the payment with the iOS message, matched ignoring case. Android used to ignore the field. - GooglePayCardParameters carries the flag to the payment request, the PayButton (new merchantCapabilities prop) and payServiceStatus (new PayServiceStatusOptions.merchantCapabilities, passed by usePaymentCheckout). iOS payServiceStatus rejects unknown values too. --- CHANGELOG.md | 12 +++ README.md | 9 +- docs/docs/api/components.md | 3 +- docs/docs/api/hybrid-payment-handler.md | 2 +- docs/docs/api/types.md | 22 ++++- docs/docs/api/use-payment-checkout.md | 4 +- docs/docs/troubleshooting.md | 2 +- example/app/(tabs)/index.tsx | 1 + .../nitro/pay/GooglePayCardParameters.kt | 30 +++++-- .../nitro/pay/GooglePayRequestBuilder.kt | 3 +- .../nitro/pay/HybridGooglePayButton.kt | 5 +- .../margelo/nitro/pay/HybridPaymentHandler.kt | 3 +- .../nitro/pay/GooglePayRequestBuilderTest.kt | 82 ++++++++++++++++++- package/ios/HybridPaymentHandler.swift | 9 +- .../c++/JHybridGooglePayButtonSpec.cpp | 27 ++++++ .../c++/JHybridGooglePayButtonSpec.hpp | 2 + .../android/c++/JPayServiceStatusOptions.hpp | 28 ++++++- .../JHybridGooglePayButtonStateUpdater.cpp | 4 + .../nitro/pay/HybridGooglePayButtonSpec.kt | 6 ++ .../nitro/pay/PayServiceStatusOptions.kt | 13 ++- .../ios/swift/PayServiceStatusOptions.swift | 26 +++++- .../shared/c++/HybridGooglePayButtonSpec.cpp | 2 + .../shared/c++/HybridGooglePayButtonSpec.hpp | 2 + .../shared/c++/PayServiceStatusOptions.hpp | 8 +- .../views/HybridGooglePayButtonComponent.cpp | 11 +++ .../views/HybridGooglePayButtonComponent.hpp | 1 + .../shared/json/GooglePayButtonConfig.json | 1 + .../usePaymentCheckout.integration.test.ts | 17 ++++ package/src/hooks/usePaymentCheckout.ts | 5 +- package/src/specs/GooglePayButton.nitro.ts | 5 ++ package/src/types/Payment.ts | 12 ++- 31 files changed, 315 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46f0726..70d97ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,14 @@ All notable changes to this project are documented in this file. (`PayServiceStatusOptions`). Give them the values of your request, so the button and the Android readiness check use the same cards as the payment. `usePaymentCheckout` passes its config to `payServiceStatus` and checks again when they change. +- **Android honours a debit-only `merchantCapabilities`.** `'Debit'` without `'Credit'` now leaves + credit cards out of the Google Pay request (`allowCreditCards: false`), as UK gambling merchants + must. Prepaid cards stay allowed. Google Pay cannot leave debit cards out, so `'Credit'` alone + still accepts every card type on Android; `'3DS'` and `'EMV'` have no effect there. + `GooglePayButton` takes a `merchantCapabilities` prop and `PayServiceStatusOptions` a + `merchantCapabilities` field, so the button and the readiness check are sent the same card + types. `usePaymentCheckout` passes its `merchantCapabilities` to `payServiceStatus` and checks + again when they change. ### Changed @@ -47,6 +55,10 @@ All notable changes to this project are documented in this file. platform does not offer is left out; the payment fails when none is left. `canMakePayments` and `payServiceStatus` throw for an unknown name, and `canMakePayments` returns `false` when the platform offers none of the networks. +- **An unknown value in `merchantCapabilities` fails the payment on Android too,** with the same + `error` as on iOS: `Unknown merchant capability "". Use "3DS", "EMV", "Credit" or + "Debit"`. Android used to ignore the field. `payServiceStatus` throws for an unknown value on + both platforms. - **Android: `PaymentMethod.displayName` is the wallet's description of the card** (Google Pay's `paymentMethodData.description`, for example "Visa •••• 1234") instead of `"VISA 1234"`. Google Pay asks apps not to show `cardNetwork` to the payer. Use `network` for logic. diff --git a/README.md b/README.md index cee46e0..0ade072 100644 --- a/README.md +++ b/README.md @@ -368,7 +368,7 @@ interface UsePaymentCheckoutConfig { countryCode?: string; // Default: 'US' currencyCode?: string; // Default: 'USD' supportedNetworks?: string[]; // PaymentNetwork names. Default: ['visa', 'mastercard', 'amex', 'discover'] - merchantCapabilities?: MerchantCapability[]; // Default: ['3DS'] + merchantCapabilities?: MerchantCapability[]; // Default: ['3DS']. Android: only Debit without Credit applePayMerchantIdentifier?: string; // Optional iOS override // Google Pay specific (Android) googlePayMerchantId?: string; @@ -458,7 +458,7 @@ Low-level payment handler for direct control. ##### `payServiceStatus(options?: PayServiceStatusOptions): PayServiceStatus` -Check payment service availability. On Android, `options` names the cards to ask Google Pay about: pass the `supportedNetworks` and `googlePayAllowedAuthMethods` of your request. iOS only checks the network names. +Check payment service availability. On Android, `options` names the cards to ask Google Pay about: pass the `supportedNetworks`, `googlePayAllowedAuthMethods` and `merchantCapabilities` of your request. iOS only checks that the values are known. ```typescript import { HybridPaymentHandler } from "@gmisoftware/react-native-pay"; @@ -635,6 +635,7 @@ interface GooglePayButtonProps { // The cards your payment accepts, so the button never shows another card. supportedNetworks?: string[]; // as PaymentRequest.supportedNetworks allowedAuthMethods?: string[]; // as PaymentRequest.googlePayAllowedAuthMethods + merchantCapabilities?: string[]; // as PaymentRequest.merchantCapabilities onPress?: () => void; // wrap with callback() from react-native-nitro-modules style?: ViewStyle; @@ -861,7 +862,9 @@ Google Pay accepts at most two decimal places, so three-decimal amounts (`"1.234 ### Merchant capabilities -`merchantCapabilities` is used by Apple Pay only. `"3DS"` and `"EMV"` are payment protocols, and PassKit needs at least one of them: EMV only covers China UnionPay, so every other card needs 3DS. `"Credit"` and `"Debit"` limit the accepted card types. iOS matches the values case-insensitively and adds `"3DS"` when neither protocol is given, so `["Credit"]` is sent as 3DS + Credit. Any other value fails the payment with `Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"`. +`"3DS"` and `"EMV"` are Apple Pay payment protocols, and PassKit needs at least one of them: EMV only covers China UnionPay, so every other card needs 3DS. Android ignores them. `"Credit"` and `"Debit"` limit the accepted card types. iOS adds `"3DS"` when neither protocol is given, so `["Credit"]` is sent as 3DS + Credit. Both platforms match the values case-insensitively, and any other value fails the payment with `Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"`. + +Google Pay can leave credit cards out, but not debit cards. On Android, `"Debit"` without `"Credit"` sends `allowCreditCards: false`, which UK gambling merchants must do; prepaid cards stay allowed. `["3DS", "Credit"]` accepts every card type on Android, so check the card on your server if you must refuse debit cards. Give `GooglePayButton` and `payServiceStatus` the same `merchantCapabilities` as the payment. ### Shipping and contact details diff --git a/docs/docs/api/components.md b/docs/docs/api/components.md index 3cdb682..4b3ed97 100644 --- a/docs/docs/api/components.md +++ b/docs/docs/api/components.md @@ -58,10 +58,11 @@ Renders the Google Pay button. Only available on Android. | `radius` | `number` | No | Corner radius in dp. | | `supportedNetworks` | `string[]` | No | The card networks your payment accepts, as in `PaymentRequest.supportedNetworks`. Default: `visa`, `mastercard`, `amex`, `discover`. | | `allowedAuthMethods` | `string[]` | No | As in `PaymentRequest.googlePayAllowedAuthMethods`. Default: both. | +| `merchantCapabilities` | `string[]` | No | As in `PaymentRequest.merchantCapabilities`. `'Debit'` without `'Credit'` leaves credit cards out. Default: every card type. | | `onPress` | `() => void`, wrapped with `callback()` | No | Called when the user taps the button. Must be wrapped, see [Nitro and onPress](#nitro-and-onpress). | | `style` | `ViewStyle` | No | Layout/style (e.g. width, height). | -The button can show the payer's card, so give it the same `supportedNetworks` and `allowedAuthMethods` as the payment. Otherwise it may show a card the payment then refuses. With `usePaymentCheckout`, pass `paymentRequest.supportedNetworks` and `paymentRequest.googlePayAllowedAuthMethods`. With an unknown network or auth method, the button keeps its previous configuration, or does not appear on the first render, and logs an error in debug builds. +The button can show the payer's card, so give it the same `supportedNetworks`, `allowedAuthMethods` and `merchantCapabilities` as the payment. Otherwise it may show a card the payment then refuses. With `usePaymentCheckout`, pass `paymentRequest.supportedNetworks`, `paymentRequest.googlePayAllowedAuthMethods` and `paymentRequest.merchantCapabilities`. With an unknown network, auth method or merchant capability, the button keeps its previous configuration, or does not appear on the first render, and logs an error in debug builds. **GooglePayButtonType:** `'buy'` | `'book'` | `'checkout'` | `'donate'` | `'order'` | `'pay'` | `'subscribe'` | `'plain'` diff --git a/docs/docs/api/hybrid-payment-handler.md b/docs/docs/api/hybrid-payment-handler.md index d975e8e..3bca93b 100644 --- a/docs/docs/api/hybrid-payment-handler.md +++ b/docs/docs/api/hybrid-payment-handler.md @@ -26,7 +26,7 @@ const status = HybridPaymentHandler.payServiceStatus({ - **canMakePayments** — User can complete a payment (has a valid card, etc.). - **canSetupCards** — User can add or manage cards (e.g. Wallet settings). -`options` ([`PayServiceStatusOptions`](/docs/api/types#payservicestatusoptions)) names the cards your payment accepts: pass the `supportedNetworks` and `googlePayAllowedAuthMethods` of your `PaymentRequest`. Android asks Google Pay about those cards; without `options` it asks about `visa`, `mastercard`, `amex` and `discover`. iOS does not use them yet. On both platforms an unknown network name throws. +`options` ([`PayServiceStatusOptions`](/docs/api/types#payservicestatusoptions)) names the cards your payment accepts: pass the `supportedNetworks`, `googlePayAllowedAuthMethods` and `merchantCapabilities` of your `PaymentRequest`. Android asks Google Pay about those cards; without `options` it asks about `visa`, `mastercard`, `amex` and `discover`, of every card type. iOS does not use them yet. On both platforms an unknown network name or merchant capability throws. --- diff --git a/docs/docs/api/types.md b/docs/docs/api/types.md index bd774dc..c97529e 100644 --- a/docs/docs/api/types.md +++ b/docs/docs/api/types.md @@ -220,10 +220,11 @@ The cards `HybridPaymentHandler.payServiceStatus(options)` asks about. Pass the interface PayServiceStatusOptions { supportedNetworks?: string[] // default: ['visa', 'mastercard', 'amex', 'discover'] googlePayAllowedAuthMethods?: string[] // default: both + merchantCapabilities?: string[] // default: every card type } ``` -Android asks Google Pay whether the payer can pay with these cards. iOS only checks the network names. +Android asks Google Pay whether the payer can pay with these cards. iOS only checks that the values are known. --- @@ -256,16 +257,29 @@ The default is both. Pass `['CRYPTOGRAM_3DS']` when your gateway or Strong Custo ## MerchantCapability -Apple Pay merchant capabilities, used in `merchantCapabilities` (iOS only; Android ignores the field). +Merchant capabilities, used in `merchantCapabilities`. They come from Apple Pay; Android only reads `'Credit'` and `'Debit'`. ```ts type MerchantCapability = '3DS' | 'EMV' | 'Credit' | 'Debit' ``` -- `'3DS'` and `'EMV'` are payment protocols. PassKit needs at least one of them. EMV only covers China UnionPay, so every other card needs 3DS. +- `'3DS'` and `'EMV'` are Apple Pay payment protocols. PassKit needs at least one of them. EMV only covers China UnionPay, so every other card needs 3DS. Android ignores them. - `'Credit'` and `'Debit'` limit the accepted card types. -iOS matches the values case-insensitively and adds `'3DS'` when neither `'3DS'` nor `'EMV'` is given, so `[]` is sent as 3DS and `['Credit']` as 3DS + Credit. Any other value fails the payment: the result has `success: false` and `error: 'Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"'`. +Both platforms match the values case-insensitively. Any other value fails the payment: the result has `success: false` and `error: 'Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"'`. + +iOS adds `'3DS'` when neither `'3DS'` nor `'EMV'` is given, so `[]` is sent as 3DS and `['Credit']` as 3DS + Credit. + +Google Pay can leave credit cards out, but not debit cards: + +| `merchantCapabilities` | iOS accepts | Android accepts | +|---|---|---| +| `['3DS']` | Every card type | Every card type | +| `['3DS', 'Debit']` | Debit cards | Every card type but credit cards | +| `['3DS', 'Credit']` | Credit cards | Every card type | +| `['3DS', 'Credit', 'Debit']` | Credit and debit cards | Every card type | + +For `'Debit'` without `'Credit'`, Android sends `allowCreditCards: false` to Google Pay, which UK gambling merchants must do. Prepaid cards stay allowed. To refuse debit cards on Android, check the card on your server before you charge it. Give [`GooglePayButton`](/docs/api/components#googlepaybutton-android-only) and [`payServiceStatus`](#payservicestatusoptions) the same `merchantCapabilities`, so they are sent the same card types as the payment. --- diff --git a/docs/docs/api/use-payment-checkout.md b/docs/docs/api/use-payment-checkout.md index 924311c..8312a86 100644 --- a/docs/docs/api/use-payment-checkout.md +++ b/docs/docs/api/use-payment-checkout.md @@ -44,7 +44,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. - **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. On Android the hook checks `canMakePayments` for these networks too. Pass the same list to [`GooglePayButton`](/docs/api/components#googlepaybutton-android-only). - **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). -- **merchantCapabilities** — Apple Pay only. iOS adds `'3DS'` when neither `'3DS'` nor `'EMV'` is given, and fails the payment for an unknown value. See [MerchantCapability](/docs/api/types#merchantcapability). +- **merchantCapabilities** — The card types to accept and, on iOS, the payment protocols. iOS adds `'3DS'` when neither `'3DS'` nor `'EMV'` is given. On Android only `'Debit'` without `'Credit'` has an effect: it leaves credit cards out. Google Pay cannot leave debit cards out, so `['3DS', 'Credit']` accepts every card type on Android. An unknown value fails the payment on both platforms. Pass the same list to [`GooglePayButton`](/docs/api/components#googlepaybutton-android-only). See [MerchantCapability](/docs/api/types#merchantcapability). - **billingContactRequired**, **shippingContactRequired**, **emailRequired**, **phoneNumberRequired** — Ask the payer for a billing address, a shipping address, an email address or a phone number. They come back as `result.billingContact`, `result.shippingContact`, `result.emailAddress` and `result.phoneNumber`. See [Shipping and contact details](/docs/guides/contact-details). - **onAuthorize** — Called with the token and the requested contact details after the user authorizes the payment. Charge it on your server and resolve with `{ status: 'success' }` or `{ status: 'failure', error }`. See [Charge before the sheet closes](/docs/guides/server-processing#charge-before-the-sheet-closes). An inline function is fine: `startPayment()` uses the one from the latest render, and a payment keeps that function until it settles, even if the config changes meanwhile. @@ -80,7 +80,7 @@ interface UsePaymentCheckoutReturn { - **canMakePayments** — Whether the user can pay with Apple Pay / Google Pay on this device. - **canSetupCards** — Whether the user can add or manage cards (e.g. in Wallet). -- **isCheckingStatus** — `true` while availability is being checked on mount. The hook checks again when `supportedNetworks` or `googlePayAllowedAuthMethods` change. +- **isCheckingStatus** — `true` while availability is being checked on mount. The hook checks again when `supportedNetworks`, `googlePayAllowedAuthMethods` or `merchantCapabilities` change. - **items** / **total** — Current cart and its exact decimal total, as a number (`NaN` if an amount is invalid). Amounts are `number | string` ([`PaymentAmount`](/docs/api/types#paymentamount)); use `formatAmount(item.amount, currencyCode)` to display them. - **startPayment()** — Opens the native sheet. Returns `Promise`. - Returns `null` and sets `error` when the cart is empty. diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 34725e2..f09d2f0 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -41,7 +41,7 @@ npx expo prebuild --clean ### "Unknown merchant capability" -The payment fails with `Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"` when `merchantCapabilities` contains any other value. Case doesn't matter (`'3ds'` works). See [MerchantCapability](/docs/api/types#merchantcapability). +The payment fails with `Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"` when `merchantCapabilities` contains any other value, on Android too. Case doesn't matter (`'3ds'` works). See [MerchantCapability](/docs/api/types#merchantcapability). ### Invalid Apple button type/style errors diff --git a/example/app/(tabs)/index.tsx b/example/app/(tabs)/index.tsx index 6f9f28f..378bc89 100644 --- a/example/app/(tabs)/index.tsx +++ b/example/app/(tabs)/index.tsx @@ -298,6 +298,7 @@ export default function TabOneScreen() { // The cards the request accepts, so the button shows one of them. supportedNetworks={paymentRequest.supportedNetworks} allowedAuthMethods={paymentRequest.googlePayAllowedAuthMethods} + merchantCapabilities={paymentRequest.merchantCapabilities} onPress={callback(handlePayment)} style={styles.payButton} /> diff --git a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt index 5a1c09a..24dc786 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt @@ -52,12 +52,16 @@ internal object GooglePayNetworks { */ internal data class GooglePayCardParameters( val cardNetworks: List, - val authMethods: List + val authMethods: List, + val allowCreditCards: Boolean = true ) { /** The `parameters` of a CARD payment method, before any billing address */ fun toJson(): JSONObject = JSONObject().apply { put("allowedAuthMethods", JSONArray(authMethods)) put("allowedCardNetworks", JSONArray(cardNetworks)) + if (!allowCreditCards) { + put("allowCreditCards", false) + } } companion object { @@ -67,16 +71,24 @@ internal data class GooglePayCardParameters( PaymentConstants.AUTH_CRYPTOGRAM_3DS ) + private val MERCHANT_CAPABILITIES = listOf("3DS", "EMV", "Credit", "Debit") + /** - * Reads `supportedNetworks` and the allowed auth methods; null uses the - * defaults. A network Google Pay does not offer is left out. + * Reads `supportedNetworks`, the allowed auth methods and the merchant + * capabilities; null uses the defaults. A network Google Pay does not + * offer is left out. + * + * Of the capabilities, only Debit without Credit changes the request: + * it turns credit cards off. Google Pay cannot turn debit cards off, so + * Credit alone accepts both. 3DS and EMV are Apple Pay protocols. * * @throws IllegalArgumentException for an unknown value, or when no * network or no auth method is left */ fun from( supportedNetworks: Array?, - authMethods: Array? + authMethods: Array?, + merchantCapabilities: Array? = null ): GooglePayCardParameters { val networkNames = supportedNetworks ?: DEFAULT_NETWORKS require(networkNames.isNotEmpty()) { "supportedNetworks needs at least one network" } @@ -98,7 +110,15 @@ internal data class GooglePayCardParameters( "Google Pay needs at least one auth method: \"PAN_ONLY\" or \"CRYPTOGRAM_3DS\"" } - return GooglePayCardParameters(cardNetworks, methods) + val capabilities = merchantCapabilities.orEmpty().map { capability -> + MERCHANT_CAPABILITIES.firstOrNull { it.equals(capability, ignoreCase = true) } + ?: throw IllegalArgumentException( + "Unknown merchant capability \"$capability\". Use \"3DS\", \"EMV\", \"Credit\" or \"Debit\"" + ) + } + val debitOnly = "Debit" in capabilities && "Credit" !in capabilities + + return GooglePayCardParameters(cardNetworks, methods, allowCreditCards = !debitOnly) } } } 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 8cf742b..84635b5 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 @@ -54,7 +54,8 @@ object GooglePayRequestBuilder { val requested = RequestedDetails.from(request) val cardParameters = GooglePayCardParameters.from( request.supportedNetworks, - request.googlePayAllowedAuthMethods + request.googlePayAllowedAuthMethods, + request.merchantCapabilities ) return JSONObject().apply { diff --git a/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt b/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt index 2a1bb3d..e7aa9f8 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt @@ -30,6 +30,7 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton override var radius: Double? = null override var supportedNetworks: Array? = null override var allowedAuthMethods: Array? = null + override var merchantCapabilities: Array? = null override var onPress: (() -> Unit)? = null override var view: View = container @@ -50,12 +51,12 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton val context = container.context ?: return try { - // Built first, so invalid networks keep the existing button. + // Built first, so an invalid value keeps the existing button. val config = ButtonConfig( buttonType, theme, radius, - GooglePayCardParameters.from(supportedNetworks, allowedAuthMethods) + GooglePayCardParameters.from(supportedNetworks, allowedAuthMethods, merchantCapabilities) ) if (payButton?.parent == container && config == buttonConfig) { updateExistingButton() diff --git a/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt b/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt index a91cd1a..1fa609e 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt @@ -68,7 +68,8 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { // reading as "unavailable". val cardParameters = GooglePayCardParameters.from( options?.supportedNetworks, - options?.googlePayAllowedAuthMethods + options?.googlePayAllowedAuthMethods, + options?.merchantCapabilities ) return try { val client = createPaymentsClient(currentEnvironment) 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 6c5f653..84f556b 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 @@ -30,14 +30,15 @@ class GooglePayRequestBuilderTest { phoneNumberRequired: Boolean? = null, shippingMethods: Array? = null, supportedNetworks: Array = arrayOf("visa"), - googlePayAllowedAuthMethods: Array? = null + googlePayAllowedAuthMethods: Array? = null, + merchantCapabilities: Array = arrayOf("3DS") ) = PaymentRequest( applePayMerchantIdentifier = null, merchantName = merchantName, countryCode = "US", currencyCode = currencyCode, paymentItems = items, - merchantCapabilities = arrayOf("3DS"), + merchantCapabilities = merchantCapabilities, supportedNetworks = supportedNetworks, shippingType = null, shippingMethods = shippingMethods, @@ -437,8 +438,9 @@ class GooglePayRequestBuilderTest { private fun cardParametersOf( networks: Array?, - authMethods: Array? = null - ) = GooglePayCardParameters.from(networks, authMethods) + authMethods: Array? = null, + merchantCapabilities: Array? = null + ) = GooglePayCardParameters.from(networks, authMethods, merchantCapabilities) @Test fun supportedNetworks_areTheOnlyNetworksInTheRequestTheReadinessCheckAndTheButton() { @@ -551,4 +553,76 @@ class GooglePayRequestBuilderTest { empty.message ) } + + // Merchant capabilities + + @Test + fun debitOnly_leavesCreditCardsOutOfTheRequestTheReadinessCheckAndTheButton() { + val request = build(paymentRequest(coffee, merchantCapabilities = arrayOf("3DS", "Debit"))) + val parameters = cardParametersOf(null, merchantCapabilities = arrayOf("3DS", "Debit")) + val readiness = GooglePayRequestBuilder.createIsReadyToPayRequest(true, parameters) + val button = GooglePayRequestBuilder.createButtonPaymentMethods(parameters) + + assertFalse(request.cardParameters().getBoolean("allowCreditCards")) + assertFalse(readiness.cardParameters().getBoolean("allowCreditCards")) + assertFalse(button.getJSONObject(0).getJSONObject("parameters").getBoolean("allowCreditCards")) + assertEquals( + readiness.getJSONArray("allowedPaymentMethods").toString(), + button.toString() + ) + } + + @Test + fun debitOnly_isMatchedIgnoringCase() { + for (capabilities in listOf(arrayOf("debit"), arrayOf("3ds", "DEBIT"))) { + val parameters = build(paymentRequest(coffee, merchantCapabilities = capabilities)).cardParameters() + + assertFalse(capabilities.joinToString(), parameters.getBoolean("allowCreditCards")) + } + } + + @Test + fun creditOnly_acceptsEveryCardType() { + // Google Pay cannot leave debit cards out. + val parameters = build(paymentRequest(coffee, merchantCapabilities = arrayOf("3DS", "Credit"))) + .cardParameters() + + assertFalse(parameters.has("allowCreditCards")) + assertFalse(parameters.has("allowPrepaidCards")) + } + + @Test + fun creditAndDebit_acceptEveryCardType() { + val parameters = build(paymentRequest(coffee, merchantCapabilities = arrayOf("Debit", "credit"))) + .cardParameters() + + assertFalse(parameters.has("allowCreditCards")) + } + + @Test + fun neitherCreditNorDebit_acceptsEveryCardType() { + for (capabilities in listOf(arrayOf("3DS"), arrayOf("EMV"), emptyArray())) { + val parameters = build(paymentRequest(coffee, merchantCapabilities = capabilities)).cardParameters() + + assertFalse(capabilities.joinToString(), parameters.has("allowCreditCards")) + } + assertFalse(GooglePayRequestBuilder.createIsReadyToPayRequest().cardParameters().has("allowCreditCards")) + } + + @Test + fun merchantCapabilities_rejectUnknownValuesLikeIos() { + for (capability in listOf("Prepaid", "3-D Secure", "")) { + val error = assertThrows(IllegalArgumentException::class.java) { + build(paymentRequest(coffee, merchantCapabilities = arrayOf("3DS", capability))) + } + + assertEquals( + "Unknown merchant capability \"$capability\". Use \"3DS\", \"EMV\", \"Credit\" or \"Debit\"", + error.message + ) + } + assertThrows(IllegalArgumentException::class.java) { + cardParametersOf(null, merchantCapabilities = arrayOf("Unknown")) + } + } } diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index 7b22065..ddceba0 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -219,7 +219,7 @@ struct PaymentRequestBuilder { return ProcessInfo.processInfo.processName } - private static func buildMerchantCapabilities(_ capabilities: [String]) throws -> PKMerchantCapability { + static func buildMerchantCapabilities(_ capabilities: [String]) throws -> PKMerchantCapability { var merchantCapabilities: PKMerchantCapability = [] for capability in capabilities { switch capability.uppercased() { @@ -542,11 +542,14 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec { // MARK: - Public Methods func payServiceStatus(options: PayServiceStatusOptions?) throws -> PayServiceStatus { - // Rejects unknown names like Android. The status itself does not - // depend on the networks on iOS. + // Rejects unknown values like Android. The status itself does not + // depend on the networks or capabilities on iOS. if let networks = options?.supportedNetworks { _ = try PaymentRequestBuilder.convertNetworks(networks) } + if let capabilities = options?.merchantCapabilities { + _ = try PaymentRequestBuilder.buildMerchantCapabilities(capabilities) + } let canMakePayments = PKPaymentAuthorizationViewController.canMakePayments() let canSetupCards = PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: []) return PayServiceStatus.init(canMakePayments, canSetupCards) diff --git a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp index ca50b0e..afeea64 100644 --- a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp +++ b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp @@ -134,6 +134,33 @@ namespace margelo::nitro::pay { return __array; }(allowedAuthMethods.value()) : nullptr); } + std::optional> JHybridGooglePayButtonSpec::getMerchantCapabilities() { + static const auto method = _javaPart->javaClassStatic()->getMethod>()>("getMerchantCapabilities"); + auto __result = method(_javaPart); + return __result != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(__result)) : std::nullopt; + } + void JHybridGooglePayButtonSpec::setMerchantCapabilities(const std::optional>& merchantCapabilities) { + static const auto method = _javaPart->javaClassStatic()->getMethod> /* merchantCapabilities */)>("setMerchantCapabilities"); + method(_javaPart, merchantCapabilities.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(merchantCapabilities.value()) : nullptr); + } std::optional> JHybridGooglePayButtonSpec::getOnPress() { static const auto method = _javaPart->javaClassStatic()->getMethod()>("getOnPress_cxx"); auto __result = method(_javaPart); diff --git a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp index 8497ac1..68c6d7a 100644 --- a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp +++ b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp @@ -60,6 +60,8 @@ namespace margelo::nitro::pay { void setSupportedNetworks(const std::optional>& supportedNetworks) override; std::optional> getAllowedAuthMethods() override; void setAllowedAuthMethods(const std::optional>& allowedAuthMethods) override; + std::optional> getMerchantCapabilities() override; + void setMerchantCapabilities(const std::optional>& merchantCapabilities) override; std::optional> getOnPress() override; void setOnPress(const std::optional>& onPress) override; diff --git a/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp b/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp index 8eb6b26..5a76c82 100644 --- a/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp +++ b/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp @@ -37,6 +37,8 @@ namespace margelo::nitro::pay { jni::local_ref> supportedNetworks = this->getFieldValue(fieldSupportedNetworks); static const auto fieldGooglePayAllowedAuthMethods = clazz->getField>("googlePayAllowedAuthMethods"); jni::local_ref> googlePayAllowedAuthMethods = this->getFieldValue(fieldGooglePayAllowedAuthMethods); + static const auto fieldMerchantCapabilities = clazz->getField>("merchantCapabilities"); + jni::local_ref> merchantCapabilities = this->getFieldValue(fieldMerchantCapabilities); return PayServiceStatusOptions( supportedNetworks != nullptr ? std::make_optional([&](auto&& __input) { size_t __size = __input->size(); @@ -57,7 +59,17 @@ namespace margelo::nitro::pay { __vector.push_back(__element->toStdString()); } return __vector; - }(googlePayAllowedAuthMethods)) : std::nullopt + }(googlePayAllowedAuthMethods)) : std::nullopt, + merchantCapabilities != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(merchantCapabilities)) : std::nullopt ); } @@ -67,7 +79,7 @@ namespace margelo::nitro::pay { */ [[maybe_unused]] static jni::local_ref fromCpp(const PayServiceStatusOptions& value) { - using JSignature = JPayServiceStatusOptions(jni::alias_ref>, jni::alias_ref>); + using JSignature = JPayServiceStatusOptions(jni::alias_ref>, jni::alias_ref>, jni::alias_ref>); static const auto clazz = javaClassStatic(); static const auto create = clazz->getStaticMethod("fromCpp"); return create( @@ -91,7 +103,17 @@ namespace margelo::nitro::pay { __array->setElement(__i, *__elementJni); } return __array; - }(value.googlePayAllowedAuthMethods.value()) : nullptr + }(value.googlePayAllowedAuthMethods.value()) : nullptr, + value.merchantCapabilities.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(value.merchantCapabilities.value()) : nullptr ); } }; diff --git a/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp b/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp index a9d881a..70b1eed 100644 --- a/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp +++ b/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp @@ -57,6 +57,10 @@ void JHybridGooglePayButtonStateUpdater::updateViewProps(jni::alias_refsetAllowedAuthMethods(props->allowedAuthMethods.value); props->allowedAuthMethods.isDirty = false; } + if (props->merchantCapabilities.isDirty) { + hybridView->setMerchantCapabilities(props->merchantCapabilities.value); + props->merchantCapabilities.isDirty = false; + } if (props->onPress.isDirty) { hybridView->setOnPress(props->onPress.value); props->onPress.isDirty = false; diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt index 6911b3d..ed6e27c 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt @@ -56,6 +56,12 @@ abstract class HybridGooglePayButtonSpec: HybridView() { @set:Keep abstract var allowedAuthMethods: Array? + @get:DoNotStrip + @get:Keep + @set:DoNotStrip + @set:Keep + abstract var merchantCapabilities: Array? + abstract var onPress: (() -> Unit)? private var onPress_cxx: Func_void? diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt index 37a343e..2bfd3cb 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt @@ -23,7 +23,10 @@ data class PayServiceStatusOptions( val supportedNetworks: Array?, @DoNotStrip @Keep - val googlePayAllowedAuthMethods: Array? + val googlePayAllowedAuthMethods: Array?, + @DoNotStrip + @Keep + val merchantCapabilities: Array? ) { /* primary constructor */ @@ -32,12 +35,14 @@ data class PayServiceStatusOptions( if (other !is PayServiceStatusOptions) return false return Objects.deepEquals(this.supportedNetworks, other.supportedNetworks) && Objects.deepEquals(this.googlePayAllowedAuthMethods, other.googlePayAllowedAuthMethods) + && Objects.deepEquals(this.merchantCapabilities, other.merchantCapabilities) } override fun hashCode(): Int { return arrayOf( supportedNetworks, - googlePayAllowedAuthMethods + googlePayAllowedAuthMethods, + merchantCapabilities ).contentDeepHashCode() } @@ -49,8 +54,8 @@ data class PayServiceStatusOptions( @Keep @Suppress("unused") @JvmStatic - private fun fromCpp(supportedNetworks: Array?, googlePayAllowedAuthMethods: Array?): PayServiceStatusOptions { - return PayServiceStatusOptions(supportedNetworks, googlePayAllowedAuthMethods) + private fun fromCpp(supportedNetworks: Array?, googlePayAllowedAuthMethods: Array?, merchantCapabilities: Array?): PayServiceStatusOptions { + return PayServiceStatusOptions(supportedNetworks, googlePayAllowedAuthMethods, merchantCapabilities) } } } diff --git a/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift b/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift index 5d45704..82abf24 100644 --- a/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift +++ b/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift @@ -18,7 +18,7 @@ public extension PayServiceStatusOptions { /** * Create a new instance of `PayServiceStatusOptions`. */ - init(supportedNetworks: [String]?, googlePayAllowedAuthMethods: [String]?) { + init(supportedNetworks: [String]?, googlePayAllowedAuthMethods: [String]?, merchantCapabilities: [String]?) { self.init({ () -> bridge.std__optional_std__vector_std__string__ in if let __unwrappedValue = supportedNetworks { return bridge.create_std__optional_std__vector_std__string__({ () -> bridge.std__vector_std__string_ in @@ -43,6 +43,18 @@ public extension PayServiceStatusOptions { } else { return .init() } + }(), { () -> bridge.std__optional_std__vector_std__string__ in + if let __unwrappedValue = merchantCapabilities { + return bridge.create_std__optional_std__vector_std__string__({ () -> bridge.std__vector_std__string_ in + var __vector = bridge.create_std__vector_std__string_(__unwrappedValue.count) + for __item in __unwrappedValue { + __vector.push_back(std.string(__item)) + } + return __vector + }()) + } else { + return .init() + } }()) } @@ -69,4 +81,16 @@ public extension PayServiceStatusOptions { } }() } + + @inline(__always) + var merchantCapabilities: [String]? { + return { () -> [String]? in + if bridge.has_value_std__optional_std__vector_std__string__(self.__merchantCapabilities) { + let __unwrapped = bridge.get_std__optional_std__vector_std__string__(self.__merchantCapabilities) + return __unwrapped.map({ __item in String(__item) }) + } else { + return nil + } + }() + } } diff --git a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp index b2f6949..67e6464 100644 --- a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp +++ b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp @@ -24,6 +24,8 @@ namespace margelo::nitro::pay { prototype.registerHybridSetter("supportedNetworks", &HybridGooglePayButtonSpec::setSupportedNetworks); prototype.registerHybridGetter("allowedAuthMethods", &HybridGooglePayButtonSpec::getAllowedAuthMethods); prototype.registerHybridSetter("allowedAuthMethods", &HybridGooglePayButtonSpec::setAllowedAuthMethods); + prototype.registerHybridGetter("merchantCapabilities", &HybridGooglePayButtonSpec::getMerchantCapabilities); + prototype.registerHybridSetter("merchantCapabilities", &HybridGooglePayButtonSpec::setMerchantCapabilities); prototype.registerHybridGetter("onPress", &HybridGooglePayButtonSpec::getOnPress); prototype.registerHybridSetter("onPress", &HybridGooglePayButtonSpec::setOnPress); }); diff --git a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp index d93bbc4..2416f6d 100644 --- a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp +++ b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp @@ -62,6 +62,8 @@ namespace margelo::nitro::pay { virtual void setSupportedNetworks(const std::optional>& supportedNetworks) = 0; virtual std::optional> getAllowedAuthMethods() = 0; virtual void setAllowedAuthMethods(const std::optional>& allowedAuthMethods) = 0; + virtual std::optional> getMerchantCapabilities() = 0; + virtual void setMerchantCapabilities(const std::optional>& merchantCapabilities) = 0; virtual std::optional> getOnPress() = 0; virtual void setOnPress(const std::optional>& onPress) = 0; diff --git a/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp b/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp index 8b9fce5..15eafb3 100644 --- a/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp +++ b/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp @@ -43,10 +43,11 @@ namespace margelo::nitro::pay { public: std::optional> supportedNetworks SWIFT_PRIVATE; std::optional> googlePayAllowedAuthMethods SWIFT_PRIVATE; + std::optional> merchantCapabilities SWIFT_PRIVATE; public: PayServiceStatusOptions() = default; - explicit PayServiceStatusOptions(std::optional> supportedNetworks, std::optional> googlePayAllowedAuthMethods): supportedNetworks(supportedNetworks), googlePayAllowedAuthMethods(googlePayAllowedAuthMethods) {} + explicit PayServiceStatusOptions(std::optional> supportedNetworks, std::optional> googlePayAllowedAuthMethods, std::optional> merchantCapabilities): supportedNetworks(supportedNetworks), googlePayAllowedAuthMethods(googlePayAllowedAuthMethods), merchantCapabilities(merchantCapabilities) {} public: friend bool operator==(const PayServiceStatusOptions& lhs, const PayServiceStatusOptions& rhs) = default; @@ -63,13 +64,15 @@ namespace margelo::nitro { jsi::Object obj = arg.asObject(runtime); return margelo::nitro::pay::PayServiceStatusOptions( JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks"))), - JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"))) + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"))), + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::PayServiceStatusOptions& arg) { jsi::Object obj(runtime); obj.setProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks"), JSIConverter>>::toJSI(runtime, arg.supportedNetworks)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"), JSIConverter>>::toJSI(runtime, arg.googlePayAllowedAuthMethods)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"), JSIConverter>>::toJSI(runtime, arg.merchantCapabilities)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -82,6 +85,7 @@ namespace margelo::nitro { } if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks")))) 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, "merchantCapabilities")))) return false; return true; } }; diff --git a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp index 899713f..32aac90 100644 --- a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp +++ b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp @@ -76,6 +76,16 @@ namespace margelo::nitro::pay::views { throw std::runtime_error(std::string("GooglePayButton.allowedAuthMethods: ") + exc.what()); } }()), + merchantCapabilities([&]() -> CachedProp>> { + try { + const react::RawValue* rawValue = rawProps.at("merchantCapabilities", nullptr, nullptr); + if (rawValue == nullptr) return sourceProps.merchantCapabilities; + const auto& [runtime, value] = (std::pair)*rawValue; + return CachedProp>>::fromRawValue(*runtime, value, sourceProps.merchantCapabilities); + } catch (const std::exception& exc) { + throw std::runtime_error(std::string("GooglePayButton.merchantCapabilities: ") + exc.what()); + } + }()), onPress([&]() -> CachedProp>> { try { const react::RawValue* rawValue = rawProps.at("onPress", nullptr, nullptr); @@ -104,6 +114,7 @@ namespace margelo::nitro::pay::views { case hashString("radius"): return true; case hashString("supportedNetworks"): return true; case hashString("allowedAuthMethods"): return true; + case hashString("merchantCapabilities"): return true; case hashString("onPress"): return true; case hashString("hybridRef"): return true; default: return false; diff --git a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp index cdce648..75cc13c 100644 --- a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp +++ b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp @@ -50,6 +50,7 @@ namespace margelo::nitro::pay::views { CachedProp> radius; CachedProp>> supportedNetworks; CachedProp>> allowedAuthMethods; + CachedProp>> merchantCapabilities; CachedProp>> onPress; CachedProp& /* ref */)>>> hybridRef; diff --git a/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json b/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json index eab66c9..35657d3 100644 --- a/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json +++ b/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json @@ -9,6 +9,7 @@ "radius": true, "supportedNetworks": true, "allowedAuthMethods": true, + "merchantCapabilities": true, "onPress": true, "hybridRef": true } diff --git a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts index 12ffd31..a1518ba 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts @@ -72,6 +72,7 @@ describe('usePaymentCheckout integration', () => { expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) expect(mockPayServiceStatus).toHaveBeenCalledWith({ supportedNetworks: ['visa', 'mastercard', 'amex', 'discover'], + merchantCapabilities: ['3DS'], }) }) @@ -80,6 +81,7 @@ describe('usePaymentCheckout integration', () => { merchantName: 'Store A', supportedNetworks: ['visa', 'mastercard'], googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + merchantCapabilities: ['3DS', 'Debit'], } const { result, rerender } = renderWithConfig(config) @@ -89,10 +91,12 @@ describe('usePaymentCheckout integration', () => { expect(mockPayServiceStatus).toHaveBeenCalledWith({ supportedNetworks: ['visa', 'mastercard'], googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + merchantCapabilities: ['3DS', 'Debit'], }) expect(result.current.paymentRequest).toMatchObject({ supportedNetworks: ['visa', 'mastercard'], googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + merchantCapabilities: ['3DS', 'Debit'], }) rerender({ ...config, merchantName: 'Store B' }) @@ -103,6 +107,19 @@ describe('usePaymentCheckout integration', () => { expect(mockPayServiceStatus).toHaveBeenLastCalledWith({ supportedNetworks: ['visa'], googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + merchantCapabilities: ['3DS', 'Debit'], + }) + + rerender({ + ...config, + supportedNetworks: ['visa'], + merchantCapabilities: ['3DS'], + }) + expect(mockPayServiceStatus).toHaveBeenCalledTimes(3) + expect(mockPayServiceStatus).toHaveBeenLastCalledWith({ + supportedNetworks: ['visa'], + googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], + merchantCapabilities: ['3DS'], }) }) diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index a168d70..7b1d111 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -67,8 +67,8 @@ export interface UsePaymentCheckoutConfig { supportedNetworks?: string[] /** - * Merchant capabilities passed to Apple Pay. - * Defaults to `['3DS']`. + * Merchant capabilities passed to Apple Pay. On Android, `'Debit'` without + * `'Credit'` leaves credit cards out. Defaults to `['3DS']`. */ merchantCapabilities?: MerchantCapability[] @@ -339,6 +339,7 @@ export function usePaymentCheckout( const statusOptionsKey = JSON.stringify({ supportedNetworks: paymentRequest.supportedNetworks, googlePayAllowedAuthMethods: paymentRequest.googlePayAllowedAuthMethods, + merchantCapabilities: paymentRequest.merchantCapabilities, } satisfies PayServiceStatusOptions) useEffect(() => { diff --git a/package/src/specs/GooglePayButton.nitro.ts b/package/src/specs/GooglePayButton.nitro.ts index 15a19dc..e8a5338 100644 --- a/package/src/specs/GooglePayButton.nitro.ts +++ b/package/src/specs/GooglePayButton.nitro.ts @@ -27,6 +27,11 @@ export interface GooglePayButtonProps extends HybridViewProps { supportedNetworks?: string[] /** As `PaymentRequest.googlePayAllowedAuthMethods`. Defaults to both. */ allowedAuthMethods?: string[] + /** + * As `PaymentRequest.merchantCapabilities`. `'Debit'` without `'Credit'` + * leaves credit cards out. + */ + merchantCapabilities?: string[] onPress?: () => void } diff --git a/package/src/types/Payment.ts b/package/src/types/Payment.ts index 64233a8..23ab1e4 100644 --- a/package/src/types/Payment.ts +++ b/package/src/types/Payment.ts @@ -77,9 +77,11 @@ export type GooglePayEnvironment = 'TEST' | 'PRODUCTION' export type GooglePayAuthMethod = 'PAN_ONLY' | 'CRYPTOGRAM_3DS' /** - * Apple Pay merchant capability. `'3DS'` and `'EMV'` are payment protocols + * Merchant capability. `'3DS'` and `'EMV'` are Apple Pay payment protocols * (EMV only covers China UnionPay); `'Credit'` and `'Debit'` limit the * accepted card types. iOS adds `'3DS'` when neither protocol is given. + * Android only reads `'Debit'` without `'Credit'`, which leaves credit cards + * out: Google Pay cannot leave debit cards out. */ export type MerchantCapability = '3DS' | 'EMV' | 'Credit' | 'Debit' @@ -172,6 +174,7 @@ export interface PaymentRequest { paymentItems: PaymentItem[] // `MerchantCapability` values. Not typed as such: Nitro would generate a // native enum that rejects `'3ds'` or unknown values without a message. + // On Android, only `'Debit'` without `'Credit'` has an effect. merchantCapabilities: string[] /** * `PaymentNetwork` values, matched ignoring case. An unknown name fails the @@ -296,7 +299,7 @@ export interface PayServiceStatus { /** * The cards `payServiceStatus` asks about. Pass the values of your * `PaymentRequest`, so the check matches the payment. Android asks Google - * Pay about these cards; iOS only rejects unknown network names. + * Pay about these cards; iOS only rejects unknown values. */ export interface PayServiceStatusOptions { /** @@ -306,6 +309,11 @@ export interface PayServiceStatusOptions { supportedNetworks?: string[] /** As `PaymentRequest.googlePayAllowedAuthMethods`. Defaults to both. */ googlePayAllowedAuthMethods?: string[] + /** + * As `PaymentRequest.merchantCapabilities`. On Android, `'Debit'` without + * `'Credit'` leaves credit cards out. + */ + merchantCapabilities?: string[] } // Backward compatibility alias From 2e7e6eb1b492c91ec1d2c6d45d5b8d8d2f702a8d Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 23:35:51 +0100 Subject: [PATCH 6/8] refactor: name the button's auth methods prop googlePayAllowedAuthMethods The PaymentRequest, PayServiceStatusOptions and GooglePayButton now take supportedNetworks, googlePayAllowedAuthMethods and merchantCapabilities under the same names. Also points the debit-only button test at the renamed createAllowedPaymentMethods helper. --- CHANGELOG.md | 17 +++++++---------- README.md | 2 +- docs/docs/api/components.md | 4 ++-- example/app/(tabs)/index.tsx | 2 +- .../margelo/nitro/pay/HybridGooglePayButton.kt | 8 ++++++-- .../nitro/pay/GooglePayRequestBuilderTest.kt | 2 +- .../android/c++/JHybridGooglePayButtonSpec.cpp | 12 ++++++------ .../android/c++/JHybridGooglePayButtonSpec.hpp | 4 ++-- .../JHybridGooglePayButtonStateUpdater.cpp | 6 +++--- .../nitro/pay/HybridGooglePayButtonSpec.kt | 2 +- .../shared/c++/HybridGooglePayButtonSpec.cpp | 4 ++-- .../shared/c++/HybridGooglePayButtonSpec.hpp | 4 ++-- .../views/HybridGooglePayButtonComponent.cpp | 12 ++++++------ .../views/HybridGooglePayButtonComponent.hpp | 2 +- .../shared/json/GooglePayButtonConfig.json | 2 +- package/src/specs/GooglePayButton.nitro.ts | 2 +- 16 files changed, 43 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70d97ac..3a632a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,19 +30,16 @@ All notable changes to this project are documented in this file. `postFinance`, `pagoBancomat`, `tmoney`, `meeza`, `napas`, `bankAxept`, `himyan`, `jaywan` and `myDebit`, which Apple Pay accepts in `supportedNetworks` and reports in results. Android accepts `jcb` and `interac`, and `electron`, `maestro` and `elo` for Brazilian combo cards. -- **`GooglePayButton` takes `supportedNetworks` and `allowedAuthMethods`,** and - **`HybridPaymentHandler.payServiceStatus(options?)`** takes the same two values - (`PayServiceStatusOptions`). Give them the values of your request, so the button and the Android - readiness check use the same cards as the payment. `usePaymentCheckout` passes its config to - `payServiceStatus` and checks again when they change. +- **`GooglePayButton` takes `supportedNetworks`, `googlePayAllowedAuthMethods` and + `merchantCapabilities`,** and **`HybridPaymentHandler.payServiceStatus(options?)`** takes the + same values under the same names (`PayServiceStatusOptions`). Give them the values of your + request, so the button and the Android readiness check use the same cards as the payment. + `usePaymentCheckout` passes its config to `payServiceStatus` and checks again when they change. - **Android honours a debit-only `merchantCapabilities`.** `'Debit'` without `'Credit'` now leaves credit cards out of the Google Pay request (`allowCreditCards: false`), as UK gambling merchants must. Prepaid cards stay allowed. Google Pay cannot leave debit cards out, so `'Credit'` alone - still accepts every card type on Android; `'3DS'` and `'EMV'` have no effect there. - `GooglePayButton` takes a `merchantCapabilities` prop and `PayServiceStatusOptions` a - `merchantCapabilities` field, so the button and the readiness check are sent the same card - types. `usePaymentCheckout` passes its `merchantCapabilities` to `payServiceStatus` and checks - again when they change. + still accepts every card type on Android; `'3DS'` and `'EMV'` have no effect there. The button + and the readiness check leave credit cards out too. ### Changed diff --git a/README.md b/README.md index 0ade072..17c8300 100644 --- a/README.md +++ b/README.md @@ -634,7 +634,7 @@ interface GooglePayButtonProps { // The cards your payment accepts, so the button never shows another card. supportedNetworks?: string[]; // as PaymentRequest.supportedNetworks - allowedAuthMethods?: string[]; // as PaymentRequest.googlePayAllowedAuthMethods + googlePayAllowedAuthMethods?: string[]; // as PaymentRequest.googlePayAllowedAuthMethods merchantCapabilities?: string[]; // as PaymentRequest.merchantCapabilities onPress?: () => void; // wrap with callback() from react-native-nitro-modules diff --git a/docs/docs/api/components.md b/docs/docs/api/components.md index 4b3ed97..cfe9052 100644 --- a/docs/docs/api/components.md +++ b/docs/docs/api/components.md @@ -57,12 +57,12 @@ Renders the Google Pay button. Only available on Android. | `theme` | `'dark' \| 'light'` | Yes | Button theme. | | `radius` | `number` | No | Corner radius in dp. | | `supportedNetworks` | `string[]` | No | The card networks your payment accepts, as in `PaymentRequest.supportedNetworks`. Default: `visa`, `mastercard`, `amex`, `discover`. | -| `allowedAuthMethods` | `string[]` | No | As in `PaymentRequest.googlePayAllowedAuthMethods`. Default: both. | +| `googlePayAllowedAuthMethods` | `string[]` | No | As in `PaymentRequest.googlePayAllowedAuthMethods`. Default: both. | | `merchantCapabilities` | `string[]` | No | As in `PaymentRequest.merchantCapabilities`. `'Debit'` without `'Credit'` leaves credit cards out. Default: every card type. | | `onPress` | `() => void`, wrapped with `callback()` | No | Called when the user taps the button. Must be wrapped, see [Nitro and onPress](#nitro-and-onpress). | | `style` | `ViewStyle` | No | Layout/style (e.g. width, height). | -The button can show the payer's card, so give it the same `supportedNetworks`, `allowedAuthMethods` and `merchantCapabilities` as the payment. Otherwise it may show a card the payment then refuses. With `usePaymentCheckout`, pass `paymentRequest.supportedNetworks`, `paymentRequest.googlePayAllowedAuthMethods` and `paymentRequest.merchantCapabilities`. With an unknown network, auth method or merchant capability, the button keeps its previous configuration, or does not appear on the first render, and logs an error in debug builds. +The button can show the payer's card, so give it the same `supportedNetworks`, `googlePayAllowedAuthMethods` and `merchantCapabilities` as the payment, under the same names. Otherwise it may show a card the payment then refuses. With `usePaymentCheckout`, pass them from `paymentRequest`. With an unknown network, auth method or merchant capability, the button keeps its previous configuration, or does not appear on the first render, and logs an error in debug builds. **GooglePayButtonType:** `'buy'` | `'book'` | `'checkout'` | `'donate'` | `'order'` | `'pay'` | `'subscribe'` | `'plain'` diff --git a/example/app/(tabs)/index.tsx b/example/app/(tabs)/index.tsx index 378bc89..0c01486 100644 --- a/example/app/(tabs)/index.tsx +++ b/example/app/(tabs)/index.tsx @@ -297,7 +297,7 @@ export default function TabOneScreen() { radius={8} // The cards the request accepts, so the button shows one of them. supportedNetworks={paymentRequest.supportedNetworks} - allowedAuthMethods={paymentRequest.googlePayAllowedAuthMethods} + googlePayAllowedAuthMethods={paymentRequest.googlePayAllowedAuthMethods} merchantCapabilities={paymentRequest.merchantCapabilities} onPress={callback(handlePayment)} style={styles.payButton} diff --git a/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt b/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt index e7aa9f8..0017ef9 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/HybridGooglePayButton.kt @@ -29,7 +29,7 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton override var theme: GooglePayButtonTheme = GooglePayButtonTheme.DARK override var radius: Double? = null override var supportedNetworks: Array? = null - override var allowedAuthMethods: Array? = null + override var googlePayAllowedAuthMethods: Array? = null override var merchantCapabilities: Array? = null override var onPress: (() -> Unit)? = null @@ -56,7 +56,11 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton buttonType, theme, radius, - GooglePayCardParameters.from(supportedNetworks, allowedAuthMethods, merchantCapabilities) + GooglePayCardParameters.from( + supportedNetworks, + googlePayAllowedAuthMethods, + merchantCapabilities + ) ) if (payButton?.parent == container && config == buttonConfig) { updateExistingButton() 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 84f556b..abf31e2 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 @@ -561,7 +561,7 @@ class GooglePayRequestBuilderTest { val request = build(paymentRequest(coffee, merchantCapabilities = arrayOf("3DS", "Debit"))) val parameters = cardParametersOf(null, merchantCapabilities = arrayOf("3DS", "Debit")) val readiness = GooglePayRequestBuilder.createIsReadyToPayRequest(true, parameters) - val button = GooglePayRequestBuilder.createButtonPaymentMethods(parameters) + val button = GooglePayRequestBuilder.createAllowedPaymentMethods(parameters) assertFalse(request.cardParameters().getBoolean("allowCreditCards")) assertFalse(readiness.cardParameters().getBoolean("allowCreditCards")) diff --git a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp index afeea64..fc3a5b9 100644 --- a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp +++ b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.cpp @@ -107,8 +107,8 @@ namespace margelo::nitro::pay { return __array; }(supportedNetworks.value()) : nullptr); } - std::optional> JHybridGooglePayButtonSpec::getAllowedAuthMethods() { - static const auto method = _javaPart->javaClassStatic()->getMethod>()>("getAllowedAuthMethods"); + std::optional> JHybridGooglePayButtonSpec::getGooglePayAllowedAuthMethods() { + static const auto method = _javaPart->javaClassStatic()->getMethod>()>("getGooglePayAllowedAuthMethods"); auto __result = method(_javaPart); return __result != nullptr ? std::make_optional([&](auto&& __input) { size_t __size = __input->size(); @@ -121,9 +121,9 @@ namespace margelo::nitro::pay { return __vector; }(__result)) : std::nullopt; } - void JHybridGooglePayButtonSpec::setAllowedAuthMethods(const std::optional>& allowedAuthMethods) { - static const auto method = _javaPart->javaClassStatic()->getMethod> /* allowedAuthMethods */)>("setAllowedAuthMethods"); - method(_javaPart, allowedAuthMethods.has_value() ? [&](auto&& __input) { + void JHybridGooglePayButtonSpec::setGooglePayAllowedAuthMethods(const std::optional>& googlePayAllowedAuthMethods) { + static const auto method = _javaPart->javaClassStatic()->getMethod> /* googlePayAllowedAuthMethods */)>("setGooglePayAllowedAuthMethods"); + method(_javaPart, googlePayAllowedAuthMethods.has_value() ? [&](auto&& __input) { size_t __size = __input.size(); jni::local_ref> __array = jni::JArrayClass::newArray(__size); for (size_t __i = 0; __i < __size; __i++) { @@ -132,7 +132,7 @@ namespace margelo::nitro::pay { __array->setElement(__i, *__elementJni); } return __array; - }(allowedAuthMethods.value()) : nullptr); + }(googlePayAllowedAuthMethods.value()) : nullptr); } std::optional> JHybridGooglePayButtonSpec::getMerchantCapabilities() { static const auto method = _javaPart->javaClassStatic()->getMethod>()>("getMerchantCapabilities"); diff --git a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp index 68c6d7a..10d2cb0 100644 --- a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp +++ b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp @@ -58,8 +58,8 @@ namespace margelo::nitro::pay { void setRadius(std::optional radius) override; std::optional> getSupportedNetworks() override; void setSupportedNetworks(const std::optional>& supportedNetworks) override; - std::optional> getAllowedAuthMethods() override; - void setAllowedAuthMethods(const std::optional>& allowedAuthMethods) override; + std::optional> getGooglePayAllowedAuthMethods() override; + void setGooglePayAllowedAuthMethods(const std::optional>& googlePayAllowedAuthMethods) override; std::optional> getMerchantCapabilities() override; void setMerchantCapabilities(const std::optional>& merchantCapabilities) override; std::optional> getOnPress() override; diff --git a/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp b/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp index 70b1eed..884a40b 100644 --- a/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp +++ b/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp @@ -53,9 +53,9 @@ void JHybridGooglePayButtonStateUpdater::updateViewProps(jni::alias_refsetSupportedNetworks(props->supportedNetworks.value); props->supportedNetworks.isDirty = false; } - if (props->allowedAuthMethods.isDirty) { - hybridView->setAllowedAuthMethods(props->allowedAuthMethods.value); - props->allowedAuthMethods.isDirty = false; + if (props->googlePayAllowedAuthMethods.isDirty) { + hybridView->setGooglePayAllowedAuthMethods(props->googlePayAllowedAuthMethods.value); + props->googlePayAllowedAuthMethods.isDirty = false; } if (props->merchantCapabilities.isDirty) { hybridView->setMerchantCapabilities(props->merchantCapabilities.value); diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt index ed6e27c..ff7cbc5 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridGooglePayButtonSpec.kt @@ -54,7 +54,7 @@ abstract class HybridGooglePayButtonSpec: HybridView() { @get:Keep @set:DoNotStrip @set:Keep - abstract var allowedAuthMethods: Array? + abstract var googlePayAllowedAuthMethods: Array? @get:DoNotStrip @get:Keep diff --git a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp index 67e6464..a428565 100644 --- a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp +++ b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp @@ -22,8 +22,8 @@ namespace margelo::nitro::pay { prototype.registerHybridSetter("radius", &HybridGooglePayButtonSpec::setRadius); prototype.registerHybridGetter("supportedNetworks", &HybridGooglePayButtonSpec::getSupportedNetworks); prototype.registerHybridSetter("supportedNetworks", &HybridGooglePayButtonSpec::setSupportedNetworks); - prototype.registerHybridGetter("allowedAuthMethods", &HybridGooglePayButtonSpec::getAllowedAuthMethods); - prototype.registerHybridSetter("allowedAuthMethods", &HybridGooglePayButtonSpec::setAllowedAuthMethods); + prototype.registerHybridGetter("googlePayAllowedAuthMethods", &HybridGooglePayButtonSpec::getGooglePayAllowedAuthMethods); + prototype.registerHybridSetter("googlePayAllowedAuthMethods", &HybridGooglePayButtonSpec::setGooglePayAllowedAuthMethods); prototype.registerHybridGetter("merchantCapabilities", &HybridGooglePayButtonSpec::getMerchantCapabilities); prototype.registerHybridSetter("merchantCapabilities", &HybridGooglePayButtonSpec::setMerchantCapabilities); prototype.registerHybridGetter("onPress", &HybridGooglePayButtonSpec::getOnPress); diff --git a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp index 2416f6d..e198a8c 100644 --- a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp +++ b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.hpp @@ -60,8 +60,8 @@ namespace margelo::nitro::pay { virtual void setRadius(std::optional radius) = 0; virtual std::optional> getSupportedNetworks() = 0; virtual void setSupportedNetworks(const std::optional>& supportedNetworks) = 0; - virtual std::optional> getAllowedAuthMethods() = 0; - virtual void setAllowedAuthMethods(const std::optional>& allowedAuthMethods) = 0; + virtual std::optional> getGooglePayAllowedAuthMethods() = 0; + virtual void setGooglePayAllowedAuthMethods(const std::optional>& googlePayAllowedAuthMethods) = 0; virtual std::optional> getMerchantCapabilities() = 0; virtual void setMerchantCapabilities(const std::optional>& merchantCapabilities) = 0; virtual std::optional> getOnPress() = 0; diff --git a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp index 32aac90..b0ddc9b 100644 --- a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp +++ b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp @@ -66,14 +66,14 @@ namespace margelo::nitro::pay::views { throw std::runtime_error(std::string("GooglePayButton.supportedNetworks: ") + exc.what()); } }()), - allowedAuthMethods([&]() -> CachedProp>> { + googlePayAllowedAuthMethods([&]() -> CachedProp>> { try { - const react::RawValue* rawValue = rawProps.at("allowedAuthMethods", nullptr, nullptr); - if (rawValue == nullptr) return sourceProps.allowedAuthMethods; + const react::RawValue* rawValue = rawProps.at("googlePayAllowedAuthMethods", nullptr, nullptr); + if (rawValue == nullptr) return sourceProps.googlePayAllowedAuthMethods; const auto& [runtime, value] = (std::pair)*rawValue; - return CachedProp>>::fromRawValue(*runtime, value, sourceProps.allowedAuthMethods); + return CachedProp>>::fromRawValue(*runtime, value, sourceProps.googlePayAllowedAuthMethods); } catch (const std::exception& exc) { - throw std::runtime_error(std::string("GooglePayButton.allowedAuthMethods: ") + exc.what()); + throw std::runtime_error(std::string("GooglePayButton.googlePayAllowedAuthMethods: ") + exc.what()); } }()), merchantCapabilities([&]() -> CachedProp>> { @@ -113,7 +113,7 @@ namespace margelo::nitro::pay::views { case hashString("theme"): return true; case hashString("radius"): return true; case hashString("supportedNetworks"): return true; - case hashString("allowedAuthMethods"): return true; + case hashString("googlePayAllowedAuthMethods"): return true; case hashString("merchantCapabilities"): return true; case hashString("onPress"): return true; case hashString("hybridRef"): return true; diff --git a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp index 75cc13c..c764bf6 100644 --- a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp +++ b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.hpp @@ -49,7 +49,7 @@ namespace margelo::nitro::pay::views { CachedProp theme; CachedProp> radius; CachedProp>> supportedNetworks; - CachedProp>> allowedAuthMethods; + CachedProp>> googlePayAllowedAuthMethods; CachedProp>> merchantCapabilities; CachedProp>> onPress; CachedProp& /* ref */)>>> hybridRef; diff --git a/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json b/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json index 35657d3..b2b665e 100644 --- a/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json +++ b/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json @@ -8,7 +8,7 @@ "theme": true, "radius": true, "supportedNetworks": true, - "allowedAuthMethods": true, + "googlePayAllowedAuthMethods": true, "merchantCapabilities": true, "onPress": true, "hybridRef": true diff --git a/package/src/specs/GooglePayButton.nitro.ts b/package/src/specs/GooglePayButton.nitro.ts index e8a5338..755ed70 100644 --- a/package/src/specs/GooglePayButton.nitro.ts +++ b/package/src/specs/GooglePayButton.nitro.ts @@ -26,7 +26,7 @@ export interface GooglePayButtonProps extends HybridViewProps { */ supportedNetworks?: string[] /** As `PaymentRequest.googlePayAllowedAuthMethods`. Defaults to both. */ - allowedAuthMethods?: string[] + googlePayAllowedAuthMethods?: string[] /** * As `PaymentRequest.merchantCapabilities`. `'Debit'` without `'Credit'` * leaves credit cards out. From e2bff47e49ef604b0d56e9a939b78b9d46bb2834 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 23:50:16 +0100 Subject: [PATCH 7/8] chore: drop watchman cookie files committed by accident --- package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-3423 | 0 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-3424 | 0 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100755 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-3423 delete mode 100755 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-3424 diff --git a/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-3423 b/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-3423 deleted file mode 100755 index e69de29..0000000 diff --git a/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-3424 b/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-3424 deleted file mode 100755 index e69de29..0000000 From 4ea386a2b63b01b1445fef311323da736f756fed Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 23:53:01 +0100 Subject: [PATCH 8/8] docs: say the availability check rejects with the payment's configuration error --- CHANGELOG.md | 4 ++-- README.md | 2 +- docs/docs/api/hybrid-payment-handler.md | 2 +- docs/docs/api/types.md | 2 +- docs/docs/guides/availability.md | 2 +- .../main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt | 2 +- package/ios/HybridPaymentHandler.swift | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47bdf1b..1a5dae9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,8 +50,8 @@ All notable changes to this project are documented in this file. that contains `Unknown payment network "". Use a PaymentNetwork value such as "visa" or "mastercard"`. iOS used to drop it silently. Names now match ignoring case, so `'Visa'` works, and a network the platform does not offer is left out; the payment fails when none is left. - `payServiceStatus` rejects with the same message for a value the payment would refuse, instead - of answering `hasActiveCard: false`. + `payServiceStatus` rejects with the same configuration error for a value the payment would + refuse, instead of answering `hasActiveCard: false`. - **An unknown value in `merchantCapabilities` fails the payment on Android too,** with the same `error` as on iOS: `Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"`. Android used to ignore the field. diff --git a/README.md b/README.md index c46453a..5722da6 100644 --- a/README.md +++ b/README.md @@ -464,7 +464,7 @@ Low-level payment handler for direct control. ##### `payServiceStatus(options?: PayServiceStatusOptions): Promise` -Check payment service availability without blocking the JS thread. Pass the `supportedNetworks`, `merchantCapabilities`, `googlePayAllowedAuthMethods` and `googlePayEnvironment` your payment request uses. The Promise rejects with the payment's message for a value the payment would refuse. +Check payment service availability without blocking the JS thread. Pass the `supportedNetworks`, `merchantCapabilities`, `googlePayAllowedAuthMethods` and `googlePayEnvironment` your payment request uses. The Promise rejects with the payment's configuration error for a value the payment would refuse. ```typescript import { HybridPaymentHandler } from "@gmisoftware/react-native-pay"; diff --git a/docs/docs/api/hybrid-payment-handler.md b/docs/docs/api/hybrid-payment-handler.md index 8ae8e4e..ba16630 100644 --- a/docs/docs/api/hybrid-payment-handler.md +++ b/docs/docs/api/hybrid-payment-handler.md @@ -27,7 +27,7 @@ const status = await HybridPaymentHandler.payServiceStatus({ - **isSupported** — The device can pay with Apple Pay / Google Pay, whether or not a card is set up. - **hasActiveCard** — The user has a card ready on one of `supportedNetworks`. -Pass the `supportedNetworks`, `merchantCapabilities`, `googlePayAllowedAuthMethods` and `googlePayEnvironment` your payment request uses ([PayServiceStatusOptions](/docs/api/types#payservicestatusoptions)); `hasActiveCard` then counts only cards the payment accepts. Without them, both platforms ask about `visa`, `mastercard`, `amex` and `discover`. The Promise rejects with the same message as `startPayment` for a value the payment would refuse: an unknown network, capability or auth method, or no network the platform offers. A check that fails for any other reason resolves both flags as `false`. Without `googlePayEnvironment`, Android asks the `TEST` environment, where `hasActiveCard` is `true` whether or not the user has a card. What each platform checks, and which button to show, is in [Check availability](/docs/guides/availability). +Pass the `supportedNetworks`, `merchantCapabilities`, `googlePayAllowedAuthMethods` and `googlePayEnvironment` your payment request uses ([PayServiceStatusOptions](/docs/api/types#payservicestatusoptions)); `hasActiveCard` then counts only cards the payment accepts. Without them, both platforms ask about `visa`, `mastercard`, `amex` and `discover`. The Promise rejects with the configuration error that would fail `startPayment` for a value the payment would refuse: an unknown network, capability or auth method, or no network the platform offers. A check that fails for any other reason resolves both flags as `false`. Without `googlePayEnvironment`, Android asks the `TEST` environment, where `hasActiveCard` is `true` whether or not the user has a card. What each platform checks, and which button to show, is in [Check availability](/docs/guides/availability). --- diff --git a/docs/docs/api/types.md b/docs/docs/api/types.md index a0ff249..e68e27c 100644 --- a/docs/docs/api/types.md +++ b/docs/docs/api/types.md @@ -230,7 +230,7 @@ interface PayServiceStatusOptions { } ``` -The values are checked as in `startPayment`, and the Promise rejects with the same message for a value the payment would refuse. +The values are checked as in `startPayment`, and the Promise rejects with the same configuration error for a value the payment would refuse. --- diff --git a/docs/docs/guides/availability.md b/docs/docs/guides/availability.md index a4e31a1..c9b507d 100644 --- a/docs/docs/guides/availability.md +++ b/docs/docs/guides/availability.md @@ -12,7 +12,7 @@ Decide which wallet button to show before the user taps anything. The library re | `isSupported` | `PKPaymentAuthorizationViewController.canMakePayments()`: hardware and parental controls allow Apple Pay | `isReadyToPay`: Google Pay is available, and the user has a card or can add one | | `hasActiveCard` | `canMakePayments(usingNetworks:capabilities:)` with your `supportedNetworks` and `merchantCapabilities` | `isReadyToPay` with `existingPaymentMethodRequired: true` and your `supportedNetworks`, `googlePayAllowedAuthMethods` and `merchantCapabilities` | -Both flags are `false` when the check fails or, on Android, when Google Pay does not answer within 5 seconds. A value the payment would refuse rejects the `payServiceStatus` Promise with the same message as `startPayment`: an unknown network, merchant capability or auth method, or a network list the platform offers none of (Google Pay has no `idcredit` or `privateLabel`). The hook logs the rejection and reports both flags as `false`. +Both flags are `false` when the check fails or, on Android, when Google Pay does not answer within 5 seconds. A value the payment would refuse rejects the `payServiceStatus` Promise with the configuration error that would fail `startPayment`: an unknown network, merchant capability or auth method, or a network list the platform offers none of (Google Pay has no `idcredit` or `privateLabel`). The hook logs the rejection and reports both flags as `false`. ### Ask the environment you pay in diff --git a/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt b/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt index 4f4f454..ae75615 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt @@ -65,7 +65,7 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { override fun payServiceStatus(options: PayServiceStatusOptions?): Promise { val environment = determineEnvironment(options?.googlePayEnvironment) - // Rejects what the payment would refuse, with the same message. + // Rejects what the payment would refuse, with the same error. val cardParameters = try { GooglePayCardParameters.from( options?.supportedNetworks, diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index 383db11..281b4b7 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -309,7 +309,7 @@ enum PaymentReadiness { // Checked when the caller names no networks, like the hook's default. static let defaultNetworks = ["visa", "mastercard", "amex", "discover"] - /// Rejects what the payment would refuse, with the same message. + /// Rejects what the payment would refuse, with the same error. static func hasActiveCard(networks: [String], merchantCapabilities: [String]?) throws -> Bool { let capabilities = try PaymentRequestBuilder.buildMerchantCapabilities(merchantCapabilities ?? []) let paymentNetworks = try PaymentRequestBuilder.buildSupportedNetworks(networks)