Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .ai/specs/SPEC-001-2026-02-10-core-module-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,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
- `PaymentResult`: outcome envelope and token details. `status` is `'success' | 'cancelled' | 'failed'`; `code` (`PaymentErrorCode`: `CANCELLED`, `IN_PROGRESS`, `CONFIGURATION`, `NOT_AVAILABLE`, `PROVIDER_ERROR`, `UNKNOWN`) is set on every non-success result. Every native exit path of `startPayment` maps to one code; `success` and `error` stay for compatibility. `startPayment` resolves for every outcome and never rejects.
- `PayServiceStatus`: availability flags (`isSupported`, `hasActiveCard`)

Cross-layer contract rule:
Expand All @@ -70,7 +70,7 @@ Cross-layer contract rule:
Primary low-level contract:

- `payServiceStatus(options?: PayServiceStatusOptions): Promise<PayServiceStatus>`
- `startPayment(request: PaymentRequest): Promise<PaymentResult>`
- `startPayment(request: PaymentRequest, options?: StartPaymentOptions): Promise<PaymentResult>`
- `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)

Expand Down Expand Up @@ -149,6 +149,10 @@ Future migration policy:

## Changelog

### 2026-10-26

- Added `status` and `code` to `PaymentResult`. iOS reports every dismissal before authorization as `CANCELLED`, without the former 0.75 s "dismissed" heuristic. `transactionId` is deprecated, and `PaymentToken.transactionIdentifier` is optional: Android leaves it unset instead of generating one.

### 2026-10-23

- Added `isPaymentInProgress()` to the low-level contract. On iOS, `startPayment` now claims the single-payment slot on the calling thread, as Android already did, instead of on the main thread.
Expand Down
25 changes: 16 additions & 9 deletions .ai/specs/SPEC-002-2026-02-10-use-payment-checkout-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,26 +69,29 @@ Functional contract highlights:
2. During payment:
- `isProcessing` is set `true`
- previous `result`/`error` are cleared
3. On successful native return:
3. On successful native return (`status='success'`):
- `result` is set
- `error` remains `null`
4. On unsuccessful native return (`success=false`):
4. On a cancel (`status='cancelled'`, `code='CANCELLED'`):
- `result` is set
- `error` remains `null`
5. On a failed native return (`status='failed'`):
- `result` is set
- `error` is set from native error or fallback message
5. On thrown exception:
6. On thrown exception:
- `error` is set to normalized `Error`
- function returns `null`
6. On iOS merchant identifier resolution:
7. On iOS merchant identifier resolution:
- JavaScript config does not require a merchant identifier field for the default Apple Pay path.
- If `applePayMerchantIdentifier` is provided and not blank, native uses it as an explicit override.
- If the override is omitted, native resolves the first non-empty value from the app entitlement `com.apple.developer.in-app-payments`.
- If neither source yields a merchant identifier, native returns `success=false` with error `"No Apple Pay merchant identifier configured"`.
7. On Android Google Pay production validation:
- If neither source yields a merchant identifier, native returns `status='failed'`, `code='CONFIGURATION'` with error `"No Apple Pay merchant identifier configured"`.
8. On Android Google Pay production validation:
- `googlePayMerchantId` is written into `merchantInfo.merchantId` only for `googlePayEnvironment='PRODUCTION'`.
- In production, native validation requires non-blank `googlePayMerchantId`, `googlePayGateway`, and `googlePayGatewayMerchantId`.
- In non-production environments, the merchant ID may be omitted and gateway values fall back to native defaults.
8. `reset()` clears transient payment state but does not clear cart items.
9. When a payment is already in flight, `startPayment()` returns `{ success: false, error: 'A payment is already in progress' }` without calling native and without changing `isProcessing`, `result` or `error`:
9. `reset()` clears transient payment state but does not clear cart items.
10. When a payment is already in flight, `startPayment()` returns `{ status: 'failed', code: 'IN_PROGRESS', success: false, error: 'A payment is already in progress' }` without calling native and without changing `isProcessing`, `result` or `error`:
- A payment started by this hook instance is detected by the hook's own ref.
- A payment started by `HybridPaymentHandler.startPayment()` or another hook instance is detected by `PaymentHandler.isPaymentInProgress()`.
- This check runs before the empty-cart check. The native guard in `startPayment` stays the source of truth.
Expand All @@ -102,7 +105,7 @@ Recommended consumer pattern:
- Use `isCheckingStatus` for initial availability loading.
- 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.
- Use `error` for actionable feedback. It stays `null` on a cancel; use `result.status` and `result.code` to tell outcomes apart.

## Configuration

Expand Down Expand Up @@ -169,6 +172,10 @@ Future behavior changes must include:

## Changelog

### 2026-10-26

- Added contract 4 and renumbered the rest. Previous behavior: a cancel set `error` like any failure. New behavior: `PaymentResult` carries `status` and `code`, and a cancel leaves `error` as `null`. Contract 10 (formerly 9) now returns `code='IN_PROGRESS'`.

### 2026-10-23

- Added contract 9. Previous behavior: when `HybridPaymentHandler` or another hook had a payment in flight, `startPayment()` set `isProcessing`, cleared `result`/`error`, and then stored the native in-progress failure in them. New behavior: it checks `PaymentHandler.isPaymentInProgress()` first and leaves its state unchanged. No app-side updates are required.
Expand Down
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ All notable changes to this project are documented in this file.

### Added

- **`PaymentResult.status` and `PaymentResult.code` say how a payment ended.** `status` is
`'success'`, `'cancelled'` or `'failed'`. `code` is set on every other result: `'CANCELLED'`,
`'IN_PROGRESS'`, `'CONFIGURATION'` (missing merchant ID, invalid amount, Google Pay developer
error), `'NOT_AVAILABLE'` (the device can't show the sheet), `'PROVIDER_ERROR'` (Apple Pay, Google
Pay or `onAuthorize` failed, including the `onAuthorize` timeout) or `'UNKNOWN'`. Every native exit
path of `startPayment` maps to one of them, so apps no longer need to match `error` strings to
tell a cancel or a setup error from a decline. `success` and `error` stay as before. New types:
`PaymentStatus` and `PaymentErrorCode`.
- **`HybridPaymentHandler.isPaymentInProgress()`** synchronously returns whether a payment started
with `startPayment` (directly or by `usePaymentCheckout`) has not settled yet.
- **Billing and shipping addresses, email and phone number come back in the result.** Set
Expand Down Expand Up @@ -43,6 +51,20 @@ All notable changes to this project are documented in this file.

### Changed

- **`usePaymentCheckout` no longer treats a cancel as an error.** When the user closes the sheet,
the hook sets `result` to the cancelled result and leaves `error` as `null`, so UIs that render
`error` no longer show "Payment failed" for a cancel. Use `result.status` to tell the outcomes
apart. Failures still set `error`.
- **iOS: every close of the sheet before authorization is a cancel.** iOS used to report
`'Payment sheet was dismissed before authorization'` instead of `'Payment cancelled by user'`
when the sheet closed within 0.75 seconds of appearing. Both now report `status: 'cancelled'` and
`'Payment cancelled by user'`.
- **`PaymentResult` requires `status`.** Code that builds a `PaymentResult` itself, such as a test
mock of `startPayment`, needs to add it.
- **`PaymentToken.transactionIdentifier` is optional, and missing on Android.** Android used to
fill it with a random UUID generated on the device; Google Pay doesn't return a transaction
identifier. Code that reads it as a `string` no longer type-checks. If your server uses it as an
idempotency key, key idempotency on your order ID instead. On iOS it is still Apple's identifier.
- **`PaymentNetwork` has a new `'unknown'` value,** reported for a card on a network the library
cannot name. Both platforms used to report such cards as `'visa'`. Code that switches over
`token.paymentMethod.network` needs a case for it.
Expand Down Expand Up @@ -100,6 +122,12 @@ All notable changes to this project are documented in this file.
- **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.

### Deprecated

- **`PaymentResult.transactionId`.** It is a random ID generated on the device for each successful
result, not an identifier from Apple, Google or the gateway, and it changes on every attempt. The
docs no longer suggest it as an idempotency key; use your order ID. It is still set for now.

### Fixed

- **Android: `supportedNetworks` limits the cards the payer can choose.** Android ignored it and
Expand Down
60 changes: 37 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,21 +230,19 @@ function CheckoutScreen() {
const handlePay = async () => {
const result = await startPayment()

if (result?.success && result.token) {
if (result?.status === 'success' && result.token) {
// Send result.token to your server for processing
console.log('Payment successful:', result.transactionId)
console.log('Token:', result.token)

// Call your backend
await fetch('https://api.yourserver.com/process-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: result.token,
transactionId: result.transactionId,
orderId: 'order_123', // your order, also your idempotency key
}),
})
}
// 'cancelled': the user closed the sheet, and `error` stays null.
// 'failed': `error` is set, and `result.code` says why.
}

if (isCheckingStatus) {
Expand Down Expand Up @@ -416,8 +414,8 @@ interface UsePaymentCheckoutReturn {
// Payment processing
startPayment: () => Promise<PaymentResult | null>;
isProcessing: boolean; // Payment in progress?
result: PaymentResult | null; // Last payment result
error: Error | null; // Last error
result: PaymentResult | null; // Last payment result; check result.status
error: Error | null; // Last error; null after a cancel

// Utilities
reset: () => void; // Reset payment state
Expand Down Expand Up @@ -524,30 +522,34 @@ interface StartPaymentOptions {

interface PaymentAuthorizationResult {
status: "success" | "failure";
error?: string; // Becomes PaymentResult.error on failure
error?: string; // Becomes PaymentResult.error, with code "PROVIDER_ERROR", on failure
}
```

