diff --git a/CHANGELOG.md b/CHANGELOG.md index df6cc6c..1a5dae9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,9 +22,43 @@ 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`, `googlePayAllowedAuthMethods` and + `merchantCapabilities`,** and `PayServiceStatusOptions` takes `googlePayAllowedAuthMethods`, under + the same names as in `PaymentRequest`. Give them the values of your request, so the button and + `hasActiveCard` count the same cards as the payment. `usePaymentCheckout` passes its config to + `payServiceStatus`. +- **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. The button + and the readiness check leave credit cards out too. ### 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. + `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. +- **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`. @@ -68,6 +102,15 @@ 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. +- **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. @@ -83,8 +126,6 @@ All notable changes to this project are documented in this file. until a payment had started, and in `TEST` Google Pay reports a card whether or not there is one, so production apps showed the pay button for users without a card. It now uses `googlePayEnvironment` from the hook config or the options. -- **`hasActiveCard` is `false` when no checked network is one the platform knows.** iOS passed an - empty network list to PassKit, which can answer `true` for it. - **iOS: Apple Pay requests always include 3DS or EMV.** PassKit needs one of them, but iOS matched only the exact strings `3DS`, `EMV`, `Credit` and `Debit` and dropped everything else, so `[]`, `['Credit']` or `['3ds']` built a request with neither. Values are now matched diff --git a/README.md b/README.md index bd13cec..5722da6 100644 --- a/README.md +++ b/README.md @@ -372,14 +372,15 @@ 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'] - merchantCapabilities?: MerchantCapability[]; // Default: ['3DS'] + supportedNetworks?: string[]; // PaymentNetwork names. Default: ['visa', 'mastercard', 'amex', 'discover'] + merchantCapabilities?: MerchantCapability[]; // Default: ['3DS']. Android: only Debit without Credit applePayMerchantIdentifier?: string; // Optional iOS override // Google Pay specific (Android) googlePayMerchantId?: string; 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; @@ -463,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 networks, capabilities and Google Pay environment your payment request uses. +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"; @@ -634,6 +635,11 @@ 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 + googlePayAllowedAuthMethods?: string[]; // as PaymentRequest.googlePayAllowedAuthMethods + merchantCapabilities?: string[]; // as PaymentRequest.merchantCapabilities + onPress?: () => void; // wrap with callback() from react-native-nitro-modules style?: ViewStyle; } @@ -759,7 +765,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 @@ -771,6 +777,7 @@ interface PaymentRequest { googlePayEnvironment?: "TEST" | "PRODUCTION"; googlePayGateway?: string; googlePayGatewayMerchantId?: string; + googlePayAllowedAuthMethods?: string[]; // GooglePayAuthMethod values } // Payment Result @@ -790,14 +797,16 @@ interface PaymentToken { // Payment Method interface PaymentMethod { - displayName?: string; - network?: PaymentNetwork; - type: PaymentMethodType; + displayName?: string; // for the payer, e.g. "Visa •••• 1234"; don't parse it + network?: PaymentNetwork; // "unknown" when the library cannot name it + type: PaymentMethodType; // funding source; "store" is iOS only 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" @@ -809,7 +818,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"; @@ -830,7 +865,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 2f2a6dd..cfe9052 100644 --- a/docs/docs/api/components.md +++ b/docs/docs/api/components.md @@ -56,9 +56,14 @@ 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`. | +| `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`, `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'` @@ -76,6 +81,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 48558c9..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 networks, capabilities and Google Pay environment your payment request uses ([PayServiceStatusOptions](/docs/api/types#payservicestatusoptions)). A failed check resolves both flags as `false`, except that on iOS an unknown `merchantCapabilities` value rejects the Promise, as it fails `startPayment`. 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 fb18bc6..e68e27c 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,36 @@ 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. +- **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. + --- ## 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 @@ -191,22 +213,25 @@ interface PayServiceStatus { | | iOS | Android | |---|---|---| | `isSupported` | `PKPaymentAuthorizationViewController.canMakePayments()` | `isReadyToPay` | -| `hasActiveCard` | `canMakePayments(usingNetworks:capabilities:)` | `isReadyToPay` with `existingPaymentMethodRequired: true` | +| `hasActiveCard` | `canMakePayments(usingNetworks:capabilities:)` | `isReadyToPay` with `existingPaymentMethodRequired: true` and the request's card parameters | In the Google Pay `TEST` environment, `hasActiveCard` is `true` whether or not the user has a card. See [Check availability](/docs/guides/availability). ## PayServiceStatusOptions -What `payServiceStatus` checks. Pass the values your payment request uses. +What `payServiceStatus` checks. Pass the values your payment request uses, so `hasActiveCard` counts only cards the payment accepts. ```ts interface PayServiceStatusOptions { - supportedNetworks?: string[] // default: ['visa', 'mastercard', 'amex', 'discover'] - merchantCapabilities?: string[] // iOS only. Default: ['3DS'] + supportedNetworks?: string[] // default: ['visa', 'mastercard', 'amex', 'discover'] + merchantCapabilities?: string[] // default: ['3DS'] + googlePayAllowedAuthMethods?: string[] // Android only. Default: both googlePayEnvironment?: 'TEST' | 'PRODUCTION' // Android only. Default: 'TEST' } ``` +The values are checked as in `startPayment`, and the Promise rejects with the same configuration error for a value the payment would refuse. + --- ## GooglePayEnvironment @@ -221,18 +246,46 @@ 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). +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 ab9c4f3..aab4c5a 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,8 +42,10 @@ 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. -- **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). -- **supportedNetworks**, **merchantCapabilities**, **googlePayEnvironment** — Also used for the availability check. Set `googlePayEnvironment: 'PRODUCTION'` in a live app: in `TEST`, Google Pay reports a card whether or not there is one. +- **supportedNetworks** — The card networks the payer can choose, as [PaymentNetwork](/docs/api/types#paymentnetwork) names. Both platforms honour it. A network the platform does not offer is left out, and an unknown name fails the payment. Pass the same list to [`GooglePayButton`](/docs/api/components#googlepaybutton-android-only). +- **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** — 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). +- **supportedNetworks**, **merchantCapabilities**, **googlePayAllowedAuthMethods**, **googlePayEnvironment** — Also used for the availability check, which fails like the payment for a value the payment would refuse. Set `googlePayEnvironment: 'PRODUCTION'` in a live app: in `TEST`, Google Pay reports a card whether or not there is one. - **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. @@ -79,7 +82,7 @@ interface UsePaymentCheckoutReturn { - **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`. See [PayServiceStatus](/docs/api/types#payservicestatus) for what each platform checks. -- **isCheckingStatus** — `true` until the availability check settles. The hook checks on mount and again when `supportedNetworks`, `merchantCapabilities` or `googlePayEnvironment` change. The check never blocks the JS thread. +- **isCheckingStatus** — `true` until the availability check settles. The hook checks on mount and again when `supportedNetworks`, `merchantCapabilities`, `googlePayAllowedAuthMethods` or `googlePayEnvironment` change. The check never blocks the JS thread. - **refreshStatus()** — Checks availability again, for example when the app returns from Wallet after `openPaymentSetup()`. `isCheckingStatus` is `true` until it settles, and the flags keep their last values meanwhile. Which button to show for each combination is in [Check availability](/docs/guides/availability). @@ -91,7 +94,7 @@ Which button to show for each combination is in [Check availability](/docs/guide - 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/docs/docs/guides/availability.md b/docs/docs/guides/availability.md index 3f7e025..c9b507d 100644 --- a/docs/docs/guides/availability.md +++ b/docs/docs/guides/availability.md @@ -10,9 +10,9 @@ Decide which wallet button to show before the user taps anything. The library re | | iOS | Android | |---|---|---| | `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` | +| `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. One exception: on iOS, an unknown `merchantCapabilities` value rejects the `payServiceStatus` Promise, as it fails `startPayment`. The hook logs the rejection and reports both flags as `false`. `hasActiveCard` is also `false` when none of the networks is one the platform knows (Google Pay has no `idcredit` or `privateLabel`). +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/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 8c8441c..ff42f8f 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 bd01d9d..841babd 100644 --- a/example/app/(tabs)/index.tsx +++ b/example/app/(tabs)/index.tsx @@ -45,6 +45,7 @@ export default function TabOneScreen() { result, error, reset, + paymentRequest, } = usePaymentCheckout({ merchantName: "React Native Pay Demo", countryCode: "US", @@ -316,6 +317,10 @@ 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} + googlePayAllowedAuthMethods={paymentRequest.googlePayAllowedAuthMethods} + merchantCapabilities={paymentRequest.merchantCapabilities} 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 48e1c1c..50d55b3 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,23 +40,6 @@ object PaymentConstants { const val ERROR_AUTHORIZATION_FAILED = "Payment authorization failed" const val ERROR_AUTHORIZATION_TIMED_OUT = "Payment authorization timed out" - // Networks checked when the caller names none, as sent in payment requests - val DEFAULT_CARD_NETWORKS = listOf(NETWORK_VISA, NETWORK_MASTERCARD, NETWORK_AMEX, NETWORK_DISCOVER) - - // Lowercase `PaymentNetwork` name to Google Pay `allowedCardNetworks` value. - // ELECTRON, MAESTRO and ELO only apply to Brazilian combo cards. - val GOOGLE_CARD_NETWORKS = mapOf( - "visa" to NETWORK_VISA, - "mastercard" to NETWORK_MASTERCARD, - "amex" to NETWORK_AMEX, - "discover" to NETWORK_DISCOVER, - "jcb" to "JCB", - "interac" to "INTERAC", - "electron" to "ELECTRON", - "maestro" to "MAESTRO", - "elo" to "ELO" - ) - // How long an availability check waits for Google Pay const val READY_TO_PAY_TIMEOUT_SECONDS = 5L 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..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 @@ -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.createAllowedPaymentMethods(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..f7d069e --- /dev/null +++ b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayCardParameters.kt @@ -0,0 +1,127 @@ +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, + 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 { + private val DEFAULT_NETWORKS = arrayOf("visa", "mastercard", "amex", "discover") + private val AUTH_METHODS = listOf( + PaymentConstants.AUTH_PAN_ONLY, + PaymentConstants.AUTH_CRYPTOGRAM_3DS + ) + + private val MERCHANT_CAPABILITIES = listOf("3DS", "EMV", "Credit", "Debit") + + /** The cards checked when the caller names none */ + val DEFAULT = from(null, null) + + /** + * 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?, + merchantCapabilities: Array? = null + ): 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\"" + } + + 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 a6a11b2..359c730 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,16 @@ import java.math.RoundingMode object GooglePayRequestBuilder { /** - * Creates an IsReadyToPay request - * - * @param cardNetworks Google Pay `allowedCardNetworks` values, see [googleCardNetworks]. + * Creates an IsReadyToPay request for the cards in [cardParameters] */ - fun createIsReadyToPayRequest( - cardNetworks: List, + internal fun createIsReadyToPayRequest( + cardParameters: GooglePayCardParameters, existingPaymentMethodRequired: Boolean? = null ): JSONObject { return JSONObject().apply { put("apiVersion", PaymentConstants.API_VERSION) put("apiVersionMinor", PaymentConstants.API_VERSION_MINOR) - put("allowedPaymentMethods", JSONArray().apply { - put(createBaseCardPaymentMethod(JSONArray(cardNetworks))) - }) + put("allowedPaymentMethods", createAllowedPaymentMethods(cardParameters)) existingPaymentMethodRequired?.let { put("existingPaymentMethodRequired", it) } @@ -33,13 +29,13 @@ object GooglePayRequestBuilder { } /** - * Maps `PaymentNetwork` names to Google Pay `allowedCardNetworks` values, - * without duplicates. Names Google Pay has no network for are dropped. + * The `allowedPaymentMethods` of an IsReadyToPay request or a PayButton: + * the cards in [cardParameters] */ - fun googleCardNetworks(networks: Array): List { - return networks - .mapNotNull { PaymentConstants.GOOGLE_CARD_NETWORKS[it.lowercase()] } - .distinct() + internal fun createAllowedPaymentMethods(cardParameters: GooglePayCardParameters): JSONArray { + return JSONArray().apply { + put(createBaseCardPaymentMethod(cardParameters)) + } } /** @@ -56,13 +52,18 @@ object GooglePayRequestBuilder { validatePaymentRequest(request, environment) validateShippingMethods(request) val requested = RequestedDetails.from(request) + val cardParameters = GooglePayCardParameters.from( + request.supportedNetworks, + request.googlePayAllowedAuthMethods, + request.merchantCapabilities + ) 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) { @@ -100,15 +101,10 @@ object GooglePayRequestBuilder { /** * Creates base card payment method (no tokenization) */ - private fun createBaseCardPaymentMethod( - allowedCardNetworks: JSONArray = createAllowedCardNetworks() - ): 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", allowedCardNetworks) - }) + put("parameters", cardParameters.toJson()) } } @@ -118,9 +114,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) @@ -287,23 +284,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(PaymentConstants.DEFAULT_CARD_NETWORKS) - } } - - 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..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 @@ -11,19 +11,26 @@ 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 buttonConfig: ButtonConfig? = 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 googlePayAllowedAuthMethods: Array? = null + override var merchantCapabilities: Array? = null override var onPress: (() -> Unit)? = null override var view: View = container @@ -44,12 +51,23 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton val context = container.context ?: return try { - if (shouldReuseButton()) { + // Built first, so an invalid value keeps the existing button. + val config = ButtonConfig( + buttonType, + theme, + radius, + GooglePayCardParameters.from( + supportedNetworks, + googlePayAllowedAuthMethods, + merchantCapabilities + ) + ) + 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) @@ -57,17 +75,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 - return hasButton && propsUnchanged - } - /** * Updates the click listener on existing button */ @@ -81,11 +88,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" - ) + private fun recreateButton(context: android.content.Context, config: ButtonConfig) { + PayLog.d(PaymentConstants.TAG_GOOGLE_PAY_BUTTON, "Recreating button - $config") // Remove existing button container.removeAllViews() @@ -93,17 +97,16 @@ class HybridGooglePayButton(context: ThemedReactContext) : HybridGooglePayButton // Create new button val newButton = GooglePayButtonFactory.createButton( context, - buttonType, - theme, - radius, + config.buttonType, + config.theme, + config.radius, + config.cardParameters, onPress ) // Update state payButton = newButton - currentButtonType = buttonType - currentTheme = theme - currentRadius = radius + buttonConfig = config // 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 751266f..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,16 +65,23 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { override fun payServiceStatus(options: PayServiceStatusOptions?): Promise { val environment = determineEnvironment(options?.googlePayEnvironment) - val cardNetworks = options?.supportedNetworks - ?.let { GooglePayRequestBuilder.googleCardNetworks(it) } - ?: PaymentConstants.DEFAULT_CARD_NETWORKS + // Rejects what the payment would refuse, with the same error. + val cardParameters = try { + GooglePayCardParameters.from( + options?.supportedNetworks, + options?.googlePayAllowedAuthMethods, + options?.merchantCapabilities + ) + } catch (e: IllegalArgumentException) { + return Promise.rejected(e) + } // Both requests run at once; neither blocks the calling (JS) thread. val isSupported = isReadyToPay( environment, - PaymentConstants.DEFAULT_CARD_NETWORKS, + GooglePayCardParameters.DEFAULT, existingPaymentMethodRequired = false ) - val hasActiveCard = isReadyToPay(environment, cardNetworks, existingPaymentMethodRequired = true) + val hasActiveCard = isReadyToPay(environment, cardParameters, existingPaymentMethodRequired = true) val promise = Promise() Tasks.whenAll(isSupported, hasActiveCard).addOnCompleteListener { @@ -235,15 +242,12 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { */ private fun isReadyToPay( environment: Int, - cardNetworks: List, + cardParameters: GooglePayCardParameters, existingPaymentMethodRequired: Boolean ): Task { - // No network Google Pay knows: no card can be on it. - if (cardNetworks.isEmpty()) return Tasks.forResult(false) - val answer: Task = try { val requestJson = GooglePayRequestBuilder.createIsReadyToPayRequest( - cardNetworks = cardNetworks, + cardParameters = cardParameters, existingPaymentMethodRequired = existingPaymentMethodRequired ) Tasks.withTimeout( 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..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,12 +30,15 @@ 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 + // Create payment method. Google Pay asks to show `description` + // to the payer, not `cardNetwork`. val paymentMethod = PaymentMethod( - displayName = "$cardNetwork $cardDetails", - network = mapCardNetwork(cardNetwork), - type = PaymentMethodType.UNKNOWN, + displayName = paymentMethodData.optNonEmpty("description") + ?: "$cardNetwork $cardDetails", + network = GooglePayNetworks.fromGooglePay(cardNetwork), + type = mapCardFundingSource(cardFundingSource), secureElementPass = null, billingAddress = null ) @@ -134,20 +137,14 @@ object PaymentMapper { } /** - * Maps card network string to PaymentNetwork enum + * Maps a Google Pay `cardFundingSource` value to PaymentMethodType, 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 + 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 } } 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 f5c6b36..e9b723c 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,15 +28,18 @@ class GooglePayRequestBuilderTest { shippingContactRequired: Boolean? = null, emailRequired: Boolean? = null, phoneNumberRequired: Boolean? = null, - shippingMethods: Array? = null + shippingMethods: Array? = null, + supportedNetworks: Array = arrayOf("visa"), + googlePayAllowedAuthMethods: Array? = null, + merchantCapabilities: Array = arrayOf("3DS") ) = PaymentRequest( applePayMerchantIdentifier = null, merchantName = merchantName, countryCode = "US", currencyCode = currencyCode, paymentItems = items, - merchantCapabilities = arrayOf("3DS"), - supportedNetworks = arrayOf("visa"), + merchantCapabilities = merchantCapabilities, + supportedNetworks = supportedNetworks, shippingType = null, shippingMethods = shippingMethods, billingContactRequired = billingContactRequired, @@ -46,7 +49,8 @@ class GooglePayRequestBuilderTest { googlePayMerchantId = googlePayMerchantId, googlePayEnvironment = environment, googlePayGateway = googlePayGateway, - googlePayGatewayMerchantId = googlePayGatewayMerchantId + googlePayGatewayMerchantId = googlePayGatewayMerchantId, + googlePayAllowedAuthMethods = googlePayAllowedAuthMethods ) private fun build( @@ -420,9 +424,206 @@ class GooglePayRequestBuilderTest { @Test fun isReadyToPayRequest_neverAsksForContacts() { - val parameters = GooglePayRequestBuilder.createIsReadyToPayRequest(PaymentConstants.DEFAULT_CARD_NETWORKS) - .getJSONArray("allowedPaymentMethods").getJSONObject(0).getJSONObject("parameters") + val parameters = GooglePayRequestBuilder.createIsReadyToPayRequest(GooglePayCardParameters.DEFAULT).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, + merchantCapabilities: Array? = null + ) = GooglePayCardParameters.from(networks, authMethods, merchantCapabilities) + + @Test + fun supportedNetworks_areTheOnlyNetworksInTheRequestTheReadinessCheckAndTheButton() { + val request = build(paymentRequest(coffee, supportedNetworks = arrayOf("visa", "mastercard"))) + val parameters = cardParametersOf(arrayOf("visa", "mastercard")) + val readiness = GooglePayRequestBuilder.createIsReadyToPayRequest(parameters, existingPaymentMethodRequired = true) + val button = GooglePayRequestBuilder.createAllowedPaymentMethods(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(GooglePayCardParameters.DEFAULT).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 + ) + } + + // 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(parameters, existingPaymentMethodRequired = true) + val button = GooglePayRequestBuilder.createAllowedPaymentMethods(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")) + } + val readiness = GooglePayRequestBuilder.createIsReadyToPayRequest(GooglePayCardParameters.DEFAULT) + assertFalse(readiness.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/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt index ef73c31..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) } @@ -98,6 +98,44 @@ 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 + 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 +282,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) @@ -270,22 +309,88 @@ 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 fromGooglePay_reportsUnrecognizedNetworksAsUnknown() { + assertEquals(PaymentNetwork.UNKNOWN, GooglePayNetworks.fromGooglePay("unknown")) + assertEquals(PaymentNetwork.UNKNOWN, GooglePayNetworks.fromGooglePay("ELO_DEBIT")) + assertEquals(PaymentNetwork.UNKNOWN, GooglePayNetworks.fromGooglePay("")) } @Test - fun mapCardNetwork_reportsUnknownNetworksAsVisa() { - // Current behavior, tracked in #13. - assertEquals(PaymentNetwork.VISA, PaymentMapper.mapCardNetwork("unknown")) + fun fromGooglePay_readsBackEveryNetworkTheRequestSends() { + for (network in PaymentNetwork.entries) { + val cardNetwork = GooglePayNetworks.toGooglePay(network) ?: continue + assertEquals(network, GooglePayNetworks.fromGooglePay(cardNetwork)) + } + } + + @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 diff --git a/package/android/src/test/java/com/margelo/nitro/pay/ReadyToPayRequestTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/ReadyToPayRequestTest.kt index 2be2c9f..5e09216 100644 --- a/package/android/src/test/java/com/margelo/nitro/pay/ReadyToPayRequestTest.kt +++ b/package/android/src/test/java/com/margelo/nitro/pay/ReadyToPayRequestTest.kt @@ -16,42 +16,10 @@ class ReadyToPayRequestTest { return (0 until networks.length()).map { networks.getString(it) } } - @Test - fun googleCardNetworks_mapsPaymentNetworkNames() { - assertEquals( - listOf("VISA", "MASTERCARD", "AMEX", "DISCOVER", "JCB", "INTERAC"), - GooglePayRequestBuilder.googleCardNetworks( - arrayOf("visa", "mastercard", "amex", "discover", "jcb", "interac") - ) - ) - } - - @Test - fun googleCardNetworks_ignoresCaseAndDuplicates() { - assertEquals( - listOf("VISA", "AMEX"), - GooglePayRequestBuilder.googleCardNetworks(arrayOf("Visa", "AMEX", "visa")) - ) - } - - @Test - fun googleCardNetworks_dropsNetworksGooglePayDoesNotHave() { - assertEquals( - listOf("MASTERCARD"), - GooglePayRequestBuilder.googleCardNetworks( - arrayOf("idcredit", "privateLabel", "mastercard", "unknown") - ) - ) - assertEquals( - emptyList(), - GooglePayRequestBuilder.googleCardNetworks(arrayOf("privateLabel")) - ) - } - @Test fun isReadyToPayRequest_checksTheGivenNetworksForAnExistingCard() { val request = GooglePayRequestBuilder.createIsReadyToPayRequest( - cardNetworks = listOf("VISA", "JCB"), + cardParameters = GooglePayCardParameters.from(arrayOf("visa", "jcb"), null), existingPaymentMethodRequired = true ) @@ -66,7 +34,7 @@ class ReadyToPayRequestTest { @Test fun isReadyToPayRequest_canAskWithoutRequiringACard() { val request = GooglePayRequestBuilder.createIsReadyToPayRequest( - cardNetworks = PaymentConstants.DEFAULT_CARD_NETWORKS, + cardParameters = GooglePayCardParameters.DEFAULT, existingPaymentMethodRequired = false ) diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index e21c2d2..281b4b7 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\"" } @@ -86,7 +96,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) @@ -232,8 +242,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 { @@ -274,11 +309,10 @@ 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 error. static func hasActiveCard(networks: [String], merchantCapabilities: [String]?) throws -> Bool { let capabilities = try PaymentRequestBuilder.buildMerchantCapabilities(merchantCapabilities ?? []) - let paymentNetworks = networks.compactMap { PassKitTypeMapper.convertToPKPaymentNetwork($0) } - // PassKit may answer true for an empty list, but no card is on no network. - guard !paymentNetworks.isEmpty else { return false } + let paymentNetworks = try PaymentRequestBuilder.buildSupportedNetworks(networks) return PKPaymentAuthorizationViewController.canMakePayments( usingNetworks: paymentNetworks, capabilities: capabilities 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/PaymentReadinessTests.swift b/package/ios/Tests/PaymentReadinessTests.swift index 705d3c0..c572a5a 100644 --- a/package/ios/Tests/PaymentReadinessTests.swift +++ b/package/ios/Tests/PaymentReadinessTests.swift @@ -1,16 +1,23 @@ import XCTest @testable import NitroPay -// Only `hasActiveCard` paths that return before PassKit is asked: its answers +// Only `hasActiveCard` paths that fail before PassKit is asked: its answers // depend on the device and the cards in Wallet. final class PaymentReadinessTests: XCTestCase { - func testNoCardWithoutARecognisedNetwork() throws { - XCTAssertFalse(try PaymentReadiness.hasActiveCard(networks: [], merchantCapabilities: nil)) - XCTAssertFalse(try PaymentReadiness.hasActiveCard( - networks: ["unknown", "VISA"], + func testRejectsNetworksThePaymentWouldRefuse() { + XCTAssertThrowsError(try PaymentReadiness.hasActiveCard(networks: [], merchantCapabilities: nil)) { error in + XCTAssertEqual(String(describing: error), "supportedNetworks needs at least one network") + } + XCTAssertThrowsError(try PaymentReadiness.hasActiveCard( + networks: ["VISA", "unknown"], merchantCapabilities: ["3DS"] - )) + )) { error in + XCTAssertEqual( + String(describing: error), + "Unknown payment network \"unknown\". Use a PaymentNetwork value such as \"visa\" or \"mastercard\"" + ) + } } func testRejectsUnknownMerchantCapability() { 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..fc3a5b9 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,87 @@ 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::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(); + 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::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++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(googlePayAllowedAuthMethods.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 0655777..10d2cb0 100644 --- a/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp +++ b/package/nitrogen/generated/android/c++/JHybridGooglePayButtonSpec.hpp @@ -56,6 +56,12 @@ 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> getGooglePayAllowedAuthMethods() override; + void setGooglePayAllowedAuthMethods(const std::optional>& googlePayAllowedAuthMethods) 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 dba5206..c209172 100644 --- a/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp +++ b/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp @@ -39,6 +39,8 @@ namespace margelo::nitro::pay { jni::local_ref> supportedNetworks = this->getFieldValue(fieldSupportedNetworks); static const auto fieldMerchantCapabilities = clazz->getField>("merchantCapabilities"); jni::local_ref> merchantCapabilities = this->getFieldValue(fieldMerchantCapabilities); + static const auto fieldGooglePayAllowedAuthMethods = clazz->getField>("googlePayAllowedAuthMethods"); + jni::local_ref> googlePayAllowedAuthMethods = this->getFieldValue(fieldGooglePayAllowedAuthMethods); static const auto fieldGooglePayEnvironment = clazz->getField("googlePayEnvironment"); jni::local_ref googlePayEnvironment = this->getFieldValue(fieldGooglePayEnvironment); return PayServiceStatusOptions( @@ -62,6 +64,16 @@ namespace margelo::nitro::pay { } return __vector; }(merchantCapabilities)) : 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, googlePayEnvironment != nullptr ? std::make_optional(googlePayEnvironment->toCpp()) : std::nullopt ); } @@ -72,7 +84,7 @@ namespace margelo::nitro::pay { */ [[maybe_unused]] static jni::local_ref fromCpp(const PayServiceStatusOptions& value) { - using JSignature = JPayServiceStatusOptions(jni::alias_ref>, jni::alias_ref>, jni::alias_ref); + using JSignature = JPayServiceStatusOptions(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( @@ -97,6 +109,16 @@ namespace margelo::nitro::pay { } return __array; }(value.merchantCapabilities.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, value.googlePayEnvironment.has_value() ? JGooglePayEnvironment::fromCpp(value.googlePayEnvironment.value()) : nullptr ); } 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..884a40b 100644 --- a/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp +++ b/package/nitrogen/generated/android/c++/views/JHybridGooglePayButtonStateUpdater.cpp @@ -49,6 +49,18 @@ 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->googlePayAllowedAuthMethods.isDirty) { + hybridView->setGooglePayAllowedAuthMethods(props->googlePayAllowedAuthMethods.value); + props->googlePayAllowedAuthMethods.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 44560ad..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 @@ -44,6 +44,24 @@ 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 googlePayAllowedAuthMethods: 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 cc4eafd..a10708e 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 @@ -26,6 +26,9 @@ data class PayServiceStatusOptions( val merchantCapabilities: Array?, @DoNotStrip @Keep + val googlePayAllowedAuthMethods: Array?, + @DoNotStrip + @Keep val googlePayEnvironment: GooglePayEnvironment? ) { /* primary constructor */ @@ -35,6 +38,7 @@ data class PayServiceStatusOptions( if (other !is PayServiceStatusOptions) return false return Objects.deepEquals(this.supportedNetworks, other.supportedNetworks) && Objects.deepEquals(this.merchantCapabilities, other.merchantCapabilities) + && Objects.deepEquals(this.googlePayAllowedAuthMethods, other.googlePayAllowedAuthMethods) && Objects.deepEquals(this.googlePayEnvironment, other.googlePayEnvironment) } @@ -42,6 +46,7 @@ data class PayServiceStatusOptions( return arrayOf( supportedNetworks, merchantCapabilities, + googlePayAllowedAuthMethods, googlePayEnvironment ).contentDeepHashCode() } @@ -54,8 +59,8 @@ data class PayServiceStatusOptions( @Keep @Suppress("unused") @JvmStatic - private fun fromCpp(supportedNetworks: Array?, merchantCapabilities: Array?, googlePayEnvironment: GooglePayEnvironment?): PayServiceStatusOptions { - return PayServiceStatusOptions(supportedNetworks, merchantCapabilities, googlePayEnvironment) + private fun fromCpp(supportedNetworks: Array?, merchantCapabilities: Array?, googlePayAllowedAuthMethods: Array?, googlePayEnvironment: GooglePayEnvironment?): PayServiceStatusOptions { + return PayServiceStatusOptions(supportedNetworks, merchantCapabilities, googlePayAllowedAuthMethods, googlePayEnvironment) } } } 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/swift/PayServiceStatusOptions.swift b/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift index cf2ff27..38531ef 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]?, merchantCapabilities: [String]?, googlePayEnvironment: GooglePayEnvironment?) { + init(supportedNetworks: [String]?, merchantCapabilities: [String]?, googlePayAllowedAuthMethods: [String]?, googlePayEnvironment: GooglePayEnvironment?) { 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 = 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() + } }(), { () -> bridge.std__optional_GooglePayEnvironment_ in if let __unwrappedValue = googlePayEnvironment { return bridge.create_std__optional_GooglePayEnvironment_(__unwrappedValue) @@ -76,6 +88,18 @@ public extension PayServiceStatusOptions { }() } + @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 + } + }() + } + @inline(__always) var googlePayEnvironment: GooglePayEnvironment? { return self.__googlePayEnvironment.value 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..a428565 100644 --- a/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp +++ b/package/nitrogen/generated/shared/c++/HybridGooglePayButtonSpec.cpp @@ -20,6 +20,12 @@ 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("googlePayAllowedAuthMethods", &HybridGooglePayButtonSpec::getGooglePayAllowedAuthMethods); + prototype.registerHybridSetter("googlePayAllowedAuthMethods", &HybridGooglePayButtonSpec::setGooglePayAllowedAuthMethods); + 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 1efb4bb..e198a8c 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,12 @@ 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> 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; 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 001820d..599afb2 100644 --- a/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp +++ b/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp @@ -45,11 +45,12 @@ namespace margelo::nitro::pay { public: std::optional> supportedNetworks SWIFT_PRIVATE; std::optional> merchantCapabilities SWIFT_PRIVATE; + std::optional> googlePayAllowedAuthMethods SWIFT_PRIVATE; std::optional googlePayEnvironment SWIFT_PRIVATE; public: PayServiceStatusOptions() = default; - explicit PayServiceStatusOptions(std::optional> supportedNetworks, std::optional> merchantCapabilities, std::optional googlePayEnvironment): supportedNetworks(supportedNetworks), merchantCapabilities(merchantCapabilities), googlePayEnvironment(googlePayEnvironment) {} + explicit PayServiceStatusOptions(std::optional> supportedNetworks, std::optional> merchantCapabilities, std::optional> googlePayAllowedAuthMethods, std::optional googlePayEnvironment): supportedNetworks(supportedNetworks), merchantCapabilities(merchantCapabilities), googlePayAllowedAuthMethods(googlePayAllowedAuthMethods), googlePayEnvironment(googlePayEnvironment) {} public: friend bool operator==(const PayServiceStatusOptions& lhs, const PayServiceStatusOptions& rhs) = default; @@ -67,6 +68,7 @@ namespace margelo::nitro { return margelo::nitro::pay::PayServiceStatusOptions( JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks"))), JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"))), + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"))) ); } @@ -74,6 +76,7 @@ namespace margelo::nitro { jsi::Object obj(runtime); obj.setProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks"), JSIConverter>>::toJSI(runtime, arg.supportedNetworks)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"), JSIConverter>>::toJSI(runtime, arg.merchantCapabilities)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayAllowedAuthMethods"), JSIConverter>>::toJSI(runtime, arg.googlePayAllowedAuthMethods)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"), JSIConverter>::toJSI(runtime, arg.googlePayEnvironment)); return obj; } @@ -87,6 +90,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, "merchantCapabilities")))) 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, "googlePayEnvironment")))) return false; return true; } 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..b0ddc9b 100644 --- a/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp +++ b/package/nitrogen/generated/shared/c++/views/HybridGooglePayButtonComponent.cpp @@ -56,6 +56,36 @@ 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()); + } + }()), + googlePayAllowedAuthMethods([&]() -> CachedProp>> { + try { + 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.googlePayAllowedAuthMethods); + } catch (const std::exception& exc) { + throw std::runtime_error(std::string("GooglePayButton.googlePayAllowedAuthMethods: ") + 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); @@ -82,6 +112,9 @@ 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("googlePayAllowedAuthMethods"): 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 fd0a79d..c764bf6 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,9 @@ namespace margelo::nitro::pay::views { CachedProp buttonType; CachedProp theme; CachedProp> radius; + CachedProp>> supportedNetworks; + 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 56110b6..b2b665e 100644 --- a/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json +++ b/package/nitrogen/generated/shared/json/GooglePayButtonConfig.json @@ -7,6 +7,9 @@ "buttonType": true, "theme": true, "radius": true, + "supportedNetworks": true, + "googlePayAllowedAuthMethods": 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 35ff73b..b9b3c75 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts @@ -422,6 +422,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/__tests__/usePaymentCheckout.status.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts index 954872c..66a6a8a 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts @@ -93,11 +93,12 @@ describe('usePaymentCheckout availability', () => { } ) - it('checks the networks, capabilities and environment from the config', async () => { + it('checks the networks, capabilities, auth methods and environment from the config', async () => { const { result } = renderHook(() => usePaymentCheckout({ supportedNetworks: ['visa', 'mastercard'], merchantCapabilities: ['3DS', 'Debit'], + googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], googlePayEnvironment: 'PRODUCTION', }) ) @@ -110,6 +111,7 @@ describe('usePaymentCheckout availability', () => { expect(mockPayServiceStatus).toHaveBeenCalledWith({ supportedNetworks: ['visa', 'mastercard'], merchantCapabilities: ['3DS', 'Debit'], + googlePayAllowedAuthMethods: ['CRYPTOGRAM_3DS'], googlePayEnvironment: 'PRODUCTION', }) }) diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index a4015d5..560f922 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -13,9 +13,10 @@ import type { PaymentResult, PaymentItem, PayServiceStatus, - PayServiceStatusOptions, + GooglePayAuthMethod, GooglePayEnvironment, MerchantCapability, + PayServiceStatusOptions, PaymentToken, PaymentAuthorizationResult, PaymentDetails, @@ -58,14 +59,16 @@ export interface UsePaymentCheckoutConfig { currencyCode?: string /** - * Supported card networks for the payment sheet. + * Card networks the payer can pay with, as `PaymentNetwork` values. * Defaults to `['visa', 'mastercard', 'amex', 'discover']`. + * `hasActiveCard` counts only cards on these networks. See + * `PaymentRequest.supportedNetworks`. */ 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[] @@ -98,6 +101,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`. @@ -308,6 +318,7 @@ export function usePaymentCheckout( googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, + googlePayAllowedAuthMethods, billingContactRequired, shippingContactRequired, emailRequired, @@ -327,6 +338,7 @@ export function usePaymentCheckout( googlePayEnvironment, googlePayGateway, googlePayGatewayMerchantId, + googlePayAllowedAuthMethods, billingContactRequired, shippingContactRequired, emailRequired, @@ -339,8 +351,9 @@ export function usePaymentCheckout( const statusOptionsKey = JSON.stringify({ supportedNetworks: paymentRequest.supportedNetworks, merchantCapabilities: paymentRequest.merchantCapabilities, + googlePayAllowedAuthMethods: paymentRequest.googlePayAllowedAuthMethods, googlePayEnvironment: paymentRequest.googlePayEnvironment, - }) + } satisfies PayServiceStatusOptions) useEffect(() => { // Ignores a check that settles after a newer one started or after unmount. diff --git a/package/src/specs/GooglePayButton.nitro.ts b/package/src/specs/GooglePayButton.nitro.ts index 5dbe3f3..755ed70 100644 --- a/package/src/specs/GooglePayButton.nitro.ts +++ b/package/src/specs/GooglePayButton.nitro.ts @@ -20,6 +20,18 @@ 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. */ + googlePayAllowedAuthMethods?: 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 697563a..b5152c9 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' @@ -37,9 +69,19 @@ export type PassActivationState = export type GooglePayEnvironment = 'TEST' | 'PRODUCTION' /** - * Apple Pay merchant capability. `'3DS'` and `'EMV'` are payment protocols + * 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' + +/** + * 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' @@ -103,7 +145,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+ @@ -127,7 +174,14 @@ 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 + * 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 +222,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[] } /** @@ -245,7 +305,6 @@ export interface PayServiceStatus { * The user has a card ready on one of the checked networks. * iOS: `canMakePayments(usingNetworks:capabilities:)`. * Android: `isReadyToPay` with `existingPaymentMethodRequired: true`. - * `false` when no checked network is recognised. */ hasActiveCard: boolean } @@ -254,12 +313,17 @@ export interface PayServiceStatus { * What `payServiceStatus` checks. Pass the values your payment request uses. */ export interface PayServiceStatusOptions { - // Networks a card must be on to count for `hasActiveCard`. Defaults to + // Networks a card must be on to count for `hasActiveCard`, as + // `PaymentRequest.supportedNetworks`. Defaults to // `['visa', 'mastercard', 'amex', 'discover']`. supportedNetworks?: string[] - // iOS only. `MerchantCapability` values a card must support. Defaults to - // `['3DS']`; `'3DS'` is added when neither `'3DS'` nor `'EMV'` is given. + // `MerchantCapability` values. iOS: what a card must support; defaults to + // `['3DS']`, and `'3DS'` is added when neither `'3DS'` nor `'EMV'` is given. + // Android: `'Debit'` without `'Credit'` leaves credit cards out. merchantCapabilities?: string[] + // Android only. As `PaymentRequest.googlePayAllowedAuthMethods`. Defaults + // to both. + googlePayAllowedAuthMethods?: string[] // Android only. The Google Pay environment to ask. Defaults to `'TEST'`. googlePayEnvironment?: GooglePayEnvironment } 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 }