From 6da1322659bad50bd734574a3ce6074424213d52 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Fri, 23 Oct 2026 18:25:01 +0200 Subject: [PATCH 01/10] fix!: check wallet availability without blocking the JS thread `payServiceStatus()` and `canMakePayments(networks)` now return Promises. Android runs both `isReadyToPay` calls at once and resolves from the task listeners instead of `Tasks.await` on the JS thread; iOS runs the PassKit checks on a background queue. `PayServiceStatus` is now `{ isSupported, hasActiveCard }`, with the same meaning on both platforms, and both checks take the networks, merchant capabilities and Google Pay environment to ask. Android no longer answers from TEST before the first payment, and `canMakePayments(networks)` asks Google Pay instead of matching names. Adds `openPaymentSetup()` (iOS) and `refreshStatus()` on the hook. Fixes #16 BREAKING CHANGE: `payServiceStatus` and `canMakePayments` return Promises; `PayServiceStatus` and the hook return `isSupported`/`hasActiveCard` instead of `canMakePayments`/`canSetupCards`. --- ...001-2026-02-10-core-module-architecture.md | 7 +- ...02-2026-02-10-use-payment-checkout-flow.md | 2 +- CHANGELOG.md | 25 ++ README.md | 50 ++-- docs/docs/api/hybrid-payment-handler.md | 39 ++- docs/docs/api/types.md | 36 ++- docs/docs/api/use-payment-checkout.md | 17 +- docs/docs/examples.md | 2 +- docs/docs/guides/availability.md | 123 +++++++++ docs/docs/guides/manual-flow.md | 17 +- docs/docs/integrations/przelewy24.md | 4 +- docs/docs/intro.md | 2 +- docs/docs/payment-flow.md | 2 +- docs/docs/quick-start.md | 4 +- docs/docs/troubleshooting.md | 4 + docs/sidebars.ts | 1 + example/app/(tabs)/index.tsx | 69 +++-- .../java/com/margelo/nitro/pay/Constants.kt | 21 +- .../nitro/pay/GooglePayRequestBuilder.kt | 32 ++- .../margelo/nitro/pay/HybridPaymentHandler.kt | 98 +++++-- .../nitro/pay/ReadyToPayRequestTest.kt | 78 ++++++ package/ios/HybridPaymentHandler.swift | 64 ++++- package/ios/Tests/PaymentReadinessTests.swift | 31 +++ .../android/c++/JCanMakePaymentsOptions.hpp | 83 ++++++ .../android/c++/JHybridPaymentHandlerSpec.cpp | 62 ++++- .../android/c++/JHybridPaymentHandlerSpec.hpp | 5 +- .../android/c++/JPayServiceStatus.hpp | 16 +- .../android/c++/JPayServiceStatusOptions.hpp | 105 ++++++++ .../nitro/pay/CanMakePaymentsOptions.kt | 56 ++++ .../nitro/pay/HybridPaymentHandlerSpec.kt | 8 +- .../com/margelo/nitro/pay/PayServiceStatus.kt | 16 +- .../nitro/pay/PayServiceStatusOptions.kt | 61 +++++ .../ios/NitroPay-Swift-Cxx-Bridge.cpp | 24 +- .../ios/NitroPay-Swift-Cxx-Bridge.hpp | 245 ++++++++++++++---- .../ios/NitroPay-Swift-Cxx-Umbrella.hpp | 6 + .../ios/c++/HybridPaymentHandlerSpecSwift.hpp | 32 ++- .../ios/swift/CanMakePaymentsOptions.swift | 59 +++++ .../swift/Func_void_PayServiceStatus.swift | 46 ++++ .../generated/ios/swift/Func_void_bool.swift | 46 ++++ .../ios/swift/HybridPaymentHandlerSpec.swift | 5 +- .../swift/HybridPaymentHandlerSpec_cxx.swift | 45 +++- .../ios/swift/PayServiceStatus.swift | 12 +- .../ios/swift/PayServiceStatusOptions.swift | 83 ++++++ .../shared/c++/CanMakePaymentsOptions.hpp | 91 +++++++ .../shared/c++/HybridPaymentHandlerSpec.cpp | 1 + .../shared/c++/HybridPaymentHandlerSpec.hpp | 15 +- .../generated/shared/c++/PayServiceStatus.hpp | 18 +- .../shared/c++/PayServiceStatusOptions.hpp | 95 +++++++ package/src/__tests__/paymentHandler.test.ts | 15 +- .../usePaymentCheckout.integration.test.ts | 197 ++++++++++++-- package/src/hooks/usePaymentCheckout.ts | 62 ++++- package/src/specs/PaymentHandler.nitro.ts | 11 +- package/src/types/Payment.ts | 42 ++- 53 files changed, 1995 insertions(+), 295 deletions(-) create mode 100644 docs/docs/guides/availability.md create mode 100644 package/android/src/test/java/com/margelo/nitro/pay/ReadyToPayRequestTest.kt create mode 100644 package/ios/Tests/PaymentReadinessTests.swift create mode 100644 package/nitrogen/generated/android/c++/JCanMakePaymentsOptions.hpp create mode 100644 package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp create mode 100644 package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/CanMakePaymentsOptions.kt create mode 100644 package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt create mode 100644 package/nitrogen/generated/ios/swift/CanMakePaymentsOptions.swift create mode 100644 package/nitrogen/generated/ios/swift/Func_void_PayServiceStatus.swift create mode 100644 package/nitrogen/generated/ios/swift/Func_void_bool.swift create mode 100644 package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift create mode 100644 package/nitrogen/generated/shared/c++/CanMakePaymentsOptions.hpp create mode 100644 package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp diff --git a/.ai/specs/SPEC-001-2026-02-10-core-module-architecture.md b/.ai/specs/SPEC-001-2026-02-10-core-module-architecture.md index 7b50471..84dfb63 100644 --- a/.ai/specs/SPEC-001-2026-02-10-core-module-architecture.md +++ b/.ai/specs/SPEC-001-2026-02-10-core-module-architecture.md @@ -59,7 +59,7 @@ Core shared models are defined in `package/src/types/Payment.ts`: - `PaymentRequest`: input contract for native payment start - `PaymentItem`: line items used for totals and display - `PaymentResult`: success/error envelope and token details -- `PayServiceStatus`: platform availability flags +- `PayServiceStatus`: availability flags (`isSupported`, `hasActiveCard`) Cross-layer contract rule: @@ -69,10 +69,11 @@ Cross-layer contract rule: Primary low-level contract: -- `payServiceStatus(): PayServiceStatus` +- `payServiceStatus(options?: PayServiceStatusOptions): Promise` - `startPayment(request: PaymentRequest): Promise` -- `canMakePayments(usingNetworks: string[]): boolean` +- `canMakePayments(usingNetworks: string[], options?: CanMakePaymentsOptions): Promise` - `isPaymentInProgress(): boolean` — whether a payment started with `startPayment` has not settled yet. Backed by the native single-payment slot (`PendingPayment` on iOS and Android), which `startPayment` claims synchronously on the calling thread and frees when the payment settles. +- `openPaymentSetup(): void` (iOS only) Primary high-level API: diff --git a/.ai/specs/SPEC-002-2026-02-10-use-payment-checkout-flow.md b/.ai/specs/SPEC-002-2026-02-10-use-payment-checkout-flow.md index 8446786..1fbbd91 100644 --- a/.ai/specs/SPEC-002-2026-02-10-use-payment-checkout-flow.md +++ b/.ai/specs/SPEC-002-2026-02-10-use-payment-checkout-flow.md @@ -100,7 +100,7 @@ The hook provides state for UI rendering but does not own UI components. Recommended consumer pattern: - Use `isCheckingStatus` for initial availability loading. -- Use `canMakePayments` for gating payment controls. +- Use `isSupported` for gating payment controls, and `hasActiveCard` to choose between a pay and a "Set up" button on iOS. - Use `isProcessing` for disabled/loading button state. - Use `error` for actionable feedback. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c7cafa..6f3a95d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,18 @@ All notable changes to this project are documented in this file. `startPayment` now marks the payment in progress as soon as it is called, as on Android, instead of when it starts presenting the sheet, so `isPaymentInProgress()` sees a payment started in the same JS tick. +- **Availability checks are asynchronous and report `isSupported` and `hasActiveCard`.** + `HybridPaymentHandler.payServiceStatus()` and `canMakePayments(networks)` now return Promises, + and `PayServiceStatus` is `{ isSupported, hasActiveCard }` instead of + `{ canMakePayments, canSetupCards }`, which meant different things on each platform. + `usePaymentCheckout` returns `isSupported`, `hasActiveCard` and a new `refreshStatus()` instead of + `canMakePayments` and `canSetupCards`. Both checks take the networks, merchant capabilities and + Google Pay environment to check against; the hook passes its config. To migrate, `await` the + handler methods and read `isSupported` where you read `canMakePayments` (the same check on iOS, + and the one Google recommends for showing the button on Android). See + [Check availability](https://gmi-software.github.io/react-native-pay/docs/guides/availability). +- **iOS: `HybridPaymentHandler.openPaymentSetup()`** opens Wallet so the user can add a card, for a + "Set up Apple Pay" button (`ApplePayButton` with `buttonType="setUp"`). It does nothing on Android. ### Fixed @@ -59,6 +71,19 @@ All notable changes to this project are documented in this file. - **iOS: an unknown `shippingType` fails the payment** with `Unknown shipping type "". Use "shipping", "delivery", "storePickup" or "servicePickup"` instead of silently becoming `"shipping"`. Android ignores `shippingType`. +- **Android: availability checks no longer block the JS thread.** `payServiceStatus()` made two + `isReadyToPay` calls one after the other and waited up to 5 seconds for each on the JS thread, so + every checkout screen froze touches, animations and timers until Google Play services answered. + Both calls now run at once and resolve the Promise when they finish; one that takes longer than + 5 seconds counts as `false`. On iOS, the PassKit checks run off the JS thread too. +- **Android: availability is checked in the environment you pay in.** The check always used `TEST` + 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. +- **Android: `canMakePayments(networks)` asks Google Pay.** It only checked that a name was in a + fixed list, so `['visa']` was always `true`. It now asks whether the user has a card on those + networks, like iOS. Both platforms answer `false` when no network is one they know; iOS answered + for an empty network list instead. - **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 72e7801..a1d34ad 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,7 @@ import { callback } from 'react-native-nitro-modules' function CheckoutScreen() { const { // Payment availability - canMakePayments, + isSupported, // Cart management items, @@ -246,7 +246,7 @@ function CheckoutScreen() { } } - if (!canMakePayments) { + if (!isSupported) { return ( Apple Pay or Google Pay is not available on this device @@ -393,9 +393,10 @@ interface UsePaymentCheckoutConfig { ```typescript no-check interface UsePaymentCheckoutReturn { // Payment availability - canMakePayments: boolean; // Can user make payments? - canSetupCards: boolean; // Can user add cards? - isCheckingStatus: boolean; // Loading state for availability check + isSupported: boolean; // Device supports Apple Pay / Google Pay + hasActiveCard: boolean; // A card on supportedNetworks is ready + isCheckingStatus: boolean; // true until the availability check settles + refreshStatus: () => void; // Check again, e.g. after the user added a card // Cart management items: PaymentItem[]; // Current cart items @@ -455,27 +456,32 @@ Low-level payment handler for direct control. #### Methods -##### `payServiceStatus(): PayServiceStatus` +##### `payServiceStatus(options?: PayServiceStatusOptions): Promise` -Check payment service availability. +Check payment service availability without blocking the JS thread. Pass the networks, capabilities and Google Pay environment your payment request uses. ```typescript import { HybridPaymentHandler } from "@gmisoftware/react-native-pay"; -const status = HybridPaymentHandler.payServiceStatus(); -console.log("Can make payments:", status.canMakePayments); -console.log("Can setup cards:", status.canSetupCards); +const status = await HybridPaymentHandler.payServiceStatus({ + supportedNetworks: ["visa", "mastercard"], + googlePayEnvironment: "PRODUCTION", +}); +console.log("Wallet supported:", status.isSupported); +console.log("Card ready:", status.hasActiveCard); ``` **Returns:** ```typescript interface PayServiceStatus { - canMakePayments: boolean; - canSetupCards: boolean; + isSupported: boolean; // iOS: canMakePayments(); Android: isReadyToPay + hasActiveCard: boolean; // iOS: canMakePayments(usingNetworks:capabilities:); Android: isReadyToPay with existingPaymentMethodRequired } ``` +Android asks the `TEST` environment unless you pass `googlePayEnvironment`, and in `TEST` `hasActiveCard` is `true` whether or not the user has a card. See [Check availability](https://gmi-software.github.io/react-native-pay/docs/guides/availability) for which button to show. + ##### `startPayment(request: PaymentRequest, options?: StartPaymentOptions): Promise` Start a payment request. @@ -533,14 +539,16 @@ interface PaymentToken { } ``` -##### `canMakePayments(usingNetworks: string[]): boolean` +##### `canMakePayments(usingNetworks: string[], options?: CanMakePaymentsOptions): Promise` -Check if specific card networks are supported. +Check whether the user has a card ready on one of the given networks. Both platforms ask the device. ```typescript import { HybridPaymentHandler } from "@gmisoftware/react-native-pay"; -const canPay = HybridPaymentHandler.canMakePayments(["visa", "mastercard"]); +const canPay = await HybridPaymentHandler.canMakePayments(["visa", "mastercard"], { + googlePayEnvironment: "PRODUCTION", +}); ``` ##### `isPaymentInProgress(): boolean` @@ -553,6 +561,10 @@ import { HybridPaymentHandler } from "@gmisoftware/react-native-pay"; const isBusy = HybridPaymentHandler.isPaymentInProgress(); ``` +##### `openPaymentSetup(): void` + +iOS only: opens Wallet so the user can add a card. Call it from an `ApplePayButton` with `buttonType="setUp"`. It does nothing on Android, where the Google Pay sheet lets the user add a card. + --- ### Button Components @@ -912,8 +924,10 @@ import { import { Platform } from 'react-native' import { callback } from 'react-native-nitro-modules' -// 1. Check availability -const { canMakePayments } = HybridPaymentHandler.payServiceStatus() +// 1. Check availability, against the environment you pay in +const { isSupported } = await HybridPaymentHandler.payServiceStatus({ + googlePayEnvironment: 'PRODUCTION', +}) // 2. Create payment request const paymentRequest = createPaymentRequest({ @@ -951,7 +965,7 @@ const handlePayment = async () => { // 4. Render the button. onPress must be wrapped with callback(). function PaymentButton() { - if (!canMakePayments) return null + if (!isSupported) return null return Platform.OS === 'ios' ? ( void // Cart items: PaymentItem[] @@ -75,9 +77,12 @@ interface UsePaymentCheckoutReturn { } ``` -- **canMakePayments** — Whether the user can pay with Apple Pay / Google Pay on this device. -- **canSetupCards** — Whether the user can add or manage cards (e.g. in Wallet). -- **isCheckingStatus** — `true` while availability is being checked on mount. +- **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. +- **refreshStatus()** — Checks availability again, for example when the app returns from Wallet after `openPaymentSetup()`. `isCheckingStatus` is `true` until it settles. + +Which button to show for each combination is in [Check availability](/docs/guides/availability). - **items** / **total** — Current cart and its exact decimal total, as a number (`NaN` if an amount is invalid). Amounts are `number | string` ([`PaymentAmount`](/docs/api/types#paymentamount)); use `formatAmount(item.amount, currencyCode)` to display them. - **startPayment()** — Opens the native sheet. Returns `Promise`. - Returns `null` and sets `error` when the cart is empty. @@ -95,7 +100,7 @@ interface UsePaymentCheckoutReturn { import { usePaymentCheckout } from '@gmisoftware/react-native-pay' const { - canMakePayments, + isSupported, items, total, addItem, diff --git a/docs/docs/examples.md b/docs/docs/examples.md index 2453fdf..ef52eab 100644 --- a/docs/docs/examples.md +++ b/docs/docs/examples.md @@ -16,7 +16,7 @@ import { import { callback } from 'react-native-nitro-modules' const { - canMakePayments, + isSupported, isCheckingStatus, items, total, diff --git a/docs/docs/guides/availability.md b/docs/docs/guides/availability.md new file mode 100644 index 0000000..7213c2e --- /dev/null +++ b/docs/docs/guides/availability.md @@ -0,0 +1,123 @@ +# Check availability + +Decide which wallet button to show before the user taps anything. The library reports two flags, checked without blocking the JS thread: + +- **isSupported**: the device can pay with Apple Pay or Google Pay, whether or not a card is set up. +- **hasActiveCard**: the user has a card ready on one of your `supportedNetworks`. + +## What each flag checks + +| | 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` | + +Both flags are `false` when the check fails or, on Android, when Google Pay does not answer within 5 seconds. `hasActiveCard` is also `false` when none of the networks is one the platform knows (Google Pay has no `idcredit` or `privateLabel`). + +### Ask the environment you pay in + +On Android, the check goes to the Google Pay environment you pass as `googlePayEnvironment`, `'TEST'` by default. In `TEST`, Google Pay answers `hasActiveCard: true` whether or not the user has a card ([Google's reference](https://developers.google.com/pay/api/android/reference/request-objects#IsReadyToPayRequest)), so a production app must pass `'PRODUCTION'` to get real answers. An emulator with no Google account signed in answered `false` even in `TEST`, so test both signed-in and signed-out devices. + +## Show the right button + +- **Android**: show the Google Pay button when `isSupported` is `true`. A user without a card adds one in the Google Pay sheet. Google offers no separate setup screen, so `openPaymentSetup()` does nothing on Android. +- **iOS**: show the Apple Pay buy button when `hasActiveCard` is `true`. When only `isSupported` is `true`, show the **Set up Apple Pay** button (`buttonType="setUp"`) and call `HybridPaymentHandler.openPaymentSetup()` on tap. It opens Wallet (Settings on iPad) to add a card. +- **Neither platform**: when `isSupported` is `false`, hide the wallet buttons and offer another way to pay. + +The user comes back from Wallet with a card the status does not know about yet, so check again when the app returns to the foreground: + +```tsx +import { useEffect } from 'react' +import { AppState, Platform } from 'react-native' +import { callback } from 'react-native-nitro-modules' +import { + ApplePayButton, + GooglePayButton, + HybridPaymentHandler, + usePaymentCheckout, +} from '@gmisoftware/react-native-pay' + +export function WalletButton() { + const { + isSupported, + hasActiveCard, + isCheckingStatus, + refreshStatus, + startPayment, + } = usePaymentCheckout({ + merchantName: 'Your Store', + supportedNetworks: ['visa', 'mastercard'], + // The environment you pay in, so the status is real in production. + googlePayEnvironment: 'PRODUCTION', + googlePayMerchantId: 'your_google_pay_merchant_id', + googlePayGateway: 'stripe', + googlePayGatewayMerchantId: 'your_stripe_merchant_id', + }) + + useEffect(() => { + const subscription = AppState.addEventListener('change', (state) => { + if (state === 'active') refreshStatus() + }) + return () => subscription.remove() + }, [refreshStatus]) + + if (isCheckingStatus || !isSupported) return null + + if (Platform.OS === 'android') { + return ( + + ) + } + + return hasActiveCard ? ( + + ) : ( + HybridPaymentHandler.openPaymentSetup())} + /> + ) +} +``` + +The hook checks on mount, and again when `supportedNetworks`, `merchantCapabilities` or `googlePayEnvironment` change. `isCheckingStatus` is `true` until the check settles. + +## Without the hook + +`HybridPaymentHandler.payServiceStatus()` returns a `Promise`. Pass the same networks, capabilities and environment as your payment request: + +```ts +import { HybridPaymentHandler } from '@gmisoftware/react-native-pay' + +const { isSupported, hasActiveCard } = + await HybridPaymentHandler.payServiceStatus({ + supportedNetworks: ['visa', 'mastercard'], + merchantCapabilities: ['3DS'], + googlePayEnvironment: 'PRODUCTION', + }) +``` + +To check other networks only, use `canMakePayments`. It answers like `hasActiveCard`: + +```ts +import { HybridPaymentHandler } from '@gmisoftware/react-native-pay' + +const canPayWithAmex = await HybridPaymentHandler.canMakePayments(['amex'], { + googlePayEnvironment: 'PRODUCTION', +}) +``` + +## Next + +- [usePaymentCheckout](/docs/api/use-payment-checkout): the hook's availability fields +- [HybridPaymentHandler](/docs/api/hybrid-payment-handler): `payServiceStatus`, `canMakePayments` and `openPaymentSetup` +- [Components](/docs/api/components): `ApplePayButton` and `GooglePayButton` diff --git a/docs/docs/guides/manual-flow.md b/docs/docs/guides/manual-flow.md index 0034928..7277fbc 100644 --- a/docs/docs/guides/manual-flow.md +++ b/docs/docs/guides/manual-flow.md @@ -7,12 +7,17 @@ Use `HybridPaymentHandler` and `createPaymentRequest` when you want full control ```ts import { HybridPaymentHandler } from '@gmisoftware/react-native-pay' -const status = HybridPaymentHandler.payServiceStatus() -if (!status.canMakePayments) { +const status = await HybridPaymentHandler.payServiceStatus({ + supportedNetworks: ['visa', 'mastercard', 'amex'], + googlePayEnvironment: 'PRODUCTION', +}) +if (!status.isSupported) { // Hide the pay button and show "Apple Pay / Google Pay not available" } ``` +Pass the same networks and Google Pay environment as the payment request in step 2. On iOS, when `isSupported` is `true` but `hasActiveCard` is `false`, you can show a **Set up Apple Pay** button instead; see [Check availability](/docs/guides/availability). + ## 2. Build the payment request Either use a helper or build the object yourself: @@ -56,7 +61,7 @@ To charge the token before the Apple Pay sheet closes, pass `startPayment(paymen ## 4. Render the button -Use the platform-specific button, and pass it `status.canMakePayments` from step 1 so it stays hidden when payments are unavailable. Its `onPress` must be wrapped with `callback()` from `react-native-nitro-modules`, or the tap does nothing: +Use the platform-specific button, and pass it `status.isSupported` from step 1 so it stays hidden when payments are unavailable. Its `onPress` must be wrapped with `callback()` from `react-native-nitro-modules`, or the tap does nothing: ```tsx import { Platform } from 'react-native' @@ -64,13 +69,13 @@ import { ApplePayButton, GooglePayButton } from '@gmisoftware/react-native-pay' import { callback } from 'react-native-nitro-modules' function PaymentButton({ - canMakePayments, + isSupported, handlePayment, }: { - canMakePayments: boolean + isSupported: boolean handlePayment: () => Promise }) { - if (!canMakePayments) return null + if (!isSupported) return null return Platform.OS === 'ios' ? ( return ( diff --git a/docs/docs/intro.md b/docs/docs/intro.md index 8e85f1a..5c0e571 100644 --- a/docs/docs/intro.md +++ b/docs/docs/intro.md @@ -19,7 +19,7 @@ ## High-level flow -1. **Check availability** — `canMakePayments` from `usePaymentCheckout()` or `HybridPaymentHandler.payServiceStatus()`. +1. **Check availability** — `isSupported` and `hasActiveCard` from `usePaymentCheckout()` or `HybridPaymentHandler.payServiceStatus()`. See [Check availability](/docs/guides/availability). 2. **Build the cart** — `addItem()` / `addItems()` (or build a `PaymentRequest` yourself). 3. **Show the button** — `ApplePayButton` on iOS, `GooglePayButton` on Android. 4. **Start payment** — `startPayment()`; user completes the sheet; you receive a **token**. diff --git a/docs/docs/payment-flow.md b/docs/docs/payment-flow.md index 89aa8fb..ca77044 100644 --- a/docs/docs/payment-flow.md +++ b/docs/docs/payment-flow.md @@ -8,7 +8,7 @@ The library does **not** charge the user directly. It opens the native wallet sh At a minimum: -1. App checks wallet availability (`canMakePayments` / `payServiceStatus()`). +1. App checks wallet availability (`isSupported` / `payServiceStatus()`). 2. App builds a `PaymentRequest` from cart items. 3. User confirms payment in the native sheet. 4. App receives `PaymentResult` (`success`, `token`, optional `transactionId`). diff --git a/docs/docs/quick-start.md b/docs/docs/quick-start.md index a34fc83..f2f7dd4 100644 --- a/docs/docs/quick-start.md +++ b/docs/docs/quick-start.md @@ -57,7 +57,7 @@ import { callback } from 'react-native-nitro-modules' function CheckoutScreen() { const { - canMakePayments, + isSupported, isCheckingStatus, items, total, @@ -92,7 +92,7 @@ function CheckoutScreen() { return } - if (!canMakePayments) { + if (!isSupported) { return Apple Pay / Google Pay is not available } diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 34725e2..8c8441c 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -64,6 +64,10 @@ Use only supported Apple button values: - Use `googlePayEnvironment: 'TEST'` for test flows. - Verify `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId`. +### `hasActiveCard` is `true` without a card + +The check asked the Google Pay `TEST` environment, which reports a card whether or not there is one. Pass `googlePayEnvironment: 'PRODUCTION'` to `usePaymentCheckout` or `payServiceStatus`. An emulator with no Google account signed in reports `false` even in `TEST`. See [Check availability](/docs/guides/availability). + ### Manifest/build issues - Run `npx expo prebuild --clean` and rebuild. diff --git a/docs/sidebars.ts b/docs/sidebars.ts index 5597791..77c4455 100644 --- a/docs/sidebars.ts +++ b/docs/sidebars.ts @@ -38,6 +38,7 @@ const sidebars: SidebarsConfig = { label: 'Recipes & Guides', link: {type: 'doc', id: 'guides/manual-flow'}, items: [ + 'guides/availability', 'guides/dynamic-cart', 'guides/contact-details', 'guides/testing', diff --git a/example/app/(tabs)/index.tsx b/example/app/(tabs)/index.tsx index cd177c7..f351399 100644 --- a/example/app/(tabs)/index.tsx +++ b/example/app/(tabs)/index.tsx @@ -1,7 +1,8 @@ -import { useState } from "react"; +import { useEffect, useState } from "react"; import { StyleSheet, Alert, + AppState, TouchableOpacity, ScrollView, Platform, @@ -13,6 +14,7 @@ import { ApplePayButton, formatAmount, GooglePayButton, + HybridPaymentHandler, usePaymentCheckout, } from "@gmisoftware/react-native-pay"; import { callback } from "react-native-nitro-modules"; @@ -29,9 +31,10 @@ export default function TabOneScreen() { // Initialize checkout hook const { - canMakePayments, - canSetupCards, + isSupported, + hasActiveCard, isCheckingStatus, + refreshStatus, items, total, addItem, @@ -58,6 +61,14 @@ export default function TabOneScreen() { }, }); + // A card added in Wallet after "Set up Apple Pay" shows up on return. + useEffect(() => { + const subscription = AppState.addEventListener("change", (state) => { + if (state === "active") refreshStatus(); + }); + return () => subscription.remove(); + }, [refreshStatus]); + const handleCycleSimulatedServer = () => { const next = (SIMULATED_SERVER_MODES.indexOf(simulatedServer) + 1) % @@ -67,15 +78,17 @@ export default function TabOneScreen() { // Show status info const handleCheckStatus = () => { - if (canMakePayments) { + if (hasActiveCard) { Alert.alert( `${paymentServiceName} Available`, `${paymentServiceName} is ready to use!`, ); - } else if (canSetupCards) { + } else if (isSupported) { Alert.alert( - "Setup Required", - `Please set up ${paymentServiceName} in Settings`, + "No Card Yet", + Platform.OS === "ios" + ? "Tap Set up Apple Pay to add a card in Wallet" + : "You can add a card in the Google Pay sheet", ); } else { Alert.alert( @@ -153,28 +166,31 @@ export default function TabOneScreen() { Check Status + + Refresh Status + - Can Make Payments: + Supported: - {canMakePayments ? "✓ Yes" : "✗ No"} + {isSupported ? "✓ Yes" : "✗ No"} - Can Setup Cards: + Card Ready: - {canSetupCards ? "✓ Yes" : "✗ No"} + {hasActiveCard ? "✓ Yes" : "✗ No"} @@ -272,7 +288,7 @@ export default function TabOneScreen() { )} {/* Payment Button */} - {items.length > 0 && !result?.success && canMakePayments && ( + {items.length > 0 && !result?.success && isSupported && ( Complete Payment {isProcessing ? ( @@ -283,12 +299,23 @@ export default function TabOneScreen() { ) : ( <> {Platform.OS === "ios" ? ( - + hasActiveCard ? ( + + ) : ( + + HybridPaymentHandler.openPaymentSetup(), + )} + style={styles.payButton} + /> + ) ) : ( )} - {!canMakePayments && ( + {!isSupported && ( {paymentServiceName} is not available on this device diff --git a/package/android/src/main/java/com/margelo/nitro/pay/Constants.kt b/package/android/src/main/java/com/margelo/nitro/pay/Constants.kt index 09c3bf1..27f52bb 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 @@ -46,8 +46,25 @@ object PaymentConstants { const val ERROR_AUTHORIZATION_FAILED = "Payment authorization failed" const val ERROR_AUTHORIZATION_TIMED_OUT = "Payment authorization timed out" - // Supported networks (lowercase for comparison) - val SUPPORTED_NETWORKS = listOf("visa", "mastercard", "amex", "discover") + // 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" + ) + + // Availability checks give up after this, like the blocking calls they replaced + const val READY_TO_PAY_TIMEOUT_SECONDS = 5L // Errors (keep in sync with iOS `ErrorMessage`) const val ERROR_PAYMENT_IN_PROGRESS = "A payment is already in progress" diff --git a/package/android/src/main/java/com/margelo/nitro/pay/GooglePayRequestBuilder.kt b/package/android/src/main/java/com/margelo/nitro/pay/GooglePayRequestBuilder.kt index 2d924db..22ee6d1 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 @@ -13,19 +13,34 @@ object GooglePayRequestBuilder { /** * Creates an IsReadyToPay request + * + * @param cardNetworks Google Pay `allowedCardNetworks` values, see [googleCardNetworks]. */ - fun createIsReadyToPayRequest(existingPaymentMethodRequired: Boolean? = null): JSONObject { + fun createIsReadyToPayRequest( + cardNetworks: List = PaymentConstants.DEFAULT_CARD_NETWORKS, + existingPaymentMethodRequired: Boolean? = null + ): JSONObject { return JSONObject().apply { put("apiVersion", PaymentConstants.API_VERSION) put("apiVersionMinor", PaymentConstants.API_VERSION_MINOR) put("allowedPaymentMethods", JSONArray().apply { - put(createBaseCardPaymentMethod()) + put(createBaseCardPaymentMethod(JSONArray(cardNetworks))) }) existingPaymentMethodRequired?.let { put("existingPaymentMethodRequired", it) } } } + + /** + * Maps `PaymentNetwork` names to Google Pay `allowedCardNetworks` values, + * without duplicates. Names Google Pay has no network for are dropped. + */ + fun googleCardNetworks(networks: Array): List { + return networks + .mapNotNull { PaymentConstants.GOOGLE_CARD_NETWORKS[it.lowercase()] } + .distinct() + } /** * Creates a complete payment data request @@ -85,12 +100,14 @@ object GooglePayRequestBuilder { /** * Creates base card payment method (no tokenization) */ - private fun createBaseCardPaymentMethod(): JSONObject { + private fun createBaseCardPaymentMethod( + allowedCardNetworks: JSONArray = createAllowedCardNetworks() + ): JSONObject { return JSONObject().apply { put("type", PaymentConstants.PAYMENT_METHOD_CARD) put("parameters", JSONObject().apply { put("allowedAuthMethods", createAllowedAuthMethods()) - put("allowedCardNetworks", createAllowedCardNetworks()) + put("allowedCardNetworks", allowedCardNetworks) }) } } @@ -285,12 +302,7 @@ object GooglePayRequestBuilder { * Creates allowed card networks */ fun createAllowedCardNetworks(): JSONArray { - return JSONArray().apply { - put(PaymentConstants.NETWORK_VISA) - put(PaymentConstants.NETWORK_MASTERCARD) - put(PaymentConstants.NETWORK_AMEX) - put(PaymentConstants.NETWORK_DISCOVER) - } + return JSONArray(PaymentConstants.DEFAULT_CARD_NETWORKS) } } diff --git a/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt b/package/android/src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt index 24f3b5b..04e103e 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 @@ -9,6 +9,7 @@ import com.facebook.react.bridge.ReactApplicationContext import com.google.android.gms.common.api.ApiException import com.google.android.gms.common.api.ResolvableApiException import com.google.android.gms.common.api.Status +import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.Tasks import com.google.android.gms.wallet.AutoResolveHelper import com.google.android.gms.wallet.IsReadyToPayRequest @@ -38,7 +39,6 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { @Volatile private var onAuthorize: AuthorizeCallback? = null @Volatile private var requestedDetails = RequestedDetails() private val mainHandler = Handler(Looper.getMainLooper()) - private var currentEnvironment: Int = WalletConstants.ENVIRONMENT_TEST // Registered only while the sheet is open, so the React context doesn't // keep this handler alive. @@ -63,34 +63,54 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { // MARK: - Public API - override fun payServiceStatus(): PayServiceStatus { + override fun payServiceStatus(options: PayServiceStatusOptions?): Promise { return try { - val client = createPaymentsClient(currentEnvironment) - val canSetupCards = isReadyToPay( - client = client, - requestJson = GooglePayRequestBuilder.createIsReadyToPayRequest( - existingPaymentMethodRequired = false - ) + val client = createPaymentsClient(determineEnvironment(options?.googlePayEnvironment)) + val cardNetworks = options?.supportedNetworks + ?.let { GooglePayRequestBuilder.googleCardNetworks(it) } + ?: PaymentConstants.DEFAULT_CARD_NETWORKS + // Both requests run at once; neither blocks the calling (JS) thread. + val isSupported = isReadyToPay( + client, + PaymentConstants.DEFAULT_CARD_NETWORKS, + existingPaymentMethodRequired = false ) - val canMakePayments = isReadyToPay( - client = client, - requestJson = GooglePayRequestBuilder.createIsReadyToPayRequest( - existingPaymentMethodRequired = true + val hasActiveCard = isReadyToPay(client, cardNetworks, existingPaymentMethodRequired = true) + + val promise = Promise() + Tasks.whenAllComplete(isSupported, hasActiveCard).addOnCompleteListener { + promise.resolve( + PayServiceStatus( + isSupported = isSupported.resultOrFalse(), + hasActiveCard = hasActiveCard.resultOrFalse() + ) ) - ) - PayServiceStatus( - canMakePayments = canMakePayments, - canSetupCards = canSetupCards - ) + } + promise } catch (e: Exception) { PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Error checking status", e) - PayServiceStatus(canMakePayments = false, canSetupCards = false) + Promise.resolved(PayServiceStatus(isSupported = false, hasActiveCard = false)) } } - override fun canMakePayments(usingNetworks: Array): Boolean { - return usingNetworks.any { network -> - PaymentConstants.SUPPORTED_NETWORKS.contains(network.lowercase()) + override fun canMakePayments( + usingNetworks: Array, + options: CanMakePaymentsOptions? + ): Promise { + return try { + val client = createPaymentsClient(determineEnvironment(options?.googlePayEnvironment)) + val hasActiveCard = isReadyToPay( + client, + GooglePayRequestBuilder.googleCardNetworks(usingNetworks), + existingPaymentMethodRequired = true + ) + + val promise = Promise() + hasActiveCard.addOnCompleteListener { promise.resolve(it.resultOrFalse()) } + promise + } catch (e: Exception) { + PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Error checking networks", e) + Promise.resolved(false) } } @@ -98,6 +118,11 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { return pendingPayment.isInProgress } + override fun openPaymentSetup() { + // Google Pay has no setup screen to open: its sheet lets the user add a card. + PayLog.d(PaymentConstants.TAG_PAYMENT_HANDLER, "openPaymentSetup does nothing on Android") + } + override fun startPayment( request: PaymentRequest, options: StartPaymentOptions? @@ -116,7 +141,6 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { try { val environment = determineEnvironment(request.googlePayEnvironment) - currentEnvironment = environment val paymentDataRequest = GooglePayRequestBuilder.createPaymentDataRequest( request, @@ -233,13 +257,35 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { } } + /** + * Asks Google Pay without waiting for the answer. The task completes on + * the main thread, with a `TimeoutException` if Google Pay does not answer. + */ private fun isReadyToPay( client: PaymentsClient, - requestJson: org.json.JSONObject - ): Boolean { + cardNetworks: List, + existingPaymentMethodRequired: Boolean + ): Task { + // No network Google Pay knows: no card can be on it. + if (cardNetworks.isEmpty()) return Tasks.forResult(false) + + val requestJson = GooglePayRequestBuilder.createIsReadyToPayRequest( + cardNetworks = cardNetworks, + existingPaymentMethodRequired = existingPaymentMethodRequired + ) val request = IsReadyToPayRequest.fromJson(requestJson.toString()) - val task = client.isReadyToPay(request) - return Tasks.await(task, 5, TimeUnit.SECONDS) ?: false + return Tasks.withTimeout( + client.isReadyToPay(request), + PaymentConstants.READY_TO_PAY_TIMEOUT_SECONDS, + TimeUnit.SECONDS + ) + } + + /** A failed or timed-out check counts as not ready, as it did before. */ + private fun Task.resultOrFalse(): Boolean { + if (isSuccessful) return result == true + PayLog.w(PaymentConstants.TAG_PAYMENT_HANDLER, "isReadyToPay failed", exception) + return false } private fun handlePaymentSuccess(paymentData: PaymentData) { 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 new file mode 100644 index 0000000..6f9f259 --- /dev/null +++ b/package/android/src/test/java/com/margelo/nitro/pay/ReadyToPayRequestTest.kt @@ -0,0 +1,78 @@ +package com.margelo.nitro.pay + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReadyToPayRequestTest { + + private fun JSONObject.cardParameters(): JSONObject = + getJSONArray("allowedPaymentMethods").getJSONObject(0).getJSONObject("parameters") + + private fun JSONObject.allowedCardNetworks(): List { + val networks = cardParameters().getJSONArray("allowedCardNetworks") + 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"), + existingPaymentMethodRequired = true + ) + + assertEquals(listOf("VISA", "JCB"), request.allowedCardNetworks()) + assertTrue(request.getBoolean("existingPaymentMethodRequired")) + assertFalse( + request.getJSONArray("allowedPaymentMethods").getJSONObject(0) + .has("tokenizationSpecification") + ) + } + + @Test + fun isReadyToPayRequest_defaultsToTheNetworksOfPaymentRequests() { + val request = GooglePayRequestBuilder.createIsReadyToPayRequest( + existingPaymentMethodRequired = false + ) + + assertEquals( + listOf("VISA", "MASTERCARD", "AMEX", "DISCOVER"), + request.allowedCardNetworks() + ) + assertFalse(request.getBoolean("existingPaymentMethodRequired")) + } +} diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index f18d793..7cd921c 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -209,7 +209,7 @@ struct PaymentRequestBuilder { return ProcessInfo.processInfo.processName } - private static func buildMerchantCapabilities(_ capabilities: [String]) throws -> PKMerchantCapability { + static func buildMerchantCapabilities(_ capabilities: [String]) throws -> PKMerchantCapability { var merchantCapabilities: PKMerchantCapability = [] for capability in capabilities { switch capability.uppercased() { @@ -264,6 +264,35 @@ struct PaymentRequestBuilder { } } +// MARK: - Payment Readiness + +// Internal, not private, so the NitroPay unit tests can reach it. +enum PaymentReadiness { + // Checked when the caller names no networks, like the hook's default. + static let defaultNetworks = ["visa", "mastercard", "amex", "discover"] + + static func status(supportedNetworks: [String]?, merchantCapabilities: [String]?) throws -> PayServiceStatus { + return PayServiceStatus( + isSupported: PKPaymentAuthorizationViewController.canMakePayments(), + hasActiveCard: try hasActiveCard( + networks: supportedNetworks ?? defaultNetworks, + merchantCapabilities: merchantCapabilities + ) + ) + } + + 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 } + return PKPaymentAuthorizationViewController.canMakePayments( + usingNetworks: paymentNetworks, + capabilities: capabilities + ) + } +} + // MARK: - Payment Token Converter private struct PaymentTokenConverter { @@ -506,15 +535,34 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec { // MARK: - Public Methods - func payServiceStatus() throws -> PayServiceStatus { - let canMakePayments = PKPaymentAuthorizationViewController.canMakePayments() - let canSetupCards = PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: []) - return PayServiceStatus.init(canMakePayments, canSetupCards) + // PassKit asks the Wallet service, so both checks run off the JS thread. + // Its `canMakePayments` class methods may be called from any thread. + func payServiceStatus(options: PayServiceStatusOptions?) throws -> Promise { + let supportedNetworks = options?.supportedNetworks + let merchantCapabilities = options?.merchantCapabilities + return Promise.parallel { + try PaymentReadiness.status( + supportedNetworks: supportedNetworks, + merchantCapabilities: merchantCapabilities + ) + } } - func canMakePayments(usingNetworks: [String]) throws -> Bool { - let networks = usingNetworks.compactMap { PassKitTypeMapper.convertToPKPaymentNetwork($0) } - return PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: networks) + func canMakePayments(usingNetworks: [String], options: CanMakePaymentsOptions?) throws -> Promise { + let merchantCapabilities = options?.merchantCapabilities + return Promise.parallel { + try PaymentReadiness.hasActiveCard( + networks: usingNetworks, + merchantCapabilities: merchantCapabilities + ) + } + } + + func openPaymentSetup() throws { + // Hands over to Wallet (Settings on iPad); does nothing without Apple Pay support. + DispatchQueue.main.async { + PKPassLibrary().openPaymentSetup() + } } func isPaymentInProgress() throws -> Bool { diff --git a/package/ios/Tests/PaymentReadinessTests.swift b/package/ios/Tests/PaymentReadinessTests.swift new file mode 100644 index 0000000..d81bbb1 --- /dev/null +++ b/package/ios/Tests/PaymentReadinessTests.swift @@ -0,0 +1,31 @@ +import XCTest +@testable import NitroPay + +// Only `hasActiveCard` paths that return 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"], + merchantCapabilities: ["3DS"] + )) + } + + func testRejectsUnknownMerchantCapability() { + XCTAssertThrowsError(try PaymentReadiness.hasActiveCard( + networks: ["visa"], + merchantCapabilities: ["3ds2"] + )) { error in + XCTAssertEqual( + error.localizedDescription, + "Unknown merchant capability \"3ds2\". Use \"3DS\", \"EMV\", \"Credit\" or \"Debit\"" + ) + } + } + + func testDefaultNetworksMatchTheHookDefault() { + XCTAssertEqual(PaymentReadiness.defaultNetworks, ["visa", "mastercard", "amex", "discover"]) + } +} diff --git a/package/nitrogen/generated/android/c++/JCanMakePaymentsOptions.hpp b/package/nitrogen/generated/android/c++/JCanMakePaymentsOptions.hpp new file mode 100644 index 0000000..acd3a5d --- /dev/null +++ b/package/nitrogen/generated/android/c++/JCanMakePaymentsOptions.hpp @@ -0,0 +1,83 @@ +/// +/// JCanMakePaymentsOptions.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include "CanMakePaymentsOptions.hpp" + +#include "GooglePayEnvironment.hpp" +#include "JGooglePayEnvironment.hpp" +#include +#include +#include + +namespace margelo::nitro::pay { + + using namespace facebook; + + /** + * The C++ JNI bridge between the C++ struct "CanMakePaymentsOptions" and the Kotlin data class "CanMakePaymentsOptions". + */ + struct JCanMakePaymentsOptions final: public jni::JavaClass { + public: + static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/pay/CanMakePaymentsOptions;"; + + public: + /** + * Convert this Java/Kotlin-based struct to the C++ struct CanMakePaymentsOptions by copying all values to C++. + */ + [[maybe_unused]] + [[nodiscard]] + CanMakePaymentsOptions toCpp() const { + static const auto clazz = javaClassStatic(); + static const auto fieldMerchantCapabilities = clazz->getField>("merchantCapabilities"); + jni::local_ref> merchantCapabilities = this->getFieldValue(fieldMerchantCapabilities); + static const auto fieldGooglePayEnvironment = clazz->getField("googlePayEnvironment"); + jni::local_ref googlePayEnvironment = this->getFieldValue(fieldGooglePayEnvironment); + return CanMakePaymentsOptions( + merchantCapabilities != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(merchantCapabilities)) : std::nullopt, + googlePayEnvironment != nullptr ? std::make_optional(googlePayEnvironment->toCpp()) : std::nullopt + ); + } + + public: + /** + * Create a Java/Kotlin-based struct by copying all values from the given C++ struct to Java. + */ + [[maybe_unused]] + static jni::local_ref fromCpp(const CanMakePaymentsOptions& value) { + using JSignature = JCanMakePaymentsOptions(jni::alias_ref>, jni::alias_ref); + static const auto clazz = javaClassStatic(); + static const auto create = clazz->getStaticMethod("fromCpp"); + return create( + clazz, + value.merchantCapabilities.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(value.merchantCapabilities.value()) : nullptr, + value.googlePayEnvironment.has_value() ? JGooglePayEnvironment::fromCpp(value.googlePayEnvironment.value()) : nullptr + ); + } + }; + +} // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp index 3d94e2f..fac872b 100644 --- a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp +++ b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp @@ -41,14 +41,16 @@ namespace margelo::nitro::pay { struct CNPostalAddress; } namespace margelo::nitro::pay { struct PaymentContact; } // Forward declaration of `ShippingMethod` to properly resolve imports. namespace margelo::nitro::pay { struct ShippingMethod; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } +// Forward declaration of `GooglePayEnvironment` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `PaymentRequest` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentRequest; } // Forward declaration of `PaymentItem` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentItem; } // Forward declaration of `PaymentItemType` to properly resolve imports. namespace margelo::nitro::pay { enum class PaymentItemType; } -// Forward declaration of `GooglePayEnvironment` to properly resolve imports. -namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `StartPaymentOptions` to properly resolve imports. namespace margelo::nitro::pay { struct StartPaymentOptions; } // Forward declaration of `PaymentAuthorizationResult` to properly resolve imports. @@ -57,12 +59,14 @@ namespace margelo::nitro::pay { struct PaymentAuthorizationResult; } namespace margelo::nitro::pay { struct PaymentDetails; } // Forward declaration of `PaymentAuthorizationStatus` to properly resolve imports. namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } +// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PayServiceStatus.hpp" -#include "JPayServiceStatus.hpp" -#include "PaymentResult.hpp" #include #include +#include "JPayServiceStatus.hpp" +#include "PaymentResult.hpp" #include "JPaymentResult.hpp" #include #include @@ -99,14 +103,16 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include "JShippingMethod.hpp" #include #include "JPaymentAmount.hpp" +#include "PayServiceStatusOptions.hpp" +#include "JPayServiceStatusOptions.hpp" +#include "GooglePayEnvironment.hpp" +#include "JGooglePayEnvironment.hpp" #include "PaymentRequest.hpp" #include "JPaymentRequest.hpp" #include "PaymentItem.hpp" #include "JPaymentItem.hpp" #include "PaymentItemType.hpp" #include "JPaymentItemType.hpp" -#include "GooglePayEnvironment.hpp" -#include "JGooglePayEnvironment.hpp" #include "StartPaymentOptions.hpp" #include "JStartPaymentOptions.hpp" #include "PaymentAuthorizationResult.hpp" @@ -118,6 +124,8 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include "PaymentAuthorizationStatus.hpp" #include "JPaymentAuthorizationStatus.hpp" #include "JPaymentDetails.hpp" +#include "CanMakePaymentsOptions.hpp" +#include "JCanMakePaymentsOptions.hpp" namespace margelo::nitro::pay { @@ -152,10 +160,21 @@ namespace margelo::nitro::pay { // Methods - PayServiceStatus JHybridPaymentHandlerSpec::payServiceStatus() { - static const auto method = _javaPart->javaClassStatic()->getMethod()>("payServiceStatus"); - auto __result = method(_javaPart); - return __result->toCpp(); + std::shared_ptr> JHybridPaymentHandlerSpec::payServiceStatus(const std::optional& options) { + static const auto method = _javaPart->javaClassStatic()->getMethod(jni::alias_ref /* options */)>("payServiceStatus"); + auto __result = method(_javaPart, options.has_value() ? JPayServiceStatusOptions::fromCpp(options.value()) : nullptr); + return [&]() { + auto __promise = Promise::create(); + __result->cthis()->addOnResolvedListener([=](const jni::alias_ref& __boxedResult) { + auto __result = jni::static_ref_cast(__boxedResult); + __promise->resolve(__result->toCpp()); + }); + __result->cthis()->addOnRejectedListener([=](const jni::alias_ref& __throwable) { + jni::JniException __jniError(__throwable); + __promise->reject(std::make_exception_ptr(__jniError)); + }); + return __promise; + }(); } std::shared_ptr> JHybridPaymentHandlerSpec::startPayment(const PaymentRequest& request, const std::optional& options) { static const auto method = _javaPart->javaClassStatic()->getMethod(jni::alias_ref /* request */, jni::alias_ref /* options */)>("startPayment"); @@ -173,8 +192,8 @@ namespace margelo::nitro::pay { return __promise; }(); } - bool JHybridPaymentHandlerSpec::canMakePayments(const std::vector& usingNetworks) { - static const auto method = _javaPart->javaClassStatic()->getMethod> /* usingNetworks */)>("canMakePayments"); + std::shared_ptr> JHybridPaymentHandlerSpec::canMakePayments(const std::vector& usingNetworks, const std::optional& options) { + static const auto method = _javaPart->javaClassStatic()->getMethod(jni::alias_ref> /* usingNetworks */, jni::alias_ref /* options */)>("canMakePayments"); auto __result = method(_javaPart, [&](auto&& __input) { size_t __size = __input.size(); jni::local_ref> __array = jni::JArrayClass::newArray(__size); @@ -184,13 +203,28 @@ namespace margelo::nitro::pay { __array->setElement(__i, *__elementJni); } return __array; - }(usingNetworks)); - return static_cast(__result); + }(usingNetworks), options.has_value() ? JCanMakePaymentsOptions::fromCpp(options.value()) : nullptr); + return [&]() { + auto __promise = Promise::create(); + __result->cthis()->addOnResolvedListener([=](const jni::alias_ref& __boxedResult) { + auto __result = jni::static_ref_cast(__boxedResult); + __promise->resolve(static_cast(__result->value())); + }); + __result->cthis()->addOnRejectedListener([=](const jni::alias_ref& __throwable) { + jni::JniException __jniError(__throwable); + __promise->reject(std::make_exception_ptr(__jniError)); + }); + return __promise; + }(); } bool JHybridPaymentHandlerSpec::isPaymentInProgress() { static const auto method = _javaPart->javaClassStatic()->getMethod("isPaymentInProgress"); auto __result = method(_javaPart); return static_cast(__result); } + void JHybridPaymentHandlerSpec::openPaymentSetup() { + static const auto method = _javaPart->javaClassStatic()->getMethod("openPaymentSetup"); + method(_javaPart); + } } // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp index b29d19f..a277aca 100644 --- a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp +++ b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp @@ -54,10 +54,11 @@ namespace margelo::nitro::pay { public: // Methods - PayServiceStatus payServiceStatus() override; + std::shared_ptr> payServiceStatus(const std::optional& options) override; std::shared_ptr> startPayment(const PaymentRequest& request, const std::optional& options) override; - bool canMakePayments(const std::vector& usingNetworks) override; + std::shared_ptr> canMakePayments(const std::vector& usingNetworks, const std::optional& options) override; bool isPaymentInProgress() override; + void openPaymentSetup() override; private: jni::global_ref _javaPart; diff --git a/package/nitrogen/generated/android/c++/JPayServiceStatus.hpp b/package/nitrogen/generated/android/c++/JPayServiceStatus.hpp index d1b978c..80fa4fd 100644 --- a/package/nitrogen/generated/android/c++/JPayServiceStatus.hpp +++ b/package/nitrogen/generated/android/c++/JPayServiceStatus.hpp @@ -31,13 +31,13 @@ namespace margelo::nitro::pay { [[nodiscard]] PayServiceStatus toCpp() const { static const auto clazz = javaClassStatic(); - static const auto fieldCanMakePayments = clazz->getField("canMakePayments"); - jboolean canMakePayments = this->getFieldValue(fieldCanMakePayments); - static const auto fieldCanSetupCards = clazz->getField("canSetupCards"); - jboolean canSetupCards = this->getFieldValue(fieldCanSetupCards); + static const auto fieldIsSupported = clazz->getField("isSupported"); + jboolean isSupported = this->getFieldValue(fieldIsSupported); + static const auto fieldHasActiveCard = clazz->getField("hasActiveCard"); + jboolean hasActiveCard = this->getFieldValue(fieldHasActiveCard); return PayServiceStatus( - static_cast(canMakePayments), - static_cast(canSetupCards) + static_cast(isSupported), + static_cast(hasActiveCard) ); } @@ -52,8 +52,8 @@ namespace margelo::nitro::pay { static const auto create = clazz->getStaticMethod("fromCpp"); return create( clazz, - value.canMakePayments, - value.canSetupCards + value.isSupported, + value.hasActiveCard ); } }; diff --git a/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp b/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp new file mode 100644 index 0000000..dba5206 --- /dev/null +++ b/package/nitrogen/generated/android/c++/JPayServiceStatusOptions.hpp @@ -0,0 +1,105 @@ +/// +/// JPayServiceStatusOptions.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include "PayServiceStatusOptions.hpp" + +#include "GooglePayEnvironment.hpp" +#include "JGooglePayEnvironment.hpp" +#include +#include +#include + +namespace margelo::nitro::pay { + + using namespace facebook; + + /** + * The C++ JNI bridge between the C++ struct "PayServiceStatusOptions" and the Kotlin data class "PayServiceStatusOptions". + */ + struct JPayServiceStatusOptions final: public jni::JavaClass { + public: + static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/pay/PayServiceStatusOptions;"; + + public: + /** + * Convert this Java/Kotlin-based struct to the C++ struct PayServiceStatusOptions by copying all values to C++. + */ + [[maybe_unused]] + [[nodiscard]] + PayServiceStatusOptions toCpp() const { + static const auto clazz = javaClassStatic(); + static const auto fieldSupportedNetworks = clazz->getField>("supportedNetworks"); + jni::local_ref> supportedNetworks = this->getFieldValue(fieldSupportedNetworks); + static const auto fieldMerchantCapabilities = clazz->getField>("merchantCapabilities"); + jni::local_ref> merchantCapabilities = this->getFieldValue(fieldMerchantCapabilities); + static const auto fieldGooglePayEnvironment = clazz->getField("googlePayEnvironment"); + jni::local_ref googlePayEnvironment = this->getFieldValue(fieldGooglePayEnvironment); + return PayServiceStatusOptions( + supportedNetworks != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(supportedNetworks)) : std::nullopt, + merchantCapabilities != nullptr ? std::make_optional([&](auto&& __input) { + size_t __size = __input->size(); + std::vector __vector; + __vector.reserve(__size); + for (size_t __i = 0; __i < __size; __i++) { + auto __element = __input->getElement(__i); + __vector.push_back(__element->toStdString()); + } + return __vector; + }(merchantCapabilities)) : std::nullopt, + googlePayEnvironment != nullptr ? std::make_optional(googlePayEnvironment->toCpp()) : std::nullopt + ); + } + + public: + /** + * Create a Java/Kotlin-based struct by copying all values from the given C++ struct to Java. + */ + [[maybe_unused]] + static jni::local_ref fromCpp(const PayServiceStatusOptions& value) { + using JSignature = JPayServiceStatusOptions(jni::alias_ref>, jni::alias_ref>, jni::alias_ref); + static const auto clazz = javaClassStatic(); + static const auto create = clazz->getStaticMethod("fromCpp"); + return create( + clazz, + value.supportedNetworks.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(value.supportedNetworks.value()) : nullptr, + value.merchantCapabilities.has_value() ? [&](auto&& __input) { + size_t __size = __input.size(); + jni::local_ref> __array = jni::JArrayClass::newArray(__size); + for (size_t __i = 0; __i < __size; __i++) { + const auto& __element = __input[__i]; + auto __elementJni = jni::make_jstring(__element); + __array->setElement(__i, *__elementJni); + } + return __array; + }(value.merchantCapabilities.value()) : nullptr, + value.googlePayEnvironment.has_value() ? JGooglePayEnvironment::fromCpp(value.googlePayEnvironment.value()) : nullptr + ); + } + }; + +} // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/CanMakePaymentsOptions.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/CanMakePaymentsOptions.kt new file mode 100644 index 0000000..fe460ea --- /dev/null +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/CanMakePaymentsOptions.kt @@ -0,0 +1,56 @@ +/// +/// CanMakePaymentsOptions.kt +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +package com.margelo.nitro.pay + +import androidx.annotation.Keep +import com.facebook.proguard.annotations.DoNotStrip +import java.util.Objects + + +/** + * Represents the JavaScript object/struct "CanMakePaymentsOptions". + */ +@DoNotStrip +@Keep +data class CanMakePaymentsOptions( + @DoNotStrip + @Keep + val merchantCapabilities: Array?, + @DoNotStrip + @Keep + val googlePayEnvironment: GooglePayEnvironment? +) { + /* primary constructor */ + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is CanMakePaymentsOptions) return false + return Objects.deepEquals(this.merchantCapabilities, other.merchantCapabilities) + && Objects.deepEquals(this.googlePayEnvironment, other.googlePayEnvironment) + } + + override fun hashCode(): Int { + return arrayOf( + merchantCapabilities, + googlePayEnvironment + ).contentDeepHashCode() + } + + companion object { + /** + * Constructor called from C++ + */ + @DoNotStrip + @Keep + @Suppress("unused") + @JvmStatic + private fun fromCpp(merchantCapabilities: Array?, googlePayEnvironment: GooglePayEnvironment?): CanMakePaymentsOptions { + return CanMakePaymentsOptions(merchantCapabilities, googlePayEnvironment) + } + } +} diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt index b265f1b..db5489f 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt @@ -31,7 +31,7 @@ abstract class HybridPaymentHandlerSpec: HybridObject() { // Methods @DoNotStrip @Keep - abstract fun payServiceStatus(): PayServiceStatus + abstract fun payServiceStatus(options: PayServiceStatusOptions?): Promise @DoNotStrip @Keep @@ -39,11 +39,15 @@ abstract class HybridPaymentHandlerSpec: HybridObject() { @DoNotStrip @Keep - abstract fun canMakePayments(usingNetworks: Array): Boolean + abstract fun canMakePayments(usingNetworks: Array, options: CanMakePaymentsOptions?): Promise @DoNotStrip @Keep abstract fun isPaymentInProgress(): Boolean + + @DoNotStrip + @Keep + abstract fun openPaymentSetup(): Unit // Default implementation of `HybridObject.toString()` override fun toString(): String { diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatus.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatus.kt index 64aa043..e6d554a 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatus.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatus.kt @@ -20,24 +20,24 @@ import java.util.Objects data class PayServiceStatus( @DoNotStrip @Keep - val canMakePayments: Boolean, + val isSupported: Boolean, @DoNotStrip @Keep - val canSetupCards: Boolean + val hasActiveCard: Boolean ) { /* primary constructor */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PayServiceStatus) return false - return Objects.deepEquals(this.canMakePayments, other.canMakePayments) - && Objects.deepEquals(this.canSetupCards, other.canSetupCards) + return Objects.deepEquals(this.isSupported, other.isSupported) + && Objects.deepEquals(this.hasActiveCard, other.hasActiveCard) } override fun hashCode(): Int { return arrayOf( - canMakePayments, - canSetupCards + isSupported, + hasActiveCard ).contentDeepHashCode() } @@ -49,8 +49,8 @@ data class PayServiceStatus( @Keep @Suppress("unused") @JvmStatic - private fun fromCpp(canMakePayments: Boolean, canSetupCards: Boolean): PayServiceStatus { - return PayServiceStatus(canMakePayments, canSetupCards) + private fun fromCpp(isSupported: Boolean, hasActiveCard: Boolean): PayServiceStatus { + return PayServiceStatus(isSupported, hasActiveCard) } } } diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt new file mode 100644 index 0000000..cc4eafd --- /dev/null +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PayServiceStatusOptions.kt @@ -0,0 +1,61 @@ +/// +/// PayServiceStatusOptions.kt +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +package com.margelo.nitro.pay + +import androidx.annotation.Keep +import com.facebook.proguard.annotations.DoNotStrip +import java.util.Objects + + +/** + * Represents the JavaScript object/struct "PayServiceStatusOptions". + */ +@DoNotStrip +@Keep +data class PayServiceStatusOptions( + @DoNotStrip + @Keep + val supportedNetworks: Array?, + @DoNotStrip + @Keep + val merchantCapabilities: Array?, + @DoNotStrip + @Keep + val googlePayEnvironment: GooglePayEnvironment? +) { + /* primary constructor */ + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is PayServiceStatusOptions) return false + return Objects.deepEquals(this.supportedNetworks, other.supportedNetworks) + && Objects.deepEquals(this.merchantCapabilities, other.merchantCapabilities) + && Objects.deepEquals(this.googlePayEnvironment, other.googlePayEnvironment) + } + + override fun hashCode(): Int { + return arrayOf( + supportedNetworks, + merchantCapabilities, + googlePayEnvironment + ).contentDeepHashCode() + } + + companion object { + /** + * Constructor called from C++ + */ + @DoNotStrip + @Keep + @Suppress("unused") + @JvmStatic + private fun fromCpp(supportedNetworks: Array?, merchantCapabilities: Array?, googlePayEnvironment: GooglePayEnvironment?): PayServiceStatusOptions { + return PayServiceStatusOptions(supportedNetworks, merchantCapabilities, googlePayEnvironment) + } + } +} diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.cpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.cpp index afa79ad..6924f82 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.cpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.cpp @@ -39,10 +39,10 @@ namespace margelo::nitro::pay::bridge::swift { return swiftPart.toUnsafe(); } - // pragma MARK: std::function - Func_void_PaymentResult create_Func_void_PaymentResult(void* NON_NULL swiftClosureWrapper) noexcept { - auto swiftClosure = NitroPay::Func_void_PaymentResult::fromUnsafe(swiftClosureWrapper); - return [swiftClosure = std::move(swiftClosure)](const PaymentResult& result) mutable -> void { + // pragma MARK: std::function + Func_void_PayServiceStatus create_Func_void_PayServiceStatus(void* NON_NULL swiftClosureWrapper) noexcept { + auto swiftClosure = NitroPay::Func_void_PayServiceStatus::fromUnsafe(swiftClosureWrapper); + return [swiftClosure = std::move(swiftClosure)](const PayServiceStatus& result) mutable -> void { swiftClosure.call(result); }; } @@ -55,6 +55,14 @@ namespace margelo::nitro::pay::bridge::swift { }; } + // pragma MARK: std::function + Func_void_PaymentResult create_Func_void_PaymentResult(void* NON_NULL swiftClosureWrapper) noexcept { + auto swiftClosure = NitroPay::Func_void_PaymentResult::fromUnsafe(swiftClosureWrapper); + return [swiftClosure = std::move(swiftClosure)](const PaymentResult& result) mutable -> void { + swiftClosure.call(result); + }; + } + // pragma MARK: std::function Func_void_PaymentAuthorizationResult create_Func_void_PaymentAuthorizationResult(void* NON_NULL swiftClosureWrapper) noexcept { auto swiftClosure = NitroPay::Func_void_PaymentAuthorizationResult::fromUnsafe(swiftClosureWrapper); @@ -80,6 +88,14 @@ namespace margelo::nitro::pay::bridge::swift { }; } + // pragma MARK: std::function + Func_void_bool create_Func_void_bool(void* NON_NULL swiftClosureWrapper) noexcept { + auto swiftClosure = NitroPay::Func_void_bool::fromUnsafe(swiftClosureWrapper); + return [swiftClosure = std::move(swiftClosure)](bool result) mutable -> void { + swiftClosure.call(result); + }; + } + // pragma MARK: std::shared_ptr std::shared_ptr create_std__shared_ptr_HybridPaymentHandlerSpec_(void* NON_NULL swiftUnsafePointer) noexcept { NitroPay::HybridPaymentHandlerSpec_cxx swiftPart = NitroPay::HybridPaymentHandlerSpec_cxx::fromUnsafe(swiftUnsafePointer); diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp index 5c44955..58bfd0d 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp @@ -22,6 +22,8 @@ namespace margelo::nitro::pay { struct CNLabeledPostalAddress; } namespace margelo::nitro::pay { struct CNPhoneNumber; } // Forward declaration of `CNPostalAddress` to properly resolve imports. namespace margelo::nitro::pay { struct CNPostalAddress; } +// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } // Forward declaration of `GooglePayEnvironment` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `HybridApplePayButtonSpec` to properly resolve imports. @@ -32,6 +34,8 @@ namespace margelo::nitro::pay { class HybridPaymentHandlerSpec; } namespace margelo::nitro::pay { struct PKSecureElementPass; } // Forward declaration of `PassActivationState` to properly resolve imports. namespace margelo::nitro::pay { enum class PassActivationState; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } // Forward declaration of `PayServiceStatus` to properly resolve imports. namespace margelo::nitro::pay { struct PayServiceStatus; } // Forward declaration of `PaymentAuthorizationResult` to properly resolve imports. @@ -75,12 +79,14 @@ namespace NitroPay { class HybridPaymentHandlerSpec_cxx; } #include "CNLabeledPostalAddress.hpp" #include "CNPhoneNumber.hpp" #include "CNPostalAddress.hpp" +#include "CanMakePaymentsOptions.hpp" #include "GooglePayEnvironment.hpp" #include "HybridApplePayButtonSpec.hpp" #include "HybridPaymentHandlerSpec.hpp" #include "PKSecureElementPass.hpp" #include "PassActivationState.hpp" #include "PayServiceStatus.hpp" +#include "PayServiceStatusOptions.hpp" #include "PaymentAuthorizationResult.hpp" #include "PaymentAuthorizationStatus.hpp" #include "PaymentContact.hpp" @@ -160,6 +166,118 @@ namespace margelo::nitro::pay::bridge::swift { using std__weak_ptr_HybridApplePayButtonSpec_ = std::weak_ptr; inline std__weak_ptr_HybridApplePayButtonSpec_ weakify_std__shared_ptr_HybridApplePayButtonSpec_(const std::shared_ptr& strong) noexcept { return strong; } + // pragma MARK: std::shared_ptr> + /** + * Specialized version of `std::shared_ptr>`. + */ + using std__shared_ptr_Promise_PayServiceStatus__ = std::shared_ptr>; + inline std::shared_ptr> create_std__shared_ptr_Promise_PayServiceStatus__() noexcept { + return Promise::create(); + } + inline PromiseHolder wrap_std__shared_ptr_Promise_PayServiceStatus__(std::shared_ptr> promise) noexcept { + return PromiseHolder(std::move(promise)); + } + + // pragma MARK: std::function + /** + * Specialized version of `std::function`. + */ + using Func_void_PayServiceStatus = std::function; + /** + * Wrapper class for a `std::function`, this can be used from Swift. + */ + class Func_void_PayServiceStatus_Wrapper final { + public: + explicit Func_void_PayServiceStatus_Wrapper(std::function&& func): _function(std::make_unique>(std::move(func))) {} + inline void call(PayServiceStatus result) const noexcept { + _function->operator()(result); + } + private: + std::unique_ptr> _function; + } SWIFT_NONCOPYABLE; + Func_void_PayServiceStatus create_Func_void_PayServiceStatus(void* NON_NULL swiftClosureWrapper) noexcept; + inline Func_void_PayServiceStatus_Wrapper wrap_Func_void_PayServiceStatus(Func_void_PayServiceStatus value) noexcept { + return Func_void_PayServiceStatus_Wrapper(std::move(value)); + } + + // pragma MARK: std::function + /** + * Specialized version of `std::function`. + */ + using Func_void_std__exception_ptr = std::function; + /** + * Wrapper class for a `std::function`, this can be used from Swift. + */ + class Func_void_std__exception_ptr_Wrapper final { + public: + explicit Func_void_std__exception_ptr_Wrapper(std::function&& func): _function(std::make_unique>(std::move(func))) {} + inline void call(std::exception_ptr error) const noexcept { + _function->operator()(error); + } + private: + std::unique_ptr> _function; + } SWIFT_NONCOPYABLE; + Func_void_std__exception_ptr create_Func_void_std__exception_ptr(void* NON_NULL swiftClosureWrapper) noexcept; + inline Func_void_std__exception_ptr_Wrapper wrap_Func_void_std__exception_ptr(Func_void_std__exception_ptr value) noexcept { + return Func_void_std__exception_ptr_Wrapper(std::move(value)); + } + + // pragma MARK: std::vector + /** + * Specialized version of `std::vector`. + */ + using std__vector_std__string_ = std::vector; + inline std::vector create_std__vector_std__string_(size_t size) noexcept { + std::vector vector; + vector.reserve(size); + return vector; + } + + // pragma MARK: std::optional> + /** + * Specialized version of `std::optional>`. + */ + using std__optional_std__vector_std__string__ = std::optional>; + inline std::optional> create_std__optional_std__vector_std__string__(const std::vector& value) noexcept { + return std::optional>(value); + } + inline bool has_value_std__optional_std__vector_std__string__(const std::optional>& optional) noexcept { + return optional.has_value(); + } + inline std::vector get_std__optional_std__vector_std__string__(const std::optional>& optional) noexcept { + return optional.value(); + } + + // pragma MARK: std::optional + /** + * Specialized version of `std::optional`. + */ + using std__optional_GooglePayEnvironment_ = std::optional; + inline std::optional create_std__optional_GooglePayEnvironment_(const GooglePayEnvironment& value) noexcept { + return std::optional(value); + } + inline bool has_value_std__optional_GooglePayEnvironment_(const std::optional& optional) noexcept { + return optional.has_value(); + } + inline GooglePayEnvironment get_std__optional_GooglePayEnvironment_(const std::optional& optional) noexcept { + return optional.value(); + } + + // pragma MARK: std::optional + /** + * Specialized version of `std::optional`. + */ + using std__optional_PayServiceStatusOptions_ = std::optional; + inline std::optional create_std__optional_PayServiceStatusOptions_(const PayServiceStatusOptions& value) noexcept { + return std::optional(value); + } + inline bool has_value_std__optional_PayServiceStatusOptions_(const std::optional& optional) noexcept { + return optional.has_value(); + } + inline PayServiceStatusOptions get_std__optional_PayServiceStatusOptions_(const std::optional& optional) noexcept { + return optional.value(); + } + // pragma MARK: std::optional /** * Specialized version of `std::optional`. @@ -391,28 +509,6 @@ namespace margelo::nitro::pay::bridge::swift { return Func_void_PaymentResult_Wrapper(std::move(value)); } - // pragma MARK: std::function - /** - * Specialized version of `std::function`. - */ - using Func_void_std__exception_ptr = std::function; - /** - * Wrapper class for a `std::function`, this can be used from Swift. - */ - class Func_void_std__exception_ptr_Wrapper final { - public: - explicit Func_void_std__exception_ptr_Wrapper(std::function&& func): _function(std::make_unique>(std::move(func))) {} - inline void call(std::exception_ptr error) const noexcept { - _function->operator()(error); - } - private: - std::unique_ptr> _function; - } SWIFT_NONCOPYABLE; - Func_void_std__exception_ptr create_Func_void_std__exception_ptr(void* NON_NULL swiftClosureWrapper) noexcept; - inline Func_void_std__exception_ptr_Wrapper wrap_Func_void_std__exception_ptr(Func_void_std__exception_ptr value) noexcept { - return Func_void_std__exception_ptr_Wrapper(std::move(value)); - } - // pragma MARK: std::vector /** * Specialized version of `std::vector`. @@ -424,17 +520,6 @@ namespace margelo::nitro::pay::bridge::swift { return vector; } - // pragma MARK: std::vector - /** - * Specialized version of `std::vector`. - */ - using std__vector_std__string_ = std::vector; - inline std::vector create_std__vector_std__string_(size_t size) noexcept { - std::vector vector; - vector.reserve(size); - return vector; - } - // pragma MARK: std::vector /** * Specialized version of `std::vector`. @@ -461,21 +546,6 @@ namespace margelo::nitro::pay::bridge::swift { return optional.value(); } - // pragma MARK: std::optional - /** - * Specialized version of `std::optional`. - */ - using std__optional_GooglePayEnvironment_ = std::optional; - inline std::optional create_std__optional_GooglePayEnvironment_(const GooglePayEnvironment& value) noexcept { - return std::optional(value); - } - inline bool has_value_std__optional_GooglePayEnvironment_(const std::optional& optional) noexcept { - return optional.has_value(); - } - inline GooglePayEnvironment get_std__optional_GooglePayEnvironment_(const std::optional& optional) noexcept { - return optional.value(); - } - // pragma MARK: std::shared_ptr> /** * Specialized version of `std::shared_ptr>`. @@ -597,6 +667,55 @@ namespace margelo::nitro::pay::bridge::swift { return optional.value(); } + // pragma MARK: std::shared_ptr> + /** + * Specialized version of `std::shared_ptr>`. + */ + using std__shared_ptr_Promise_bool__ = std::shared_ptr>; + inline std::shared_ptr> create_std__shared_ptr_Promise_bool__() noexcept { + return Promise::create(); + } + inline PromiseHolder wrap_std__shared_ptr_Promise_bool__(std::shared_ptr> promise) noexcept { + return PromiseHolder(std::move(promise)); + } + + // pragma MARK: std::function + /** + * Specialized version of `std::function`. + */ + using Func_void_bool = std::function; + /** + * Wrapper class for a `std::function`, this can be used from Swift. + */ + class Func_void_bool_Wrapper final { + public: + explicit Func_void_bool_Wrapper(std::function&& func): _function(std::make_unique>(std::move(func))) {} + inline void call(bool result) const noexcept { + _function->operator()(result); + } + private: + std::unique_ptr> _function; + } SWIFT_NONCOPYABLE; + Func_void_bool create_Func_void_bool(void* NON_NULL swiftClosureWrapper) noexcept; + inline Func_void_bool_Wrapper wrap_Func_void_bool(Func_void_bool value) noexcept { + return Func_void_bool_Wrapper(std::move(value)); + } + + // pragma MARK: std::optional + /** + * Specialized version of `std::optional`. + */ + using std__optional_CanMakePaymentsOptions_ = std::optional; + inline std::optional create_std__optional_CanMakePaymentsOptions_(const CanMakePaymentsOptions& value) noexcept { + return std::optional(value); + } + inline bool has_value_std__optional_CanMakePaymentsOptions_(const std::optional& optional) noexcept { + return optional.has_value(); + } + inline CanMakePaymentsOptions get_std__optional_CanMakePaymentsOptions_(const std::optional& optional) noexcept { + return optional.value(); + } + // pragma MARK: std::shared_ptr /** * Specialized version of `std::shared_ptr`. @@ -609,13 +728,13 @@ namespace margelo::nitro::pay::bridge::swift { using std__weak_ptr_HybridPaymentHandlerSpec_ = std::weak_ptr; inline std__weak_ptr_HybridPaymentHandlerSpec_ weakify_std__shared_ptr_HybridPaymentHandlerSpec_(const std::shared_ptr& strong) noexcept { return strong; } - // pragma MARK: Result - using Result_PayServiceStatus_ = Result; - inline Result_PayServiceStatus_ create_Result_PayServiceStatus_(const PayServiceStatus& value) noexcept { - return Result::withValue(value); + // pragma MARK: Result>> + using Result_std__shared_ptr_Promise_PayServiceStatus___ = Result>>; + inline Result_std__shared_ptr_Promise_PayServiceStatus___ create_Result_std__shared_ptr_Promise_PayServiceStatus___(const std::shared_ptr>& value) noexcept { + return Result>>::withValue(value); } - inline Result_PayServiceStatus_ create_Result_PayServiceStatus_(const std::exception_ptr& error) noexcept { - return Result::withError(error); + inline Result_std__shared_ptr_Promise_PayServiceStatus___ create_Result_std__shared_ptr_Promise_PayServiceStatus___(const std::exception_ptr& error) noexcept { + return Result>>::withError(error); } // pragma MARK: Result>> @@ -627,6 +746,15 @@ namespace margelo::nitro::pay::bridge::swift { return Result>>::withError(error); } + // pragma MARK: Result>> + using Result_std__shared_ptr_Promise_bool___ = Result>>; + inline Result_std__shared_ptr_Promise_bool___ create_Result_std__shared_ptr_Promise_bool___(const std::shared_ptr>& value) noexcept { + return Result>>::withValue(value); + } + inline Result_std__shared_ptr_Promise_bool___ create_Result_std__shared_ptr_Promise_bool___(const std::exception_ptr& error) noexcept { + return Result>>::withError(error); + } + // pragma MARK: Result using Result_bool_ = Result; inline Result_bool_ create_Result_bool_(bool value) noexcept { @@ -635,5 +763,14 @@ namespace margelo::nitro::pay::bridge::swift { inline Result_bool_ create_Result_bool_(const std::exception_ptr& error) noexcept { return Result::withError(error); } + + // pragma MARK: Result + using Result_void_ = Result; + inline Result_void_ create_Result_void_() noexcept { + return Result::withValue(); + } + inline Result_void_ create_Result_void_(const std::exception_ptr& error) noexcept { + return Result::withError(error); + } } // namespace margelo::nitro::pay::bridge::swift diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp index 120c346..52bcb88 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp @@ -26,6 +26,8 @@ namespace margelo::nitro::pay { struct CNLabeledPostalAddress; } namespace margelo::nitro::pay { struct CNPhoneNumber; } // Forward declaration of `CNPostalAddress` to properly resolve imports. namespace margelo::nitro::pay { struct CNPostalAddress; } +// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } // Forward declaration of `GooglePayEnvironment` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `HybridApplePayButtonSpec` to properly resolve imports. @@ -36,6 +38,8 @@ namespace margelo::nitro::pay { class HybridPaymentHandlerSpec; } namespace margelo::nitro::pay { struct PKSecureElementPass; } // Forward declaration of `PassActivationState` to properly resolve imports. namespace margelo::nitro::pay { enum class PassActivationState; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } // Forward declaration of `PayServiceStatus` to properly resolve imports. namespace margelo::nitro::pay { struct PayServiceStatus; } // Forward declaration of `PaymentAuthorizationResult` to properly resolve imports. @@ -77,12 +81,14 @@ namespace margelo::nitro::pay { struct StartPaymentOptions; } #include "CNLabeledPostalAddress.hpp" #include "CNPhoneNumber.hpp" #include "CNPostalAddress.hpp" +#include "CanMakePaymentsOptions.hpp" #include "GooglePayEnvironment.hpp" #include "HybridApplePayButtonSpec.hpp" #include "HybridPaymentHandlerSpec.hpp" #include "PKSecureElementPass.hpp" #include "PassActivationState.hpp" #include "PayServiceStatus.hpp" +#include "PayServiceStatusOptions.hpp" #include "PaymentAuthorizationResult.hpp" #include "PaymentAuthorizationStatus.hpp" #include "PaymentContact.hpp" diff --git a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp index dc10f54..0562932 100644 --- a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp +++ b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp @@ -14,6 +14,10 @@ namespace NitroPay { class HybridPaymentHandlerSpec_cxx; } // Forward declaration of `PayServiceStatus` to properly resolve imports. namespace margelo::nitro::pay { struct PayServiceStatus; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } +// Forward declaration of `GooglePayEnvironment` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `PaymentResult` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentResult; } // Forward declaration of `PaymentToken` to properly resolve imports. @@ -52,8 +56,6 @@ namespace margelo::nitro::pay { struct PaymentRequest; } namespace margelo::nitro::pay { struct PaymentItem; } // Forward declaration of `PaymentItemType` to properly resolve imports. namespace margelo::nitro::pay { enum class PaymentItemType; } -// Forward declaration of `GooglePayEnvironment` to properly resolve imports. -namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `StartPaymentOptions` to properly resolve imports. namespace margelo::nitro::pay { struct StartPaymentOptions; } // Forward declaration of `PaymentAuthorizationResult` to properly resolve imports. @@ -62,12 +64,17 @@ namespace margelo::nitro::pay { struct PaymentAuthorizationResult; } namespace margelo::nitro::pay { struct PaymentDetails; } // Forward declaration of `PaymentAuthorizationStatus` to properly resolve imports. namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } +// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PayServiceStatus.hpp" -#include "PaymentResult.hpp" #include -#include +#include "PayServiceStatusOptions.hpp" #include +#include +#include +#include "GooglePayEnvironment.hpp" +#include "PaymentResult.hpp" #include "PaymentToken.hpp" #include "PaymentMethod.hpp" #include "PaymentNetwork.hpp" @@ -77,7 +84,6 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include "CNContact.hpp" #include "CNContactType.hpp" #include "CNLabeledPhoneNumber.hpp" -#include #include "CNPhoneNumber.hpp" #include "CNLabeledEmailAddress.hpp" #include "CNLabeledPostalAddress.hpp" @@ -88,12 +94,12 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include "PaymentRequest.hpp" #include "PaymentItem.hpp" #include "PaymentItemType.hpp" -#include "GooglePayEnvironment.hpp" #include "StartPaymentOptions.hpp" #include "PaymentAuthorizationResult.hpp" #include "PaymentDetails.hpp" #include #include "PaymentAuthorizationStatus.hpp" +#include "CanMakePaymentsOptions.hpp" #include "NitroPay-Swift-Cxx-Umbrella.hpp" @@ -145,8 +151,8 @@ namespace margelo::nitro::pay { public: // Methods - inline PayServiceStatus payServiceStatus() override { - auto __result = _swiftPart.payServiceStatus(); + inline std::shared_ptr> payServiceStatus(const std::optional& options) override { + auto __result = _swiftPart.payServiceStatus(options); if (__result.hasError()) [[unlikely]] { std::rethrow_exception(__result.error()); } @@ -161,8 +167,8 @@ namespace margelo::nitro::pay { auto __value = std::move(__result.value()); return __value; } - inline bool canMakePayments(const std::vector& usingNetworks) override { - auto __result = _swiftPart.canMakePayments(usingNetworks); + inline std::shared_ptr> canMakePayments(const std::vector& usingNetworks, const std::optional& options) override { + auto __result = _swiftPart.canMakePayments(usingNetworks, options); if (__result.hasError()) [[unlikely]] { std::rethrow_exception(__result.error()); } @@ -177,6 +183,12 @@ namespace margelo::nitro::pay { auto __value = std::move(__result.value()); return __value; } + inline void openPaymentSetup() override { + auto __result = _swiftPart.openPaymentSetup(); + if (__result.hasError()) [[unlikely]] { + std::rethrow_exception(__result.error()); + } + } private: NitroPay::HybridPaymentHandlerSpec_cxx _swiftPart; diff --git a/package/nitrogen/generated/ios/swift/CanMakePaymentsOptions.swift b/package/nitrogen/generated/ios/swift/CanMakePaymentsOptions.swift new file mode 100644 index 0000000..bb3550c --- /dev/null +++ b/package/nitrogen/generated/ios/swift/CanMakePaymentsOptions.swift @@ -0,0 +1,59 @@ +/// +/// CanMakePaymentsOptions.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +import NitroModules + +/** + * Represents an instance of `CanMakePaymentsOptions`, backed by a C++ struct. + */ +public typealias CanMakePaymentsOptions = margelo.nitro.pay.CanMakePaymentsOptions + +public extension CanMakePaymentsOptions { + private typealias bridge = margelo.nitro.pay.bridge.swift + + /** + * Create a new instance of `CanMakePaymentsOptions`. + */ + init(merchantCapabilities: [String]?, googlePayEnvironment: GooglePayEnvironment?) { + self.init({ () -> bridge.std__optional_std__vector_std__string__ in + if let __unwrappedValue = merchantCapabilities { + return bridge.create_std__optional_std__vector_std__string__({ () -> bridge.std__vector_std__string_ in + var __vector = bridge.create_std__vector_std__string_(__unwrappedValue.count) + for __item in __unwrappedValue { + __vector.push_back(std.string(__item)) + } + return __vector + }()) + } else { + return .init() + } + }(), { () -> bridge.std__optional_GooglePayEnvironment_ in + if let __unwrappedValue = googlePayEnvironment { + return bridge.create_std__optional_GooglePayEnvironment_(__unwrappedValue) + } else { + return .init() + } + }()) + } + + @inline(__always) + var merchantCapabilities: [String]? { + return { () -> [String]? in + if bridge.has_value_std__optional_std__vector_std__string__(self.__merchantCapabilities) { + let __unwrapped = bridge.get_std__optional_std__vector_std__string__(self.__merchantCapabilities) + return __unwrapped.map({ __item in String(__item) }) + } else { + return nil + } + }() + } + + @inline(__always) + var googlePayEnvironment: GooglePayEnvironment? { + return self.__googlePayEnvironment.value + } +} diff --git a/package/nitrogen/generated/ios/swift/Func_void_PayServiceStatus.swift b/package/nitrogen/generated/ios/swift/Func_void_PayServiceStatus.swift new file mode 100644 index 0000000..f2ed4ee --- /dev/null +++ b/package/nitrogen/generated/ios/swift/Func_void_PayServiceStatus.swift @@ -0,0 +1,46 @@ +/// +/// Func_void_PayServiceStatus.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +import NitroModules + +/** + * Wraps a Swift `(_ value: PayServiceStatus) -> Void` as a class. + * This class can be used from C++, e.g. to wrap the Swift closure as a `std::function`. + */ +public final class Func_void_PayServiceStatus { + public typealias bridge = margelo.nitro.pay.bridge.swift + + private let closure: (_ value: PayServiceStatus) -> Void + + public init(_ closure: @escaping (_ value: PayServiceStatus) -> Void) { + self.closure = closure + } + + @inline(__always) + public func call(value: PayServiceStatus) -> Void { + self.closure(value) + } + + /** + * Casts this instance to a retained unsafe raw pointer. + * This acquires one additional strong reference on the object! + */ + @inline(__always) + public func toUnsafe() -> UnsafeMutableRawPointer { + return Unmanaged.passRetained(self).toOpaque() + } + + /** + * Casts an unsafe pointer to a `Func_void_PayServiceStatus`. + * The pointer has to be a retained opaque `Unmanaged`. + * This removes one strong reference from the object! + */ + @inline(__always) + public static func fromUnsafe(_ pointer: UnsafeMutableRawPointer) -> Func_void_PayServiceStatus { + return Unmanaged.fromOpaque(pointer).takeRetainedValue() + } +} diff --git a/package/nitrogen/generated/ios/swift/Func_void_bool.swift b/package/nitrogen/generated/ios/swift/Func_void_bool.swift new file mode 100644 index 0000000..4a8b03e --- /dev/null +++ b/package/nitrogen/generated/ios/swift/Func_void_bool.swift @@ -0,0 +1,46 @@ +/// +/// Func_void_bool.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +import NitroModules + +/** + * Wraps a Swift `(_ value: Bool) -> Void` as a class. + * This class can be used from C++, e.g. to wrap the Swift closure as a `std::function`. + */ +public final class Func_void_bool { + public typealias bridge = margelo.nitro.pay.bridge.swift + + private let closure: (_ value: Bool) -> Void + + public init(_ closure: @escaping (_ value: Bool) -> Void) { + self.closure = closure + } + + @inline(__always) + public func call(value: Bool) -> Void { + self.closure(value) + } + + /** + * Casts this instance to a retained unsafe raw pointer. + * This acquires one additional strong reference on the object! + */ + @inline(__always) + public func toUnsafe() -> UnsafeMutableRawPointer { + return Unmanaged.passRetained(self).toOpaque() + } + + /** + * Casts an unsafe pointer to a `Func_void_bool`. + * The pointer has to be a retained opaque `Unmanaged`. + * This removes one strong reference from the object! + */ + @inline(__always) + public static func fromUnsafe(_ pointer: UnsafeMutableRawPointer) -> Func_void_bool { + return Unmanaged.fromOpaque(pointer).takeRetainedValue() + } +} diff --git a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift index 68d9884..ed82572 100644 --- a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift +++ b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift @@ -13,10 +13,11 @@ public protocol HybridPaymentHandlerSpec_protocol: HybridObject { // Methods - func payServiceStatus() throws -> PayServiceStatus + func payServiceStatus(options: PayServiceStatusOptions?) throws -> Promise func startPayment(request: PaymentRequest, options: StartPaymentOptions?) throws -> Promise - func canMakePayments(usingNetworks: [String]) throws -> Bool + func canMakePayments(usingNetworks: [String], options: CanMakePaymentsOptions?) throws -> Promise func isPaymentInProgress() throws -> Bool + func openPaymentSetup() throws -> Void } public extension HybridPaymentHandlerSpec_protocol { diff --git a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift index bb4876d..51b39e4 100644 --- a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift +++ b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift @@ -125,14 +125,21 @@ open class HybridPaymentHandlerSpec_cxx { // Methods @inline(__always) - public final func payServiceStatus() -> bridge.Result_PayServiceStatus_ { + public final func payServiceStatus(options: bridge.std__optional_PayServiceStatusOptions_) -> bridge.Result_std__shared_ptr_Promise_PayServiceStatus___ { do { - let __result = try self.__implementation.payServiceStatus() - let __resultCpp = __result - return bridge.create_Result_PayServiceStatus_(__resultCpp) + let __result = try self.__implementation.payServiceStatus(options: options.value) + let __resultCpp = { () -> bridge.std__shared_ptr_Promise_PayServiceStatus__ in + let __promise = bridge.create_std__shared_ptr_Promise_PayServiceStatus__() + let __promiseHolder = bridge.wrap_std__shared_ptr_Promise_PayServiceStatus__(__promise) + __result + .then({ __result in __promiseHolder.resolve(__result) }) + .catch({ __error in __promiseHolder.reject(__error.toCpp()) }) + return __promise + }() + return bridge.create_Result_std__shared_ptr_Promise_PayServiceStatus___(__resultCpp) } catch (let __error) { let __exceptionPtr = __error.toCpp() - return bridge.create_Result_PayServiceStatus_(__exceptionPtr) + return bridge.create_Result_std__shared_ptr_Promise_PayServiceStatus___(__exceptionPtr) } } @@ -156,14 +163,21 @@ open class HybridPaymentHandlerSpec_cxx { } @inline(__always) - public final func canMakePayments(usingNetworks: bridge.std__vector_std__string_) -> bridge.Result_bool_ { + public final func canMakePayments(usingNetworks: bridge.std__vector_std__string_, options: bridge.std__optional_CanMakePaymentsOptions_) -> bridge.Result_std__shared_ptr_Promise_bool___ { do { - let __result = try self.__implementation.canMakePayments(usingNetworks: usingNetworks.map({ __item in String(__item) })) - let __resultCpp = __result - return bridge.create_Result_bool_(__resultCpp) + let __result = try self.__implementation.canMakePayments(usingNetworks: usingNetworks.map({ __item in String(__item) }), options: options.value) + let __resultCpp = { () -> bridge.std__shared_ptr_Promise_bool__ in + let __promise = bridge.create_std__shared_ptr_Promise_bool__() + let __promiseHolder = bridge.wrap_std__shared_ptr_Promise_bool__(__promise) + __result + .then({ __result in __promiseHolder.resolve(__result) }) + .catch({ __error in __promiseHolder.reject(__error.toCpp()) }) + return __promise + }() + return bridge.create_Result_std__shared_ptr_Promise_bool___(__resultCpp) } catch (let __error) { let __exceptionPtr = __error.toCpp() - return bridge.create_Result_bool_(__exceptionPtr) + return bridge.create_Result_std__shared_ptr_Promise_bool___(__exceptionPtr) } } @@ -178,4 +192,15 @@ open class HybridPaymentHandlerSpec_cxx { return bridge.create_Result_bool_(__exceptionPtr) } } + + @inline(__always) + public final func openPaymentSetup() -> bridge.Result_void_ { + do { + try self.__implementation.openPaymentSetup() + return bridge.create_Result_void_() + } catch (let __error) { + let __exceptionPtr = __error.toCpp() + return bridge.create_Result_void_(__exceptionPtr) + } + } } diff --git a/package/nitrogen/generated/ios/swift/PayServiceStatus.swift b/package/nitrogen/generated/ios/swift/PayServiceStatus.swift index a480fff..f17cf76 100644 --- a/package/nitrogen/generated/ios/swift/PayServiceStatus.swift +++ b/package/nitrogen/generated/ios/swift/PayServiceStatus.swift @@ -18,17 +18,17 @@ public extension PayServiceStatus { /** * Create a new instance of `PayServiceStatus`. */ - init(canMakePayments: Bool, canSetupCards: Bool) { - self.init(canMakePayments, canSetupCards) + init(isSupported: Bool, hasActiveCard: Bool) { + self.init(isSupported, hasActiveCard) } @inline(__always) - var canMakePayments: Bool { - return self.__canMakePayments + var isSupported: Bool { + return self.__isSupported } @inline(__always) - var canSetupCards: Bool { - return self.__canSetupCards + var hasActiveCard: Bool { + return self.__hasActiveCard } } diff --git a/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift b/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift new file mode 100644 index 0000000..cf2ff27 --- /dev/null +++ b/package/nitrogen/generated/ios/swift/PayServiceStatusOptions.swift @@ -0,0 +1,83 @@ +/// +/// PayServiceStatusOptions.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +import NitroModules + +/** + * Represents an instance of `PayServiceStatusOptions`, backed by a C++ struct. + */ +public typealias PayServiceStatusOptions = margelo.nitro.pay.PayServiceStatusOptions + +public extension PayServiceStatusOptions { + private typealias bridge = margelo.nitro.pay.bridge.swift + + /** + * Create a new instance of `PayServiceStatusOptions`. + */ + init(supportedNetworks: [String]?, merchantCapabilities: [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 + var __vector = bridge.create_std__vector_std__string_(__unwrappedValue.count) + for __item in __unwrappedValue { + __vector.push_back(std.string(__item)) + } + return __vector + }()) + } else { + return .init() + } + }(), { () -> bridge.std__optional_std__vector_std__string__ in + if let __unwrappedValue = merchantCapabilities { + return bridge.create_std__optional_std__vector_std__string__({ () -> bridge.std__vector_std__string_ in + var __vector = bridge.create_std__vector_std__string_(__unwrappedValue.count) + for __item in __unwrappedValue { + __vector.push_back(std.string(__item)) + } + return __vector + }()) + } else { + return .init() + } + }(), { () -> bridge.std__optional_GooglePayEnvironment_ in + if let __unwrappedValue = googlePayEnvironment { + return bridge.create_std__optional_GooglePayEnvironment_(__unwrappedValue) + } else { + return .init() + } + }()) + } + + @inline(__always) + var supportedNetworks: [String]? { + return { () -> [String]? in + if bridge.has_value_std__optional_std__vector_std__string__(self.__supportedNetworks) { + let __unwrapped = bridge.get_std__optional_std__vector_std__string__(self.__supportedNetworks) + return __unwrapped.map({ __item in String(__item) }) + } else { + return nil + } + }() + } + + @inline(__always) + var merchantCapabilities: [String]? { + return { () -> [String]? in + if bridge.has_value_std__optional_std__vector_std__string__(self.__merchantCapabilities) { + let __unwrapped = bridge.get_std__optional_std__vector_std__string__(self.__merchantCapabilities) + return __unwrapped.map({ __item in String(__item) }) + } else { + return nil + } + }() + } + + @inline(__always) + var googlePayEnvironment: GooglePayEnvironment? { + return self.__googlePayEnvironment.value + } +} diff --git a/package/nitrogen/generated/shared/c++/CanMakePaymentsOptions.hpp b/package/nitrogen/generated/shared/c++/CanMakePaymentsOptions.hpp new file mode 100644 index 0000000..084df44 --- /dev/null +++ b/package/nitrogen/generated/shared/c++/CanMakePaymentsOptions.hpp @@ -0,0 +1,91 @@ +/// +/// CanMakePaymentsOptions.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +// Forward declaration of `GooglePayEnvironment` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayEnvironment; } + +#include +#include +#include +#include "GooglePayEnvironment.hpp" + +namespace margelo::nitro::pay { + + /** + * A struct which can be represented as a JavaScript object (CanMakePaymentsOptions). + */ + struct CanMakePaymentsOptions final { + public: + std::optional> merchantCapabilities SWIFT_PRIVATE; + std::optional googlePayEnvironment SWIFT_PRIVATE; + + public: + CanMakePaymentsOptions() = default; + explicit CanMakePaymentsOptions(std::optional> merchantCapabilities, std::optional googlePayEnvironment): merchantCapabilities(merchantCapabilities), googlePayEnvironment(googlePayEnvironment) {} + + public: + friend bool operator==(const CanMakePaymentsOptions& lhs, const CanMakePaymentsOptions& rhs) = default; + }; + +} // namespace margelo::nitro::pay + +namespace margelo::nitro { + + // C++ CanMakePaymentsOptions <> JS CanMakePaymentsOptions (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::pay::CanMakePaymentsOptions fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::pay::CanMakePaymentsOptions( + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::CanMakePaymentsOptions& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"), JSIConverter>>::toJSI(runtime, arg.merchantCapabilities)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"), JSIConverter>::toJSI(runtime, arg.googlePayEnvironment)); + return obj; + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.cpp b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.cpp index 9044cd4..9b969b8 100644 --- a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.cpp +++ b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.cpp @@ -18,6 +18,7 @@ namespace margelo::nitro::pay { prototype.registerHybridMethod("startPayment", &HybridPaymentHandlerSpec::startPayment); prototype.registerHybridMethod("canMakePayments", &HybridPaymentHandlerSpec::canMakePayments); prototype.registerHybridMethod("isPaymentInProgress", &HybridPaymentHandlerSpec::isPaymentInProgress); + prototype.registerHybridMethod("openPaymentSetup", &HybridPaymentHandlerSpec::openPaymentSetup); }); } diff --git a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp index f92e5c5..5ebbfd9 100644 --- a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp +++ b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp @@ -15,21 +15,27 @@ // Forward declaration of `PayServiceStatus` to properly resolve imports. namespace margelo::nitro::pay { struct PayServiceStatus; } +// Forward declaration of `PayServiceStatusOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct PayServiceStatusOptions; } // Forward declaration of `PaymentResult` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentResult; } // Forward declaration of `PaymentRequest` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentRequest; } // Forward declaration of `StartPaymentOptions` to properly resolve imports. namespace margelo::nitro::pay { struct StartPaymentOptions; } +// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. +namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PayServiceStatus.hpp" -#include "PaymentResult.hpp" #include +#include "PayServiceStatusOptions.hpp" +#include +#include "PaymentResult.hpp" #include "PaymentRequest.hpp" #include "StartPaymentOptions.hpp" -#include #include #include +#include "CanMakePaymentsOptions.hpp" namespace margelo::nitro::pay { @@ -62,10 +68,11 @@ namespace margelo::nitro::pay { public: // Methods - virtual PayServiceStatus payServiceStatus() = 0; + virtual std::shared_ptr> payServiceStatus(const std::optional& options) = 0; virtual std::shared_ptr> startPayment(const PaymentRequest& request, const std::optional& options) = 0; - virtual bool canMakePayments(const std::vector& usingNetworks) = 0; + virtual std::shared_ptr> canMakePayments(const std::vector& usingNetworks, const std::optional& options) = 0; virtual bool isPaymentInProgress() = 0; + virtual void openPaymentSetup() = 0; protected: // Hybrid Setup diff --git a/package/nitrogen/generated/shared/c++/PayServiceStatus.hpp b/package/nitrogen/generated/shared/c++/PayServiceStatus.hpp index 64dc68c..daa3031 100644 --- a/package/nitrogen/generated/shared/c++/PayServiceStatus.hpp +++ b/package/nitrogen/generated/shared/c++/PayServiceStatus.hpp @@ -39,12 +39,12 @@ namespace margelo::nitro::pay { */ struct PayServiceStatus final { public: - bool canMakePayments SWIFT_PRIVATE; - bool canSetupCards SWIFT_PRIVATE; + bool isSupported SWIFT_PRIVATE; + bool hasActiveCard SWIFT_PRIVATE; public: PayServiceStatus() = default; - explicit PayServiceStatus(bool canMakePayments, bool canSetupCards): canMakePayments(canMakePayments), canSetupCards(canSetupCards) {} + explicit PayServiceStatus(bool isSupported, bool hasActiveCard): isSupported(isSupported), hasActiveCard(hasActiveCard) {} public: friend bool operator==(const PayServiceStatus& lhs, const PayServiceStatus& rhs) = default; @@ -60,14 +60,14 @@ namespace margelo::nitro { static inline margelo::nitro::pay::PayServiceStatus fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { jsi::Object obj = arg.asObject(runtime); return margelo::nitro::pay::PayServiceStatus( - JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "canMakePayments"))), - JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "canSetupCards"))) + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "isSupported"))), + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "hasActiveCard"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::PayServiceStatus& arg) { jsi::Object obj(runtime); - obj.setProperty(runtime, PropNameIDCache::get(runtime, "canMakePayments"), JSIConverter::toJSI(runtime, arg.canMakePayments)); - obj.setProperty(runtime, PropNameIDCache::get(runtime, "canSetupCards"), JSIConverter::toJSI(runtime, arg.canSetupCards)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "isSupported"), JSIConverter::toJSI(runtime, arg.isSupported)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "hasActiveCard"), JSIConverter::toJSI(runtime, arg.hasActiveCard)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -78,8 +78,8 @@ namespace margelo::nitro { if (!nitro::isPlainObject(runtime, obj)) { return false; } - if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "canMakePayments")))) return false; - if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "canSetupCards")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "isSupported")))) return false; + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "hasActiveCard")))) return false; return true; } }; diff --git a/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp b/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp new file mode 100644 index 0000000..001820d --- /dev/null +++ b/package/nitrogen/generated/shared/c++/PayServiceStatusOptions.hpp @@ -0,0 +1,95 @@ +/// +/// PayServiceStatusOptions.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif +#if __has_include() +#include +#else +#error NitroModules cannot be found! Are you sure you installed NitroModules properly? +#endif + +// Forward declaration of `GooglePayEnvironment` to properly resolve imports. +namespace margelo::nitro::pay { enum class GooglePayEnvironment; } + +#include +#include +#include +#include "GooglePayEnvironment.hpp" + +namespace margelo::nitro::pay { + + /** + * A struct which can be represented as a JavaScript object (PayServiceStatusOptions). + */ + struct PayServiceStatusOptions final { + public: + std::optional> supportedNetworks SWIFT_PRIVATE; + std::optional> merchantCapabilities 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) {} + + public: + friend bool operator==(const PayServiceStatusOptions& lhs, const PayServiceStatusOptions& rhs) = default; + }; + +} // namespace margelo::nitro::pay + +namespace margelo::nitro { + + // C++ PayServiceStatusOptions <> JS PayServiceStatusOptions (object) + template <> + struct JSIConverter final { + static inline margelo::nitro::pay::PayServiceStatusOptions fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::pay::PayServiceStatusOptions( + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks"))), + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"))) + ); + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::PayServiceStatusOptions& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks"), JSIConverter>>::toJSI(runtime, arg.supportedNetworks)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"), JSIConverter>>::toJSI(runtime, arg.merchantCapabilities)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"), JSIConverter>::toJSI(runtime, arg.googlePayEnvironment)); + return obj; + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "supportedNetworks")))) return false; + if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment")))) return false; + return true; + } + }; + +} // namespace margelo::nitro diff --git a/package/src/__tests__/paymentHandler.test.ts b/package/src/__tests__/paymentHandler.test.ts index bcdb1d7..1c355d5 100644 --- a/package/src/__tests__/paymentHandler.test.ts +++ b/package/src/__tests__/paymentHandler.test.ts @@ -1,4 +1,4 @@ -import { act, renderHook } from '@testing-library/react-native' +import { act, renderHook, waitFor } from '@testing-library/react-native' const IN_PROGRESS_RESULT = { success: false, @@ -15,10 +15,8 @@ jest.mock('react-native-nitro-modules', () => ({ // Mirrors the per-instance in-progress guard of the native handlers. let inFlight = false const instance = { - payServiceStatus: () => ({ - canMakePayments: true, - canSetupCards: true, - }), + payServiceStatus: () => + Promise.resolve({ isSupported: true, hasActiveCard: true }), isPaymentInProgress: () => inFlight, startPayment: () => { if (inFlight) { @@ -84,8 +82,11 @@ describe('shared PaymentHandler instance', () => { afterEach(() => settlePresentations()) - it('uses one native handler for the hook and HybridPaymentHandler', () => { - renderHook(() => usePaymentCheckout({})) + it('uses one native handler for the hook and HybridPaymentHandler', async () => { + const { result } = renderHook(() => usePaymentCheckout({})) + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) expect(mockInstances).toHaveLength(1) expect(mockInstances[0]).toBe(HybridPaymentHandler) diff --git a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts index a3ffa11..1967b50 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts @@ -34,9 +34,10 @@ function createDeferred() { describe('usePaymentCheckout integration', () => { beforeEach(() => { - mockPayServiceStatus.mockReturnValue({ - canMakePayments: true, - canSetupCards: true, + mockPayServiceStatus.mockReset() + mockPayServiceStatus.mockResolvedValue({ + isSupported: true, + hasActiveCard: true, }) mockStartPayment.mockReset() mockIsPaymentInProgress.mockReset().mockReturnValue(false) @@ -58,26 +59,177 @@ describe('usePaymentCheckout integration', () => { expect(result.current.isCheckingStatus).toBe(false) }) - expect(result.current.canMakePayments).toBe(true) - expect(result.current.canSetupCards).toBe(true) + expect(result.current.isSupported).toBe(true) + expect(result.current.hasActiveCard).toBe(true) }) - it('falls back to unavailable status when status check fails', async () => { - mockPayServiceStatus.mockImplementationOnce(() => { - throw new Error('Native status failure') + describe('payment service status', () => { + const SUPPORTED_WITHOUT_CARD = { isSupported: true, hasActiveCard: false } + + it('reports isCheckingStatus until the status check settles', async () => { + const status = createDeferred() + mockPayServiceStatus.mockReturnValueOnce(status.promise) + + const { result } = renderCheckout() + + expect(result.current.isCheckingStatus).toBe(true) + expect(result.current.isSupported).toBe(false) + expect(result.current.hasActiveCard).toBe(false) + + await act(async () => { + status.resolve(SUPPORTED_WITHOUT_CARD) + }) + + expect(result.current.isCheckingStatus).toBe(false) + expect(result.current.isSupported).toBe(true) + expect(result.current.hasActiveCard).toBe(false) + }) + + it.each([ + ['rejects', () => Promise.reject(new Error('Native status failure'))], + [ + 'throws synchronously', + () => { + throw new Error('Native status failure') + }, + ], + ])( + 'falls back to unavailable status when the check %s', + async (_, failingCheck) => { + mockPayServiceStatus.mockImplementationOnce(failingCheck) + const consoleSpy = jest + .spyOn(console, 'error') + .mockImplementation(() => {}) + + const { result } = renderCheckout() + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + expect(result.current.isSupported).toBe(false) + expect(result.current.hasActiveCard).toBe(false) + expect(consoleSpy).toHaveBeenCalled() + consoleSpy.mockRestore() + } + ) + + it('checks the networks, capabilities and environment from the config', async () => { + const { result } = renderHook(() => + usePaymentCheckout({ + supportedNetworks: ['visa', 'mastercard'], + merchantCapabilities: ['3DS', 'Debit'], + googlePayEnvironment: 'PRODUCTION', + }) + ) + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) + expect(mockPayServiceStatus).toHaveBeenCalledWith({ + supportedNetworks: ['visa', 'mastercard'], + merchantCapabilities: ['3DS', 'Debit'], + googlePayEnvironment: 'PRODUCTION', + }) }) - const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) - const { result } = renderCheckout() + it('leaves unset options to the native defaults', async () => { + const { result } = renderCheckout() - await waitFor(() => { + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + expect(mockPayServiceStatus).toHaveBeenCalledWith({}) + }) + + it('does not check again when an inline config re-renders unchanged', async () => { + const { result, rerender } = renderHook(() => + usePaymentCheckout({ + supportedNetworks: ['visa'], + googlePayEnvironment: 'PRODUCTION', + }) + ) + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + rerender(undefined) + act(() => { + result.current.addItem('Coffee', 4.99) + }) + + expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) expect(result.current.isCheckingStatus).toBe(false) }) - expect(result.current.canMakePayments).toBe(false) - expect(result.current.canSetupCards).toBe(false) - expect(consoleSpy).toHaveBeenCalled() - consoleSpy.mockRestore() + it('checks again when a checked config value changes', async () => { + const { result, rerender } = renderHook( + (props: { googlePayEnvironment: 'TEST' | 'PRODUCTION' }) => + usePaymentCheckout({ ...props }), + { initialProps: { googlePayEnvironment: 'TEST' } } + ) + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + rerender({ googlePayEnvironment: 'PRODUCTION' }) + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + expect(mockPayServiceStatus).toHaveBeenCalledTimes(2) + expect(mockPayServiceStatus).toHaveBeenLastCalledWith({ + googlePayEnvironment: 'PRODUCTION', + }) + }) + + it('refreshStatus checks again and reports the new status', async () => { + const { result } = renderCheckout() + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + const refreshed = createDeferred() + mockPayServiceStatus.mockReturnValueOnce(refreshed.promise) + + act(() => { + result.current.refreshStatus() + }) + + expect(result.current.isCheckingStatus).toBe(true) + expect(mockPayServiceStatus).toHaveBeenCalledTimes(2) + + await act(async () => { + refreshed.resolve(SUPPORTED_WITHOUT_CARD) + }) + + expect(result.current.isCheckingStatus).toBe(false) + expect(result.current.hasActiveCard).toBe(false) + }) + + it('ignores a check that settles after a newer one', async () => { + const first = createDeferred() + const second = createDeferred() + mockPayServiceStatus + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + const { result } = renderCheckout() + + act(() => { + result.current.refreshStatus() + }) + await act(async () => { + second.resolve(SUPPORTED_WITHOUT_CARD) + }) + await act(async () => { + first.resolve({ isSupported: true, hasActiveCard: true }) + }) + + expect(result.current.isCheckingStatus).toBe(false) + expect(result.current.hasActiveCard).toBe(false) + }) }) it('manages cart operations and total correctly', async () => { @@ -123,8 +275,11 @@ describe('usePaymentCheckout integration', () => { expect(result.current.total).toBe(0) }) - it('provides default fallback payment item when cart is empty', () => { + it('provides default fallback payment item when cart is empty', async () => { const { result } = renderCheckout() + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) expect(result.current.paymentRequest.paymentItems).toEqual([ { label: 'Total', amount: 0, type: 'final' }, @@ -388,6 +543,12 @@ describe('usePaymentCheckout integration', () => { }) describe('identity across re-renders', () => { + // These tests end synchronously: a status check settling after them would + // update the hook outside act. + beforeEach(() => { + mockPayServiceStatus.mockReturnValue(new Promise(() => {})) + }) + it('keeps paymentRequest and startPayment with an inline config', () => { const { result, rerender } = renderHook(() => usePaymentCheckout({ @@ -648,7 +809,9 @@ describe('usePaymentCheckout integration', () => { payment = result.current.startPayment() }) rerender({}) - await mockStartPayment.mock.calls[0]?.[1].onAuthorize(token, details) + await act(async () => { + await mockStartPayment.mock.calls[0]?.[1].onAuthorize(token, details) + }) expect(onAuthorize).toHaveBeenCalledWith(token, details) diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index 96f89d4..8296e4b 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -13,6 +13,7 @@ import type { PaymentResult, PaymentItem, PayServiceStatus, + PayServiceStatusOptions, GooglePayEnvironment, MerchantCapability, PaymentToken, @@ -144,9 +145,14 @@ export interface UsePaymentCheckoutConfig { export interface UsePaymentCheckoutReturn { // Payment availability - canMakePayments: boolean - canSetupCards: boolean + /** The device supports Apple Pay / Google Pay. See `PayServiceStatus`. */ + isSupported: boolean + /** A card on `supportedNetworks` is ready. See `PayServiceStatus`. */ + hasActiveCard: boolean + /** `true` until the availability check settles. */ isCheckingStatus: boolean + /** Checks availability again, for example after the user added a card. */ + refreshStatus: () => void // Cart management items: PaymentItem[] @@ -196,7 +202,7 @@ export interface UsePaymentCheckoutReturn { * ```typescript * function CheckoutScreen() { * const { - * canMakePayments, + * isSupported, * items, * total, * addItem, @@ -222,7 +228,7 @@ export interface UsePaymentCheckoutReturn { * { label: 'Tax', amount: 1.20, type: 'final' } * ]) * - * if (!canMakePayments) { + * if (!isSupported) { * return Payment not available * } * @@ -272,6 +278,7 @@ export function usePaymentCheckout( const [status, setStatus] = useState(null) const [isCheckingStatus, setIsCheckingStatus] = useState(true) + const [statusCheck, setStatusCheck] = useState(0) const [items, setItems] = useState([]) @@ -282,16 +289,42 @@ export function usePaymentCheckout( // Set synchronously, so two calls in the same frame still see each other. const isPaymentInFlight = useRef(false) + // Check against what the payment will use. Keyed on only these fields, by + // value like `requestConfigKey`, so another config change does not re-query. + const statusOptionsKey = JSON.stringify({ + supportedNetworks: config.supportedNetworks, + merchantCapabilities: config.merchantCapabilities, + googlePayEnvironment: config.googlePayEnvironment, + }) + useEffect(() => { - try { - const paymentStatus = getPaymentHandler().payServiceStatus() - setStatus(paymentStatus) - } catch (err) { - console.error('Failed to check payment status:', err) - setStatus({ canMakePayments: false, canSetupCards: false }) - } finally { - setIsCheckingStatus(false) + // Ignores a check that settles after a newer one started or after unmount. + let isCurrent = true + const options: PayServiceStatusOptions = JSON.parse(statusOptionsKey) + + const checkStatus = async () => { + setIsCheckingStatus(true) + let nextStatus: PayServiceStatus + try { + nextStatus = await getPaymentHandler().payServiceStatus(options) + } catch (err) { + console.error('Failed to check payment status:', err) + nextStatus = { isSupported: false, hasActiveCard: false } + } + if (isCurrent) { + setStatus(nextStatus) + setIsCheckingStatus(false) + } } + checkStatus() + + return () => { + isCurrent = false + } + }, [statusOptionsKey, statusCheck]) + + const refreshStatus = useCallback(() => { + setStatusCheck((check) => check + 1) }, []) const total = useMemo(() => calculateTotal(items), [items]) @@ -450,9 +483,10 @@ export function usePaymentCheckout( return { // Status - canMakePayments: status?.canMakePayments ?? false, - canSetupCards: status?.canSetupCards ?? false, + isSupported: status?.isSupported ?? false, + hasActiveCard: status?.hasActiveCard ?? false, isCheckingStatus, + refreshStatus, // Cart items, diff --git a/package/src/specs/PaymentHandler.nitro.ts b/package/src/specs/PaymentHandler.nitro.ts index b0230d3..49fceb2 100644 --- a/package/src/specs/PaymentHandler.nitro.ts +++ b/package/src/specs/PaymentHandler.nitro.ts @@ -1,6 +1,8 @@ import type { HybridObject } from 'react-native-nitro-modules' import type { + CanMakePaymentsOptions, PayServiceStatus, + PayServiceStatusOptions, PaymentRequest, PaymentResult, StartPaymentOptions, @@ -8,11 +10,16 @@ import type { export interface PaymentHandler extends HybridObject<{ ios: 'swift'; android: 'kotlin' }> { - payServiceStatus(): PayServiceStatus + payServiceStatus(options?: PayServiceStatusOptions): Promise startPayment( request: PaymentRequest, options?: StartPaymentOptions ): Promise - canMakePayments(usingNetworks: string[]): boolean + canMakePayments( + usingNetworks: string[], + options?: CanMakePaymentsOptions + ): Promise isPaymentInProgress(): boolean + // iOS only: opens Wallet to add a card. Does nothing on Android. + openPaymentSetup(): void } diff --git a/package/src/types/Payment.ts b/package/src/types/Payment.ts index f5cbfbc..15f6ead 100644 --- a/package/src/types/Payment.ts +++ b/package/src/types/Payment.ts @@ -231,9 +231,47 @@ export interface StartPaymentOptions { ) => Promise } +/** + * Wallet readiness on this device, from `HybridPaymentHandler.payServiceStatus()`. + */ export interface PayServiceStatus { - canMakePayments: boolean - canSetupCards: boolean + /** + * The device can pay with Apple Pay or Google Pay, with or without a card. + * iOS: `PKPaymentAuthorizationViewController.canMakePayments()`. + * Android: `isReadyToPay` without `existingPaymentMethodRequired`. + */ + isSupported: boolean + /** + * 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 +} + +/** + * 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 + // `['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. + merchantCapabilities?: string[] + // Android only. The Google Pay environment to ask. Defaults to `'TEST'`. + googlePayEnvironment?: GooglePayEnvironment +} + +/** + * What `canMakePayments(usingNetworks, options)` checks besides the networks. + */ +export interface CanMakePaymentsOptions { + // iOS only. Same as `PayServiceStatusOptions.merchantCapabilities`. + merchantCapabilities?: string[] + // Android only. The Google Pay environment to ask. Defaults to `'TEST'`. + googlePayEnvironment?: GooglePayEnvironment } // Backward compatibility alias From a4ec87434847cf361520f5ca08257e8373efc476 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Fri, 23 Oct 2026 18:33:28 +0200 Subject: [PATCH 02/10] docs: keep the wallet button on screen while availability refreshes --- docs/docs/api/hybrid-payment-handler.md | 2 +- docs/docs/api/use-payment-checkout.md | 2 +- docs/docs/guides/availability.md | 33 +++++++++++-------------- example/app/(tabs)/index.tsx | 3 ++- 4 files changed, 19 insertions(+), 21 deletions(-) diff --git a/docs/docs/api/hybrid-payment-handler.md b/docs/docs/api/hybrid-payment-handler.md index 9d8ced0..e8aeb11 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)). 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 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). --- diff --git a/docs/docs/api/use-payment-checkout.md b/docs/docs/api/use-payment-checkout.md index b51592e..ab9c4f3 100644 --- a/docs/docs/api/use-payment-checkout.md +++ b/docs/docs/api/use-payment-checkout.md @@ -80,7 +80,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. -- **refreshStatus()** — Checks availability again, for example when the app returns from Wallet after `openPaymentSetup()`. `isCheckingStatus` is `true` until it settles. +- **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). - **items** / **total** — Current cart and its exact decimal total, as a number (`NaN` if an amount is invalid). Amounts are `number | string` ([`PaymentAmount`](/docs/api/types#paymentamount)); use `formatAmount(item.amount, currencyCode)` to display them. diff --git a/docs/docs/guides/availability.md b/docs/docs/guides/availability.md index 7213c2e..124b739 100644 --- a/docs/docs/guides/availability.md +++ b/docs/docs/guides/availability.md @@ -12,7 +12,7 @@ Decide which wallet button to show before the user taps anything. The library re | `isSupported` | `PKPaymentAuthorizationViewController.canMakePayments()`: hardware and parental controls allow Apple Pay | `isReadyToPay`: Google Pay is available, and the user has a card or can add one | | `hasActiveCard` | `canMakePayments(usingNetworks:capabilities:)` with your `supportedNetworks` and `merchantCapabilities` | `isReadyToPay` with `existingPaymentMethodRequired: true` and your `supportedNetworks` | -Both flags are `false` when the check fails or, on Android, when Google Pay does not answer within 5 seconds. `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. 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`). ### Ask the environment you pay in @@ -38,21 +38,16 @@ import { } from '@gmisoftware/react-native-pay' export function WalletButton() { - const { - isSupported, - hasActiveCard, - isCheckingStatus, - refreshStatus, - startPayment, - } = usePaymentCheckout({ - merchantName: 'Your Store', - supportedNetworks: ['visa', 'mastercard'], - // The environment you pay in, so the status is real in production. - googlePayEnvironment: 'PRODUCTION', - googlePayMerchantId: 'your_google_pay_merchant_id', - googlePayGateway: 'stripe', - googlePayGatewayMerchantId: 'your_stripe_merchant_id', - }) + const { isSupported, hasActiveCard, refreshStatus, startPayment } = + usePaymentCheckout({ + merchantName: 'Your Store', + supportedNetworks: ['visa', 'mastercard'], + // The environment you pay in, so the status is real in production. + googlePayEnvironment: 'PRODUCTION', + googlePayMerchantId: 'your_google_pay_merchant_id', + googlePayGateway: 'stripe', + googlePayGatewayMerchantId: 'your_stripe_merchant_id', + }) useEffect(() => { const subscription = AppState.addEventListener('change', (state) => { @@ -61,7 +56,9 @@ export function WalletButton() { return () => subscription.remove() }, [refreshStatus]) - if (isCheckingStatus || !isSupported) return null + // `isSupported` is `false` until the first check settles, and a refresh + // keeps the last answer, so the button does not flicker on return. + if (!isSupported) return null if (Platform.OS === 'android') { return ( @@ -89,7 +86,7 @@ export function WalletButton() { } ``` -The hook checks on mount, and again when `supportedNetworks`, `merchantCapabilities` or `googlePayEnvironment` change. `isCheckingStatus` is `true` until the check settles. +The hook checks on mount, and again when `supportedNetworks`, `merchantCapabilities` or `googlePayEnvironment` change. `isCheckingStatus` is `true` while a check runs; the flags keep their last values until it settles. ## Without the hook diff --git a/example/app/(tabs)/index.tsx b/example/app/(tabs)/index.tsx index f351399..85f7a62 100644 --- a/example/app/(tabs)/index.tsx +++ b/example/app/(tabs)/index.tsx @@ -145,7 +145,8 @@ export default function TabOneScreen() { } }; - if (isCheckingStatus) { + // Only before the first answer: a refresh keeps the last one on screen. + if (isCheckingStatus && !isSupported) { return ( From f2c879f6d8064779800178fc4c3a2f984891d240 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Fri, 23 Oct 2026 21:17:16 +0200 Subject: [PATCH 03/10] fix(ios): reject availability checks with the plain error message Nitro rejects JS promises with the error's description, so an unknown merchant capability surfaced as 'PaymentRequestError(message: ...)'. --- package/ios/HybridPaymentHandler.swift | 5 ++++- package/ios/Tests/PaymentReadinessTests.swift | 8 ++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index 7cd921c..e86068c 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -40,10 +40,13 @@ private enum ErrorMessage { } } -private struct PaymentRequestError: LocalizedError { +// `CustomStringConvertible` because Nitro rejects JS promises with the +// error's description. +private struct PaymentRequestError: LocalizedError, CustomStringConvertible { let message: String var errorDescription: String? { message } + var description: String { message } } // PassKit fails the sheet on its own when the authorization completion is not diff --git a/package/ios/Tests/PaymentReadinessTests.swift b/package/ios/Tests/PaymentReadinessTests.swift index d81bbb1..376c9b6 100644 --- a/package/ios/Tests/PaymentReadinessTests.swift +++ b/package/ios/Tests/PaymentReadinessTests.swift @@ -18,10 +18,10 @@ final class PaymentReadinessTests: XCTestCase { networks: ["visa"], merchantCapabilities: ["3ds2"] )) { error in - XCTAssertEqual( - error.localizedDescription, - "Unknown merchant capability \"3ds2\". Use \"3DS\", \"EMV\", \"Credit\" or \"Debit\"" - ) + let message = "Unknown merchant capability \"3ds2\". Use \"3DS\", \"EMV\", \"Credit\" or \"Debit\"" + XCTAssertEqual(error.localizedDescription, message) + // What a rejected JS promise carries. + XCTAssertEqual(String(describing: error), message) } } From 3361ae17bdeec6e3ff7b9e3b98c821e464d6060d Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 14:32:21 +0100 Subject: [PATCH 04/10] chore(android): describe the readiness timeout, not the code it replaced --- .../android/src/main/java/com/margelo/nitro/pay/Constants.kt | 2 +- .../src/main/java/com/margelo/nitro/pay/HybridPaymentHandler.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 27f52bb..48e1c1c 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 @@ -63,7 +63,7 @@ object PaymentConstants { "elo" to "ELO" ) - // Availability checks give up after this, like the blocking calls they replaced + // How long an availability check waits for Google Pay const val READY_TO_PAY_TIMEOUT_SECONDS = 5L // Errors (keep in sync with iOS `ErrorMessage`) 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 04e103e..e216ea6 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 @@ -281,7 +281,7 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { ) } - /** A failed or timed-out check counts as not ready, as it did before. */ + /** A failed or timed-out check counts as not ready. */ private fun Task.resultOrFalse(): Boolean { if (isSuccessful) return result == true PayLog.w(PaymentConstants.TAG_PAYMENT_HANDLER, "isReadyToPay failed", exception) From cca1118c5cfebfe45d30eb03851ff886079535e9 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 14:42:42 +0100 Subject: [PATCH 05/10] docs: describe availability testing with isSupported and hasActiveCard --- docs/docs/guides/testing.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/guides/testing.md b/docs/docs/guides/testing.md index 2e2ca9e..a5f445c 100644 --- a/docs/docs/guides/testing.md +++ b/docs/docs/guides/testing.md @@ -10,10 +10,10 @@ Only `PRODUCTION` with real cards proves that a charge goes through. Each test e |---|---|---| | iOS Simulator | The sheet opens and shows your line items and the "Pay *merchantName*" total. Cancel, [`onAuthorize`](/docs/guides/server-processing#charge-before-the-sheet-closes) success and failure, and the double-tap guard. No card or account needed. | A token your gateway can charge. Apple doesn't document what the Simulator's token contains, and developers report that its `paymentData` is empty. Apple also says the Simulator doesn't support every Apple Pay feature, without listing which. | | iPhone with a sandbox tester | The full sheet with Apple's test cards, Face ID or passcode, and a token your payment processor can test decrypting. | A completed charge. Apple says sandbox transactions are declined before fulfillment, because the test key doesn't match your production key. | -| Android, `TEST` environment | The Google Pay sheet with Google's test cards, the result handling, and `onAuthorize`. No Google Pay merchant ID needed. | Availability: `canMakePayments` is always `true` in `TEST`. A live charge: `TEST` tokens never carry real card data, so only your gateway's test environment can process them. Your production request: the merchant ID and the `PRODUCTION` checks only run in `PRODUCTION`. | +| Android, `TEST` environment | The Google Pay sheet with Google's test cards, the result handling, and `onAuthorize`. No Google Pay merchant ID needed. | Availability: `hasActiveCard` is always `true` in `TEST`. A live charge: `TEST` tokens never carry real card data, so only your gateway's test environment can process them. Your production request: the merchant ID and the `PRODUCTION` checks only run in `PRODUCTION`. | | Android, `PRODUCTION` | Everything, with real cards. | Nothing. It needs [production access](#production-access) first. | -Availability is hard to test on both platforms. On iOS, `canMakePayments` comes from `PKPaymentAuthorizationViewController.canMakePayments()`, which Apple documents as `true` when the device supports payments, even with no card in Wallet. On Android, the library checks availability against the `TEST` environment until a payment has started, even in a `PRODUCTION` build ([#16](https://github.com/gmi-software/react-native-pay/issues/16)). +Availability is hard to test on both platforms. On iOS, `isSupported` comes from `PKPaymentAuthorizationViewController.canMakePayments()`, which Apple documents as `true` when the device supports payments, even with no card in Wallet; `hasActiveCard` also needs a card on your networks. On Android, both flags come from the environment you pass as `googlePayEnvironment`, so only a `PRODUCTION` build shows real answers. See [Check availability](/docs/guides/availability). ## Apple Pay @@ -83,7 +83,7 @@ Some gateways, such as Stripe, Braintree, and Adyen, show their own test cards i **What `TEST` can't verify:** -- **Availability.** With `existingPaymentMethodRequired`, `isReadyToPay` [always returns `true` in `TEST`](https://developers.google.com/pay/api/android/reference/request-objects#IsReadyToPayRequest), so `canMakePayments` is `true` even with no card. You can't test the "no card" path in `TEST`. +- **Availability.** With `existingPaymentMethodRequired`, `isReadyToPay` [always returns `true` in `TEST`](https://developers.google.com/pay/api/android/reference/request-objects#IsReadyToPayRequest), so `hasActiveCard` is `true` even with no card. An emulator with no Google account signed in answers `false` instead. You can't test the "no card" path of a signed-in user in `TEST`. - **A live charge.** `TEST` tokens never carry real card data. With your gateway's test values, its test environment can process them, but nothing is charged. - **Your production request.** The library sends `googlePayMerchantId` and requires `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId` only in `PRODUCTION`. A missing value fails with, for example, `googlePayMerchantId is required in PRODUCTION`, which you only see in a `PRODUCTION` build. From c8de585eb1c9ce0002575deb788f57bc34b86cf6 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 15:05:33 +0100 Subject: [PATCH 06/10] refactor: one failure path for readiness checks, availability tests in their own file - Android: isReadyToPay returns a task that never fails, so the two public methods lose their try/catch and resultOrFalse goes away. - Android: createIsReadyToPayRequest takes the networks; no caller used the default. - iOS: inline PaymentReadiness.status, a single-use wrapper the tests could not reach. - Move the availability tests to usePaymentCheckout.status.test.ts, which takes the integration test file back under its size on main. --- ...cookie-Jakubs-MacBook-Pro.local-51623-2898 | 0 ...cookie-Jakubs-MacBook-Pro.local-51623-2901 | 0 ...cookie-Jakubs-MacBook-Pro.local-51623-2902 | 0 .../nitro/pay/GooglePayRequestBuilder.kt | 2 +- .../margelo/nitro/pay/HybridPaymentHandler.kt | 107 ++++----- .../nitro/pay/ReadyToPayRequestTest.kt | 4 +- package/ios/HybridPaymentHandler.swift | 21 +- .../usePaymentCheckout.integration.test.ts | 180 --------------- .../usePaymentCheckout.status.test.ts | 213 ++++++++++++++++++ 9 files changed, 272 insertions(+), 255 deletions(-) create mode 100755 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2898 create mode 100755 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2901 create mode 100755 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2902 create mode 100644 package/src/hooks/__tests__/usePaymentCheckout.status.test.ts diff --git a/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2898 b/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2898 new file mode 100755 index 0000000..e69de29 diff --git a/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2901 b/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2901 new file mode 100755 index 0000000..e69de29 diff --git a/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2902 b/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2902 new file mode 100755 index 0000000..e69de29 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 22ee6d1..a6a11b2 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 @@ -17,7 +17,7 @@ object GooglePayRequestBuilder { * @param cardNetworks Google Pay `allowedCardNetworks` values, see [googleCardNetworks]. */ fun createIsReadyToPayRequest( - cardNetworks: List = PaymentConstants.DEFAULT_CARD_NETWORKS, + cardNetworks: List, existingPaymentMethodRequired: Boolean? = null ): JSONObject { return JSONObject().apply { 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 e216ea6..c3ff40f 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 @@ -64,54 +64,38 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { // MARK: - Public API override fun payServiceStatus(options: PayServiceStatusOptions?): Promise { - return try { - val client = createPaymentsClient(determineEnvironment(options?.googlePayEnvironment)) - val cardNetworks = options?.supportedNetworks - ?.let { GooglePayRequestBuilder.googleCardNetworks(it) } - ?: PaymentConstants.DEFAULT_CARD_NETWORKS - // Both requests run at once; neither blocks the calling (JS) thread. - val isSupported = isReadyToPay( - client, - PaymentConstants.DEFAULT_CARD_NETWORKS, - existingPaymentMethodRequired = false + val environment = determineEnvironment(options?.googlePayEnvironment) + val cardNetworks = options?.supportedNetworks + ?.let { GooglePayRequestBuilder.googleCardNetworks(it) } + ?: PaymentConstants.DEFAULT_CARD_NETWORKS + // Both requests run at once; neither blocks the calling (JS) thread. + val isSupported = isReadyToPay( + environment, + PaymentConstants.DEFAULT_CARD_NETWORKS, + existingPaymentMethodRequired = false + ) + val hasActiveCard = isReadyToPay(environment, cardNetworks, existingPaymentMethodRequired = true) + + val promise = Promise() + Tasks.whenAll(isSupported, hasActiveCard).addOnCompleteListener { + promise.resolve( + PayServiceStatus(isSupported = isSupported.result, hasActiveCard = hasActiveCard.result) ) - val hasActiveCard = isReadyToPay(client, cardNetworks, existingPaymentMethodRequired = true) - - val promise = Promise() - Tasks.whenAllComplete(isSupported, hasActiveCard).addOnCompleteListener { - promise.resolve( - PayServiceStatus( - isSupported = isSupported.resultOrFalse(), - hasActiveCard = hasActiveCard.resultOrFalse() - ) - ) - } - promise - } catch (e: Exception) { - PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Error checking status", e) - Promise.resolved(PayServiceStatus(isSupported = false, hasActiveCard = false)) } + return promise } override fun canMakePayments( usingNetworks: Array, options: CanMakePaymentsOptions? ): Promise { - return try { - val client = createPaymentsClient(determineEnvironment(options?.googlePayEnvironment)) - val hasActiveCard = isReadyToPay( - client, - GooglePayRequestBuilder.googleCardNetworks(usingNetworks), - existingPaymentMethodRequired = true - ) - - val promise = Promise() - hasActiveCard.addOnCompleteListener { promise.resolve(it.resultOrFalse()) } - promise - } catch (e: Exception) { - PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Error checking networks", e) - Promise.resolved(false) - } + val promise = Promise() + isReadyToPay( + determineEnvironment(options?.googlePayEnvironment), + GooglePayRequestBuilder.googleCardNetworks(usingNetworks), + existingPaymentMethodRequired = true + ).addOnCompleteListener { promise.resolve(it.result) } + return promise } override fun isPaymentInProgress(): Boolean { @@ -259,33 +243,38 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { /** * Asks Google Pay without waiting for the answer. The task completes on - * the main thread, with a `TimeoutException` if Google Pay does not answer. + * the main thread and never fails: an error, or no answer within the + * timeout, counts as not ready. */ private fun isReadyToPay( - client: PaymentsClient, + environment: Int, cardNetworks: List, existingPaymentMethodRequired: Boolean ): Task { // No network Google Pay knows: no card can be on it. if (cardNetworks.isEmpty()) return Tasks.forResult(false) - val requestJson = GooglePayRequestBuilder.createIsReadyToPayRequest( - cardNetworks = cardNetworks, - existingPaymentMethodRequired = existingPaymentMethodRequired - ) - val request = IsReadyToPayRequest.fromJson(requestJson.toString()) - return Tasks.withTimeout( - client.isReadyToPay(request), - PaymentConstants.READY_TO_PAY_TIMEOUT_SECONDS, - TimeUnit.SECONDS - ) - } - - /** A failed or timed-out check counts as not ready. */ - private fun Task.resultOrFalse(): Boolean { - if (isSuccessful) return result == true - PayLog.w(PaymentConstants.TAG_PAYMENT_HANDLER, "isReadyToPay failed", exception) - return false + val answer: Task = try { + val requestJson = GooglePayRequestBuilder.createIsReadyToPayRequest( + cardNetworks = cardNetworks, + existingPaymentMethodRequired = existingPaymentMethodRequired + ) + Tasks.withTimeout( + createPaymentsClient(environment).isReadyToPay( + IsReadyToPayRequest.fromJson(requestJson.toString()) + ), + PaymentConstants.READY_TO_PAY_TIMEOUT_SECONDS, + TimeUnit.SECONDS + ) + } catch (e: Exception) { + Tasks.forException(e) + } + return answer.continueWith { task -> + if (!task.isSuccessful) { + PayLog.w(PaymentConstants.TAG_PAYMENT_HANDLER, "isReadyToPay failed", task.exception) + } + task.isSuccessful && task.result == true + } } private fun handlePaymentSuccess(paymentData: PaymentData) { 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 6f9f259..2be2c9f 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 @@ -64,8 +64,9 @@ class ReadyToPayRequestTest { } @Test - fun isReadyToPayRequest_defaultsToTheNetworksOfPaymentRequests() { + fun isReadyToPayRequest_canAskWithoutRequiringACard() { val request = GooglePayRequestBuilder.createIsReadyToPayRequest( + cardNetworks = PaymentConstants.DEFAULT_CARD_NETWORKS, existingPaymentMethodRequired = false ) @@ -73,6 +74,7 @@ class ReadyToPayRequestTest { listOf("VISA", "MASTERCARD", "AMEX", "DISCOVER"), request.allowedCardNetworks() ) + assertTrue(request.has("existingPaymentMethodRequired")) assertFalse(request.getBoolean("existingPaymentMethodRequired")) } } diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index e86068c..498c8ba 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -274,16 +274,6 @@ enum PaymentReadiness { // Checked when the caller names no networks, like the hook's default. static let defaultNetworks = ["visa", "mastercard", "amex", "discover"] - static func status(supportedNetworks: [String]?, merchantCapabilities: [String]?) throws -> PayServiceStatus { - return PayServiceStatus( - isSupported: PKPaymentAuthorizationViewController.canMakePayments(), - hasActiveCard: try hasActiveCard( - networks: supportedNetworks ?? defaultNetworks, - merchantCapabilities: merchantCapabilities - ) - ) - } - static func hasActiveCard(networks: [String], merchantCapabilities: [String]?) throws -> Bool { let capabilities = try PaymentRequestBuilder.buildMerchantCapabilities(merchantCapabilities ?? []) let paymentNetworks = networks.compactMap { PassKitTypeMapper.convertToPKPaymentNetwork($0) } @@ -541,12 +531,15 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec { // PassKit asks the Wallet service, so both checks run off the JS thread. // Its `canMakePayments` class methods may be called from any thread. func payServiceStatus(options: PayServiceStatusOptions?) throws -> Promise { - let supportedNetworks = options?.supportedNetworks + let networks = options?.supportedNetworks ?? PaymentReadiness.defaultNetworks let merchantCapabilities = options?.merchantCapabilities return Promise.parallel { - try PaymentReadiness.status( - supportedNetworks: supportedNetworks, - merchantCapabilities: merchantCapabilities + PayServiceStatus( + isSupported: PKPaymentAuthorizationViewController.canMakePayments(), + hasActiveCard: try PaymentReadiness.hasActiveCard( + networks: networks, + merchantCapabilities: merchantCapabilities + ) ) } } diff --git a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts index 1967b50..35ff73b 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts @@ -52,186 +52,6 @@ describe('usePaymentCheckout integration', () => { { initialProps } ) - it('loads payment service status on mount', async () => { - const { result } = renderCheckout() - - await waitFor(() => { - expect(result.current.isCheckingStatus).toBe(false) - }) - - expect(result.current.isSupported).toBe(true) - expect(result.current.hasActiveCard).toBe(true) - }) - - describe('payment service status', () => { - const SUPPORTED_WITHOUT_CARD = { isSupported: true, hasActiveCard: false } - - it('reports isCheckingStatus until the status check settles', async () => { - const status = createDeferred() - mockPayServiceStatus.mockReturnValueOnce(status.promise) - - const { result } = renderCheckout() - - expect(result.current.isCheckingStatus).toBe(true) - expect(result.current.isSupported).toBe(false) - expect(result.current.hasActiveCard).toBe(false) - - await act(async () => { - status.resolve(SUPPORTED_WITHOUT_CARD) - }) - - expect(result.current.isCheckingStatus).toBe(false) - expect(result.current.isSupported).toBe(true) - expect(result.current.hasActiveCard).toBe(false) - }) - - it.each([ - ['rejects', () => Promise.reject(new Error('Native status failure'))], - [ - 'throws synchronously', - () => { - throw new Error('Native status failure') - }, - ], - ])( - 'falls back to unavailable status when the check %s', - async (_, failingCheck) => { - mockPayServiceStatus.mockImplementationOnce(failingCheck) - const consoleSpy = jest - .spyOn(console, 'error') - .mockImplementation(() => {}) - - const { result } = renderCheckout() - - await waitFor(() => { - expect(result.current.isCheckingStatus).toBe(false) - }) - - expect(result.current.isSupported).toBe(false) - expect(result.current.hasActiveCard).toBe(false) - expect(consoleSpy).toHaveBeenCalled() - consoleSpy.mockRestore() - } - ) - - it('checks the networks, capabilities and environment from the config', async () => { - const { result } = renderHook(() => - usePaymentCheckout({ - supportedNetworks: ['visa', 'mastercard'], - merchantCapabilities: ['3DS', 'Debit'], - googlePayEnvironment: 'PRODUCTION', - }) - ) - - await waitFor(() => { - expect(result.current.isCheckingStatus).toBe(false) - }) - - expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) - expect(mockPayServiceStatus).toHaveBeenCalledWith({ - supportedNetworks: ['visa', 'mastercard'], - merchantCapabilities: ['3DS', 'Debit'], - googlePayEnvironment: 'PRODUCTION', - }) - }) - - it('leaves unset options to the native defaults', async () => { - const { result } = renderCheckout() - - await waitFor(() => { - expect(result.current.isCheckingStatus).toBe(false) - }) - - expect(mockPayServiceStatus).toHaveBeenCalledWith({}) - }) - - it('does not check again when an inline config re-renders unchanged', async () => { - const { result, rerender } = renderHook(() => - usePaymentCheckout({ - supportedNetworks: ['visa'], - googlePayEnvironment: 'PRODUCTION', - }) - ) - await waitFor(() => { - expect(result.current.isCheckingStatus).toBe(false) - }) - - rerender(undefined) - act(() => { - result.current.addItem('Coffee', 4.99) - }) - - expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) - expect(result.current.isCheckingStatus).toBe(false) - }) - - it('checks again when a checked config value changes', async () => { - const { result, rerender } = renderHook( - (props: { googlePayEnvironment: 'TEST' | 'PRODUCTION' }) => - usePaymentCheckout({ ...props }), - { initialProps: { googlePayEnvironment: 'TEST' } } - ) - await waitFor(() => { - expect(result.current.isCheckingStatus).toBe(false) - }) - - rerender({ googlePayEnvironment: 'PRODUCTION' }) - - await waitFor(() => { - expect(result.current.isCheckingStatus).toBe(false) - }) - expect(mockPayServiceStatus).toHaveBeenCalledTimes(2) - expect(mockPayServiceStatus).toHaveBeenLastCalledWith({ - googlePayEnvironment: 'PRODUCTION', - }) - }) - - it('refreshStatus checks again and reports the new status', async () => { - const { result } = renderCheckout() - await waitFor(() => { - expect(result.current.isCheckingStatus).toBe(false) - }) - const refreshed = createDeferred() - mockPayServiceStatus.mockReturnValueOnce(refreshed.promise) - - act(() => { - result.current.refreshStatus() - }) - - expect(result.current.isCheckingStatus).toBe(true) - expect(mockPayServiceStatus).toHaveBeenCalledTimes(2) - - await act(async () => { - refreshed.resolve(SUPPORTED_WITHOUT_CARD) - }) - - expect(result.current.isCheckingStatus).toBe(false) - expect(result.current.hasActiveCard).toBe(false) - }) - - it('ignores a check that settles after a newer one', async () => { - const first = createDeferred() - const second = createDeferred() - mockPayServiceStatus - .mockReturnValueOnce(first.promise) - .mockReturnValueOnce(second.promise) - const { result } = renderCheckout() - - act(() => { - result.current.refreshStatus() - }) - await act(async () => { - second.resolve(SUPPORTED_WITHOUT_CARD) - }) - await act(async () => { - first.resolve({ isSupported: true, hasActiveCard: true }) - }) - - expect(result.current.isCheckingStatus).toBe(false) - expect(result.current.hasActiveCard).toBe(false) - }) - }) - it('manages cart operations and total correctly', async () => { const { result } = renderCheckout() diff --git a/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts new file mode 100644 index 0000000..d17786b --- /dev/null +++ b/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts @@ -0,0 +1,213 @@ +import { act, renderHook, waitFor } from '@testing-library/react-native' + +const mockPayServiceStatus = jest.fn() + +jest.mock('react-native-nitro-modules', () => ({ + NitroModules: { + createHybridObject: jest.fn(() => ({ + payServiceStatus: (...args: any[]) => mockPayServiceStatus(...args), + })), + }, +})) + +import { usePaymentCheckout } from '../usePaymentCheckout' + +function createDeferred() { + let resolve!: (value: T) => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + +describe('usePaymentCheckout availability', () => { + beforeEach(() => { + mockPayServiceStatus.mockReset() + mockPayServiceStatus.mockResolvedValue({ + isSupported: true, + hasActiveCard: true, + }) + }) + + const renderCheckout = () => renderHook(() => usePaymentCheckout({})) + + it('loads payment service status on mount', async () => { + const { result } = renderCheckout() + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + expect(result.current.isSupported).toBe(true) + expect(result.current.hasActiveCard).toBe(true) + }) + + describe('payment service status', () => { + const SUPPORTED_WITHOUT_CARD = { isSupported: true, hasActiveCard: false } + + it('reports isCheckingStatus until the status check settles', async () => { + const status = createDeferred() + mockPayServiceStatus.mockReturnValueOnce(status.promise) + + const { result } = renderCheckout() + + expect(result.current.isCheckingStatus).toBe(true) + expect(result.current.isSupported).toBe(false) + expect(result.current.hasActiveCard).toBe(false) + + await act(async () => { + status.resolve(SUPPORTED_WITHOUT_CARD) + }) + + expect(result.current.isCheckingStatus).toBe(false) + expect(result.current.isSupported).toBe(true) + expect(result.current.hasActiveCard).toBe(false) + }) + + it.each([ + ['rejects', () => Promise.reject(new Error('Native status failure'))], + [ + 'throws synchronously', + () => { + throw new Error('Native status failure') + }, + ], + ])( + 'falls back to unavailable status when the check %s', + async (_, failingCheck) => { + mockPayServiceStatus.mockImplementationOnce(failingCheck) + const consoleSpy = jest + .spyOn(console, 'error') + .mockImplementation(() => {}) + + const { result } = renderCheckout() + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + expect(result.current.isSupported).toBe(false) + expect(result.current.hasActiveCard).toBe(false) + expect(consoleSpy).toHaveBeenCalled() + consoleSpy.mockRestore() + } + ) + + it('checks the networks, capabilities and environment from the config', async () => { + const { result } = renderHook(() => + usePaymentCheckout({ + supportedNetworks: ['visa', 'mastercard'], + merchantCapabilities: ['3DS', 'Debit'], + googlePayEnvironment: 'PRODUCTION', + }) + ) + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) + expect(mockPayServiceStatus).toHaveBeenCalledWith({ + supportedNetworks: ['visa', 'mastercard'], + merchantCapabilities: ['3DS', 'Debit'], + googlePayEnvironment: 'PRODUCTION', + }) + }) + + it('leaves unset options to the native defaults', async () => { + const { result } = renderCheckout() + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + expect(mockPayServiceStatus).toHaveBeenCalledWith({}) + }) + + it('does not check again when an inline config re-renders unchanged', async () => { + const { result, rerender } = renderHook(() => + usePaymentCheckout({ + supportedNetworks: ['visa'], + googlePayEnvironment: 'PRODUCTION', + }) + ) + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + rerender(undefined) + act(() => { + result.current.addItem('Coffee', 4.99) + }) + + expect(mockPayServiceStatus).toHaveBeenCalledTimes(1) + expect(result.current.isCheckingStatus).toBe(false) + }) + + it('checks again when a checked config value changes', async () => { + const { result, rerender } = renderHook( + (props: { googlePayEnvironment: 'TEST' | 'PRODUCTION' }) => + usePaymentCheckout({ ...props }), + { initialProps: { googlePayEnvironment: 'TEST' } } + ) + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + + rerender({ googlePayEnvironment: 'PRODUCTION' }) + + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + expect(mockPayServiceStatus).toHaveBeenCalledTimes(2) + expect(mockPayServiceStatus).toHaveBeenLastCalledWith({ + googlePayEnvironment: 'PRODUCTION', + }) + }) + + it('refreshStatus checks again and reports the new status', async () => { + const { result } = renderCheckout() + await waitFor(() => { + expect(result.current.isCheckingStatus).toBe(false) + }) + const refreshed = createDeferred() + mockPayServiceStatus.mockReturnValueOnce(refreshed.promise) + + act(() => { + result.current.refreshStatus() + }) + + expect(result.current.isCheckingStatus).toBe(true) + expect(mockPayServiceStatus).toHaveBeenCalledTimes(2) + + await act(async () => { + refreshed.resolve(SUPPORTED_WITHOUT_CARD) + }) + + expect(result.current.isCheckingStatus).toBe(false) + expect(result.current.hasActiveCard).toBe(false) + }) + + it('ignores a check that settles after a newer one', async () => { + const first = createDeferred() + const second = createDeferred() + mockPayServiceStatus + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + const { result } = renderCheckout() + + act(() => { + result.current.refreshStatus() + }) + await act(async () => { + second.resolve(SUPPORTED_WITHOUT_CARD) + }) + await act(async () => { + first.resolve({ isSupported: true, hasActiveCard: true }) + }) + + expect(result.current.isCheckingStatus).toBe(false) + expect(result.current.hasActiveCard).toBe(false) + }) + }) +}) From 427b9cf689a1eb67ec66d4ef46336af42bbf7f94 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 15:14:49 +0100 Subject: [PATCH 07/10] refactor: check availability with the payment request's networks and capabilities The hook built the check from the raw config and relied on the native defaults matching its own, which an iOS test asserted. Reading the values from paymentRequest makes "check what the payment will use" hold by construction, so that test goes. --- ...cookie-Jakubs-MacBook-Pro.local-51623-2898 | 0 ...cookie-Jakubs-MacBook-Pro.local-51623-2901 | 0 ...cookie-Jakubs-MacBook-Pro.local-51623-2902 | 0 package/ios/Tests/PaymentReadinessTests.swift | 4 - .../usePaymentCheckout.status.test.ts | 14 ++-- package/src/hooks/usePaymentCheckout.ts | 76 +++++++++---------- 6 files changed, 47 insertions(+), 47 deletions(-) delete mode 100755 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2898 delete mode 100755 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2901 delete mode 100755 package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2902 diff --git a/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2898 b/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2898 deleted file mode 100755 index e69de29..0000000 diff --git a/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2901 b/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2901 deleted file mode 100755 index e69de29..0000000 diff --git a/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2902 b/package/.watchman-cookie-Jakubs-MacBook-Pro.local-51623-2902 deleted file mode 100755 index e69de29..0000000 diff --git a/package/ios/Tests/PaymentReadinessTests.swift b/package/ios/Tests/PaymentReadinessTests.swift index 376c9b6..705d3c0 100644 --- a/package/ios/Tests/PaymentReadinessTests.swift +++ b/package/ios/Tests/PaymentReadinessTests.swift @@ -24,8 +24,4 @@ final class PaymentReadinessTests: XCTestCase { XCTAssertEqual(String(describing: error), message) } } - - func testDefaultNetworksMatchTheHookDefault() { - XCTAssertEqual(PaymentReadiness.defaultNetworks, ["visa", "mastercard", "amex", "discover"]) - } } diff --git a/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts index d17786b..954872c 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.status.test.ts @@ -114,14 +114,18 @@ describe('usePaymentCheckout availability', () => { }) }) - it('leaves unset options to the native defaults', async () => { + it('checks the defaults the payment request uses', async () => { const { result } = renderCheckout() await waitFor(() => { expect(result.current.isCheckingStatus).toBe(false) }) - expect(mockPayServiceStatus).toHaveBeenCalledWith({}) + expect(mockPayServiceStatus).toHaveBeenCalledWith({ + supportedNetworks: result.current.paymentRequest.supportedNetworks, + merchantCapabilities: + result.current.paymentRequest.merchantCapabilities, + }) }) it('does not check again when an inline config re-renders unchanged', async () => { @@ -160,9 +164,9 @@ describe('usePaymentCheckout availability', () => { expect(result.current.isCheckingStatus).toBe(false) }) expect(mockPayServiceStatus).toHaveBeenCalledTimes(2) - expect(mockPayServiceStatus).toHaveBeenLastCalledWith({ - googlePayEnvironment: 'PRODUCTION', - }) + expect(mockPayServiceStatus).toHaveBeenLastCalledWith( + expect.objectContaining({ googlePayEnvironment: 'PRODUCTION' }) + ) }) it('refreshStatus checks again and reports the new status', async () => { diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index 8296e4b..781cae9 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -289,44 +289,6 @@ export function usePaymentCheckout( // Set synchronously, so two calls in the same frame still see each other. const isPaymentInFlight = useRef(false) - // Check against what the payment will use. Keyed on only these fields, by - // value like `requestConfigKey`, so another config change does not re-query. - const statusOptionsKey = JSON.stringify({ - supportedNetworks: config.supportedNetworks, - merchantCapabilities: config.merchantCapabilities, - googlePayEnvironment: config.googlePayEnvironment, - }) - - useEffect(() => { - // Ignores a check that settles after a newer one started or after unmount. - let isCurrent = true - const options: PayServiceStatusOptions = JSON.parse(statusOptionsKey) - - const checkStatus = async () => { - setIsCheckingStatus(true) - let nextStatus: PayServiceStatus - try { - nextStatus = await getPaymentHandler().payServiceStatus(options) - } catch (err) { - console.error('Failed to check payment status:', err) - nextStatus = { isSupported: false, hasActiveCard: false } - } - if (isCurrent) { - setStatus(nextStatus) - setIsCheckingStatus(false) - } - } - checkStatus() - - return () => { - isCurrent = false - } - }, [statusOptionsKey, statusCheck]) - - const refreshStatus = useCallback(() => { - setStatusCheck((check) => check + 1) - }, []) - const total = useMemo(() => calculateTotal(items), [items]) const paymentRequest = useMemo(() => { @@ -367,6 +329,44 @@ export function usePaymentCheckout( }) }, [stableRequestConfig, items]) + // Check exactly what the payment will use. By value: the request changes + // with the cart and the rest of the config, these fields rarely do. + const statusOptionsKey = JSON.stringify({ + supportedNetworks: paymentRequest.supportedNetworks, + merchantCapabilities: paymentRequest.merchantCapabilities, + googlePayEnvironment: paymentRequest.googlePayEnvironment, + }) + + useEffect(() => { + // Ignores a check that settles after a newer one started or after unmount. + let isCurrent = true + const options: PayServiceStatusOptions = JSON.parse(statusOptionsKey) + + const checkStatus = async () => { + setIsCheckingStatus(true) + let nextStatus: PayServiceStatus + try { + nextStatus = await getPaymentHandler().payServiceStatus(options) + } catch (err) { + console.error('Failed to check payment status:', err) + nextStatus = { isSupported: false, hasActiveCard: false } + } + if (isCurrent) { + setStatus(nextStatus) + setIsCheckingStatus(false) + } + } + checkStatus() + + return () => { + isCurrent = false + } + }, [statusOptionsKey, statusCheck]) + + const refreshStatus = useCallback(() => { + setStatusCheck((check) => check + 1) + }, []) + // Cart operations const addItem = useCallback( ( From ca2858b9e35bed38362a9bbcb7de5694e01f975f Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 16:38:17 +0100 Subject: [PATCH 08/10] feat!: remove canMakePayments, which duplicated hasActiveCard `canMakePayments(networks, options)` answered the same question as `payServiceStatus({ supportedNetworks: networks, ...options }).hasActiveCard`, at the cost of a second spec method, its own options struct and a native implementation on each platform. Use payServiceStatus instead. BREAKING CHANGE: HybridPaymentHandler.canMakePayments and CanMakePaymentsOptions are removed. --- ...001-2026-02-10-core-module-architecture.md | 1 - CHANGELOG.md | 25 ++--- README.md | 12 --- docs/docs/api/hybrid-payment-handler.md | 16 ---- docs/docs/api/types.md | 11 --- docs/docs/guides/availability.md | 12 +-- .../margelo/nitro/pay/HybridPaymentHandler.kt | 13 --- package/ios/HybridPaymentHandler.swift | 10 -- .../android/c++/JCanMakePaymentsOptions.hpp | 83 ----------------- .../android/c++/JHybridPaymentHandlerSpec.cpp | 29 ------ .../android/c++/JHybridPaymentHandlerSpec.hpp | 1 - .../nitro/pay/CanMakePaymentsOptions.kt | 56 ------------ .../nitro/pay/HybridPaymentHandlerSpec.kt | 4 - .../ios/NitroPay-Swift-Cxx-Bridge.cpp | 8 -- .../ios/NitroPay-Swift-Cxx-Bridge.hpp | 61 ------------- .../ios/NitroPay-Swift-Cxx-Umbrella.hpp | 3 - .../ios/c++/HybridPaymentHandlerSpecSwift.hpp | 11 --- .../ios/swift/CanMakePaymentsOptions.swift | 59 ------------ .../generated/ios/swift/Func_void_bool.swift | 46 ---------- .../ios/swift/HybridPaymentHandlerSpec.swift | 1 - .../swift/HybridPaymentHandlerSpec_cxx.swift | 19 ---- .../shared/c++/CanMakePaymentsOptions.hpp | 91 ------------------- .../shared/c++/HybridPaymentHandlerSpec.cpp | 1 - .../shared/c++/HybridPaymentHandlerSpec.hpp | 6 -- package/src/specs/PaymentHandler.nitro.ts | 5 - package/src/types/Payment.ts | 10 -- 26 files changed, 14 insertions(+), 580 deletions(-) delete mode 100644 package/nitrogen/generated/android/c++/JCanMakePaymentsOptions.hpp delete mode 100644 package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/CanMakePaymentsOptions.kt delete mode 100644 package/nitrogen/generated/ios/swift/CanMakePaymentsOptions.swift delete mode 100644 package/nitrogen/generated/ios/swift/Func_void_bool.swift delete mode 100644 package/nitrogen/generated/shared/c++/CanMakePaymentsOptions.hpp diff --git a/.ai/specs/SPEC-001-2026-02-10-core-module-architecture.md b/.ai/specs/SPEC-001-2026-02-10-core-module-architecture.md index 84dfb63..4a8206d 100644 --- a/.ai/specs/SPEC-001-2026-02-10-core-module-architecture.md +++ b/.ai/specs/SPEC-001-2026-02-10-core-module-architecture.md @@ -71,7 +71,6 @@ Primary low-level contract: - `payServiceStatus(options?: PayServiceStatusOptions): Promise` - `startPayment(request: PaymentRequest): Promise` -- `canMakePayments(usingNetworks: string[], options?: CanMakePaymentsOptions): Promise` - `isPaymentInProgress(): boolean` — whether a payment started with `startPayment` has not settled yet. Backed by the native single-payment slot (`PendingPayment` on iOS and Android), which `startPayment` claims synchronously on the calling thread and frees when the payment settles. - `openPaymentSetup(): void` (iOS only) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f3a95d..df6cc6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,15 +51,18 @@ All notable changes to this project are documented in this file. of when it starts presenting the sheet, so `isPaymentInProgress()` sees a payment started in the same JS tick. - **Availability checks are asynchronous and report `isSupported` and `hasActiveCard`.** - `HybridPaymentHandler.payServiceStatus()` and `canMakePayments(networks)` now return Promises, - and `PayServiceStatus` is `{ isSupported, hasActiveCard }` instead of - `{ canMakePayments, canSetupCards }`, which meant different things on each platform. - `usePaymentCheckout` returns `isSupported`, `hasActiveCard` and a new `refreshStatus()` instead of - `canMakePayments` and `canSetupCards`. Both checks take the networks, merchant capabilities and - Google Pay environment to check against; the hook passes its config. To migrate, `await` the - handler methods and read `isSupported` where you read `canMakePayments` (the same check on iOS, - and the one Google recommends for showing the button on Android). See + `HybridPaymentHandler.payServiceStatus()` now returns a Promise, and `PayServiceStatus` is + `{ isSupported, hasActiveCard }` instead of `{ canMakePayments, canSetupCards }`, which meant + different things on each platform. `usePaymentCheckout` returns `isSupported`, `hasActiveCard` + and a new `refreshStatus()` instead of `canMakePayments` and `canSetupCards`. The check takes the + networks, merchant capabilities and Google Pay environment to check against; the hook passes + those of its payment request. To migrate, `await` the call and read `isSupported` where you read + `canMakePayments` (the same check on iOS, and the one Google recommends for showing the button on + Android). See [Check availability](https://gmi-software.github.io/react-native-pay/docs/guides/availability). +- **`HybridPaymentHandler.canMakePayments(networks)` is removed.** It answered the same question as + `hasActiveCard`: call `payServiceStatus({ supportedNetworks: networks })` and read + `hasActiveCard`. On Android it never asked the device, so `['visa']` was always `true`. - **iOS: `HybridPaymentHandler.openPaymentSetup()`** opens Wallet so the user can add a card, for a "Set up Apple Pay" button (`ApplePayButton` with `buttonType="setUp"`). It does nothing on Android. @@ -80,10 +83,8 @@ 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. -- **Android: `canMakePayments(networks)` asks Google Pay.** It only checked that a name was in a - fixed list, so `['visa']` was always `true`. It now asks whether the user has a card on those - networks, like iOS. Both platforms answer `false` when no network is one they know; iOS answered - for an empty network list instead. +- **`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 a1d34ad..eb4af96 100644 --- a/README.md +++ b/README.md @@ -539,18 +539,6 @@ interface PaymentToken { } ``` -##### `canMakePayments(usingNetworks: string[], options?: CanMakePaymentsOptions): Promise` - -Check whether the user has a card ready on one of the given networks. Both platforms ask the device. - -```typescript -import { HybridPaymentHandler } from "@gmisoftware/react-native-pay"; - -const canPay = await HybridPaymentHandler.canMakePayments(["visa", "mastercard"], { - googlePayEnvironment: "PRODUCTION", -}); -``` - ##### `isPaymentInProgress(): boolean` Check whether a payment started with `startPayment` (directly or by `usePaymentCheckout`) has not settled yet. While it returns `true`, `startPayment` resolves with `{ success: false, error: "A payment is already in progress" }`. diff --git a/docs/docs/api/hybrid-payment-handler.md b/docs/docs/api/hybrid-payment-handler.md index e8aeb11..48558c9 100644 --- a/docs/docs/api/hybrid-payment-handler.md +++ b/docs/docs/api/hybrid-payment-handler.md @@ -106,22 +106,6 @@ const isBusy = HybridPaymentHandler.isPaymentInProgress() --- -### canMakePayments(usingNetworks, options?) - -Resolves with whether the user has a card ready on one of the given networks, like `hasActiveCard`. Both platforms ask the device. It resolves `false` when no network is one the platform knows. - -```ts -import { HybridPaymentHandler } from '@gmisoftware/react-native-pay' - -const canPay = await HybridPaymentHandler.canMakePayments(['visa', 'mastercard'], { - googlePayEnvironment: 'PRODUCTION', -}) -``` - -`options` takes `merchantCapabilities` (iOS) and `googlePayEnvironment` (Android, `'TEST'` by default). See [CanMakePaymentsOptions](/docs/api/types#canmakepaymentsoptions). - ---- - ### openPaymentSetup() iOS only. Opens Wallet (Settings on iPad) so the user can add a card. Call it from a **Set up Apple Pay** button (`ApplePayButton` with `buttonType="setUp"`) when `isSupported` is `true` and `hasActiveCard` is `false`. It does nothing on devices without Apple Pay, and nothing on Android, where the Google Pay sheet lets the user add a card. diff --git a/docs/docs/api/types.md b/docs/docs/api/types.md index 76b99ae..fb18bc6 100644 --- a/docs/docs/api/types.md +++ b/docs/docs/api/types.md @@ -207,17 +207,6 @@ interface PayServiceStatusOptions { } ``` -## CanMakePaymentsOptions - -What `canMakePayments(usingNetworks, options)` checks besides the networks. - -```ts -interface CanMakePaymentsOptions { - merchantCapabilities?: string[] // iOS only. Default: ['3DS'] - googlePayEnvironment?: 'TEST' | 'PRODUCTION' // Android only. Default: 'TEST' -} -``` - --- ## GooglePayEnvironment diff --git a/docs/docs/guides/availability.md b/docs/docs/guides/availability.md index 124b739..4b86124 100644 --- a/docs/docs/guides/availability.md +++ b/docs/docs/guides/availability.md @@ -103,18 +103,8 @@ const { isSupported, hasActiveCard } = }) ``` -To check other networks only, use `canMakePayments`. It answers like `hasActiveCard`: - -```ts -import { HybridPaymentHandler } from '@gmisoftware/react-native-pay' - -const canPayWithAmex = await HybridPaymentHandler.canMakePayments(['amex'], { - googlePayEnvironment: 'PRODUCTION', -}) -``` - ## Next - [usePaymentCheckout](/docs/api/use-payment-checkout): the hook's availability fields -- [HybridPaymentHandler](/docs/api/hybrid-payment-handler): `payServiceStatus`, `canMakePayments` and `openPaymentSetup` +- [HybridPaymentHandler](/docs/api/hybrid-payment-handler): `payServiceStatus` and `openPaymentSetup` - [Components](/docs/api/components): `ApplePayButton` and `GooglePayButton` 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 c3ff40f..751266f 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 @@ -85,19 +85,6 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { return promise } - override fun canMakePayments( - usingNetworks: Array, - options: CanMakePaymentsOptions? - ): Promise { - val promise = Promise() - isReadyToPay( - determineEnvironment(options?.googlePayEnvironment), - GooglePayRequestBuilder.googleCardNetworks(usingNetworks), - existingPaymentMethodRequired = true - ).addOnCompleteListener { promise.resolve(it.result) } - return promise - } - override fun isPaymentInProgress(): Boolean { return pendingPayment.isInProgress } diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index 498c8ba..e21c2d2 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -544,16 +544,6 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec { } } - func canMakePayments(usingNetworks: [String], options: CanMakePaymentsOptions?) throws -> Promise { - let merchantCapabilities = options?.merchantCapabilities - return Promise.parallel { - try PaymentReadiness.hasActiveCard( - networks: usingNetworks, - merchantCapabilities: merchantCapabilities - ) - } - } - func openPaymentSetup() throws { // Hands over to Wallet (Settings on iPad); does nothing without Apple Pay support. DispatchQueue.main.async { diff --git a/package/nitrogen/generated/android/c++/JCanMakePaymentsOptions.hpp b/package/nitrogen/generated/android/c++/JCanMakePaymentsOptions.hpp deleted file mode 100644 index acd3a5d..0000000 --- a/package/nitrogen/generated/android/c++/JCanMakePaymentsOptions.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/// -/// JCanMakePaymentsOptions.hpp -/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. -/// https://github.com/mrousavy/nitro -/// Copyright © Marc Rousavy @ Margelo -/// - -#pragma once - -#include -#include "CanMakePaymentsOptions.hpp" - -#include "GooglePayEnvironment.hpp" -#include "JGooglePayEnvironment.hpp" -#include -#include -#include - -namespace margelo::nitro::pay { - - using namespace facebook; - - /** - * The C++ JNI bridge between the C++ struct "CanMakePaymentsOptions" and the Kotlin data class "CanMakePaymentsOptions". - */ - struct JCanMakePaymentsOptions final: public jni::JavaClass { - public: - static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/pay/CanMakePaymentsOptions;"; - - public: - /** - * Convert this Java/Kotlin-based struct to the C++ struct CanMakePaymentsOptions by copying all values to C++. - */ - [[maybe_unused]] - [[nodiscard]] - CanMakePaymentsOptions toCpp() const { - static const auto clazz = javaClassStatic(); - static const auto fieldMerchantCapabilities = clazz->getField>("merchantCapabilities"); - jni::local_ref> merchantCapabilities = this->getFieldValue(fieldMerchantCapabilities); - static const auto fieldGooglePayEnvironment = clazz->getField("googlePayEnvironment"); - jni::local_ref googlePayEnvironment = this->getFieldValue(fieldGooglePayEnvironment); - return CanMakePaymentsOptions( - merchantCapabilities != nullptr ? std::make_optional([&](auto&& __input) { - size_t __size = __input->size(); - std::vector __vector; - __vector.reserve(__size); - for (size_t __i = 0; __i < __size; __i++) { - auto __element = __input->getElement(__i); - __vector.push_back(__element->toStdString()); - } - return __vector; - }(merchantCapabilities)) : std::nullopt, - googlePayEnvironment != nullptr ? std::make_optional(googlePayEnvironment->toCpp()) : std::nullopt - ); - } - - public: - /** - * Create a Java/Kotlin-based struct by copying all values from the given C++ struct to Java. - */ - [[maybe_unused]] - static jni::local_ref fromCpp(const CanMakePaymentsOptions& value) { - using JSignature = JCanMakePaymentsOptions(jni::alias_ref>, jni::alias_ref); - static const auto clazz = javaClassStatic(); - static const auto create = clazz->getStaticMethod("fromCpp"); - return create( - clazz, - value.merchantCapabilities.has_value() ? [&](auto&& __input) { - size_t __size = __input.size(); - jni::local_ref> __array = jni::JArrayClass::newArray(__size); - for (size_t __i = 0; __i < __size; __i++) { - const auto& __element = __input[__i]; - auto __elementJni = jni::make_jstring(__element); - __array->setElement(__i, *__elementJni); - } - return __array; - }(value.merchantCapabilities.value()) : nullptr, - value.googlePayEnvironment.has_value() ? JGooglePayEnvironment::fromCpp(value.googlePayEnvironment.value()) : nullptr - ); - } - }; - -} // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp index fac872b..ae0979c 100644 --- a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp +++ b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp @@ -59,8 +59,6 @@ namespace margelo::nitro::pay { struct PaymentAuthorizationResult; } namespace margelo::nitro::pay { struct PaymentDetails; } // Forward declaration of `PaymentAuthorizationStatus` to properly resolve imports. namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } -// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. -namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PayServiceStatus.hpp" #include @@ -124,8 +122,6 @@ namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PaymentAuthorizationStatus.hpp" #include "JPaymentAuthorizationStatus.hpp" #include "JPaymentDetails.hpp" -#include "CanMakePaymentsOptions.hpp" -#include "JCanMakePaymentsOptions.hpp" namespace margelo::nitro::pay { @@ -192,31 +188,6 @@ namespace margelo::nitro::pay { return __promise; }(); } - std::shared_ptr> JHybridPaymentHandlerSpec::canMakePayments(const std::vector& usingNetworks, const std::optional& options) { - static const auto method = _javaPart->javaClassStatic()->getMethod(jni::alias_ref> /* usingNetworks */, jni::alias_ref /* options */)>("canMakePayments"); - auto __result = method(_javaPart, [&](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; - }(usingNetworks), options.has_value() ? JCanMakePaymentsOptions::fromCpp(options.value()) : nullptr); - return [&]() { - auto __promise = Promise::create(); - __result->cthis()->addOnResolvedListener([=](const jni::alias_ref& __boxedResult) { - auto __result = jni::static_ref_cast(__boxedResult); - __promise->resolve(static_cast(__result->value())); - }); - __result->cthis()->addOnRejectedListener([=](const jni::alias_ref& __throwable) { - jni::JniException __jniError(__throwable); - __promise->reject(std::make_exception_ptr(__jniError)); - }); - return __promise; - }(); - } bool JHybridPaymentHandlerSpec::isPaymentInProgress() { static const auto method = _javaPart->javaClassStatic()->getMethod("isPaymentInProgress"); auto __result = method(_javaPart); diff --git a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp index a277aca..5ad05ee 100644 --- a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp +++ b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.hpp @@ -56,7 +56,6 @@ namespace margelo::nitro::pay { // Methods std::shared_ptr> payServiceStatus(const std::optional& options) override; std::shared_ptr> startPayment(const PaymentRequest& request, const std::optional& options) override; - std::shared_ptr> canMakePayments(const std::vector& usingNetworks, const std::optional& options) override; bool isPaymentInProgress() override; void openPaymentSetup() override; diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/CanMakePaymentsOptions.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/CanMakePaymentsOptions.kt deleted file mode 100644 index fe460ea..0000000 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/CanMakePaymentsOptions.kt +++ /dev/null @@ -1,56 +0,0 @@ -/// -/// CanMakePaymentsOptions.kt -/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. -/// https://github.com/mrousavy/nitro -/// Copyright © Marc Rousavy @ Margelo -/// - -package com.margelo.nitro.pay - -import androidx.annotation.Keep -import com.facebook.proguard.annotations.DoNotStrip -import java.util.Objects - - -/** - * Represents the JavaScript object/struct "CanMakePaymentsOptions". - */ -@DoNotStrip -@Keep -data class CanMakePaymentsOptions( - @DoNotStrip - @Keep - val merchantCapabilities: Array?, - @DoNotStrip - @Keep - val googlePayEnvironment: GooglePayEnvironment? -) { - /* primary constructor */ - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other !is CanMakePaymentsOptions) return false - return Objects.deepEquals(this.merchantCapabilities, other.merchantCapabilities) - && Objects.deepEquals(this.googlePayEnvironment, other.googlePayEnvironment) - } - - override fun hashCode(): Int { - return arrayOf( - merchantCapabilities, - googlePayEnvironment - ).contentDeepHashCode() - } - - companion object { - /** - * Constructor called from C++ - */ - @DoNotStrip - @Keep - @Suppress("unused") - @JvmStatic - private fun fromCpp(merchantCapabilities: Array?, googlePayEnvironment: GooglePayEnvironment?): CanMakePaymentsOptions { - return CanMakePaymentsOptions(merchantCapabilities, googlePayEnvironment) - } - } -} diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt index db5489f..a8b7e29 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/HybridPaymentHandlerSpec.kt @@ -37,10 +37,6 @@ abstract class HybridPaymentHandlerSpec: HybridObject() { @Keep abstract fun startPayment(request: PaymentRequest, options: StartPaymentOptions?): Promise - @DoNotStrip - @Keep - abstract fun canMakePayments(usingNetworks: Array, options: CanMakePaymentsOptions?): Promise - @DoNotStrip @Keep abstract fun isPaymentInProgress(): Boolean diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.cpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.cpp index 6924f82..abf14fe 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.cpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.cpp @@ -88,14 +88,6 @@ namespace margelo::nitro::pay::bridge::swift { }; } - // pragma MARK: std::function - Func_void_bool create_Func_void_bool(void* NON_NULL swiftClosureWrapper) noexcept { - auto swiftClosure = NitroPay::Func_void_bool::fromUnsafe(swiftClosureWrapper); - return [swiftClosure = std::move(swiftClosure)](bool result) mutable -> void { - swiftClosure.call(result); - }; - } - // pragma MARK: std::shared_ptr std::shared_ptr create_std__shared_ptr_HybridPaymentHandlerSpec_(void* NON_NULL swiftUnsafePointer) noexcept { NitroPay::HybridPaymentHandlerSpec_cxx swiftPart = NitroPay::HybridPaymentHandlerSpec_cxx::fromUnsafe(swiftUnsafePointer); diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp index 58bfd0d..706b018 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp @@ -22,8 +22,6 @@ namespace margelo::nitro::pay { struct CNLabeledPostalAddress; } namespace margelo::nitro::pay { struct CNPhoneNumber; } // Forward declaration of `CNPostalAddress` to properly resolve imports. namespace margelo::nitro::pay { struct CNPostalAddress; } -// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. -namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } // Forward declaration of `GooglePayEnvironment` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `HybridApplePayButtonSpec` to properly resolve imports. @@ -79,7 +77,6 @@ namespace NitroPay { class HybridPaymentHandlerSpec_cxx; } #include "CNLabeledPostalAddress.hpp" #include "CNPhoneNumber.hpp" #include "CNPostalAddress.hpp" -#include "CanMakePaymentsOptions.hpp" #include "GooglePayEnvironment.hpp" #include "HybridApplePayButtonSpec.hpp" #include "HybridPaymentHandlerSpec.hpp" @@ -667,55 +664,6 @@ namespace margelo::nitro::pay::bridge::swift { return optional.value(); } - // pragma MARK: std::shared_ptr> - /** - * Specialized version of `std::shared_ptr>`. - */ - using std__shared_ptr_Promise_bool__ = std::shared_ptr>; - inline std::shared_ptr> create_std__shared_ptr_Promise_bool__() noexcept { - return Promise::create(); - } - inline PromiseHolder wrap_std__shared_ptr_Promise_bool__(std::shared_ptr> promise) noexcept { - return PromiseHolder(std::move(promise)); - } - - // pragma MARK: std::function - /** - * Specialized version of `std::function`. - */ - using Func_void_bool = std::function; - /** - * Wrapper class for a `std::function`, this can be used from Swift. - */ - class Func_void_bool_Wrapper final { - public: - explicit Func_void_bool_Wrapper(std::function&& func): _function(std::make_unique>(std::move(func))) {} - inline void call(bool result) const noexcept { - _function->operator()(result); - } - private: - std::unique_ptr> _function; - } SWIFT_NONCOPYABLE; - Func_void_bool create_Func_void_bool(void* NON_NULL swiftClosureWrapper) noexcept; - inline Func_void_bool_Wrapper wrap_Func_void_bool(Func_void_bool value) noexcept { - return Func_void_bool_Wrapper(std::move(value)); - } - - // pragma MARK: std::optional - /** - * Specialized version of `std::optional`. - */ - using std__optional_CanMakePaymentsOptions_ = std::optional; - inline std::optional create_std__optional_CanMakePaymentsOptions_(const CanMakePaymentsOptions& value) noexcept { - return std::optional(value); - } - inline bool has_value_std__optional_CanMakePaymentsOptions_(const std::optional& optional) noexcept { - return optional.has_value(); - } - inline CanMakePaymentsOptions get_std__optional_CanMakePaymentsOptions_(const std::optional& optional) noexcept { - return optional.value(); - } - // pragma MARK: std::shared_ptr /** * Specialized version of `std::shared_ptr`. @@ -746,15 +694,6 @@ namespace margelo::nitro::pay::bridge::swift { return Result>>::withError(error); } - // pragma MARK: Result>> - using Result_std__shared_ptr_Promise_bool___ = Result>>; - inline Result_std__shared_ptr_Promise_bool___ create_Result_std__shared_ptr_Promise_bool___(const std::shared_ptr>& value) noexcept { - return Result>>::withValue(value); - } - inline Result_std__shared_ptr_Promise_bool___ create_Result_std__shared_ptr_Promise_bool___(const std::exception_ptr& error) noexcept { - return Result>>::withError(error); - } - // pragma MARK: Result using Result_bool_ = Result; inline Result_bool_ create_Result_bool_(bool value) noexcept { diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp index 52bcb88..16f2fc4 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp @@ -26,8 +26,6 @@ namespace margelo::nitro::pay { struct CNLabeledPostalAddress; } namespace margelo::nitro::pay { struct CNPhoneNumber; } // Forward declaration of `CNPostalAddress` to properly resolve imports. namespace margelo::nitro::pay { struct CNPostalAddress; } -// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. -namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } // Forward declaration of `GooglePayEnvironment` to properly resolve imports. namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `HybridApplePayButtonSpec` to properly resolve imports. @@ -81,7 +79,6 @@ namespace margelo::nitro::pay { struct StartPaymentOptions; } #include "CNLabeledPostalAddress.hpp" #include "CNPhoneNumber.hpp" #include "CNPostalAddress.hpp" -#include "CanMakePaymentsOptions.hpp" #include "GooglePayEnvironment.hpp" #include "HybridApplePayButtonSpec.hpp" #include "HybridPaymentHandlerSpec.hpp" diff --git a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp index 0562932..c2fa745 100644 --- a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp +++ b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp @@ -64,8 +64,6 @@ namespace margelo::nitro::pay { struct PaymentAuthorizationResult; } namespace margelo::nitro::pay { struct PaymentDetails; } // Forward declaration of `PaymentAuthorizationStatus` to properly resolve imports. namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } -// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. -namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PayServiceStatus.hpp" #include @@ -99,7 +97,6 @@ namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PaymentDetails.hpp" #include #include "PaymentAuthorizationStatus.hpp" -#include "CanMakePaymentsOptions.hpp" #include "NitroPay-Swift-Cxx-Umbrella.hpp" @@ -167,14 +164,6 @@ namespace margelo::nitro::pay { auto __value = std::move(__result.value()); return __value; } - inline std::shared_ptr> canMakePayments(const std::vector& usingNetworks, const std::optional& options) override { - auto __result = _swiftPart.canMakePayments(usingNetworks, options); - if (__result.hasError()) [[unlikely]] { - std::rethrow_exception(__result.error()); - } - auto __value = std::move(__result.value()); - return __value; - } inline bool isPaymentInProgress() override { auto __result = _swiftPart.isPaymentInProgress(); if (__result.hasError()) [[unlikely]] { diff --git a/package/nitrogen/generated/ios/swift/CanMakePaymentsOptions.swift b/package/nitrogen/generated/ios/swift/CanMakePaymentsOptions.swift deleted file mode 100644 index bb3550c..0000000 --- a/package/nitrogen/generated/ios/swift/CanMakePaymentsOptions.swift +++ /dev/null @@ -1,59 +0,0 @@ -/// -/// CanMakePaymentsOptions.swift -/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. -/// https://github.com/mrousavy/nitro -/// Copyright © Marc Rousavy @ Margelo -/// - -import NitroModules - -/** - * Represents an instance of `CanMakePaymentsOptions`, backed by a C++ struct. - */ -public typealias CanMakePaymentsOptions = margelo.nitro.pay.CanMakePaymentsOptions - -public extension CanMakePaymentsOptions { - private typealias bridge = margelo.nitro.pay.bridge.swift - - /** - * Create a new instance of `CanMakePaymentsOptions`. - */ - init(merchantCapabilities: [String]?, googlePayEnvironment: GooglePayEnvironment?) { - self.init({ () -> bridge.std__optional_std__vector_std__string__ in - if let __unwrappedValue = merchantCapabilities { - return bridge.create_std__optional_std__vector_std__string__({ () -> bridge.std__vector_std__string_ in - var __vector = bridge.create_std__vector_std__string_(__unwrappedValue.count) - for __item in __unwrappedValue { - __vector.push_back(std.string(__item)) - } - return __vector - }()) - } else { - return .init() - } - }(), { () -> bridge.std__optional_GooglePayEnvironment_ in - if let __unwrappedValue = googlePayEnvironment { - return bridge.create_std__optional_GooglePayEnvironment_(__unwrappedValue) - } else { - return .init() - } - }()) - } - - @inline(__always) - var merchantCapabilities: [String]? { - return { () -> [String]? in - if bridge.has_value_std__optional_std__vector_std__string__(self.__merchantCapabilities) { - let __unwrapped = bridge.get_std__optional_std__vector_std__string__(self.__merchantCapabilities) - return __unwrapped.map({ __item in String(__item) }) - } else { - return nil - } - }() - } - - @inline(__always) - var googlePayEnvironment: GooglePayEnvironment? { - return self.__googlePayEnvironment.value - } -} diff --git a/package/nitrogen/generated/ios/swift/Func_void_bool.swift b/package/nitrogen/generated/ios/swift/Func_void_bool.swift deleted file mode 100644 index 4a8b03e..0000000 --- a/package/nitrogen/generated/ios/swift/Func_void_bool.swift +++ /dev/null @@ -1,46 +0,0 @@ -/// -/// Func_void_bool.swift -/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. -/// https://github.com/mrousavy/nitro -/// Copyright © Marc Rousavy @ Margelo -/// - -import NitroModules - -/** - * Wraps a Swift `(_ value: Bool) -> Void` as a class. - * This class can be used from C++, e.g. to wrap the Swift closure as a `std::function`. - */ -public final class Func_void_bool { - public typealias bridge = margelo.nitro.pay.bridge.swift - - private let closure: (_ value: Bool) -> Void - - public init(_ closure: @escaping (_ value: Bool) -> Void) { - self.closure = closure - } - - @inline(__always) - public func call(value: Bool) -> Void { - self.closure(value) - } - - /** - * Casts this instance to a retained unsafe raw pointer. - * This acquires one additional strong reference on the object! - */ - @inline(__always) - public func toUnsafe() -> UnsafeMutableRawPointer { - return Unmanaged.passRetained(self).toOpaque() - } - - /** - * Casts an unsafe pointer to a `Func_void_bool`. - * The pointer has to be a retained opaque `Unmanaged`. - * This removes one strong reference from the object! - */ - @inline(__always) - public static func fromUnsafe(_ pointer: UnsafeMutableRawPointer) -> Func_void_bool { - return Unmanaged.fromOpaque(pointer).takeRetainedValue() - } -} diff --git a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift index ed82572..0a57a93 100644 --- a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift +++ b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec.swift @@ -15,7 +15,6 @@ public protocol HybridPaymentHandlerSpec_protocol: HybridObject { // Methods func payServiceStatus(options: PayServiceStatusOptions?) throws -> Promise func startPayment(request: PaymentRequest, options: StartPaymentOptions?) throws -> Promise - func canMakePayments(usingNetworks: [String], options: CanMakePaymentsOptions?) throws -> Promise func isPaymentInProgress() throws -> Bool func openPaymentSetup() throws -> Void } diff --git a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift index 51b39e4..40a131a 100644 --- a/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift +++ b/package/nitrogen/generated/ios/swift/HybridPaymentHandlerSpec_cxx.swift @@ -162,25 +162,6 @@ open class HybridPaymentHandlerSpec_cxx { } } - @inline(__always) - public final func canMakePayments(usingNetworks: bridge.std__vector_std__string_, options: bridge.std__optional_CanMakePaymentsOptions_) -> bridge.Result_std__shared_ptr_Promise_bool___ { - do { - let __result = try self.__implementation.canMakePayments(usingNetworks: usingNetworks.map({ __item in String(__item) }), options: options.value) - let __resultCpp = { () -> bridge.std__shared_ptr_Promise_bool__ in - let __promise = bridge.create_std__shared_ptr_Promise_bool__() - let __promiseHolder = bridge.wrap_std__shared_ptr_Promise_bool__(__promise) - __result - .then({ __result in __promiseHolder.resolve(__result) }) - .catch({ __error in __promiseHolder.reject(__error.toCpp()) }) - return __promise - }() - return bridge.create_Result_std__shared_ptr_Promise_bool___(__resultCpp) - } catch (let __error) { - let __exceptionPtr = __error.toCpp() - return bridge.create_Result_std__shared_ptr_Promise_bool___(__exceptionPtr) - } - } - @inline(__always) public final func isPaymentInProgress() -> bridge.Result_bool_ { do { diff --git a/package/nitrogen/generated/shared/c++/CanMakePaymentsOptions.hpp b/package/nitrogen/generated/shared/c++/CanMakePaymentsOptions.hpp deleted file mode 100644 index 084df44..0000000 --- a/package/nitrogen/generated/shared/c++/CanMakePaymentsOptions.hpp +++ /dev/null @@ -1,91 +0,0 @@ -/// -/// CanMakePaymentsOptions.hpp -/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. -/// https://github.com/mrousavy/nitro -/// Copyright © Marc Rousavy @ Margelo -/// - -#pragma once - -#if __has_include() -#include -#else -#error NitroModules cannot be found! Are you sure you installed NitroModules properly? -#endif -#if __has_include() -#include -#else -#error NitroModules cannot be found! Are you sure you installed NitroModules properly? -#endif -#if __has_include() -#include -#else -#error NitroModules cannot be found! Are you sure you installed NitroModules properly? -#endif -#if __has_include() -#include -#else -#error NitroModules cannot be found! Are you sure you installed NitroModules properly? -#endif - -// Forward declaration of `GooglePayEnvironment` to properly resolve imports. -namespace margelo::nitro::pay { enum class GooglePayEnvironment; } - -#include -#include -#include -#include "GooglePayEnvironment.hpp" - -namespace margelo::nitro::pay { - - /** - * A struct which can be represented as a JavaScript object (CanMakePaymentsOptions). - */ - struct CanMakePaymentsOptions final { - public: - std::optional> merchantCapabilities SWIFT_PRIVATE; - std::optional googlePayEnvironment SWIFT_PRIVATE; - - public: - CanMakePaymentsOptions() = default; - explicit CanMakePaymentsOptions(std::optional> merchantCapabilities, std::optional googlePayEnvironment): merchantCapabilities(merchantCapabilities), googlePayEnvironment(googlePayEnvironment) {} - - public: - friend bool operator==(const CanMakePaymentsOptions& lhs, const CanMakePaymentsOptions& rhs) = default; - }; - -} // namespace margelo::nitro::pay - -namespace margelo::nitro { - - // C++ CanMakePaymentsOptions <> JS CanMakePaymentsOptions (object) - template <> - struct JSIConverter final { - static inline margelo::nitro::pay::CanMakePaymentsOptions fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { - jsi::Object obj = arg.asObject(runtime); - return margelo::nitro::pay::CanMakePaymentsOptions( - JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"))), - JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"))) - ); - } - static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::CanMakePaymentsOptions& arg) { - jsi::Object obj(runtime); - obj.setProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities"), JSIConverter>>::toJSI(runtime, arg.merchantCapabilities)); - obj.setProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment"), JSIConverter>::toJSI(runtime, arg.googlePayEnvironment)); - return obj; - } - static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { - if (!value.isObject()) { - return false; - } - jsi::Object obj = value.getObject(runtime); - if (!nitro::isPlainObject(runtime, obj)) { - return false; - } - if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "merchantCapabilities")))) return false; - if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "googlePayEnvironment")))) return false; - return true; - } - }; - -} // namespace margelo::nitro diff --git a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.cpp b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.cpp index 9b969b8..82e44e2 100644 --- a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.cpp +++ b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.cpp @@ -16,7 +16,6 @@ namespace margelo::nitro::pay { registerHybrids(this, [](Prototype& prototype) { prototype.registerHybridMethod("payServiceStatus", &HybridPaymentHandlerSpec::payServiceStatus); prototype.registerHybridMethod("startPayment", &HybridPaymentHandlerSpec::startPayment); - prototype.registerHybridMethod("canMakePayments", &HybridPaymentHandlerSpec::canMakePayments); prototype.registerHybridMethod("isPaymentInProgress", &HybridPaymentHandlerSpec::isPaymentInProgress); prototype.registerHybridMethod("openPaymentSetup", &HybridPaymentHandlerSpec::openPaymentSetup); }); diff --git a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp index 5ebbfd9..251e157 100644 --- a/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp +++ b/package/nitrogen/generated/shared/c++/HybridPaymentHandlerSpec.hpp @@ -23,8 +23,6 @@ namespace margelo::nitro::pay { struct PaymentResult; } namespace margelo::nitro::pay { struct PaymentRequest; } // Forward declaration of `StartPaymentOptions` to properly resolve imports. namespace margelo::nitro::pay { struct StartPaymentOptions; } -// Forward declaration of `CanMakePaymentsOptions` to properly resolve imports. -namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PayServiceStatus.hpp" #include @@ -33,9 +31,6 @@ namespace margelo::nitro::pay { struct CanMakePaymentsOptions; } #include "PaymentResult.hpp" #include "PaymentRequest.hpp" #include "StartPaymentOptions.hpp" -#include -#include -#include "CanMakePaymentsOptions.hpp" namespace margelo::nitro::pay { @@ -70,7 +65,6 @@ namespace margelo::nitro::pay { // Methods virtual std::shared_ptr> payServiceStatus(const std::optional& options) = 0; virtual std::shared_ptr> startPayment(const PaymentRequest& request, const std::optional& options) = 0; - virtual std::shared_ptr> canMakePayments(const std::vector& usingNetworks, const std::optional& options) = 0; virtual bool isPaymentInProgress() = 0; virtual void openPaymentSetup() = 0; diff --git a/package/src/specs/PaymentHandler.nitro.ts b/package/src/specs/PaymentHandler.nitro.ts index 49fceb2..4c456fe 100644 --- a/package/src/specs/PaymentHandler.nitro.ts +++ b/package/src/specs/PaymentHandler.nitro.ts @@ -1,6 +1,5 @@ import type { HybridObject } from 'react-native-nitro-modules' import type { - CanMakePaymentsOptions, PayServiceStatus, PayServiceStatusOptions, PaymentRequest, @@ -15,10 +14,6 @@ export interface PaymentHandler request: PaymentRequest, options?: StartPaymentOptions ): Promise - canMakePayments( - usingNetworks: string[], - options?: CanMakePaymentsOptions - ): Promise isPaymentInProgress(): boolean // iOS only: opens Wallet to add a card. Does nothing on Android. openPaymentSetup(): void diff --git a/package/src/types/Payment.ts b/package/src/types/Payment.ts index 15f6ead..697563a 100644 --- a/package/src/types/Payment.ts +++ b/package/src/types/Payment.ts @@ -264,15 +264,5 @@ export interface PayServiceStatusOptions { googlePayEnvironment?: GooglePayEnvironment } -/** - * What `canMakePayments(usingNetworks, options)` checks besides the networks. - */ -export interface CanMakePaymentsOptions { - // iOS only. Same as `PayServiceStatusOptions.merchantCapabilities`. - merchantCapabilities?: string[] - // Android only. The Google Pay environment to ask. Defaults to `'TEST'`. - googlePayEnvironment?: GooglePayEnvironment -} - // Backward compatibility alias export type ApplePayStatus = PayServiceStatus From 8816eae97947f03a3c5e9459364337af205d8622 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 16:40:42 +0100 Subject: [PATCH 09/10] test(android): pass the networks to the readiness request in the contacts test --- .../java/com/margelo/nitro/pay/GooglePayRequestBuilderTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package/android/src/test/java/com/margelo/nitro/pay/GooglePayRequestBuilderTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/GooglePayRequestBuilderTest.kt index de74737..f5c6b36 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 @@ -420,7 +420,7 @@ class GooglePayRequestBuilderTest { @Test fun isReadyToPayRequest_neverAsksForContacts() { - val parameters = GooglePayRequestBuilder.createIsReadyToPayRequest() + val parameters = GooglePayRequestBuilder.createIsReadyToPayRequest(PaymentConstants.DEFAULT_CARD_NETWORKS) .getJSONArray("allowedPaymentMethods").getJSONObject(0).getJSONObject("parameters") assertFalse(parameters.has("billingAddressRequired")) From 67d21ed5abb6c7360159d4f88c6760273f45761f Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 26 Oct 2026 21:02:05 +0100 Subject: [PATCH 10/10] docs: wait for the first availability check and pay with a filled cart - README and the hook's JSDoc example showed "not available" while the first check was still running; they show a loader first, like Quick Start. - The availability guide's WalletButton had an empty cart, so startPayment returned "Cart is empty". The checkout screen now owns the hook and the cart, and passes the checkout to WalletButton. - The example app showed a full-screen loader on every refresh after an unsupported answer. It shows the check in place instead. --- README.md | 5 +++ docs/docs/guides/availability.md | 41 +++++++++++++++++-------- example/app/(tabs)/index.tsx | 20 +++++------- package/src/hooks/usePaymentCheckout.ts | 5 +++ 4 files changed, 45 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index eb4af96..bd13cec 100644 --- a/README.md +++ b/README.md @@ -196,6 +196,7 @@ function CheckoutScreen() { const { // Payment availability isSupported, + isCheckingStatus, // Cart management items, @@ -246,6 +247,10 @@ function CheckoutScreen() { } } + if (isCheckingStatus) { + return + } + if (!isSupported) { return ( diff --git a/docs/docs/guides/availability.md b/docs/docs/guides/availability.md index 4b86124..3f7e025 100644 --- a/docs/docs/guides/availability.md +++ b/docs/docs/guides/availability.md @@ -24,30 +24,31 @@ On Android, the check goes to the Google Pay environment you pass as `googlePayE - **iOS**: show the Apple Pay buy button when `hasActiveCard` is `true`. When only `isSupported` is `true`, show the **Set up Apple Pay** button (`buttonType="setUp"`) and call `HybridPaymentHandler.openPaymentSetup()` on tap. It opens Wallet (Settings on iPad) to add a card. - **Neither platform**: when `isSupported` is `false`, hide the wallet buttons and offer another way to pay. -The user comes back from Wallet with a card the status does not know about yet, so check again when the app returns to the foreground: +In the example below, the checkout screen owns the hook and the cart, and `WalletButton` picks the button from the status. The user comes back from Wallet with a card the status does not know about yet, so the screen checks again when the app returns to the foreground: ```tsx import { useEffect } from 'react' -import { AppState, Platform } from 'react-native' +import { AppState, Button, Platform, View } from 'react-native' import { callback } from 'react-native-nitro-modules' import { ApplePayButton, GooglePayButton, HybridPaymentHandler, usePaymentCheckout, + type UsePaymentCheckoutReturn, } from '@gmisoftware/react-native-pay' -export function WalletButton() { - const { isSupported, hasActiveCard, refreshStatus, startPayment } = - usePaymentCheckout({ - merchantName: 'Your Store', - supportedNetworks: ['visa', 'mastercard'], - // The environment you pay in, so the status is real in production. - googlePayEnvironment: 'PRODUCTION', - googlePayMerchantId: 'your_google_pay_merchant_id', - googlePayGateway: 'stripe', - googlePayGatewayMerchantId: 'your_stripe_merchant_id', - }) +export function CheckoutScreen() { + const checkout = usePaymentCheckout({ + merchantName: 'Your Store', + supportedNetworks: ['visa', 'mastercard'], + // The environment you pay in, so the status is real in production. + googlePayEnvironment: 'PRODUCTION', + googlePayMerchantId: 'your_google_pay_merchant_id', + googlePayGateway: 'stripe', + googlePayGatewayMerchantId: 'your_stripe_merchant_id', + }) + const { refreshStatus } = checkout useEffect(() => { const subscription = AppState.addEventListener('change', (state) => { @@ -56,6 +57,20 @@ export function WalletButton() { return () => subscription.remove() }, [refreshStatus]) + return ( + +