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..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 @@ -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,10 @@ Cross-layer contract rule: Primary low-level contract: -- `payServiceStatus(): PayServiceStatus` +- `payServiceStatus(options?: PayServiceStatusOptions): Promise` - `startPayment(request: PaymentRequest): Promise` -- `canMakePayments(usingNetworks: string[]): boolean` - `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..df6cc6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,21 @@ 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()` 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. ### Fixed @@ -59,6 +74,17 @@ 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. +- **`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 72e7801..bd13cec 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,8 @@ import { callback } from 'react-native-nitro-modules' function CheckoutScreen() { const { // Payment availability - canMakePayments, + isSupported, + isCheckingStatus, // Cart management items, @@ -246,7 +247,11 @@ function CheckoutScreen() { } } - if (!canMakePayments) { + if (isCheckingStatus) { + return + } + + if (!isSupported) { return ( Apple Pay or Google Pay is not available on this device @@ -393,9 +398,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 +461,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,16 +544,6 @@ interface PaymentToken { } ``` -##### `canMakePayments(usingNetworks: string[]): boolean` - -Check if specific card networks are supported. - -```typescript -import { HybridPaymentHandler } from "@gmisoftware/react-native-pay"; - -const canPay = HybridPaymentHandler.canMakePayments(["visa", "mastercard"]); -``` - ##### `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" }`. @@ -553,6 +554,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 +917,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 +958,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, 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. - **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..3f7e025 --- /dev/null +++ b/docs/docs/guides/availability.md @@ -0,0 +1,125 @@ +# 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. 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 + +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. + +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, 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 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) => { + if (state === 'active') refreshStatus() + }) + return () => subscription.remove() + }, [refreshStatus]) + + return ( + +