**Returns:**
**Returns** a promise that resolves for every outcome, including a cancel and an invalid request:

```typescript no-check
interface PaymentResult extends PaymentDetails {
success: boolean;
transactionId?: string;
status: "success" | "cancelled" | "failed";
code?: PaymentErrorCode; // Why it didn't succeed, see below
success: boolean; // status === "success"
transactionId?: string; // Deprecated: random, generated on the device
token?: PaymentToken;
error?: string;
error?: string; // Message for logs, also set on a cancel
}

interface PaymentToken {
paymentMethod: PaymentMethod;
transactionIdentifier: string;
transactionIdentifier?: string; // Apple's ID on iOS, missing on Android
paymentData: string; // Base64 encoded
}
```

A cancel has `status: "cancelled"` and `code: "CANCELLED"`; it is not an error. Any other outcome that isn't a success has `status: "failed"` and one of `IN_PROGRESS`, `CONFIGURATION`, `NOT_AVAILABLE`, `PROVIDER_ERROR` or `UNKNOWN`. Branch on `status` and `code`, not on `error`. The [error codes](https://gmi-software.github.io/react-native-pay/docs/payment-flow#error-codes) page says what each code means and which native cases produce it.

##### `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" }`.
Check whether a payment started with `startPayment` (directly or by `usePaymentCheckout`) has not settled yet. While it returns `true`, `startPayment` resolves with `{ status: "failed", code: "IN_PROGRESS" }` and the message `"A payment is already in progress"`.

