From cec1036b38ee0e643b065f5fcd3a2c37e44ae228 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Mon, 23 Nov 2026 19:09:56 +0100 Subject: [PATCH] feat: merchant token fields in usePaymentCheckout Take recurring, deferred and automaticReload in the hook config, keep their Date values, and allow an empty cart with them. Fixes #96 --- README.md | 6 +- docs/docs/api/types.md | 2 +- docs/docs/api/use-payment-checkout.md | 11 +- docs/docs/guides/merchant-tokens.md | 43 +++- docs/docs/payment-flow.md | 2 +- docs/docs/troubleshooting.md | 2 +- .../usePaymentCheckout.integration.test.ts | 185 +++++++++++++++++- package/src/hooks/usePaymentCheckout.ts | 74 ++++++- 8 files changed, 310 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 401518cf..58555c81 100644 --- a/README.md +++ b/README.md @@ -374,6 +374,10 @@ interface UsePaymentCheckoutConfig { emailRequired?: boolean; phoneNumberRequired?: boolean; couponCode?: string; // iOS: a code already applied, needs onCouponCodeChange + // Charge again later; set at most one, and the cart may then be empty + recurring?: RecurringPaymentRequest; // subscriptions, iOS 16+ + deferred?: DeferredPaymentRequest; // one later charge, iOS 16.4+ + automaticReload?: AutomaticReloadPaymentRequest; // top-ups, iOS 16+ // Charge the token while the sheet waits (see "Charging before the sheet closes") onAuthorize?: ( token: PaymentToken, @@ -964,7 +968,7 @@ The cart can follow the payer's choices while the Apple Pay or Google Pay sheet ### Subscriptions and later payments -`recurring`, `deferred` and `automaticReload` (with `HybridPaymentHandler`) charge the payer again later: a subscription, a payment on a later date, or a balance top-up. The sheet shows the schedule, and the payment asks for a merchant token your payment provider can charge later. When the card's network has no merchant tokens, Apple Pay returns a device token instead, so check with your provider. `paymentItems` stay what the payer pays today, which may be nothing. Android sends them to Google Pay as Merchant Initiated Transactions. See the [subscriptions guide](https://gmi-software.github.io/react-native-pay/docs/guides/merchant-tokens). +`recurring`, `deferred` and `automaticReload` (in the `PaymentRequest` or the hook's config) charge the payer again later: a subscription, a payment on a later date, or a balance top-up. The sheet shows the schedule, and the payment asks for a merchant token your payment provider can charge later. When the card's network has no merchant tokens, Apple Pay returns a device token instead, so check with your provider. `paymentItems`, or the hook's cart, stay what the payer pays today, which may be nothing. Android sends them to Google Pay as Merchant Initiated Transactions. See the [subscriptions guide](https://gmi-software.github.io/react-native-pay/docs/guides/merchant-tokens). ### Several merchants (iOS) diff --git a/docs/docs/api/types.md b/docs/docs/api/types.md index 1e440bcf..42452d6f 100644 --- a/docs/docs/api/types.md +++ b/docs/docs/api/types.md @@ -596,7 +596,7 @@ interface PaymentDetails { ## Recurring and later payments -Set at most one of these on `PaymentRequest`. Use them with `HybridPaymentHandler.startPayment`; see [Subscriptions and later payments](/docs/guides/merchant-tokens) for examples and the validation rules. On Android they become Google Pay's Merchant Initiated Transactions; see [On Android](/docs/guides/merchant-tokens#on-android). +Set at most one of these on `PaymentRequest`. Use them with `HybridPaymentHandler.startPayment` or in the config of [`usePaymentCheckout`](/docs/api/use-payment-checkout); see [Subscriptions and later payments](/docs/guides/merchant-tokens) for examples and the validation rules. On Android they become Google Pay's Merchant Initiated Transactions; see [On Android](/docs/guides/merchant-tokens#on-android). ```ts no-check // Shared by all three diff --git a/docs/docs/api/use-payment-checkout.md b/docs/docs/api/use-payment-checkout.md index 2871ef25..027c4736 100644 --- a/docs/docs/api/use-payment-checkout.md +++ b/docs/docs/api/use-payment-checkout.md @@ -39,6 +39,10 @@ interface UsePaymentCheckoutConfig { emailRequired?: boolean phoneNumberRequired?: boolean couponCode?: string // iOS: a code already applied + // Charge again later; set at most one + recurring?: RecurringPaymentRequest + deferred?: DeferredPaymentRequest + automaticReload?: AutomaticReloadPaymentRequest // Charge the token before the sheet closes onAuthorize?: ( token: PaymentToken, @@ -66,6 +70,7 @@ interface UsePaymentCheckoutConfig { - **onAuthorize** — Called with the token and the requested contact details after the user authorizes the payment. Charge it on your server and resolve with `{ status: 'success' }` or `{ status: 'failure', error }`. See [Charge before the sheet closes](/docs/guides/server-processing#charge-before-the-sheet-closes). An inline function is fine: `startPayment()` uses the one from the latest render, and a payment keeps that function until it settles, even if the config changes meanwhile. - **onShippingAddressChange**, **onShippingMethodChange**, **onPaymentMethodChange**, **onCouponCodeChange** — Update the cart while the sheet is open, as in [`StartPaymentOptions`](/docs/api/types#startpaymentoptions). What they return changes only the sheet: `items` stays as you set it, so a coupon the payer tried and then cancelled leaves no discount behind. Inline functions are fine, as for `onAuthorize`. Android has no coupon field and differs in a few ways; see [On Android](/docs/guides/dynamic-cart#on-android). See [Update the cart in the sheet](/docs/guides/dynamic-cart#update-the-cart-in-the-sheet). - **couponCode** — A coupon code already applied, shown in the sheet's coupon field. `items` must already include its discount. Needs `onCouponCodeChange`. iOS only. +- **recurring**, **deferred**, **automaticReload** — Charge the payer again later: a subscription, a payment on a later date, or a balance top-up. Set at most one. `items` stay what the payer pays today, and the cart may then be empty, as in a free trial. The hook compares them by value, `Date`s included, so build the dates once, for example in a `useState` initializer: a `new Date(...)` built on every render gives a new `paymentRequest` and `startPayment` on every render. A date that has passed by the time the payer taps fails with `'CONFIGURATION'`. See [Subscriptions and later payments](/docs/guides/merchant-tokens). ## Return value @@ -106,7 +111,7 @@ interface UsePaymentCheckoutReturn { 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` and never rejects, so check `status` and `code` (see [Error codes](/docs/payment-flow#error-codes)). Except for `'IN_PROGRESS'`, it also sets `result` to what it returns, and sets `error` to a `PaymentError` with its `code` whenever `status` is `'failed'` (`'UNKNOWN'` if a native result has none). - - Returns `{ status: 'failed', code: 'CONFIGURATION', success: false, error: 'Cart is empty' }` when the cart is empty. + - Returns `{ status: 'failed', code: 'CONFIGURATION', success: false, error: 'Cart is empty' }` when the cart is empty, unless `recurring`, `deferred` or `automaticReload` is set. - Returns `status: 'failed'` and `code: 'CONFIGURATION'`, without opening the sheet, when an amount is invalid or the total is negative (see [`PaymentAmount`](/docs/api/types#paymentamount)). `error` holds the validation message, and the validation error is in the hook's `error.cause`. [`HybridPaymentHandler`](/docs/api/hybrid-payment-handler) returns the same result. - Returns the native `PaymentResult` when the sheet closes. - A cancel returns `status: 'cancelled'` and `code: 'CANCELLED'`. It sets `result` but leaves `error` as `null`, so the user closing the sheet doesn't show up as a failed payment. @@ -167,11 +172,13 @@ if (result.status === 'success' && result.token) { If you call `startPayment()` when `items.length === 0`, it returns `status: 'failed'` with `code: 'CONFIGURATION'` and sets `error` to a “Cart is empty” error. Add at least one item before starting payment. +With `recurring`, `deferred` or `automaticReload`, an empty cart is allowed: the payer pays nothing today, and `paymentRequest.paymentItems` is `[]`. Without them, `paymentRequest.paymentItems` holds a `Total` item of `0` while the cart is empty. + ## Hook vs low-level API Use `usePaymentCheckout` when you want cart state + defaults managed in React state. -Use [HybridPaymentHandler](/docs/api/hybrid-payment-handler) when you need to build the full `PaymentRequest` yourself (for example `shippingMethods`, `shippingType`, [subscriptions and later payments](/docs/guides/merchant-tokens) or prebuilt request payloads from your backend). The hook's `total` covers only the cart, so it doesn't take `shippingMethods`, `recurring`, `deferred` or `automaticReload`. Utility helpers for this path are documented in [Utility functions](/docs/api/utils). +Use [HybridPaymentHandler](/docs/api/hybrid-payment-handler) when you need to build the full `PaymentRequest` yourself (for example `shippingMethods`, `shippingType` or prebuilt request payloads from your backend). The hook's `total` covers only the cart, so it doesn't take `shippingMethods`. Utility helpers for this path are documented in [Utility functions](/docs/api/utils). ## Next diff --git a/docs/docs/guides/merchant-tokens.md b/docs/docs/guides/merchant-tokens.md index 4a6a55ee..69d6fbcb 100644 --- a/docs/docs/guides/merchant-tokens.md +++ b/docs/docs/guides/merchant-tokens.md @@ -12,7 +12,7 @@ The sheet shows the schedule and your management URL, and the payment asks Apple A merchant token is not guaranteed: when the card's network doesn't offer merchant tokens, Apple Pay returns a device token, as for a one-off payment. Ask your payment provider how it tells the two apart and which one it can charge later. -These requests need `HybridPaymentHandler.startPayment`. `usePaymentCheckout` does not take them. +Pass them to `HybridPaymentHandler.startPayment`, or in the config of `usePaymentCheckout`. See [With usePaymentCheckout](#with-usepaymentcheckout). ## What is charged today @@ -133,11 +133,50 @@ export async function enableTopUp() { } ``` +## With usePaymentCheckout + +The hook takes the same three fields in its config. Its cart is what the payer pays today, and with one of the fields set it may be empty: + +```tsx +import { useState } from 'react' +import { usePaymentCheckout } from '@gmisoftware/react-native-pay' + +const DAY = 24 * 60 * 60 * 1000 + +export function useMembershipCheckout() { + // Built once: a new Date on every render would give a new paymentRequest + // and startPayment on every render. + const [trialEnd] = useState(() => new Date(Date.now() + 7 * DAY)) + + return usePaymentCheckout({ + merchantName: 'Coffee Club', + recurring: { + description: 'Coffee Club membership', + managementUrl: 'https://example.com/account/membership', + trialBilling: { + label: 'Free trial', + amount: '0.00', + intervalUnit: 'day', + intervalCount: 7, + endDate: trialEnd, + }, + regularBilling: { + label: 'Coffee Club Monthly', + amount: '9.99', + intervalUnit: 'month', + }, + }, + }) +} +``` + +Call `startPayment()` from the returned object with the cart empty. The hook compares the config by value, `Date`s included, so an inline config is fine as long as its dates don't change. A date checked at render can pass while the screen stays open: the payment then fails with `code: 'CONFIGURATION'`, so build a new one when that matters, for example when the screen comes back into focus. + ## Rules `normalizePaymentRequest` checks these before the sheet opens. How a broken rule surfaces depends on what you call: -- `HybridPaymentHandler.startPayment` resolves with `status: 'failed'` and `code: 'CONFIGURATION'`, and the sheet doesn't open. +- `HybridPaymentHandler.startPayment` and the hook's `startPayment` resolve with `status: 'failed'` and `code: 'CONFIGURATION'`, and the sheet doesn't open. The hook also sets its `error`. - `normalizePaymentRequest` and `createPaymentRequest` throw an `Error`. Call them in a `try`/`catch`. The rules are the stricter of Apple Pay's and Google Pay's, so a request that passes works on both, with one exception below: diff --git a/docs/docs/payment-flow.md b/docs/docs/payment-flow.md index 29b9cb68..e4c38c81 100644 --- a/docs/docs/payment-flow.md +++ b/docs/docs/payment-flow.md @@ -99,7 +99,7 @@ A Google Pay error arrives either from `loadPaymentData` or as the sheet's `RESU ### Empty cart or invalid amounts (hook) -- Calling `startPayment()` with no cart items returns `status: 'failed'` with `code: 'CONFIGURATION'`, and sets a "Cart is empty" error with the same `code`. +- Calling `startPayment()` with no cart items returns `status: 'failed'` with `code: 'CONFIGURATION'`, and sets a "Cart is empty" error with the same `code`. With `recurring`, `deferred` or `automaticReload` in the config, an empty cart is allowed. - An invalid amount or a negative total also returns `code: 'CONFIGURATION'` and sets `error`, without opening the sheet. - Gate the pay button on `items.length > 0`. diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 49ab7e7e..5d51c498 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -4,7 +4,7 @@ Common issues and fixes for React Native Pay. ## Before you debug -- Ensure your cart is not empty. `startPayment()` fails with `code: 'CONFIGURATION'` and a "Cart is empty" error when `items.length === 0`. +- Ensure your cart is not empty. `startPayment()` fails with `code: 'CONFIGURATION'` and a "Cart is empty" error when `items.length === 0`, unless the config sets `recurring`, `deferred` or `automaticReload`. - Test on a real device whenever possible (simulator/emulator payment support is limited). - Re-run native generation after plugin changes: diff --git a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts index eba24a47..2962ad9e 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts @@ -20,7 +20,12 @@ import { } from '../usePaymentCheckout' import { PAYMENT_IN_PROGRESS_RESULT as IN_PROGRESS_RESULT } from '../../paymentHandler' import { PaymentError } from '../../errors' -import type { StartPaymentOptions } from '../../types' +import type { + AutomaticReloadPaymentRequest, + DeferredPaymentRequest, + RecurringPaymentRequest, + StartPaymentOptions, +} from '../../types' const CANCELLED_RESULT = { status: 'cancelled', @@ -29,6 +34,42 @@ const CANCELLED_RESULT = { error: 'Payment cancelled by user', } +const DAY = 24 * 60 * 60 * 1000 +const inDays = (days: number) => new Date(Date.now() + days * DAY) + +const subscription = (trialEnd: Date): RecurringPaymentRequest => ({ + description: 'Coffee Club membership', + managementUrl: 'https://example.com/membership', + trialBilling: { + label: 'Free trial', + amount: '0.00', + intervalUnit: 'day', + intervalCount: 7, + endDate: trialEnd, + }, + regularBilling: { + label: 'Coffee Club Monthly', + amount: '9.99', + intervalUnit: 'month', + }, +}) + +const booking = (date: Date): DeferredPaymentRequest => ({ + description: 'Seaside Hotel, 2 nights', + managementUrl: 'https://example.com/bookings', + deferredBilling: { label: 'Room', amount: '240.00', date }, +}) + +const topUp = (amount: string): AutomaticReloadPaymentRequest => ({ + description: 'Coffee card auto top-up', + managementUrl: 'https://example.com/card', + automaticReloadBilling: { + label: 'Coffee Card Top-Up', + amount, + thresholdAmount: '5.00', + }, +}) + function createDeferred() { let resolve!: (value: T) => void const promise = new Promise((res) => { @@ -150,6 +191,121 @@ describe('usePaymentCheckout integration', () => { expect(mockStartPayment).not.toHaveBeenCalled() }) + describe('later charges', () => { + it('starts a subscription with an empty cart', async () => { + mockStartPayment.mockResolvedValueOnce({ + status: 'success', + success: true, + }) + const trialEnd = inDays(7) + const { result } = renderWithConfig({ recurring: subscription(trialEnd) }) + + expect(result.current.paymentRequest.paymentItems).toEqual([]) + let paymentResult: any = null + await act(async () => { + paymentResult = await result.current.startPayment() + }) + + expect(paymentResult).toEqual({ status: 'success', success: true }) + expect(result.current.error).toBeNull() + expect(mockStartPayment).toHaveBeenCalledTimes(1) + const request = mockStartPayment.mock.calls[0][0] + expect(request.paymentItems).toEqual([]) + expect(request.recurring).toMatchObject({ + description: 'Coffee Club membership', + trialBilling: { + label: 'Free trial', + amount: '0.00', + endDate: trialEnd, + }, + regularBilling: { label: 'Coffee Club Monthly', amount: '9.99' }, + }) + expect(request.recurring.trialBilling.endDate).toBeInstanceOf(Date) + }) + + it.each([ + ['deferred', { deferred: booking(inDays(7)) }], + ['automaticReload', { automaticReload: topUp('25.00') }], + ] as const)( + 'starts a %s payment with an empty cart', + async (key, config) => { + mockStartPayment.mockResolvedValueOnce({ success: true }) + const { result } = renderWithConfig(config) + + await act(async () => { + await result.current.startPayment() + }) + + expect(mockStartPayment).toHaveBeenCalledWith( + expect.objectContaining({ + paymentItems: [], + [key]: expect.any(Object), + }) + ) + } + ) + + it('sends the cart as what is paid today', async () => { + mockStartPayment.mockResolvedValueOnce({ success: true }) + const { result } = renderWithConfig({ automaticReload: topUp('25.00') }) + act(() => { + result.current.addItem('Initial load', '25.00') + }) + + await act(async () => { + await result.current.startPayment() + }) + + expect(mockStartPayment).toHaveBeenCalledWith( + expect.objectContaining({ + paymentItems: [ + { label: 'Initial load', amount: '25.00', type: 'final' }, + ], + }) + ) + }) + + it('fails without opening the sheet when the request is invalid', async () => { + const { result } = renderWithConfig({ + recurring: subscription(inDays(7)), + deferred: booking(inDays(7)), + }) + + let paymentResult: any = null + await act(async () => { + paymentResult = await result.current.startPayment() + }) + + expect(paymentResult).toMatchObject({ + status: 'failed', + code: 'CONFIGURATION', + error: 'Set at most one of recurring, deferred and automaticReload', + }) + expect(result.current.error).toMatchObject({ code: 'CONFIGURATION' }) + expect(mockStartPayment).not.toHaveBeenCalled() + }) + + it('fails when a date has passed by the time the payer taps', async () => { + const { result } = renderWithConfig({ + deferred: booking(new Date(Date.now() - DAY)), + }) + + let paymentResult: any = null + await act(async () => { + paymentResult = await result.current.startPayment() + }) + + expect(paymentResult).toMatchObject({ + status: 'failed', + code: 'CONFIGURATION', + }) + expect(paymentResult.error).toMatch( + /^deferred\.deferredBilling\.date must be in the future/ + ) + expect(mockStartPayment).not.toHaveBeenCalled() + }) + }) + it('handles successful payments', async () => { const nativeSuccess = { status: 'success', success: true } mockStartPayment.mockResolvedValueOnce(nativeSuccess) @@ -658,6 +814,9 @@ describe('usePaymentCheckout integration', () => { emailRequired: [false, true], phoneNumberRequired: [false, true], couponCode: ['WELCOME', 'SAVE10'], + recurring: [subscription(inDays(7)), subscription(inDays(14))], + deferred: [booking(inDays(7)), booking(inDays(14))], + automaticReload: [topUp('25.00'), topUp('50.00')], } it.each(Object.entries(configChanges))( @@ -679,6 +838,30 @@ describe('usePaymentCheckout integration', () => { } ) + it('keeps the Date objects of the config', () => { + const trialEnd = inDays(7) + const { result, rerender } = renderWithConfig({ + recurring: subscription(trialEnd), + }) + const initial = result.current + expect( + initial.paymentRequest.recurring?.trialBilling?.endDate + ).toBeInstanceOf(Date) + + // Another Date at the same time is the same config. + rerender({ recurring: subscription(new Date(trialEnd.getTime())) }) + expect(result.current.paymentRequest).toBe(initial.paymentRequest) + expect(result.current.startPayment).toBe(initial.startPayment) + + const later = new Date(trialEnd.getTime() + 1) + rerender({ recurring: subscription(later) }) + expect(result.current.paymentRequest).not.toBe(initial.paymentRequest) + expect( + result.current.paymentRequest.recurring?.trialBilling?.endDate + ).toBe(later) + expect(result.current.startPayment).not.toBe(initial.startPayment) + }) + it('ignores the key order of googlePayTokenization', () => { const { result, rerender } = renderWithConfig({ googlePayTokenization: { type: 'direct', publicKey: 'key' }, diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index 304b96d5..7057e614 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -29,6 +29,9 @@ import type { PaymentDetails, PaymentErrorCode, StartPaymentOptions, + RecurringPaymentRequest, + DeferredPaymentRequest, + AutomaticReloadPaymentRequest, } from '../types' import { PaymentError } from '../errors' import { @@ -59,6 +62,17 @@ function sortObjectKeys(_key: string, value: unknown): unknown { return Object.fromEntries(entries) } +// Whether the payment charges again later, so its cart may be empty. +function hasLaterCharge( + request: Pick +): boolean { + return ( + request.recurring !== undefined || + request.deferred !== undefined || + request.automaticReload !== undefined + ) +} + // Wraps what a call threw, keeping its message and the original as `cause`. function toPaymentError( err: unknown, @@ -225,6 +239,29 @@ export interface UsePaymentCheckoutConfig */ couponCode?: string + /** + * A subscription, charged again later. Set at most one of `recurring`, + * `deferred` and `automaticReload`. With one of them, `items` stay what + * the payer pays today, and the cart may be empty, as in a free trial. + * Their `Date`s are compared by value: build them once, for example in a + * `useState` initializer, or a `Date` built on every render changes + * `paymentRequest` and `startPayment` on every render. See + * `PaymentRequest.recurring`. + */ + recurring?: RecurringPaymentRequest + + /** + * A payment charged later, on one date, such as a hotel booking. See + * `recurring` and `PaymentRequest.deferred`. + */ + deferred?: DeferredPaymentRequest + + /** + * A balance topped up whenever it runs low. See `recurring` and + * `PaymentRequest.automaticReload`. + */ + automaticReload?: AutomaticReloadPaymentRequest + /** * Called with the token after the user authorizes the payment. Charge it on * your server and resolve with the outcome; `startPayment` then resolves @@ -282,7 +319,8 @@ export interface UsePaymentCheckoutReturn { // Payment processing /** * Opens the payment sheet and resolves with the outcome. A payment that - * can't start, such as with an empty cart or an invalid amount, or whose + * can't start, such as with an empty cart (allowed with `recurring`, + * `deferred` or `automaticReload`) or an invalid amount, or whose * native call throws resolves with `status: 'failed'` and a `code`, and * sets `result` and `error` to match. A call while a payment is in flight * resolves with `code: 'IN_PROGRESS'` and leaves `result` and `error` to @@ -386,13 +424,16 @@ export function usePaymentCheckout( onShippingMethodChange, onPaymentMethodChange, onCouponCodeChange, + recurring, + deferred, + automaticReload, ...requestConfig } = config // Apps usually pass an inline config, which is new on every render, so // compare the rest of it by value, with the keys of every object sorted. A - // callback added to the config fails `satisfies` here: pull it out above, - // like `onAuthorize`. + // callback or a `Date` added to the config fails `satisfies` here: pull it + // out above, like `onAuthorize` or `recurring`. const requestConfigKey = JSON.stringify( requestConfig satisfies { readonly [key: string]: JsonValue }, sortObjectKeys @@ -402,6 +443,21 @@ export function usePaymentCheckout( [requestConfigKey] ) + // Compared by value too, but kept as passed: a JSON round trip would turn + // their `Date`s into strings. A `Date` is in the key as its ISO string. + const merchantTokensKey = JSON.stringify( + { recurring, deferred, automaticReload }, + sortObjectKeys + ) + const merchantTokens = useMemo< + Pick + >( + () => ({ recurring, deferred, automaticReload }), + // The objects of the render where the key last changed. + // eslint-disable-next-line react-hooks/exhaustive-deps + [merchantTokensKey] + ) + // The latest callbacks, so `startPayment` can stay stable when they change. const callbacks: StartPaymentOptions = { onAuthorize, @@ -455,13 +511,18 @@ export function usePaymentCheckout( couponCode, } = stableRequestConfig + // A later charge may leave nothing to pay today, as in a free trial. + const chargesLater = hasLaterCharge(merchantTokens) + return sanitizePaymentRequest({ countryCode, currencyCode, supportedNetworks, merchantCapabilities, paymentItems: - items.length > 0 ? items : [createPaymentItem('Total', 0, 'final')], + items.length > 0 || chargesLater + ? items + : [createPaymentItem('Total', 0, 'final')], applePayMerchantIdentifier, merchantName, totalLabel, @@ -479,8 +540,9 @@ export function usePaymentCheckout( emailRequired, phoneNumberRequired, couponCode, + ...merchantTokens, }) - }, [stableRequestConfig, items]) + }, [stableRequestConfig, merchantTokens, 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. @@ -598,7 +660,7 @@ export function usePaymentCheckout( return { ...PAYMENT_IN_PROGRESS_RESULT } } - if (items.length === 0) { + if (items.length === 0 && !hasLaterCharge(paymentRequest)) { return fail(new PaymentError('Cart is empty', 'CONFIGURATION')) }