```typescript
import { HybridPaymentHandler } from "@gmisoftware/react-native-pay";
Expand Down Expand Up @@ -781,17 +783,29 @@ interface PaymentRequest {
}

// Payment Result
type PaymentStatus = "success" | "cancelled" | "failed";

type PaymentErrorCode =
| "CANCELLED"
| "IN_PROGRESS"
| "CONFIGURATION"
| "NOT_AVAILABLE"
| "PROVIDER_ERROR"
| "UNKNOWN";

interface PaymentResult extends PaymentDetails {
success: boolean;
transactionId?: string;
status: PaymentStatus;
code?: PaymentErrorCode; // Set when status isn't "success"
success: boolean; // status === "success"
transactionId?: string; // Deprecated: random, generated on the device
token?: PaymentToken;
error?: string;
error?: string; // Message for logs, also set on a cancel
}

// Payment Token
interface PaymentToken {
paymentMethod: PaymentMethod;
transactionIdentifier: string;
transactionIdentifier?: string; // Apple's ID on iOS, missing on Android
paymentData: string; // Base64 encoded
}

Expand Down Expand Up @@ -977,16 +991,16 @@ const handlePayment = async () => {
try {
const result = await HybridPaymentHandler.startPayment(paymentRequest)

if (result.success && result.token) {
if (result.status === 'success' && result.token) {
// Send the token to your server
const response = await fetch('https://api.yourserver.com/process-payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: result.token }),
})
if (!response.ok) throw new Error('Payment processing failed')
} else {
console.error('Payment failed:', result.error)
} else if (result.status === 'failed') {
console.error('Payment failed:', result.code, result.error)
}
} catch (error) {
console.error('Payment error:', error)
Expand Down Expand Up @@ -1113,7 +1127,7 @@ function useOrderPayment() {

return async () => {
const result = await checkout.startPayment();
// result?.success reflects your server's answer
// result?.status is "success" only when your server approved
};
}
```
Expand Down
14 changes: 9 additions & 5 deletions docs/docs/api/hybrid-payment-handler.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,19 @@ const result = await HybridPaymentHandler.startPayment(

```ts no-check
interface PaymentResult extends PaymentDetails {
success: boolean
transactionId?: string
status: 'success' | 'cancelled' | 'failed'
code?: PaymentErrorCode // set when status isn't 'success'
success: boolean // status === 'success'
transactionId?: string // deprecated
token?: PaymentToken
error?: string
error?: string // message for logs, also set on a cancel
// From PaymentDetails, set only when requested:
// billingContact, shippingContact, emailAddress, phoneNumber, shippingMethod
}
```

The promise resolves for every outcome, including a cancel and a misconfigured request; it doesn't reject. Branch on `status` and `code`. See [Error codes](/docs/payment-flow#error-codes) for each code and [PaymentResult](/docs/api/types#paymentresult) for the fields.

**options.onAuthorize** charges the token before the Apple Pay sheet closes. The result follows your callback:

```ts no-check
Expand All @@ -88,13 +92,13 @@ On iOS, the Apple Pay sheet lists your `paymentItems` and then a total labelled

Build the request yourself or use [createPaymentRequest](/docs/api/utils#createpaymentrequestoptions) for a single line item with defaults.

Only one payment can be in flight at a time, on iOS and Android. A call made while another payment is still in progress, including one started by `usePaymentCheckout`, resolves immediately with `{ success: false, error: 'A payment is already in progress' }` and does not affect the payment in flight. A payment stays in flight until the native side settles it, right before its `startPayment` promise resolves. A new payment can start from that moment, even before your `await` continues. On iOS, the payment settles only after the Apple Pay sheet has closed. With `onAuthorize`, it also waits for your callback to settle or time out, so on iOS the payment ends once both have happened. Use [`isPaymentInProgress()`](#ispaymentinprogress) to check first.
Only one payment can be in flight at a time, on iOS and Android. A call made while another payment is still in progress, including one started by `usePaymentCheckout`, resolves immediately with `{ status: 'failed', code: 'IN_PROGRESS', success: false, error: 'A payment is already in progress' }` and does not affect the payment in flight. A payment stays in flight until the native side settles it, right before its `startPayment` promise resolves. A new payment can start from that moment, even before your `await` continues. On iOS, the payment settles only after the Apple Pay sheet has closed. With `onAuthorize`, it also waits for your callback to settle or time out, so on iOS the payment ends once both have happened. Use [`isPaymentInProgress()`](#ispaymentinprogress) to check first.

---

### isPaymentInProgress()

Synchronously returns whether a payment started with `startPayment` has not settled yet, including one started by `usePaymentCheckout`. While it returns `true`, `startPayment` resolves immediately with `{ success: false, error: 'A payment is already in progress' }`.
Synchronously returns whether a payment started with `startPayment` has not settled yet, including one started by `usePaymentCheckout`. While it returns `true`, `startPayment` resolves immediately with `code: 'IN_PROGRESS'`.

```ts
import { HybridPaymentHandler } from '@gmisoftware/react-native-pay'
Expand Down
Loading
Loading