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 4a8206d..e5eb4f5 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 @@ -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: @@ -70,7 +70,7 @@ Cross-layer contract rule: Primary low-level contract: - `payServiceStatus(options?: PayServiceStatusOptions): Promise` -- `startPayment(request: PaymentRequest): Promise` +- `startPayment(request: PaymentRequest, options?: StartPaymentOptions): 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) @@ -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. 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 1fbbd91..557fb89 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 @@ -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. @@ -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 @@ -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. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a5dae9..81c97f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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. @@ -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 diff --git a/README.md b/README.md index 5722da6..cf4ae24 100644 --- a/README.md +++ b/README.md @@ -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) { @@ -416,8 +414,8 @@ interface UsePaymentCheckoutReturn { // Payment processing startPayment: () => Promise; 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 @@ -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"; @@ -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 } @@ -977,7 +991,7 @@ 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', @@ -985,8 +999,8 @@ const handlePayment = async () => { 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) @@ -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 }; } ``` diff --git a/docs/docs/api/hybrid-payment-handler.md b/docs/docs/api/hybrid-payment-handler.md index ba16630..bca3ff1 100644 --- a/docs/docs/api/hybrid-payment-handler.md +++ b/docs/docs/api/hybrid-payment-handler.md @@ -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 @@ -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' diff --git a/docs/docs/api/types.md b/docs/docs/api/types.md index e68e27c..130786e 100644 --- a/docs/docs/api/types.md +++ b/docs/docs/api/types.md @@ -78,7 +78,7 @@ On iOS, `applePayMerchantIdentifier` is optional and only needed when you want t `merchantCapabilities` takes [`MerchantCapability`](#merchantcapability) values. -`supportedNetworks` takes [`PaymentNetwork`](#paymentnetwork) names, matched ignoring case, and limits the cards the payer can choose on both platforms. A name that is not a `PaymentNetwork` fails the payment, with an `error` that contains `Unknown payment network "". Use a PaymentNetwork value such as "visa" or "mastercard"`. A network the platform does not offer is left out, so one cross-platform list works: Android drops `cartesBancaires`, for example. The payment fails when no network is left. +`supportedNetworks` takes [`PaymentNetwork`](#paymentnetwork) names, matched ignoring case, and limits the cards the payer can choose on both platforms. A name that is not a `PaymentNetwork` fails the payment with `code: 'CONFIGURATION'` and an `error` that contains `Unknown payment network "". Use a PaymentNetwork value such as "visa" or "mastercard"`. A network the platform does not offer is left out, so one cross-platform list works: Android drops `cartesBancaires`, for example. The payment fails when no network is left. `googlePayAllowedAuthMethods` takes [`GooglePayAuthMethod`](#googlepayauthmethod) values and defaults to both. Android only. @@ -94,16 +94,34 @@ Returned from `startPayment()` (hook or handler). ```ts no-check interface PaymentResult extends PaymentDetails { - success: boolean - transactionId?: string + status: PaymentStatus // '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 } + +type PaymentStatus = 'success' | 'cancelled' | 'failed' + +type PaymentErrorCode = + | 'CANCELLED' + | 'IN_PROGRESS' + | 'CONFIGURATION' + | 'NOT_AVAILABLE' + | 'PROVIDER_ERROR' + | 'UNKNOWN' ``` -Send `token` (and optionally `transactionId`) to your backend to complete the charge with your gateway. A successful result also holds the contact details and shipping method the request asked for; see [PaymentDetails](#paymentdetails). +- **status** — `'cancelled'` means the user closed the sheet before authorizing. It is not an error: `usePaymentCheckout` leaves `error` as `null` for it. +- **code** — Why the payment didn't succeed. `'CANCELLED'` for a cancel, one of the others for a failure. See [Error codes](/docs/payment-flow#error-codes) for what each one means and which native cases produce it. +- **success** — Kept for compatibility. Use `status` to tell a cancel from a failure. +- **transactionId** — Deprecated. A random ID the device generates for each successful result; it doesn't come from Apple, Google or your gateway. Don't use it as an idempotency key: use your order ID. +- **token** — Set on success. Send it to your backend to complete the charge with your gateway, unless `onAuthorize` already did. +- **Contact details and shipping method** — A successful result also holds the ones the request asked for; see [PaymentDetails](#paymentdetails). +- **error** — A message for logs, such as `'Payment cancelled by user'`. Don't match on it; use `code`. --- @@ -121,7 +139,7 @@ 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 } ``` @@ -136,13 +154,13 @@ The token you send to your server. **Do not log or expose; treat as sensitive.** ```ts no-check interface PaymentToken { paymentMethod: PaymentMethod - transactionIdentifier: string + transactionIdentifier?: string paymentData: string // Opaque token payload (format depends on platform + gateway) } ``` - **paymentMethod** — Card/network and optional billing contact. -- **transactionIdentifier** — Unique id for this payment session. +- **transactionIdentifier** — On iOS, Apple's identifier for the payment (`PKPaymentToken.transactionIdentifier`), generated on the device. Missing on Android: Google Pay doesn't return one. Key idempotency on your order ID instead. - **paymentData** — Opaque payload for your gateway. - iOS: Base64-encoded Apple Pay token data. - Android: Google Pay tokenization payload (`tokenizationData.token`), gateway-dependent. @@ -257,7 +275,7 @@ type GooglePayAuthMethod = 'PAN_ONLY' | 'CRYPTOGRAM_3DS' - `'PAN_ONLY'` — Cards saved to the payer's Google account. The token holds the card number. - `'CRYPTOGRAM_3DS'` — Cards tokenized on the device. The token holds a 3-D Secure cryptogram. Google Pay does not offer `jcb` or `discover` with it. -The default is both. Pass `['CRYPTOGRAM_3DS']` when your gateway or Strong Customer Authentication requires device tokens. Android matches the values ignoring case, and any other value fails the payment, with an `error` that contains `Unknown Google Pay auth method "". Use "PAN_ONLY" or "CRYPTOGRAM_3DS"`. They are separate from `merchantCapabilities`: every Apple Pay card is a device token, so iOS has nothing like `'PAN_ONLY'`. +The default is both. Pass `['CRYPTOGRAM_3DS']` when your gateway or Strong Customer Authentication requires device tokens. Android matches the values ignoring case, and any other value fails the payment with `code: 'CONFIGURATION'` and an `error` that contains `Unknown Google Pay auth method "". Use "PAN_ONLY" or "CRYPTOGRAM_3DS"`. They are separate from `merchantCapabilities`: every Apple Pay card is a device token, so iOS has nothing like `'PAN_ONLY'`. --- @@ -272,7 +290,7 @@ type MerchantCapability = '3DS' | 'EMV' | 'Credit' | 'Debit' - `'3DS'` and `'EMV'` are Apple Pay payment protocols. PassKit needs at least one of them. EMV only covers China UnionPay, so every other card needs 3DS. Android ignores them. - `'Credit'` and `'Debit'` limit the accepted card types. -Both platforms match the values case-insensitively. Any other value fails the payment: the result has `success: false` and `error: 'Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"'`. +Both platforms match the values case-insensitively. Any other value fails the payment: the result has `code: 'CONFIGURATION'` and `error: 'Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"'`. iOS adds `'3DS'` when neither `'3DS'` nor `'EMV'` is given, so `[]` is sent as 3DS and `['Credit']` as 3DS + Credit. @@ -297,7 +315,7 @@ How Apple Pay labels the address, used in `PaymentRequest.shippingType` (iOS onl type ShippingType = 'shipping' | 'delivery' | 'storePickup' | 'servicePickup' ``` -For example, `'delivery'` shows "Delivery Address" instead of "Shipping Address". Without `shippingType`, Apple Pay uses `'shipping'`. Any other value fails the payment: the result has `success: false` and `error: 'Unknown shipping type "". Use "shipping", "delivery", "storePickup" or "servicePickup"'`. +For example, `'delivery'` shows "Delivery Address" instead of "Shipping Address". Without `shippingType`, Apple Pay uses `'shipping'`. Any other value fails the payment: the result has `code: 'CONFIGURATION'` and `error: 'Unknown shipping type "". Use "shipping", "delivery", "storePickup" or "servicePickup"'`. --- diff --git a/docs/docs/api/use-payment-checkout.md b/docs/docs/api/use-payment-checkout.md index aab4c5a..19b54d1 100644 --- a/docs/docs/api/use-payment-checkout.md +++ b/docs/docs/api/use-payment-checkout.md @@ -71,8 +71,8 @@ interface UsePaymentCheckoutReturn { // Payment startPayment: () => Promise isProcessing: boolean - result: PaymentResult | null - error: Error | null + result: PaymentResult | null // last result; check result.status + error: Error | null // null after a cancel // Utilities reset: () => void @@ -90,10 +90,12 @@ Which button to show for each combination is in [Check availability](/docs/guide - **startPayment()** — Opens the native sheet. Returns `Promise`. - Returns `null` and sets `error` when the cart is empty. - Returns `null` and sets `error`, without opening the sheet, when an amount is invalid or the total is negative (see [`PaymentAmount`](/docs/api/types#paymentamount)). - - Returns `PaymentResult` (including `{ success: false, error }`) when the native flow completes with a failure result. + - Returns the native `PaymentResult` when the sheet closes. Check `status` and `code` (see [Error codes](/docs/payment-flow#error-codes)). + - 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. + - Any other failure from the native flow returns `status: 'failed'` with its `code`, and sets `error` to an `Error` with the result's message. - Returns `null` if an exception is thrown while starting/processing the payment. - - With `onAuthorize`, resolves after your callback settles. A `'failure'` result becomes `{ success: false, error }` and sets `error`. - - Returns `{ success: false, error: 'A payment is already in progress' }` without opening a second sheet if a payment is still in flight, whether this hook, another `usePaymentCheckout` or [`HybridPaymentHandler`](/docs/api/hybrid-payment-handler) started it. `isProcessing`, `result` and `error` stay as they were. This check comes first, so it also applies when the cart is empty. + - With `onAuthorize`, resolves after your callback settles. A `'failure'` result becomes `{ status: 'failed', code: 'PROVIDER_ERROR', error }` and sets `error`. + - Returns `{ status: 'failed', code: 'IN_PROGRESS', success: false, error: 'A payment is already in progress' }` without opening a second sheet if a payment is still in flight, whether this hook, another `usePaymentCheckout` or [`HybridPaymentHandler`](/docs/api/hybrid-payment-handler) started it. `isProcessing`, `result` and `error` stay as they were. This check comes first, so it also applies when the cart is empty. - **paymentRequest** / **startPayment** — Keep their identity until a config value or the cart changes. The hook compares the config by value (arrays such as `supportedNetworks` by content), so an inline config object is fine, and both are safe as hook dependencies and props of memoized components. - **reset()** — Clears `result` and `error` (does not clear cart). It does not clear `isProcessing` while a payment is in flight; `isProcessing` becomes `false` when that payment settles. @@ -134,9 +136,11 @@ addItems([ ]) const result = await startPayment() -if (result?.success && result.token) { +if (result?.status === 'success' && result.token) { // Send result.token to your server } +// 'cancelled': the user closed the sheet; `error` stays null. +// 'failed': `error` is set, and result.code says why. ``` ## Empty cart diff --git a/docs/docs/examples.md b/docs/docs/examples.md index ef52eab..abee8f7 100644 --- a/docs/docs/examples.md +++ b/docs/docs/examples.md @@ -41,7 +41,7 @@ const handleAddCoffee = () => { const handlePayment = async () => { const paymentResult = await startPayment() - if (paymentResult?.success) { + if (paymentResult?.status === 'success') { reset() clearItems() } diff --git a/docs/docs/guides/contact-details.md b/docs/docs/guides/contact-details.md index eefa812..0339e92 100644 --- a/docs/docs/guides/contact-details.md +++ b/docs/docs/guides/contact-details.md @@ -49,7 +49,7 @@ function useShippedOrder() { return async () => { const result = await startPayment() - if (result?.success) { + if (result?.status === 'success') { console.log('Shipping to', result.shippingContact?.postalAddress?.city) } } @@ -102,7 +102,7 @@ async function payWithShipping() { }, }) - if (result.success) { + if (result.status === 'success') { console.log('Shipping with', result.shippingMethod?.label) } } @@ -111,7 +111,7 @@ async function payWithShipping() { - The selected method is shown as its own line, labelled with its `label`, and included in the total. The total is your `paymentItems` plus the method's `amount`. - The order matters. On iOS the first method is selected when the sheet opens, so put the default first. - `result.shippingMethod` and the second argument of `onAuthorize` hold the selected entry of `shippingMethods`, as you sent it. -- Every `identifier` must be non-empty and unique, no `amount` may be negative, and the `paymentItems` must not total less than zero on their own: shipping can't make up for a larger discount. Otherwise the payment fails before the sheet opens, with an error such as `Shipping method identifier "express" is used more than once`. +- Every `identifier` must be non-empty and unique, no `amount` may be negative, and the `paymentItems` must not total less than zero on their own: shipping can't make up for a larger discount. Otherwise the payment fails before the sheet opens, with `code: 'CONFIGURATION'` and an error such as `Shipping method identifier "express" is used more than once`. - **Android:** Google Pay can't offer a choice yet (see below), so Android charges the first method: it appears as a line item, is included in the total and is returned as `shippingMethod`. ## Platform differences diff --git a/docs/docs/guides/manual-flow.md b/docs/docs/guides/manual-flow.md index 7277fbc..5b2c31f 100644 --- a/docs/docs/guides/manual-flow.md +++ b/docs/docs/guides/manual-flow.md @@ -46,11 +46,12 @@ const paymentRequest = createPaymentRequest({ const handlePayment = async () => { try { const result = await HybridPaymentHandler.startPayment(paymentRequest) - if (result.success && result.token) { - await sendTokenToServer(result.token, result.transactionId) - } else { - console.error('Payment failed:', result.error) + if (result.status === 'success' && result.token) { + await sendTokenToServer(result.token, orderId) + } else if (result.status === 'failed') { + console.error('Payment failed:', result.code, result.error) } + // 'cancelled': the user closed the sheet, nothing to report } catch (err) { console.error('Payment error:', err) } diff --git a/docs/docs/guides/server-processing.md b/docs/docs/guides/server-processing.md index c339228..748f43e 100644 --- a/docs/docs/guides/server-processing.md +++ b/docs/docs/guides/server-processing.md @@ -1,15 +1,16 @@ # Server-side processing -After a successful payment, your app receives a **token** and optional **transactionId**. Your backend must use this token with your payment gateway (Stripe, Braintree, etc.) to create the charge. +After a successful payment (`result.status === 'success'`), your app receives a **token**. Your backend must use this token with your payment gateway (Stripe, Braintree, etc.) to create the charge. ## What to send to the server From the client, send at least: - **token** — The full `PaymentToken` object (or the fields your gateway needs). Treat as sensitive. -- **transactionId** — From `PaymentResult.transactionId`, for idempotency or logging. - **amount** (and currency) — So the server can validate and charge the correct amount. -- Any **order/cart id** — So the server knows what was purchased. +- Any **order/cart id** — So the server knows what was purchased, and as the base of your idempotency key. + +Don't key idempotency on `PaymentResult.transactionId` or `token.transactionIdentifier`. `transactionId` is deprecated: the device generates a new one for every successful result, so a retry gets a new key. `transactionIdentifier` is missing on Android. Example: @@ -34,13 +35,12 @@ function useOrderPayment() { // Pass this to the pay button's onPress, wrapped with callback(). return async () => { const result = await startPayment() - if (result?.success && result.token) { + if (result?.status === 'success' && result.token) { const response = await fetch('https://api.yourserver.com/process-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: result.token, - transactionId: result.transactionId, amount: total, currency: 'USD', orderId: order.id, @@ -88,7 +88,7 @@ function useOrderPayment() { return async () => { const result = await startPayment() - // result.success is true only when onAuthorize returned 'success'. + // result.status is 'success' only when onAuthorize returned 'success'. // The token is already charged, so don't send it to your server again. } } @@ -100,9 +100,9 @@ The second argument of `onAuthorize` holds the contact details and shipping meth How it behaves: -- **Failure:** `{ status: 'failure', error }` makes the sheet show the failure state. `startPayment` resolves with `success: false` and your `error`. A rejected promise is treated the same way. +- **Failure:** `{ status: 'failure', error }` makes the sheet show the failure state. `startPayment` resolves with `status: 'failed'`, `code: 'PROVIDER_ERROR'` and your `error`. A rejected promise is treated the same way. - **Retries on iOS:** if the user retries from the sheet after a failure or a timeout, `onAuthorize` runs again with the new token. The result reflects the last attempt. A retry can start while a timed-out charge is still running, so key idempotency on your order ID, not on the token. -- **Timeout:** `onAuthorize` must settle within 25 seconds (Apple Pay itself gives up after about 30). Otherwise the payment fails with "Payment authorization timed out" and the late result is ignored. Your server may still have charged the card, so make the charge idempotent and reconcile by order ID. +- **Timeout:** `onAuthorize` must settle within 25 seconds (Apple Pay itself gives up after about 30). Otherwise the payment fails with `code: 'PROVIDER_ERROR'` and "Payment authorization timed out", and the late result is ignored. Your server may still have charged the card, so make the charge idempotent and reconcile by order ID. - **Android:** Google Pay closes its sheet before it returns the token, and its basic flow has no step that waits for the merchant. `onAuthorize` still runs, with the same timeout, after the sheet closes, and its outcome decides the `PaymentResult`. The same callback works on both platforms. ## Example: Node.js (conceptual, gateway-specific) @@ -128,7 +128,7 @@ app.post('/process-payment', async (req, res) => { tokenPayload: token.paymentData, token: token, orderId, - transactionId: token.transactionIdentifier, + idempotencyKey: `charge-${orderId}`, }) res.json({ success: true, chargeId: charge.id }) @@ -142,7 +142,7 @@ app.post('/process-payment', async (req, res) => { - Mapping `PaymentToken` fields to provider-specific request fields. - Creating a payment method/source/intent from Apple Pay or Google Pay token payloads. -- Idempotency (e.g. using `transactionId` to avoid duplicate charges). +- Idempotency (e.g. a key derived from your order ID to avoid duplicate charges). - Handling failures and refunds. - Provider-specific walkthroughs in [Przelewy24 Apple Pay + Google Pay cookbook](/docs/integrations/przelewy24). diff --git a/docs/docs/guides/testing.md b/docs/docs/guides/testing.md index a5f445c..90ce3be 100644 --- a/docs/docs/guides/testing.md +++ b/docs/docs/guides/testing.md @@ -113,25 +113,24 @@ Run these flows on an iPhone and on an Android device before every release, with In your own app, use your server against your gateway's test mode, and your gateway's decline test cards or amounts for the decline flow. - [ ] **Success.** Pay with a test card. - - `startPayment` resolves with `success: true` and a `token`, and your server charges once. + - `startPayment` resolves with `status: 'success'` and a `token`, and your server charges once. - With `onAuthorize`, the Apple Pay sheet shows its checkmark only after your server answers. On Android, the Google Pay sheet closes first and `onAuthorize` runs after. - [ ] **User cancel.** Open the sheet and close it without paying. - - `startPayment` resolves with `success: false` and `error: 'Payment cancelled by user'`. Your server is not called. - - On iOS, a sheet closed within 0.75 seconds of appearing reports `'Payment sheet was dismissed before authorization'`. - - The hook also sets `error` for a cancel, so check that your UI doesn't show it as a failed payment. + - `startPayment` resolves with `status: 'cancelled'` and `code: 'CANCELLED'`. Your server is not called. + - The hook leaves `error` as `null`, so your UI shows no failure. - [ ] **Decline through `onAuthorize`.** Set the example app to `decline`, or make your server decline. - - On iOS, the sheet shows the failure and lets the user retry, which calls `onAuthorize` again with a new token. Closing the sheet resolves `startPayment` with `success: false` and your `error`. - - On Android, the sheet has already closed, and `startPayment` resolves with `success: false` and your `error`. + - On iOS, the sheet shows the failure and lets the user retry, which calls `onAuthorize` again with a new token. Closing the sheet resolves `startPayment` with `status: 'failed'`, `code: 'PROVIDER_ERROR'` and your `error`. + - On Android, the sheet has already closed, and `startPayment` resolves with `status: 'failed'`, `code: 'PROVIDER_ERROR'` and your `error`. - The order isn't marked paid, and a retry doesn't charge twice. Make the charge idempotent per order ID, not per token. - [ ] **Slow server.** Make your server take longer than 25 seconds to answer `onAuthorize`. - - `startPayment` resolves with `success: false` and `error: 'Payment authorization timed out'`. On iOS, the user can first retry from the sheet. + - `startPayment` resolves with `code: 'PROVIDER_ERROR'` and `error: 'Payment authorization timed out'`. On iOS, the user can first retry from the sheet. - Your server may still charge after the app has given up. Check that your backend can reconcile that order. - [ ] **Double tap.** Tap the pay button twice quickly. - - Only one sheet opens. The second call resolves at once with `success: false` and `error: 'A payment is already in progress'`, and the first payment settles normally. + - Only one sheet opens. The second call resolves at once with `code: 'IN_PROGRESS'`, and the first payment settles normally. - Your UI doesn't show the second result as a failed payment, and your server charges once. - [ ] **Backgrounding.** Open the sheet, go to the home screen, and return to the app. Repeat after switching to another app. - `startPayment` settles exactly once, `isProcessing` returns to `false`, and the next tap opens a new sheet. - - If the next payment reports `'A payment is already in progress'`, or the app stays in its processing state, [open an issue](https://github.com/gmi-software/react-native-pay/issues) with the platform and OS version. + - If the next payment reports `code: 'IN_PROGRESS'`, or the app stays in its processing state, [open an issue](https://github.com/gmi-software/react-native-pay/issues) with the platform and OS version. Then check the release configuration: diff --git a/docs/docs/integrations/przelewy24.md b/docs/docs/integrations/przelewy24.md index 137343b..1ce70e1 100644 --- a/docs/docs/integrations/przelewy24.md +++ b/docs/docs/integrations/przelewy24.md @@ -50,7 +50,7 @@ Implement a backend endpoint that: 1. App displays wallet button (`ApplePayButton` on iOS, `GooglePayButton` on Android). 2. User confirms payment in the native sheet. -3. App receives `PaymentResult` (`token`, `transactionId`). +3. App receives `PaymentResult` (`status`, `token`). 4. App sends token + amount/currency/order data to backend over HTTPS. 5. Backend calls Przelewy24 with platform-appropriate payload mapping. 6. Backend verifies final status and returns checkout result to the app. @@ -80,7 +80,7 @@ export function CheckoutWithPrzelewy24() { const onPayPress = async () => { const result = await startPayment() - if (!result?.success || !result.token) return + if (result?.status !== 'success' || !result.token) return await fetch('https://api.yourserver.com/payments/przelewy24/wallet', { method: 'POST', @@ -90,7 +90,6 @@ export function CheckoutWithPrzelewy24() { amount: 49.99, currency: 'PLN', orderId: 'order_123', - transactionId: result.transactionId ?? result.token.transactionIdentifier, token: result.token, }), }) @@ -127,8 +126,7 @@ export function CheckoutWithPrzelewy24() { Forward at least: - `token.paymentData` (opaque payload; token format is platform/provider-dependent) -- `token.transactionIdentifier` and/or `PaymentResult.transactionId` -- order/cart identifier +- order/cart identifier, which your backend also uses for idempotency - amount and currency - optional platform marker (`ios` / `android`) to simplify provider mapping @@ -140,7 +138,7 @@ Provider field mapping must remain server-side. Keep this as an internal adapter ```ts no-check app.post('/payments/przelewy24/wallet', async (req, res) => { - const {platform, token, amount, currency, orderId, transactionId} = req.body + const {platform, token, amount, currency, orderId} = req.body // 1) Validate amount/currency/order ownership server-side. // 2) Branch mapping by wallet platform. @@ -152,7 +150,8 @@ app.post('/payments/przelewy24/wallet', async (req, res) => { amountMinor: Math.round(amount * 100), currency, orderId, - idempotencyKey: transactionId ?? token?.transactionIdentifier, + // Not token.transactionIdentifier: it is missing on Android. + idempotencyKey: `wallet-${orderId}`, walletTokenPayload: token?.paymentData, rawToken: token, }) @@ -166,7 +165,7 @@ app.post('/payments/przelewy24/wallet', async (req, res) => { - Always use HTTPS between app and backend. - Never log raw token payloads. - Validate amount/currency/order ownership server-side. -- Use idempotency keys based on transaction identifiers. +- Use idempotency keys based on your order ID, not on `transactionId` or `token.transactionIdentifier`. - Treat provider callbacks/webhooks and verification as the source of final payment state. ## Notes diff --git a/docs/docs/payment-flow.md b/docs/docs/payment-flow.md index ca77044..5a577d3 100644 --- a/docs/docs/payment-flow.md +++ b/docs/docs/payment-flow.md @@ -11,7 +11,7 @@ At a minimum: 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`). +4. App receives `PaymentResult` (`status`, `code`, `token`). 5. Backend validates order context and charges through your provider. ## Runtime sequence @@ -27,15 +27,17 @@ sequenceDiagram App->>App: Build paymentRequest from cart App->>NativeSheet: startPayment(paymentRequest) User->>NativeSheet: Confirm or cancel - NativeSheet-->>App: PaymentResult(success, token, transactionId) + NativeSheet-->>App: PaymentResult(status, code, token) alt success with token App->>Backend: POST token + amount + currency + orderId Backend->>Backend: Validate order state and idempotency Backend->>Gateway: Create charge/intent using token Gateway-->>Backend: Authorized or failed Backend-->>App: Final checkout status - else cancelled or failed - App->>App: Show retry/cancel state + else status cancelled + App->>App: Stay on checkout, no error + else status failed + App->>App: Handle result.code end ``` @@ -43,27 +45,62 @@ sequenceDiagram With [`onAuthorize`](/docs/guides/server-processing#charge-before-the-sheet-closes), your backend charges the token before `startPayment` resolves: on iOS while the Apple Pay sheet is still up, on Android after the Google Pay sheet has closed. The result below already reflects the charge, so don't send `result.token` to your backend again. -### 1) Success +Every result has a `status`. When it isn't `'success'`, `code` says why: + +| `status` | `success` | `code` | What to do | +| --- | --- | --- | --- | +| `'success'` | `true` | none | Forward `result.token` to your backend, unless `onAuthorize` already charged it. Wait for your backend before marking the order paid. | +| `'cancelled'` | `false` | `'CANCELLED'` | The user closed the sheet. Leave the checkout as it was and don't show an error. | +| `'failed'` | `false` | any other code | See the table below. | + +Neither platform rejects the `startPayment` promise for these outcomes. `error` is a message for your logs, and it is also set on a cancel (`'Payment cancelled by user'`). Branch on `status` and `code`, not on the message. + +```ts +import type { PaymentResult } from '@gmisoftware/react-native-pay' + +function describeOutcome(result: PaymentResult): string | null { + switch (result.status) { + case 'success': + return null + case 'cancelled': + return null // the user closed the sheet + case 'failed': + switch (result.code) { + case 'IN_PROGRESS': + return null // the payment already in flight will settle + case 'NOT_AVAILABLE': + return 'Apple Pay / Google Pay is not available. Choose another payment method.' + case 'PROVIDER_ERROR': + return 'The payment did not go through. Try again or choose another payment method.' + default: + return 'Something went wrong. Please try again later.' + } + } +} +``` -- `result.success === true` -- `result.token` is present and should be forwarded to your backend. -- Your client should still wait for backend confirmation before marking the order paid. +### Error codes -### 2) Native flow completed but failed +| `code` | Meaning | Where it comes from | What to do | +| --- | --- | --- | --- | +| `'CANCELLED'` | The sheet closed before the user authorized. | iOS: the sheet closed without an authorization. PassKit doesn't say why, so a sheet that closes by itself also reports a cancel (see [Troubleshooting](/docs/troubleshooting#the-apple-pay-sheet-closes-right-away)). Android: the sheet returned `RESULT_CANCELED`, also when the user dismisses Google's sign-in prompt, or a Google Pay error has `CANCELED` / `ERROR_CODE_USER_CANCELLED`. | Nothing. Don't show an error. | +| `'IN_PROGRESS'` | Another payment is still in flight. No sheet was shown. | Both: `startPayment` called while a payment hasn't settled (see [`isPaymentInProgress()`](/docs/api/hybrid-payment-handler#ispaymentinprogress)). | Ignore it. The payment in flight settles normally. | +| `'CONFIGURATION'` | The request or the app's setup is invalid. Retrying won't help. | Both: an invalid amount, a negative total, an unknown merchant capability, invalid `shippingMethods`, and `supportedNetworks` that is empty, has an unknown name or has no network the platform offers. iOS: no Apple Pay merchant ID, an unknown `shippingType`. Android: more than two decimal places, an unknown `googlePayAllowedAuthMethods` value, `PRODUCTION` without `googlePayMerchantId`, `googlePayGateway` or `googlePayGatewayMerchantId`, and a Google Pay error with `DEVELOPER_ERROR`, `ERROR_CODE_INVALID_PARAMETERS`, `ERROR_CODE_MERCHANT_ACCOUNT_ERROR` or `ERROR_CODE_UNSUPPORTED_API_VERSION`. | Fix the request or the setup; `error` says what is wrong. Show the user a generic error. | +| `'NOT_AVAILABLE'` | The device can't show the payment sheet right now. | iOS: PassKit can't create the sheet, which Apple documents for a user who can't pay with any of the request's networks, or there is no active window to present it from. Android: no current activity, the Google Pay sheet fails to start, and a Google Pay error with `SIGN_IN_REQUIRED`, `API_NOT_CONNECTED`, `ERROR_CODE_BUYER_ACCOUNT_ERROR` or `ERROR_CODE_AUTHENTICATION_FAILURE`. | Offer another payment method. Show the pay button only as [Check availability](/docs/guides/availability#show-the-right-button) describes, from `isSupported` and `hasActiveCard`. | +| `'PROVIDER_ERROR'` | Apple Pay, Google Pay or your `onAuthorize` reported a failure. | Both: [`onAuthorize`](/docs/guides/server-processing#charge-before-the-sheet-closes) resolved with `'failure'`, rejected, or didn't settle within 25 seconds. Android: any other Google Pay error, such as a network or internal error, and payment data that is missing or can't be read. | Let the user retry or choose another payment method. After a timeout, your server may still have charged: reconcile the order. | +| `'UNKNOWN'` | Anything else. | iOS: an unexpected error while starting the payment. Android: an unexpected result code or exception, or a Google Pay error without a status. | Show a generic error and log `error`. | -- `result.success === false` with `result.error`. -- Treat this as a completed wallet flow with a failed outcome (not a thrown exception). -- Show a recoverable UI (retry, choose another method). +A Google Pay error arrives either from `loadPaymentData` or as the sheet's `RESULT_ERROR`; both are mapped the same way, and its status code is added to `error`, for example `Payment error: (status code 10)`. -### 3) Start/processing exception +### Start/processing exception (hook) -- `startPayment()` may return `null` when an exception occurs. -- The hook also sets `error` in state. +- `startPayment()` from `usePaymentCheckout` returns `null` when an exception occurs, and sets `error`. - Handle this as an app/runtime failure path (show generic error + retry). -### 4) Empty cart +### Empty cart or invalid amounts (hook) - Calling `startPayment()` with no cart items returns `null` and sets a "Cart is empty" error. +- An invalid amount or a negative total also returns `null` and sets `error`, without opening the sheet. - Gate the pay button on `items.length > 0`. ## Token format @@ -80,7 +117,7 @@ Always send the **entire token object** (or exactly the fields your gateway asks Your backend should: - Validate order ownership, amount, and currency from server-side order data. -- Use an idempotency key (for example `transactionId` + `orderId`) to prevent duplicate charges. +- Use an idempotency key derived from your order ID to prevent duplicate charges. Don't use `PaymentResult.transactionId`: the device generates a new one for every result. - Call gateway APIs with the provider-specific token mapping. - Persist both wallet result and gateway result for audit/debug. - Return a final, app-friendly checkout status. diff --git a/docs/docs/quick-start.md b/docs/docs/quick-start.md index f2f7dd4..655a5b5 100644 --- a/docs/docs/quick-start.md +++ b/docs/docs/quick-start.md @@ -75,14 +75,14 @@ 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 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 }), }) } diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index ff42f8f..16f4336 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -12,6 +12,13 @@ Common issues and fixes for React Native Pay. npx expo prebuild --clean ``` +## Reading a failed payment + +`startPayment` doesn't throw for a declined, cancelled or misconfigured payment. It resolves with a `PaymentResult` whose `status` and `code` say how it ended; [Error codes](/docs/payment-flow#error-codes) explains each code. When debugging: + +- Read `error`: it names the problem, and on Android it ends with Google Pay's status code. Branch on `code` in your app, though: the text may change. +- A `'CANCELLED'` you didn't cause by closing the sheet usually points to setup. See [The Apple Pay sheet closes right away](#the-apple-pay-sheet-closes-right-away) and [Cancelled on a device without a Google account](#cancelled-on-a-device-without-a-google-account). + ## iOS (Apple Pay) ### App crashes at launch with `folly dynamic.cpp:378 Check failed: 0` @@ -39,9 +46,18 @@ npx expo prebuild --clean - Confirm the App ID has Apple Pay enabled and linked to your Merchant ID. - For production, ensure your Payment Processing Certificate is created and installed in your gateway. +### The Apple Pay sheet closes right away + +`startPayment` resolves with `status: 'cancelled'` whenever the sheet closes before the user authorizes. PassKit doesn't tell the app why the sheet closed, so a sheet that closes by itself, or barely appears, reports the same cancel. One reported cause is a merchant ID that Apple Pay isn't set up for: + +- The merchant ID in the request, or the first one in your app's entitlements, must be listed under the **Apple Pay Payment Processing** capability in Xcode and in your App ID. +- Rebuild after changing the Expo plugin's `merchantIdentifier`: `npx expo prebuild --clean`. + +See [Apple Pay button not showing](#apple-pay-button-not-showing) for the full checklist. + ### "Unknown merchant capability" -The payment fails with `Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"` when `merchantCapabilities` contains any other value, on Android too. Case doesn't matter (`'3ds'` works). See [MerchantCapability](/docs/api/types#merchantcapability). +The payment fails with `code: 'CONFIGURATION'` and `Unknown merchant capability "". Use "3DS", "EMV", "Credit" or "Debit"` when `merchantCapabilities` contains any other value, on Android too. Case doesn't matter (`'3ds'` works). See [MerchantCapability](/docs/api/types#merchantcapability). ### Invalid Apple button type/style errors @@ -68,6 +84,20 @@ Use only supported Apple button values: 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). +### Cancelled on a device without a Google account + +Google Pay asks the user to sign in to a Google account before it shows the sheet. Dismissing that prompt returns the same result as closing the sheet, so `startPayment` resolves with `status: 'cancelled'`. Sign in to a Google account on the device or emulator, and add a card to it. + +### `CONFIGURATION` from Google Pay + +When Google Pay reports a setup problem, such as `DEVELOPER_ERROR`, the result has `code: 'CONFIGURATION'` and Google's status code at the end of `error` (for example `(status code 10)`). Google logs the details of merchant setup problems to logcat: + +```bash +adb logcat -s WalletMerchantError +``` + +The `OR_BIBED_*` codes there are explained on Google's [troubleshooting page](https://developers.google.com/pay/api/android/support/troubleshooting), such as `OR_BIBED_06` for the `example` gateway in production. + ### Manifest/build issues - Run `npx expo prebuild --clean` and rebuild. diff --git a/example/app/(tabs)/index.tsx b/example/app/(tabs)/index.tsx index 841babd..52a8833 100644 --- a/example/app/(tabs)/index.tsx +++ b/example/app/(tabs)/index.tsx @@ -126,11 +126,11 @@ export default function TabOneScreen() { const handlePayment = async () => { const paymentResult = await startPayment(); - if (paymentResult?.success) { + if (paymentResult?.status === "success") { console.log("Payment successful:", paymentResult.token); Alert.alert( "Payment Successful!", - `Transaction ID: ${paymentResult.transactionId}`, + `Paid with ${paymentResult.token?.paymentMethod.displayName ?? "your card"}`, [ { text: "OK", @@ -141,9 +141,17 @@ export default function TabOneScreen() { }, ], ); - } else if (paymentResult?.error) { - Alert.alert("Payment Failed", paymentResult.error, [{ text: "OK" }]); + } else if ( + paymentResult?.status === "failed" && + paymentResult.code !== "IN_PROGRESS" + ) { + Alert.alert( + "Payment Failed", + `${paymentResult.error} (${paymentResult.code})`, + [{ text: "OK" }], + ); } + // "cancelled": the user closed the sheet, so there is nothing to report. }; return ( @@ -274,17 +282,17 @@ export default function TabOneScreen() { )} - {result?.success && ( + {result?.status === "success" && ( ✅ Payment Successful! - Transaction: {result.transactionId} + Paid with {result.token?.paymentMethod.displayName ?? "your card"} )} {/* Payment Button */} - {items.length > 0 && !result?.success && isSupported && ( + {items.length > 0 && result?.status !== "success" && isSupported && ( Complete Payment {isProcessing ? ( 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 50d55b3..d4c8b7a 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,6 +46,7 @@ object PaymentConstants { // Errors (keep in sync with iOS `ErrorMessage`) const val ERROR_PAYMENT_IN_PROGRESS = "A payment is already in progress" const val ERROR_NO_ACTIVITY = "No activity available to show payment UI" + const val ERROR_PAYMENT_CANCELLED = "Payment cancelled by user" // Logging tags const val TAG_PAYMENT_HANDLER = "HybridPaymentHandler" 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 ae75615..1d58d4c 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 @@ -111,7 +111,12 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { // promise still settles and no second Google Pay sheet is requested. if (!pendingPayment.tryBegin { result -> promise.resolve(result) }) { PayLog.w(PaymentConstants.TAG_PAYMENT_HANDLER, PaymentConstants.ERROR_PAYMENT_IN_PROGRESS) - promise.resolve(PaymentMapper.createErrorResult(PaymentConstants.ERROR_PAYMENT_IN_PROGRESS)) + promise.resolve( + PaymentMapper.createErrorResult( + PaymentErrorCode.IN_PROGRESS, + PaymentConstants.ERROR_PAYMENT_IN_PROGRESS + ) + ) return promise } onAuthorize = options?.onAuthorize @@ -120,11 +125,18 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { try { val environment = determineEnvironment(request.googlePayEnvironment) - val paymentDataRequest = GooglePayRequestBuilder.createPaymentDataRequest( - request, - environment, - fallbackMerchantName = appLabel() - ) + val paymentDataRequest = try { + GooglePayRequestBuilder.createPaymentDataRequest( + request, + environment, + fallbackMerchantName = appLabel() + ) + } catch (e: IllegalArgumentException) { + // The builder's validation: only this call reports a configuration error. + PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Invalid payment request", e) + handlePaymentError(PaymentErrorCode.CONFIGURATION, "Failed to start payment: ${e.message}") + return promise + } logPaymentRequest(paymentDataRequest, environment) @@ -132,7 +144,7 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { } catch (e: Exception) { PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Failed to start payment", e) - handlePaymentError("Failed to start payment: ${e.message}") + handlePaymentError(PaymentErrorCode.UNKNOWN, "Failed to start payment: ${e.message}") } return promise @@ -160,7 +172,10 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { when (val error = task.exception) { is ResolvableApiException -> showPaymentSheet(error) is ApiException -> handleWalletError(error.status) - else -> handlePaymentError("Payment error: ${error?.message ?: "Unknown error"}") + else -> handlePaymentError( + PaymentErrorCode.UNKNOWN, + "Payment error: ${error?.message ?: "Unknown error"}" + ) } } } @@ -168,7 +183,7 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { private fun showPaymentSheet(sheet: ResolvableApiException) { val activity = reactContext.currentActivity if (activity == null) { - handlePaymentError(PaymentConstants.ERROR_NO_ACTIVITY) + handlePaymentError(PaymentErrorCode.NOT_AVAILABLE, PaymentConstants.ERROR_NO_ACTIVITY) return } @@ -180,7 +195,7 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { // Outside startPayment's try, so settle here instead of crashing. stopListeningForSheetResult() PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Failed to show payment UI", e) - handlePaymentError("Failed to show payment UI: ${e.message}") + handlePaymentError(PaymentErrorCode.NOT_AVAILABLE, "Failed to show payment UI: ${e.message}") } } @@ -195,17 +210,21 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { PaymentData.getFromIntent(it)?.let { paymentData -> handlePaymentSuccess(paymentData) } - } ?: handlePaymentError("No payment data received") + } ?: handlePaymentError(PaymentErrorCode.PROVIDER_ERROR, "No payment data received") } Activity.RESULT_CANCELED -> { - PayLog.d(PaymentConstants.TAG_PAYMENT_HANDLER, "Payment cancelled by user") - handlePaymentError("Payment cancelled by user") + // Also returned when the user dismisses Google's sign-in prompt. + PayLog.d(PaymentConstants.TAG_PAYMENT_HANDLER, PaymentConstants.ERROR_PAYMENT_CANCELLED) + handlePaymentError(PaymentErrorCode.CANCELLED, PaymentConstants.ERROR_PAYMENT_CANCELLED) } AutoResolveHelper.RESULT_ERROR -> { handleWalletError(data?.let { AutoResolveHelper.getStatusFromIntent(it) }) } else -> { - handlePaymentError("Payment failed with result code: $resultCode") + handlePaymentError( + PaymentErrorCode.UNKNOWN, + "Payment failed with result code: $resultCode" + ) } } } @@ -281,15 +300,13 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { authorizePayment(authorize, token, result) } - private fun handlePaymentError(errorMessage: String) { - val result = PaymentMapper.createErrorResult(errorMessage) - settlePayment(result) + private fun handlePaymentError(code: PaymentErrorCode, errorMessage: String) { + settlePayment(PaymentMapper.createErrorResult(code, errorMessage)) } private fun handleWalletError(status: Status?) { - val message = status?.statusMessage ?: "Unknown error" - PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Payment error: $message") - handlePaymentError("Payment error: $message") + PayLog.e(PaymentConstants.TAG_PAYMENT_HANDLER, "Payment error ${status?.statusCode}: ${status?.statusMessage}") + settlePayment(PaymentMapper.walletErrorResult(status?.statusCode, status?.statusMessage)) } private fun settlePayment(result: PaymentResult) { @@ -325,13 +342,19 @@ class HybridPaymentHandler : HybridPaymentHandlerSpec() { val settleWithError = { error: Throwable -> settleOnMain( PaymentMapper.createErrorResult( + PaymentErrorCode.PROVIDER_ERROR, error.message ?: PaymentConstants.ERROR_AUTHORIZATION_FAILED ) ) } mainHandler.postDelayed({ - settle(PaymentMapper.createErrorResult(PaymentConstants.ERROR_AUTHORIZATION_TIMED_OUT)) + settle( + PaymentMapper.createErrorResult( + PaymentErrorCode.PROVIDER_ERROR, + PaymentConstants.ERROR_AUTHORIZATION_TIMED_OUT + ) + ) }, PaymentConstants.AUTHORIZATION_TIMEOUT_MS) try { diff --git a/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt b/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt index 568026f..10dd132 100644 --- a/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt +++ b/package/android/src/main/java/com/margelo/nitro/pay/PaymentMapper.kt @@ -1,6 +1,8 @@ package com.margelo.nitro.pay +import com.google.android.gms.common.api.CommonStatusCodes import com.google.android.gms.wallet.PaymentData +import com.google.android.gms.wallet.WalletConstants import org.json.JSONException import org.json.JSONObject import java.util.UUID @@ -46,7 +48,8 @@ object PaymentMapper { // Create payment token val paymentToken = PaymentToken( paymentMethod = paymentMethod, - transactionIdentifier = UUID.randomUUID().toString(), + // Google Pay doesn't return a transaction identifier. + transactionIdentifier = null, paymentData = token ) @@ -54,6 +57,8 @@ object PaymentMapper { // Create successful result PaymentResult( + status = PaymentStatus.SUCCESS, + code = null, success = true, transactionId = UUID.randomUUID().toString(), token = paymentToken, @@ -65,7 +70,10 @@ object PaymentMapper { shippingMethod = details.shippingMethod ) } catch (e: JSONException) { - createErrorResult("Failed to parse payment data: ${e.message}") + createErrorResult( + PaymentErrorCode.PROVIDER_ERROR, + "Failed to parse payment data: ${e.message}" + ) } } @@ -158,16 +166,19 @@ object PaymentMapper { return when (authorization.status) { PaymentAuthorizationStatus.SUCCESS -> authorizedResult PaymentAuthorizationStatus.FAILURE -> createErrorResult( + PaymentErrorCode.PROVIDER_ERROR, authorization.error ?: PaymentConstants.ERROR_AUTHORIZATION_FAILED ) } } /** - * Creates an error PaymentResult + * Creates the PaymentResult of a payment that ended without success */ - fun createErrorResult(errorMessage: String): PaymentResult { + fun createErrorResult(code: PaymentErrorCode, errorMessage: String): PaymentResult { return PaymentResult( + status = if (code == PaymentErrorCode.CANCELLED) PaymentStatus.CANCELLED else PaymentStatus.FAILED, + code = code, success = false, transactionId = null, token = null, @@ -179,6 +190,42 @@ object PaymentMapper { shippingMethod = null ) } + + /** + * The result of a Google Pay error, from a failed `loadPaymentData` task or the + * sheet's `RESULT_ERROR` + */ + fun walletErrorResult(statusCode: Int?, statusMessage: String?): PaymentResult { + val message = statusMessage ?: "Unknown error" + return createErrorResult( + mapWalletErrorCode(statusCode), + if (statusCode == null) "Payment error: $message" + else "Payment error: $message (status code $statusCode)" + ) + } + + /** + * Maps a Google Pay status code, a `WalletConstants.ERROR_CODE_*` or + * `CommonStatusCodes` value, to an error code. + * Keep in sync with the table in docs/docs/payment-flow.md#error-codes. + */ + fun mapWalletErrorCode(statusCode: Int?): PaymentErrorCode { + return when (statusCode) { + null -> PaymentErrorCode.UNKNOWN + CommonStatusCodes.DEVELOPER_ERROR, + WalletConstants.ERROR_CODE_INVALID_PARAMETERS, + WalletConstants.ERROR_CODE_MERCHANT_ACCOUNT_ERROR, + WalletConstants.ERROR_CODE_UNSUPPORTED_API_VERSION -> PaymentErrorCode.CONFIGURATION + CommonStatusCodes.SIGN_IN_REQUIRED, + CommonStatusCodes.API_NOT_CONNECTED, + WalletConstants.ERROR_CODE_BUYER_ACCOUNT_ERROR, + WalletConstants.ERROR_CODE_AUTHENTICATION_FAILURE -> PaymentErrorCode.NOT_AVAILABLE + CommonStatusCodes.CANCELED, + WalletConstants.ERROR_CODE_USER_CANCELLED -> PaymentErrorCode.CANCELLED + // Includes SERVICE_UNAVAILABLE, NETWORK_ERROR and INTERNAL_ERROR. + else -> PaymentErrorCode.PROVIDER_ERROR + } + } } diff --git a/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt index 15dd1e1..e001f81 100644 --- a/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt +++ b/package/android/src/test/java/com/margelo/nitro/pay/PaymentMapperTest.kt @@ -1,6 +1,8 @@ package com.margelo.nitro.pay +import com.google.android.gms.common.api.CommonStatusCodes import com.google.android.gms.wallet.PaymentData +import com.google.android.gms.wallet.WalletConstants import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull @@ -15,6 +17,8 @@ class PaymentMapperTest { PaymentData.fromJson("""{"apiVersion":2,"apiVersionMinor":0,"paymentMethodData":$paymentMethodData}""") private fun authorizedResult() = PaymentResult( + status = PaymentStatus.SUCCESS, + code = null, success = true, transactionId = "transaction", token = null, @@ -79,11 +83,15 @@ class PaymentMapperTest { ) ) + assertEquals(PaymentStatus.SUCCESS, result.status) + assertNull(result.code) assertTrue(result.success) assertNull(result.error) assertNotNull(result.transactionId) val token = result.token!! assertEquals("gateway-token", token.paymentData) + // Google Pay returns no transaction identifier; don't invent one. + assertNull(token.transactionIdentifier) assertEquals("MASTERCARD 4242", token.paymentMethod.displayName) assertEquals(PaymentNetwork.MASTERCARD, token.paymentMethod.network) assertEquals(PaymentMethodType.CREDIT, token.paymentMethod.type) @@ -144,6 +152,8 @@ class PaymentMapperTest { paymentData("""{"info": {"cardNetwork": "VISA", "cardDetails": "4242"}}""") ) + assertEquals(PaymentStatus.FAILED, result.status) + assertEquals(PaymentErrorCode.PROVIDER_ERROR, result.code) assertFalse(result.success) assertNull(result.token) assertTrue(result.error!!.startsWith("Failed to parse payment data:")) @@ -412,7 +422,10 @@ class PaymentMapperTest { authorizedResult() ) - assertEquals(PaymentMapper.createErrorResult("Card declined"), result) + assertEquals( + PaymentMapper.createErrorResult(PaymentErrorCode.PROVIDER_ERROR, "Card declined"), + result + ) } @Test @@ -425,6 +438,116 @@ class PaymentMapperTest { assertFalse(result.success) assertNull(result.transactionId) assertNull(result.token) + assertEquals(PaymentErrorCode.PROVIDER_ERROR, result.code) assertEquals(PaymentConstants.ERROR_AUTHORIZATION_FAILED, result.error) } + + @Test + fun createErrorResult_reportsACancelAsCancelled() { + val result = PaymentMapper.createErrorResult( + PaymentErrorCode.CANCELLED, + PaymentConstants.ERROR_PAYMENT_CANCELLED + ) + + assertEquals(PaymentStatus.CANCELLED, result.status) + assertEquals(PaymentErrorCode.CANCELLED, result.code) + assertFalse(result.success) + assertEquals("Payment cancelled by user", result.error) + } + + @Test + fun createErrorResult_reportsEveryOtherCodeAsFailed() { + PaymentErrorCode.values() + .filter { it != PaymentErrorCode.CANCELLED } + .forEach { code -> + val result = PaymentMapper.createErrorResult(code, "message") + + assertEquals(code.name, PaymentStatus.FAILED, result.status) + assertEquals(code, result.code) + assertFalse(result.success) + assertNull(result.token) + assertNull(result.transactionId) + } + } + + @Test + fun mapWalletErrorCode_reportsMerchantSetupErrorsAsConfiguration() { + listOf( + CommonStatusCodes.DEVELOPER_ERROR, + WalletConstants.ERROR_CODE_INVALID_PARAMETERS, + WalletConstants.ERROR_CODE_MERCHANT_ACCOUNT_ERROR, + WalletConstants.ERROR_CODE_UNSUPPORTED_API_VERSION, + ).forEach { + assertEquals("$it", PaymentErrorCode.CONFIGURATION, PaymentMapper.mapWalletErrorCode(it)) + } + } + + @Test + fun mapWalletErrorCode_reportsBuyerAndDeviceErrorsAsNotAvailable() { + listOf( + CommonStatusCodes.SIGN_IN_REQUIRED, + CommonStatusCodes.API_NOT_CONNECTED, + WalletConstants.ERROR_CODE_BUYER_ACCOUNT_ERROR, + WalletConstants.ERROR_CODE_AUTHENTICATION_FAILURE, + ).forEach { + assertEquals("$it", PaymentErrorCode.NOT_AVAILABLE, PaymentMapper.mapWalletErrorCode(it)) + } + } + + @Test + fun mapWalletErrorCode_reportsCancelsAsCancelled() { + assertEquals( + PaymentErrorCode.CANCELLED, + PaymentMapper.mapWalletErrorCode(CommonStatusCodes.CANCELED) + ) + assertEquals( + PaymentErrorCode.CANCELLED, + PaymentMapper.mapWalletErrorCode(WalletConstants.ERROR_CODE_USER_CANCELLED) + ) + } + + @Test + fun mapWalletErrorCode_reportsOtherGooglePayErrorsAsProviderErrors() { + listOf( + CommonStatusCodes.NETWORK_ERROR, + CommonStatusCodes.INTERNAL_ERROR, + WalletConstants.ERROR_CODE_SERVICE_UNAVAILABLE, + WalletConstants.ERROR_CODE_UNKNOWN, + ).forEach { + assertEquals("$it", PaymentErrorCode.PROVIDER_ERROR, PaymentMapper.mapWalletErrorCode(it)) + } + } + + @Test + fun walletErrorResult_addsTheStatusCodeToTheMessage() { + val result = PaymentMapper.walletErrorResult( + CommonStatusCodes.DEVELOPER_ERROR, + "Merchant not enabled" + ) + + assertEquals(PaymentStatus.FAILED, result.status) + assertEquals(PaymentErrorCode.CONFIGURATION, result.code) + assertEquals("Payment error: Merchant not enabled (status code 10)", result.error) + } + + @Test + fun walletErrorResult_reportsAMissingStatusAsUnknown() { + val result = PaymentMapper.walletErrorResult(null, null) + + assertEquals(PaymentErrorCode.UNKNOWN, result.code) + assertEquals("Payment error: Unknown error", result.error) + } + + @Test + fun walletErrorResult_reportsAUserCancelAsCancelled() { + val result = PaymentMapper.walletErrorResult(WalletConstants.ERROR_CODE_USER_CANCELLED, null) + + assertEquals(PaymentStatus.CANCELLED, result.status) + assertEquals(PaymentErrorCode.CANCELLED, result.code) + } + + @Test + fun mapWalletErrorCode_reportsAMissingStatusAsUnknown() { + assertEquals(PaymentErrorCode.UNKNOWN, PaymentMapper.mapWalletErrorCode(null)) + } } diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index 281b4b7..baa4f82 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -6,7 +6,6 @@ import NitroModules private enum ErrorMessage { static let paymentCancelled = "Payment cancelled by user" - static let paymentDismissed = "Payment sheet was dismissed before authorization" static let paymentInProgress = "A payment is already in progress" static let missingMerchantIdentifier = "No Apple Pay merchant identifier configured" static let unableToPresent = "Unable to present payment authorization" @@ -50,13 +49,24 @@ private enum ErrorMessage { } } +/// Why a payment ended without success. +// Internal, not private, so the NitroPay unit tests can check the code. // `CustomStringConvertible` because Nitro rejects JS promises with the // error's description. -private struct PaymentRequestError: LocalizedError, CustomStringConvertible { +struct PaymentFailure: LocalizedError, CustomStringConvertible { + let code: PaymentErrorCode let message: String var errorDescription: String? { message } var description: String { message } + + var status: PaymentStatus { + return code == .cancelled ? .cancelled : .failed + } + + static func configuration(_ message: String) -> PaymentFailure { + return PaymentFailure(code: .configuration, message: message) + } } // PassKit fails the sheet on its own when the authorization completion is not @@ -78,7 +88,7 @@ struct PaymentRequestBuilder { static func build(from request: PaymentRequest) throws -> PKPaymentRequest { guard let merchantIdentifier = resolveMerchantIdentifier(from: request) else { - throw PaymentRequestError(message: ErrorMessage.missingMerchantIdentifier) + throw PaymentFailure.configuration(ErrorMessage.missingMerchantIdentifier) } let paymentRequest = PKPaymentRequest() @@ -135,10 +145,10 @@ struct PaymentRequestBuilder { var identifiers = Set() return try methods.map { method in guard !method.identifier.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { - throw PaymentRequestError(message: ErrorMessage.missingShippingMethodIdentifier(method.label)) + throw PaymentFailure.configuration(ErrorMessage.missingShippingMethodIdentifier(method.label)) } guard identifiers.insert(method.identifier).inserted else { - throw PaymentRequestError(message: ErrorMessage.duplicateShippingMethodIdentifier(method.identifier)) + throw PaymentFailure.configuration(ErrorMessage.duplicateShippingMethodIdentifier(method.identifier)) } let amount = try shippingMethodAmount(method) let pkMethod = PKShippingMethod(label: method.label, amount: amount) @@ -150,10 +160,10 @@ struct PaymentRequestBuilder { private static func shippingMethodAmount(_ method: ShippingMethod) throws -> NSDecimalNumber { guard let amount = method.amount.decimalNumber else { - throw PaymentRequestError(message: ErrorMessage.invalidAmount(method.label)) + throw PaymentFailure.configuration(ErrorMessage.invalidAmount(method.label)) } guard amount.decimalValue >= Decimal.zero else { - throw PaymentRequestError(message: ErrorMessage.negativeShippingMethodAmount(method.label)) + throw PaymentFailure.configuration(ErrorMessage.negativeShippingMethodAmount(method.label)) } return amount } @@ -166,7 +176,7 @@ struct PaymentRequestBuilder { ) throws -> [PKPaymentSummaryItem] { let amounts = try request.paymentItems.map { item -> NSDecimalNumber in guard let amount = item.amount.decimalNumber else { - throw PaymentRequestError(message: ErrorMessage.invalidAmount(item.label)) + throw PaymentFailure.configuration(ErrorMessage.invalidAmount(item.label)) } return amount } @@ -177,7 +187,7 @@ struct PaymentRequestBuilder { partialResult + amount.decimalValue } guard totalAmount >= Decimal.zero else { - throw PaymentRequestError(message: ErrorMessage.negativeTotal) + throw PaymentFailure.configuration(ErrorMessage.negativeTotal) } var lineItems = zip(request.paymentItems, amounts).map { item, amount in @@ -231,7 +241,7 @@ struct PaymentRequestBuilder { case "CREDIT": merchantCapabilities.insert(.capabilityCredit) case "DEBIT": merchantCapabilities.insert(.capabilityDebit) default: - throw PaymentRequestError(message: ErrorMessage.unknownMerchantCapability(capability)) + throw PaymentFailure.configuration(ErrorMessage.unknownMerchantCapability(capability)) } } // PassKit requires 3DS or EMV. EMV only covers China UnionPay, so @@ -246,11 +256,11 @@ struct PaymentRequestBuilder { /// this iOS version lacks is left out, and at least one must be left. static func buildSupportedNetworks(_ names: [String]) throws -> [PKPaymentNetwork] { guard !names.isEmpty else { - throw PaymentRequestError(message: ErrorMessage.missingSupportedNetwork) + throw PaymentFailure.configuration(ErrorMessage.missingSupportedNetwork) } let networks = try convertNetworks(names) guard !networks.isEmpty else { - throw PaymentRequestError(message: ErrorMessage.unavailableNetworks(names)) + throw PaymentFailure.configuration(ErrorMessage.unavailableNetworks(names)) } return networks } @@ -261,7 +271,7 @@ struct PaymentRequestBuilder { var networks: [PKPaymentNetwork] = [] for name in names { guard let network = PassKitTypeMapper.paymentNetwork(named: name) else { - throw PaymentRequestError(message: ErrorMessage.unknownNetwork(name)) + throw PaymentFailure.configuration(ErrorMessage.unknownNetwork(name)) } if let pkNetwork = PassKitTypeMapper.convertToPKPaymentNetwork(network), !networks.contains(pkNetwork) { @@ -278,7 +288,7 @@ struct PaymentRequestBuilder { case "storePickup": return .storePickup case "servicePickup": return .servicePickup default: - throw PaymentRequestError(message: ErrorMessage.unknownShippingType(type)) + throw PaymentFailure.configuration(ErrorMessage.unknownShippingType(type)) } } @@ -367,6 +377,8 @@ private enum PaymentResultFactory { static func success(token: PaymentToken, details: PaymentDetails) -> PaymentResult { return PaymentResult.init( + status: .success, + code: nil, success: true, transactionId: UUID().uuidString, token: token, @@ -379,12 +391,14 @@ private enum PaymentResultFactory { ) } - static func failure(_ error: String) -> PaymentResult { + static func failure(_ failure: PaymentFailure) -> PaymentResult { return PaymentResult.init( + status: failure.status, + code: failure.code, success: false, transactionId: nil, token: nil, - error: error, + error: failure.message, billingContact: nil, shippingContact: nil, emailAddress: nil, @@ -393,9 +407,14 @@ private enum PaymentResultFactory { ) } - static func failure(_ error: Error) -> PaymentResult { + static func failure(_ code: PaymentErrorCode, _ message: String) -> PaymentResult { + return failure(PaymentFailure(code: code, message: message)) + } + + /// An `onAuthorize` that rejected. + static func authorizationFailure(_ error: Error) -> PaymentResult { // Nitro reports JS rejections as `RuntimeError`, whose description is the message. - return failure(String(describing: error)) + return failure(.providerError, String(describing: error)) } static func from( @@ -407,7 +426,7 @@ private enum PaymentResultFactory { case .success: return success(token: token, details: details) case .failure: - return failure(authorization.error ?? ErrorMessage.authorizationFailed) + return failure(.providerError, authorization.error ?? ErrorMessage.authorizationFailed) } } } @@ -425,8 +444,6 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel private var authorizedResult: PaymentResult? private var isAuthorizing: Bool = false private var finishedWhileAuthorizing: Bool = false - private var presentationDate: Date? - private let userDismissThreshold: TimeInterval = 0.75 init( paymentHandler: HybridPaymentHandler, @@ -441,10 +458,6 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel self.selectedShippingMethodIdentifier = paymentRequest.shippingMethods?.first?.identifier self.summaryItems = paymentRequest.paymentSummaryItems } - - func markPresented() { - presentationDate = Date() - } func paymentAuthorizationViewController( _ controller: PKPaymentAuthorizationViewController, @@ -507,16 +520,16 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel } DispatchQueue.main.asyncAfter(deadline: .now() + authorizationTimeout) { - settle(PaymentResultFactory.failure(ErrorMessage.authorizationTimedOut)) + settle(PaymentResultFactory.failure(.providerError, ErrorMessage.authorizationTimedOut)) } onAuthorize(paymentToken, details) .then { authorization in authorization .then { settleOnMain(PaymentResultFactory.from($0, token: paymentToken, details: details)) } - .catch { settleOnMain(PaymentResultFactory.failure($0)) } + .catch { settleOnMain(PaymentResultFactory.authorizationFailure($0)) } } - .catch { settleOnMain(PaymentResultFactory.failure($0)) } + .catch { settleOnMain(PaymentResultFactory.authorizationFailure($0)) } } /// The request's entry for the method the payer authorized with. @@ -542,14 +555,11 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel return } - let errorMessage: String - if let presentationDate, - Date().timeIntervalSince(presentationDate) >= userDismissThreshold { - errorMessage = ErrorMessage.paymentCancelled - } else { - errorMessage = ErrorMessage.paymentDismissed - } - paymentHandler?.handlePaymentResult(PaymentResultFactory.failure(errorMessage)) + // PassKit doesn't say why a sheet closed before authorization, so a + // sheet that closes by itself also reports a cancel. + paymentHandler?.handlePaymentResult( + PaymentResultFactory.failure(.cancelled, ErrorMessage.paymentCancelled) + ) } } @@ -596,7 +606,7 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec { // payment before the sheet is presented. Reject overlaps without // touching the in-flight payment, so its promise still settles. guard pendingPayment.tryBegin({ result in promise.resolve(withResult: result) }) else { - promise.resolve(withResult: PaymentResultFactory.failure(ErrorMessage.paymentInProgress)) + promise.resolve(withResult: PaymentResultFactory.failure(.inProgress, ErrorMessage.paymentInProgress)) return promise } let onAuthorize = options?.onAuthorize @@ -604,8 +614,10 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec { DispatchQueue.main.async { do { try self.performPayment(request: request, onAuthorize: onAuthorize) + } catch let failure as PaymentFailure { + self.handlePaymentResult(PaymentResultFactory.failure(failure)) } catch { - self.handlePaymentResult(PaymentResultFactory.failure(error.localizedDescription)) + self.handlePaymentResult(PaymentResultFactory.failure(.unknown, error.localizedDescription)) } } @@ -633,18 +645,16 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec { ) guard let paymentAuthVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest) else { - throw PaymentRequestError(message: ErrorMessage.unableToCreate) + throw PaymentFailure(code: .notAvailable, message: ErrorMessage.unableToCreate) } paymentAuthVC.delegate = delegate guard let rootViewController = getRootViewController() else { - throw PaymentRequestError(message: ErrorMessage.unableToPresent) + throw PaymentFailure(code: .notAvailable, message: ErrorMessage.unableToPresent) } - rootViewController.present(paymentAuthVC, animated: true) { - self.delegate?.markPresented() - } + rootViewController.present(paymentAuthVC, animated: true) } private func getRootViewController() -> UIViewController? { diff --git a/package/ios/Tests/PaymentFailureTests.swift b/package/ios/Tests/PaymentFailureTests.swift new file mode 100644 index 0000000..558fbf2 --- /dev/null +++ b/package/ios/Tests/PaymentFailureTests.swift @@ -0,0 +1,26 @@ +import XCTest +@testable import NitroPay + +final class PaymentFailureTests: XCTestCase { + + private let codes: [PaymentErrorCode] = [ + .cancelled, .inProgress, .configuration, .notAvailable, .providerError, .unknown, + ] + + func testReportsACancelAsCancelled() { + XCTAssertEqual(PaymentFailure(code: .cancelled, message: "").status, .cancelled) + } + + func testReportsEveryOtherCodeAsFailed() { + for code in codes where code != .cancelled { + XCTAssertEqual(PaymentFailure(code: code, message: "").status, .failed, code.stringValue) + } + } + + func testConfigurationFailureKeepsItsMessage() { + let failure = PaymentFailure.configuration("No Apple Pay merchant identifier configured") + + XCTAssertEqual(failure.code, .configuration) + XCTAssertEqual(failure.localizedDescription, "No Apple Pay merchant identifier configured") + } +} diff --git a/package/ios/Tests/PaymentRequestBuilderTests.swift b/package/ios/Tests/PaymentRequestBuilderTests.swift index 333e477..8b15908 100644 --- a/package/ios/Tests/PaymentRequestBuilderTests.swift +++ b/package/ios/Tests/PaymentRequestBuilderTests.swift @@ -60,6 +60,7 @@ final class PaymentRequestBuilderTests: XCTestCase { ) { XCTAssertThrowsError(try PaymentRequestBuilder.build(from: request), file: file, line: line) { error in XCTAssertEqual(error.localizedDescription, message, file: file, line: line) + XCTAssertEqual((error as? PaymentFailure)?.code, .configuration, file: file, line: line) } } diff --git a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp index ae0979c..ba2d76d 100644 --- a/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp +++ b/package/nitrogen/generated/android/c++/JHybridPaymentHandlerSpec.cpp @@ -11,6 +11,10 @@ namespace margelo::nitro::pay { struct PayServiceStatus; } // Forward declaration of `PaymentResult` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentResult; } +// Forward declaration of `PaymentStatus` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentStatus; } +// Forward declaration of `PaymentErrorCode` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentErrorCode; } // Forward declaration of `PaymentToken` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentToken; } // Forward declaration of `PaymentMethod` to properly resolve imports. @@ -66,8 +70,12 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include "JPayServiceStatus.hpp" #include "PaymentResult.hpp" #include "JPaymentResult.hpp" -#include +#include "PaymentStatus.hpp" +#include "JPaymentStatus.hpp" +#include "PaymentErrorCode.hpp" #include +#include "JPaymentErrorCode.hpp" +#include #include "PaymentToken.hpp" #include "JPaymentToken.hpp" #include "PaymentMethod.hpp" diff --git a/package/nitrogen/generated/android/c++/JPaymentErrorCode.hpp b/package/nitrogen/generated/android/c++/JPaymentErrorCode.hpp new file mode 100644 index 0000000..0dd3e24 --- /dev/null +++ b/package/nitrogen/generated/android/c++/JPaymentErrorCode.hpp @@ -0,0 +1,70 @@ +/// +/// JPaymentErrorCode.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 "PaymentErrorCode.hpp" + +namespace margelo::nitro::pay { + + using namespace facebook; + + /** + * The C++ JNI bridge between the C++ enum "PaymentErrorCode" and the Kotlin enum "PaymentErrorCode". + */ + struct JPaymentErrorCode final: public jni::JavaClass { + public: + static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/pay/PaymentErrorCode;"; + + public: + /** + * Convert this Java/Kotlin-based enum to the C++ enum PaymentErrorCode. + */ + [[maybe_unused]] + [[nodiscard]] + PaymentErrorCode toCpp() const { + static const auto clazz = javaClassStatic(); + static const auto fieldOrdinal = clazz->getField("value"); + int ordinal = this->getFieldValue(fieldOrdinal); + return static_cast(ordinal); + } + + public: + /** + * Create a Java/Kotlin-based enum with the given C++ enum's value. + */ + [[maybe_unused]] + static jni::alias_ref fromCpp(PaymentErrorCode value) { + static const auto clazz = javaClassStatic(); + switch (value) { + case PaymentErrorCode::CANCELLED: + static const auto fieldCANCELLED = clazz->getStaticField("CANCELLED"); + return clazz->getStaticFieldValue(fieldCANCELLED); + case PaymentErrorCode::IN_PROGRESS: + static const auto fieldIN_PROGRESS = clazz->getStaticField("IN_PROGRESS"); + return clazz->getStaticFieldValue(fieldIN_PROGRESS); + case PaymentErrorCode::CONFIGURATION: + static const auto fieldCONFIGURATION = clazz->getStaticField("CONFIGURATION"); + return clazz->getStaticFieldValue(fieldCONFIGURATION); + case PaymentErrorCode::NOT_AVAILABLE: + static const auto fieldNOT_AVAILABLE = clazz->getStaticField("NOT_AVAILABLE"); + return clazz->getStaticFieldValue(fieldNOT_AVAILABLE); + case PaymentErrorCode::PROVIDER_ERROR: + static const auto fieldPROVIDER_ERROR = clazz->getStaticField("PROVIDER_ERROR"); + return clazz->getStaticFieldValue(fieldPROVIDER_ERROR); + case PaymentErrorCode::UNKNOWN: + static const auto fieldUNKNOWN = clazz->getStaticField("UNKNOWN"); + return clazz->getStaticFieldValue(fieldUNKNOWN); + default: + std::string stringValue = std::to_string(static_cast(value)); + throw std::invalid_argument("Invalid enum value (" + stringValue + "!"); + } + } + }; + +} // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/c++/JPaymentResult.hpp b/package/nitrogen/generated/android/c++/JPaymentResult.hpp index 612efd4..8c6cc89 100644 --- a/package/nitrogen/generated/android/c++/JPaymentResult.hpp +++ b/package/nitrogen/generated/android/c++/JPaymentResult.hpp @@ -28,17 +28,21 @@ #include "JPassActivationState.hpp" #include "JPaymentAmount.hpp" #include "JPaymentContact.hpp" +#include "JPaymentErrorCode.hpp" #include "JPaymentMethod.hpp" #include "JPaymentMethodType.hpp" #include "JPaymentNetwork.hpp" +#include "JPaymentStatus.hpp" #include "JPaymentToken.hpp" #include "JShippingMethod.hpp" #include "PKSecureElementPass.hpp" #include "PassActivationState.hpp" #include "PaymentContact.hpp" +#include "PaymentErrorCode.hpp" #include "PaymentMethod.hpp" #include "PaymentMethodType.hpp" #include "PaymentNetwork.hpp" +#include "PaymentStatus.hpp" #include "PaymentToken.hpp" #include "ShippingMethod.hpp" #include @@ -65,6 +69,10 @@ namespace margelo::nitro::pay { [[nodiscard]] PaymentResult toCpp() const { static const auto clazz = javaClassStatic(); + static const auto fieldStatus = clazz->getField("status"); + jni::local_ref status = this->getFieldValue(fieldStatus); + static const auto fieldCode = clazz->getField("code"); + jni::local_ref code = this->getFieldValue(fieldCode); static const auto fieldSuccess = clazz->getField("success"); jboolean success = this->getFieldValue(fieldSuccess); static const auto fieldTransactionId = clazz->getField("transactionId"); @@ -84,6 +92,8 @@ namespace margelo::nitro::pay { static const auto fieldShippingMethod = clazz->getField("shippingMethod"); jni::local_ref shippingMethod = this->getFieldValue(fieldShippingMethod); return PaymentResult( + status->toCpp(), + code != nullptr ? std::make_optional(code->toCpp()) : std::nullopt, static_cast(success), transactionId != nullptr ? std::make_optional(transactionId->toStdString()) : std::nullopt, token != nullptr ? std::make_optional(token->toCpp()) : std::nullopt, @@ -102,11 +112,13 @@ namespace margelo::nitro::pay { */ [[maybe_unused]] static jni::local_ref fromCpp(const PaymentResult& value) { - using JSignature = JPaymentResult(jboolean, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref); + using JSignature = JPaymentResult(jni::alias_ref, jni::alias_ref, jboolean, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref, jni::alias_ref); static const auto clazz = javaClassStatic(); static const auto create = clazz->getStaticMethod("fromCpp"); return create( clazz, + JPaymentStatus::fromCpp(value.status), + value.code.has_value() ? JPaymentErrorCode::fromCpp(value.code.value()) : nullptr, value.success, value.transactionId.has_value() ? jni::make_jstring(value.transactionId.value()) : nullptr, value.token.has_value() ? JPaymentToken::fromCpp(value.token.value()) : nullptr, diff --git a/package/nitrogen/generated/android/c++/JPaymentStatus.hpp b/package/nitrogen/generated/android/c++/JPaymentStatus.hpp new file mode 100644 index 0000000..5f50ba2 --- /dev/null +++ b/package/nitrogen/generated/android/c++/JPaymentStatus.hpp @@ -0,0 +1,61 @@ +/// +/// JPaymentStatus.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 "PaymentStatus.hpp" + +namespace margelo::nitro::pay { + + using namespace facebook; + + /** + * The C++ JNI bridge between the C++ enum "PaymentStatus" and the Kotlin enum "PaymentStatus". + */ + struct JPaymentStatus final: public jni::JavaClass { + public: + static constexpr auto kJavaDescriptor = "Lcom/margelo/nitro/pay/PaymentStatus;"; + + public: + /** + * Convert this Java/Kotlin-based enum to the C++ enum PaymentStatus. + */ + [[maybe_unused]] + [[nodiscard]] + PaymentStatus toCpp() const { + static const auto clazz = javaClassStatic(); + static const auto fieldOrdinal = clazz->getField("value"); + int ordinal = this->getFieldValue(fieldOrdinal); + return static_cast(ordinal); + } + + public: + /** + * Create a Java/Kotlin-based enum with the given C++ enum's value. + */ + [[maybe_unused]] + static jni::alias_ref fromCpp(PaymentStatus value) { + static const auto clazz = javaClassStatic(); + switch (value) { + case PaymentStatus::SUCCESS: + static const auto fieldSUCCESS = clazz->getStaticField("SUCCESS"); + return clazz->getStaticFieldValue(fieldSUCCESS); + case PaymentStatus::CANCELLED: + static const auto fieldCANCELLED = clazz->getStaticField("CANCELLED"); + return clazz->getStaticFieldValue(fieldCANCELLED); + case PaymentStatus::FAILED: + static const auto fieldFAILED = clazz->getStaticField("FAILED"); + return clazz->getStaticFieldValue(fieldFAILED); + default: + std::string stringValue = std::to_string(static_cast(value)); + throw std::invalid_argument("Invalid enum value (" + stringValue + "!"); + } + } + }; + +} // namespace margelo::nitro::pay diff --git a/package/nitrogen/generated/android/c++/JPaymentToken.hpp b/package/nitrogen/generated/android/c++/JPaymentToken.hpp index f73c3c4..07a6f03 100644 --- a/package/nitrogen/generated/android/c++/JPaymentToken.hpp +++ b/package/nitrogen/generated/android/c++/JPaymentToken.hpp @@ -65,7 +65,7 @@ namespace margelo::nitro::pay { jni::local_ref paymentData = this->getFieldValue(fieldPaymentData); return PaymentToken( paymentMethod->toCpp(), - transactionIdentifier->toStdString(), + transactionIdentifier != nullptr ? std::make_optional(transactionIdentifier->toStdString()) : std::nullopt, paymentData->toStdString() ); } @@ -82,7 +82,7 @@ namespace margelo::nitro::pay { return create( clazz, JPaymentMethod::fromCpp(value.paymentMethod), - jni::make_jstring(value.transactionIdentifier), + value.transactionIdentifier.has_value() ? jni::make_jstring(value.transactionIdentifier.value()) : nullptr, jni::make_jstring(value.paymentData) ); } diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentErrorCode.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentErrorCode.kt new file mode 100644 index 0000000..db37da4 --- /dev/null +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentErrorCode.kt @@ -0,0 +1,27 @@ +/// +/// PaymentErrorCode.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 + +/** + * Represents the JavaScript enum/union "PaymentErrorCode". + */ +@DoNotStrip +@Keep +enum class PaymentErrorCode(@DoNotStrip @Keep val value: Int) { + CANCELLED(0), + IN_PROGRESS(1), + CONFIGURATION(2), + NOT_AVAILABLE(3), + PROVIDER_ERROR(4), + UNKNOWN(5); + + companion object +} diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentResult.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentResult.kt index 14ddea9..cc045c9 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentResult.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentResult.kt @@ -18,6 +18,12 @@ import java.util.Objects @DoNotStrip @Keep data class PaymentResult( + @DoNotStrip + @Keep + val status: PaymentStatus, + @DoNotStrip + @Keep + val code: PaymentErrorCode?, @DoNotStrip @Keep val success: Boolean, @@ -51,7 +57,9 @@ data class PaymentResult( override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PaymentResult) return false - return Objects.deepEquals(this.success, other.success) + return Objects.deepEquals(this.status, other.status) + && Objects.deepEquals(this.code, other.code) + && Objects.deepEquals(this.success, other.success) && Objects.deepEquals(this.transactionId, other.transactionId) && Objects.deepEquals(this.token, other.token) && Objects.deepEquals(this.error, other.error) @@ -64,6 +72,8 @@ data class PaymentResult( override fun hashCode(): Int { return arrayOf( + status, + code, success, transactionId, token, @@ -84,8 +94,8 @@ data class PaymentResult( @Keep @Suppress("unused") @JvmStatic - private fun fromCpp(success: Boolean, transactionId: String?, token: PaymentToken?, error: String?, billingContact: PaymentContact?, shippingContact: PaymentContact?, emailAddress: String?, phoneNumber: String?, shippingMethod: ShippingMethod?): PaymentResult { - return PaymentResult(success, transactionId, token, error, billingContact, shippingContact, emailAddress, phoneNumber, shippingMethod) + private fun fromCpp(status: PaymentStatus, code: PaymentErrorCode?, success: Boolean, transactionId: String?, token: PaymentToken?, error: String?, billingContact: PaymentContact?, shippingContact: PaymentContact?, emailAddress: String?, phoneNumber: String?, shippingMethod: ShippingMethod?): PaymentResult { + return PaymentResult(status, code, success, transactionId, token, error, billingContact, shippingContact, emailAddress, phoneNumber, shippingMethod) } } } diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentStatus.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentStatus.kt new file mode 100644 index 0000000..4731374 --- /dev/null +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentStatus.kt @@ -0,0 +1,24 @@ +/// +/// PaymentStatus.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 + +/** + * Represents the JavaScript enum/union "PaymentStatus". + */ +@DoNotStrip +@Keep +enum class PaymentStatus(@DoNotStrip @Keep val value: Int) { + SUCCESS(0), + CANCELLED(1), + FAILED(2); + + companion object +} diff --git a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentToken.kt b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentToken.kt index 870b876..95fe2eb 100644 --- a/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentToken.kt +++ b/package/nitrogen/generated/android/kotlin/com/margelo/nitro/pay/PaymentToken.kt @@ -23,7 +23,7 @@ data class PaymentToken( val paymentMethod: PaymentMethod, @DoNotStrip @Keep - val transactionIdentifier: String, + val transactionIdentifier: String?, @DoNotStrip @Keep val paymentData: String @@ -54,7 +54,7 @@ data class PaymentToken( @Keep @Suppress("unused") @JvmStatic - private fun fromCpp(paymentMethod: PaymentMethod, transactionIdentifier: String, paymentData: String): PaymentToken { + private fun fromCpp(paymentMethod: PaymentMethod, transactionIdentifier: String?, paymentData: String): PaymentToken { return PaymentToken(paymentMethod, transactionIdentifier, paymentData) } } diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp index 706b018..68ac741 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Bridge.hpp @@ -44,6 +44,8 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } namespace margelo::nitro::pay { struct PaymentContact; } // Forward declaration of `PaymentDetails` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentDetails; } +// Forward declaration of `PaymentErrorCode` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentErrorCode; } // Forward declaration of `PaymentItemType` to properly resolve imports. namespace margelo::nitro::pay { enum class PaymentItemType; } // Forward declaration of `PaymentItem` to properly resolve imports. @@ -56,6 +58,8 @@ namespace margelo::nitro::pay { struct PaymentMethod; } namespace margelo::nitro::pay { enum class PaymentNetwork; } // Forward declaration of `PaymentResult` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentResult; } +// Forward declaration of `PaymentStatus` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentStatus; } // Forward declaration of `PaymentToken` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentToken; } // Forward declaration of `ShippingMethod` to properly resolve imports. @@ -88,12 +92,14 @@ namespace NitroPay { class HybridPaymentHandlerSpec_cxx; } #include "PaymentAuthorizationStatus.hpp" #include "PaymentContact.hpp" #include "PaymentDetails.hpp" +#include "PaymentErrorCode.hpp" #include "PaymentItem.hpp" #include "PaymentItemType.hpp" #include "PaymentMethod.hpp" #include "PaymentMethodType.hpp" #include "PaymentNetwork.hpp" #include "PaymentResult.hpp" +#include "PaymentStatus.hpp" #include "PaymentToken.hpp" #include "ShippingMethod.hpp" #include "StartPaymentOptions.hpp" @@ -275,6 +281,21 @@ namespace margelo::nitro::pay::bridge::swift { return optional.value(); } + // pragma MARK: std::optional + /** + * Specialized version of `std::optional`. + */ + using std__optional_PaymentErrorCode_ = std::optional; + inline std::optional create_std__optional_PaymentErrorCode_(const PaymentErrorCode& value) noexcept { + return std::optional(value); + } + inline bool has_value_std__optional_PaymentErrorCode_(const std::optional& optional) noexcept { + return optional.has_value(); + } + inline PaymentErrorCode get_std__optional_PaymentErrorCode_(const std::optional& optional) noexcept { + return optional.value(); + } + // pragma MARK: std::optional /** * Specialized version of `std::optional`. diff --git a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp index 16f2fc4..f00b63b 100644 --- a/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp +++ b/package/nitrogen/generated/ios/NitroPay-Swift-Cxx-Umbrella.hpp @@ -48,6 +48,8 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } namespace margelo::nitro::pay { struct PaymentContact; } // Forward declaration of `PaymentDetails` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentDetails; } +// Forward declaration of `PaymentErrorCode` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentErrorCode; } // Forward declaration of `PaymentItemType` to properly resolve imports. namespace margelo::nitro::pay { enum class PaymentItemType; } // Forward declaration of `PaymentItem` to properly resolve imports. @@ -62,6 +64,8 @@ namespace margelo::nitro::pay { enum class PaymentNetwork; } namespace margelo::nitro::pay { struct PaymentRequest; } // Forward declaration of `PaymentResult` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentResult; } +// Forward declaration of `PaymentStatus` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentStatus; } // Forward declaration of `PaymentToken` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentToken; } // Forward declaration of `ShippingMethod` to properly resolve imports. @@ -90,6 +94,7 @@ namespace margelo::nitro::pay { struct StartPaymentOptions; } #include "PaymentAuthorizationStatus.hpp" #include "PaymentContact.hpp" #include "PaymentDetails.hpp" +#include "PaymentErrorCode.hpp" #include "PaymentItem.hpp" #include "PaymentItemType.hpp" #include "PaymentMethod.hpp" @@ -97,6 +102,7 @@ namespace margelo::nitro::pay { struct StartPaymentOptions; } #include "PaymentNetwork.hpp" #include "PaymentRequest.hpp" #include "PaymentResult.hpp" +#include "PaymentStatus.hpp" #include "PaymentToken.hpp" #include "ShippingMethod.hpp" #include "StartPaymentOptions.hpp" diff --git a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp index c2fa745..0a2fbe0 100644 --- a/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp +++ b/package/nitrogen/generated/ios/c++/HybridPaymentHandlerSpecSwift.hpp @@ -20,6 +20,10 @@ namespace margelo::nitro::pay { struct PayServiceStatusOptions; } namespace margelo::nitro::pay { enum class GooglePayEnvironment; } // Forward declaration of `PaymentResult` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentResult; } +// Forward declaration of `PaymentStatus` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentStatus; } +// Forward declaration of `PaymentErrorCode` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentErrorCode; } // Forward declaration of `PaymentToken` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentToken; } // Forward declaration of `PaymentMethod` to properly resolve imports. @@ -73,6 +77,8 @@ namespace margelo::nitro::pay { enum class PaymentAuthorizationStatus; } #include #include "GooglePayEnvironment.hpp" #include "PaymentResult.hpp" +#include "PaymentStatus.hpp" +#include "PaymentErrorCode.hpp" #include "PaymentToken.hpp" #include "PaymentMethod.hpp" #include "PaymentNetwork.hpp" diff --git a/package/nitrogen/generated/ios/swift/PaymentErrorCode.swift b/package/nitrogen/generated/ios/swift/PaymentErrorCode.swift new file mode 100644 index 0000000..c61c3a5 --- /dev/null +++ b/package/nitrogen/generated/ios/swift/PaymentErrorCode.swift @@ -0,0 +1,56 @@ +/// +/// PaymentErrorCode.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +/** + * Represents the JS union `PaymentErrorCode`, backed by a C++ enum. + */ +public typealias PaymentErrorCode = margelo.nitro.pay.PaymentErrorCode + +public extension PaymentErrorCode { + /** + * Get a PaymentErrorCode for the given String value, or + * return `nil` if the given value was invalid/unknown. + */ + init?(fromString string: String) { + switch string { + case "CANCELLED": + self = .cancelled + case "IN_PROGRESS": + self = .inProgress + case "CONFIGURATION": + self = .configuration + case "NOT_AVAILABLE": + self = .notAvailable + case "PROVIDER_ERROR": + self = .providerError + case "UNKNOWN": + self = .unknown + default: + return nil + } + } + + /** + * Get the String value this PaymentErrorCode represents. + */ + var stringValue: String { + switch self { + case .cancelled: + return "CANCELLED" + case .inProgress: + return "IN_PROGRESS" + case .configuration: + return "CONFIGURATION" + case .notAvailable: + return "NOT_AVAILABLE" + case .providerError: + return "PROVIDER_ERROR" + case .unknown: + return "UNKNOWN" + } + } +} diff --git a/package/nitrogen/generated/ios/swift/PaymentResult.swift b/package/nitrogen/generated/ios/swift/PaymentResult.swift index f119499..3d5f963 100644 --- a/package/nitrogen/generated/ios/swift/PaymentResult.swift +++ b/package/nitrogen/generated/ios/swift/PaymentResult.swift @@ -18,8 +18,14 @@ public extension PaymentResult { /** * Create a new instance of `PaymentResult`. */ - init(success: Bool, transactionId: String?, token: PaymentToken?, error: String?, billingContact: PaymentContact?, shippingContact: PaymentContact?, emailAddress: String?, phoneNumber: String?, shippingMethod: ShippingMethod?) { - self.init(success, { () -> bridge.std__optional_std__string_ in + init(status: PaymentStatus, code: PaymentErrorCode?, success: Bool, transactionId: String?, token: PaymentToken?, error: String?, billingContact: PaymentContact?, shippingContact: PaymentContact?, emailAddress: String?, phoneNumber: String?, shippingMethod: ShippingMethod?) { + self.init(status, { () -> bridge.std__optional_PaymentErrorCode_ in + if let __unwrappedValue = code { + return bridge.create_std__optional_PaymentErrorCode_(__unwrappedValue) + } else { + return .init() + } + }(), success, { () -> bridge.std__optional_std__string_ in if let __unwrappedValue = transactionId { return bridge.create_std__optional_std__string_(std.string(__unwrappedValue)) } else { @@ -70,6 +76,16 @@ public extension PaymentResult { }()) } + @inline(__always) + var status: PaymentStatus { + return self.__status + } + + @inline(__always) + var code: PaymentErrorCode? { + return self.__code.value + } + @inline(__always) var success: Bool { return self.__success diff --git a/package/nitrogen/generated/ios/swift/PaymentStatus.swift b/package/nitrogen/generated/ios/swift/PaymentStatus.swift new file mode 100644 index 0000000..af87a52 --- /dev/null +++ b/package/nitrogen/generated/ios/swift/PaymentStatus.swift @@ -0,0 +1,44 @@ +/// +/// PaymentStatus.swift +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/mrousavy/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +/** + * Represents the JS union `PaymentStatus`, backed by a C++ enum. + */ +public typealias PaymentStatus = margelo.nitro.pay.PaymentStatus + +public extension PaymentStatus { + /** + * Get a PaymentStatus for the given String value, or + * return `nil` if the given value was invalid/unknown. + */ + init?(fromString string: String) { + switch string { + case "success": + self = .success + case "cancelled": + self = .cancelled + case "failed": + self = .failed + default: + return nil + } + } + + /** + * Get the String value this PaymentStatus represents. + */ + var stringValue: String { + switch self { + case .success: + return "success" + case .cancelled: + return "cancelled" + case .failed: + return "failed" + } + } +} diff --git a/package/nitrogen/generated/ios/swift/PaymentToken.swift b/package/nitrogen/generated/ios/swift/PaymentToken.swift index f0b65c7..ccd3512 100644 --- a/package/nitrogen/generated/ios/swift/PaymentToken.swift +++ b/package/nitrogen/generated/ios/swift/PaymentToken.swift @@ -18,8 +18,14 @@ public extension PaymentToken { /** * Create a new instance of `PaymentToken`. */ - init(paymentMethod: PaymentMethod, transactionIdentifier: String, paymentData: String) { - self.init(paymentMethod, std.string(transactionIdentifier), std.string(paymentData)) + init(paymentMethod: PaymentMethod, transactionIdentifier: String?, paymentData: String) { + self.init(paymentMethod, { () -> bridge.std__optional_std__string_ in + if let __unwrappedValue = transactionIdentifier { + return bridge.create_std__optional_std__string_(std.string(__unwrappedValue)) + } else { + return .init() + } + }(), std.string(paymentData)) } @inline(__always) @@ -28,8 +34,15 @@ public extension PaymentToken { } @inline(__always) - var transactionIdentifier: String { - return String(self.__transactionIdentifier) + var transactionIdentifier: String? { + return { () -> String? in + if bridge.has_value_std__optional_std__string_(self.__transactionIdentifier) { + let __unwrapped = bridge.get_std__optional_std__string_(self.__transactionIdentifier) + return String(__unwrapped) + } else { + return nil + } + }() } @inline(__always) diff --git a/package/nitrogen/generated/shared/c++/PaymentErrorCode.hpp b/package/nitrogen/generated/shared/c++/PaymentErrorCode.hpp new file mode 100644 index 0000000..1c6df1b --- /dev/null +++ b/package/nitrogen/generated/shared/c++/PaymentErrorCode.hpp @@ -0,0 +1,92 @@ +/// +/// PaymentErrorCode.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 + +namespace margelo::nitro::pay { + + /** + * An enum which can be represented as a JavaScript union (PaymentErrorCode). + */ + enum class PaymentErrorCode { + CANCELLED SWIFT_NAME(cancelled) = 0, + IN_PROGRESS SWIFT_NAME(inProgress) = 1, + CONFIGURATION SWIFT_NAME(configuration) = 2, + NOT_AVAILABLE SWIFT_NAME(notAvailable) = 3, + PROVIDER_ERROR SWIFT_NAME(providerError) = 4, + UNKNOWN SWIFT_NAME(unknown) = 5, + } CLOSED_ENUM; + +} // namespace margelo::nitro::pay + +namespace margelo::nitro { + + // C++ PaymentErrorCode <> JS PaymentErrorCode (union) + template <> + struct JSIConverter final { + static inline margelo::nitro::pay::PaymentErrorCode fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + std::string unionValue = JSIConverter::fromJSI(runtime, arg); + switch (hashString(unionValue.c_str(), unionValue.size())) { + case hashString("CANCELLED"): return margelo::nitro::pay::PaymentErrorCode::CANCELLED; + case hashString("IN_PROGRESS"): return margelo::nitro::pay::PaymentErrorCode::IN_PROGRESS; + case hashString("CONFIGURATION"): return margelo::nitro::pay::PaymentErrorCode::CONFIGURATION; + case hashString("NOT_AVAILABLE"): return margelo::nitro::pay::PaymentErrorCode::NOT_AVAILABLE; + case hashString("PROVIDER_ERROR"): return margelo::nitro::pay::PaymentErrorCode::PROVIDER_ERROR; + case hashString("UNKNOWN"): return margelo::nitro::pay::PaymentErrorCode::UNKNOWN; + default: [[unlikely]] + throw std::invalid_argument("Cannot convert \"" + unionValue + "\" to enum PaymentErrorCode - invalid value!"); + } + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, margelo::nitro::pay::PaymentErrorCode arg) { + switch (arg) { + case margelo::nitro::pay::PaymentErrorCode::CANCELLED: return JSIConverter::toJSI(runtime, "CANCELLED"); + case margelo::nitro::pay::PaymentErrorCode::IN_PROGRESS: return JSIConverter::toJSI(runtime, "IN_PROGRESS"); + case margelo::nitro::pay::PaymentErrorCode::CONFIGURATION: return JSIConverter::toJSI(runtime, "CONFIGURATION"); + case margelo::nitro::pay::PaymentErrorCode::NOT_AVAILABLE: return JSIConverter::toJSI(runtime, "NOT_AVAILABLE"); + case margelo::nitro::pay::PaymentErrorCode::PROVIDER_ERROR: return JSIConverter::toJSI(runtime, "PROVIDER_ERROR"); + case margelo::nitro::pay::PaymentErrorCode::UNKNOWN: return JSIConverter::toJSI(runtime, "UNKNOWN"); + default: [[unlikely]] + throw std::invalid_argument("Cannot convert PaymentErrorCode to JS - invalid value: " + + std::to_string(static_cast(arg)) + "!"); + } + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isString()) { + return false; + } + std::string unionValue = JSIConverter::fromJSI(runtime, value); + switch (hashString(unionValue.c_str(), unionValue.size())) { + case hashString("CANCELLED"): + case hashString("IN_PROGRESS"): + case hashString("CONFIGURATION"): + case hashString("NOT_AVAILABLE"): + case hashString("PROVIDER_ERROR"): + case hashString("UNKNOWN"): + return true; + default: + return false; + } + } + }; + +} // namespace margelo::nitro diff --git a/package/nitrogen/generated/shared/c++/PaymentResult.hpp b/package/nitrogen/generated/shared/c++/PaymentResult.hpp index bd37c16..6a9943d 100644 --- a/package/nitrogen/generated/shared/c++/PaymentResult.hpp +++ b/package/nitrogen/generated/shared/c++/PaymentResult.hpp @@ -28,6 +28,10 @@ #error NitroModules cannot be found! Are you sure you installed NitroModules properly? #endif +// Forward declaration of `PaymentStatus` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentStatus; } +// Forward declaration of `PaymentErrorCode` to properly resolve imports. +namespace margelo::nitro::pay { enum class PaymentErrorCode; } // Forward declaration of `PaymentToken` to properly resolve imports. namespace margelo::nitro::pay { struct PaymentToken; } // Forward declaration of `PaymentContact` to properly resolve imports. @@ -35,8 +39,10 @@ namespace margelo::nitro::pay { struct PaymentContact; } // Forward declaration of `ShippingMethod` to properly resolve imports. namespace margelo::nitro::pay { struct ShippingMethod; } -#include +#include "PaymentStatus.hpp" +#include "PaymentErrorCode.hpp" #include +#include #include "PaymentToken.hpp" #include "PaymentContact.hpp" #include "ShippingMethod.hpp" @@ -48,6 +54,8 @@ namespace margelo::nitro::pay { */ struct PaymentResult final { public: + PaymentStatus status SWIFT_PRIVATE; + std::optional code SWIFT_PRIVATE; bool success SWIFT_PRIVATE; std::optional transactionId SWIFT_PRIVATE; std::optional token SWIFT_PRIVATE; @@ -60,7 +68,7 @@ namespace margelo::nitro::pay { public: PaymentResult() = default; - explicit PaymentResult(bool success, std::optional transactionId, std::optional token, std::optional error, std::optional billingContact, std::optional shippingContact, std::optional emailAddress, std::optional phoneNumber, std::optional shippingMethod): success(success), transactionId(transactionId), token(token), error(error), billingContact(billingContact), shippingContact(shippingContact), emailAddress(emailAddress), phoneNumber(phoneNumber), shippingMethod(shippingMethod) {} + explicit PaymentResult(PaymentStatus status, std::optional code, bool success, std::optional transactionId, std::optional token, std::optional error, std::optional billingContact, std::optional shippingContact, std::optional emailAddress, std::optional phoneNumber, std::optional shippingMethod): status(status), code(code), success(success), transactionId(transactionId), token(token), error(error), billingContact(billingContact), shippingContact(shippingContact), emailAddress(emailAddress), phoneNumber(phoneNumber), shippingMethod(shippingMethod) {} public: friend bool operator==(const PaymentResult& lhs, const PaymentResult& rhs) = default; @@ -76,6 +84,8 @@ namespace margelo::nitro { static inline margelo::nitro::pay::PaymentResult fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { jsi::Object obj = arg.asObject(runtime); return margelo::nitro::pay::PaymentResult( + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "status"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "code"))), JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "success"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "transactionId"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "token"))), @@ -89,6 +99,8 @@ namespace margelo::nitro { } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::PaymentResult& arg) { jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "status"), JSIConverter::toJSI(runtime, arg.status)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "code"), JSIConverter>::toJSI(runtime, arg.code)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "success"), JSIConverter::toJSI(runtime, arg.success)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "transactionId"), JSIConverter>::toJSI(runtime, arg.transactionId)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "token"), JSIConverter>::toJSI(runtime, arg.token)); @@ -108,6 +120,8 @@ namespace margelo::nitro { if (!nitro::isPlainObject(runtime, obj)) { return false; } + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "status")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "code")))) return false; if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "success")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "transactionId")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "token")))) return false; diff --git a/package/nitrogen/generated/shared/c++/PaymentStatus.hpp b/package/nitrogen/generated/shared/c++/PaymentStatus.hpp new file mode 100644 index 0000000..635cf25 --- /dev/null +++ b/package/nitrogen/generated/shared/c++/PaymentStatus.hpp @@ -0,0 +1,80 @@ +/// +/// PaymentStatus.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 + +namespace margelo::nitro::pay { + + /** + * An enum which can be represented as a JavaScript union (PaymentStatus). + */ + enum class PaymentStatus { + SUCCESS SWIFT_NAME(success) = 0, + CANCELLED SWIFT_NAME(cancelled) = 1, + FAILED SWIFT_NAME(failed) = 2, + } CLOSED_ENUM; + +} // namespace margelo::nitro::pay + +namespace margelo::nitro { + + // C++ PaymentStatus <> JS PaymentStatus (union) + template <> + struct JSIConverter final { + static inline margelo::nitro::pay::PaymentStatus fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + std::string unionValue = JSIConverter::fromJSI(runtime, arg); + switch (hashString(unionValue.c_str(), unionValue.size())) { + case hashString("success"): return margelo::nitro::pay::PaymentStatus::SUCCESS; + case hashString("cancelled"): return margelo::nitro::pay::PaymentStatus::CANCELLED; + case hashString("failed"): return margelo::nitro::pay::PaymentStatus::FAILED; + default: [[unlikely]] + throw std::invalid_argument("Cannot convert \"" + unionValue + "\" to enum PaymentStatus - invalid value!"); + } + } + static inline jsi::Value toJSI(jsi::Runtime& runtime, margelo::nitro::pay::PaymentStatus arg) { + switch (arg) { + case margelo::nitro::pay::PaymentStatus::SUCCESS: return JSIConverter::toJSI(runtime, "success"); + case margelo::nitro::pay::PaymentStatus::CANCELLED: return JSIConverter::toJSI(runtime, "cancelled"); + case margelo::nitro::pay::PaymentStatus::FAILED: return JSIConverter::toJSI(runtime, "failed"); + default: [[unlikely]] + throw std::invalid_argument("Cannot convert PaymentStatus to JS - invalid value: " + + std::to_string(static_cast(arg)) + "!"); + } + } + static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isString()) { + return false; + } + std::string unionValue = JSIConverter::fromJSI(runtime, value); + switch (hashString(unionValue.c_str(), unionValue.size())) { + case hashString("success"): + case hashString("cancelled"): + case hashString("failed"): + return true; + default: + return false; + } + } + }; + +} // namespace margelo::nitro diff --git a/package/nitrogen/generated/shared/c++/PaymentToken.hpp b/package/nitrogen/generated/shared/c++/PaymentToken.hpp index ecee4cf..54b0b91 100644 --- a/package/nitrogen/generated/shared/c++/PaymentToken.hpp +++ b/package/nitrogen/generated/shared/c++/PaymentToken.hpp @@ -33,6 +33,7 @@ namespace margelo::nitro::pay { struct PaymentMethod; } #include "PaymentMethod.hpp" #include +#include namespace margelo::nitro::pay { @@ -42,12 +43,12 @@ namespace margelo::nitro::pay { struct PaymentToken final { public: PaymentMethod paymentMethod SWIFT_PRIVATE; - std::string transactionIdentifier SWIFT_PRIVATE; + std::optional transactionIdentifier SWIFT_PRIVATE; std::string paymentData SWIFT_PRIVATE; public: PaymentToken() = default; - explicit PaymentToken(PaymentMethod paymentMethod, std::string transactionIdentifier, std::string paymentData): paymentMethod(paymentMethod), transactionIdentifier(transactionIdentifier), paymentData(paymentData) {} + explicit PaymentToken(PaymentMethod paymentMethod, std::optional transactionIdentifier, std::string paymentData): paymentMethod(paymentMethod), transactionIdentifier(transactionIdentifier), paymentData(paymentData) {} public: friend bool operator==(const PaymentToken& lhs, const PaymentToken& rhs) = default; @@ -64,14 +65,14 @@ namespace margelo::nitro { jsi::Object obj = arg.asObject(runtime); return margelo::nitro::pay::PaymentToken( JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "paymentMethod"))), - JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "transactionIdentifier"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "transactionIdentifier"))), JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "paymentData"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::pay::PaymentToken& arg) { jsi::Object obj(runtime); obj.setProperty(runtime, PropNameIDCache::get(runtime, "paymentMethod"), JSIConverter::toJSI(runtime, arg.paymentMethod)); - obj.setProperty(runtime, PropNameIDCache::get(runtime, "transactionIdentifier"), JSIConverter::toJSI(runtime, arg.transactionIdentifier)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "transactionIdentifier"), JSIConverter>::toJSI(runtime, arg.transactionIdentifier)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "paymentData"), JSIConverter::toJSI(runtime, arg.paymentData)); return obj; } @@ -84,7 +85,7 @@ namespace margelo::nitro { return false; } if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "paymentMethod")))) return false; - if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "transactionIdentifier")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "transactionIdentifier")))) return false; if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "paymentData")))) return false; return true; } diff --git a/package/src/__tests__/paymentHandler.test.ts b/package/src/__tests__/paymentHandler.test.ts index 1c355d5..a5eb258 100644 --- a/package/src/__tests__/paymentHandler.test.ts +++ b/package/src/__tests__/paymentHandler.test.ts @@ -1,10 +1,12 @@ import { act, renderHook, waitFor } from '@testing-library/react-native' +import { PAYMENT_IN_PROGRESS_RESULT as IN_PROGRESS_RESULT } from '../paymentHandler' -const IN_PROGRESS_RESULT = { +const DECLINED_RESULT = { + status: 'failed', + code: 'PROVIDER_ERROR', success: false, - error: 'A payment is already in progress', + error: 'Declined', } -const DECLINED_RESULT = { success: false, error: 'Declined' } const mockInstances: object[] = [] const mockPresentations: Array<(result: any) => void> = [] @@ -21,6 +23,8 @@ jest.mock('react-native-nitro-modules', () => ({ startPayment: () => { if (inFlight) { return Promise.resolve({ + status: 'failed', + code: 'IN_PROGRESS', success: false, error: 'A payment is already in progress', }) diff --git a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts index b9b3c75..05aa93d 100644 --- a/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts +++ b/package/src/hooks/__tests__/usePaymentCheckout.integration.test.ts @@ -18,10 +18,13 @@ import { usePaymentCheckout, type UsePaymentCheckoutConfig, } from '../usePaymentCheckout' +import { PAYMENT_IN_PROGRESS_RESULT as IN_PROGRESS_RESULT } from '../../paymentHandler' -const IN_PROGRESS_RESULT = { +const CANCELLED_RESULT = { + status: 'cancelled', + code: 'CANCELLED', success: false, - error: 'A payment is already in progress', + error: 'Payment cancelled by user', } function createDeferred() { @@ -309,10 +312,13 @@ describe('usePaymentCheckout integration', () => { }) it('sets an error when native payment response has success=false', async () => { - mockStartPayment.mockResolvedValueOnce({ + const declined = { + status: 'failed', + code: 'PROVIDER_ERROR', success: false, error: 'Declined by issuer', - }) + } + mockStartPayment.mockResolvedValueOnce(declined) const { result } = renderCheckout() act(() => { @@ -324,10 +330,54 @@ describe('usePaymentCheckout integration', () => { }) expect(result.current.error?.message).toBe('Declined by issuer') - expect(result.current.result).toEqual({ - success: false, - error: 'Declined by issuer', + expect(result.current.result).toEqual(declined) + }) + + it('does not treat a cancel as an error', async () => { + mockStartPayment.mockResolvedValueOnce(CANCELLED_RESULT) + const { result } = renderCheckout() + + act(() => { + result.current.addItem('Order', 9.99) }) + + let paymentResult: any = null + await act(async () => { + paymentResult = await result.current.startPayment() + }) + + expect(paymentResult).toEqual(CANCELLED_RESULT) + expect(result.current.result?.status).toBe('cancelled') + expect(result.current.result?.code).toBe('CANCELLED') + expect(result.current.error).toBeNull() + expect(result.current.isProcessing).toBe(false) + }) + + it('clears the previous error when the next payment is cancelled', async () => { + mockStartPayment + .mockResolvedValueOnce({ + status: 'failed', + code: 'PROVIDER_ERROR', + success: false, + error: 'Declined by issuer', + }) + .mockResolvedValueOnce(CANCELLED_RESULT) + const { result } = renderCheckout() + + act(() => { + result.current.addItem('Order', 9.99) + }) + await act(async () => { + await result.current.startPayment() + }) + expect(result.current.error).not.toBeNull() + + await act(async () => { + await result.current.startPayment() + }) + + expect(result.current.error).toBeNull() + expect(result.current.result).toEqual(CANCELLED_RESULT) }) it('forwards Apple Pay override and Google Pay config when provided', async () => { @@ -488,13 +538,20 @@ describe('usePaymentCheckout integration', () => { try { const authorization = await options.onAuthorize(token, details) return authorization.status === 'success' - ? { success: true, token, ...details } + ? { status: 'success', success: true, token, ...details } : { + status: 'failed', + code: 'PROVIDER_ERROR', success: false, error: authorization.error ?? 'Payment authorization failed', } } catch (err) { - return { success: false, error: (err as Error).message } + return { + status: 'failed', + code: 'PROVIDER_ERROR', + success: false, + error: (err as Error).message, + } } } @@ -532,6 +589,7 @@ describe('usePaymentCheckout integration', () => { expect(onAuthorize).toHaveBeenCalledWith(token, details) expect(paymentResult).toEqual({ + status: 'success', success: true, token, emailAddress: 'jane@example.com', @@ -554,7 +612,12 @@ describe('usePaymentCheckout integration', () => { paymentResult = await result.current.startPayment() }) - expect(paymentResult).toEqual({ success: false, error: 'Card declined' }) + expect(paymentResult).toEqual({ + status: 'failed', + code: 'PROVIDER_ERROR', + success: false, + error: 'Card declined', + }) expect(result.current.error?.message).toBe('Card declined') }) @@ -664,7 +727,12 @@ describe('usePaymentCheckout integration', () => { }) it('resets transient checkout state', async () => { - mockStartPayment.mockResolvedValueOnce({ success: false, error: 'Failed' }) + mockStartPayment.mockResolvedValueOnce({ + status: 'failed', + code: 'PROVIDER_ERROR', + success: false, + error: 'Failed', + }) const { result } = renderCheckout() act(() => { @@ -755,6 +823,8 @@ describe('usePaymentCheckout integration', () => { it('leaves its state alone when native reports a payment in progress', async () => { mockStartPayment.mockResolvedValueOnce({ + status: 'failed', + code: 'PROVIDER_ERROR', success: false, error: 'Declined', }) diff --git a/package/src/hooks/usePaymentCheckout.ts b/package/src/hooks/usePaymentCheckout.ts index 560f922..c02e747 100644 --- a/package/src/hooks/usePaymentCheckout.ts +++ b/package/src/hooks/usePaymentCheckout.ts @@ -6,7 +6,10 @@ import { useLayoutEffect, useRef, } from 'react' -import { getPaymentHandler, PAYMENT_IN_PROGRESS_ERROR } from '../paymentHandler' +import { + getPaymentHandler, + PAYMENT_IN_PROGRESS_RESULT, +} from '../paymentHandler' import type { PaymentAmount, PaymentRequest, @@ -135,7 +138,8 @@ export interface UsePaymentCheckoutConfig { /** * Called with the token after the user authorizes the payment. Charge it on * your server and resolve with the outcome; `startPayment` then resolves - * with `success: false` and your `error` on `'failure'`. + * with `status: 'failed'`, `code: 'PROVIDER_ERROR'` and your `error` on + * `'failure'`. * On iOS the Apple Pay sheet waits for it and shows the outcome. On Android * it runs after the Google Pay sheet has closed. * It must settle within 25 seconds, or the payment fails with a timeout. @@ -187,7 +191,9 @@ export interface UsePaymentCheckoutReturn { // Payment processing startPayment: () => Promise isProcessing: boolean + /** The last result. A cancel has `status: 'cancelled'` and no `error`. */ result: PaymentResult | null + /** Set when a payment fails or can't start; stays `null` on a cancel. */ error: Error | null // Utilities @@ -444,7 +450,7 @@ export function usePaymentCheckout( return null } if (isPaymentInProgress) { - return { success: false, error: PAYMENT_IN_PROGRESS_ERROR } + return { ...PAYMENT_IN_PROGRESS_RESULT } } if (items.length === 0) { @@ -478,7 +484,8 @@ export function usePaymentCheckout( setResult(paymentResult) - if (!paymentResult.success) { + // A cancel is the user's choice, not an error. + if (paymentResult.status === 'failed') { setError(new Error(paymentResult.error || 'Payment failed')) } diff --git a/package/src/paymentHandler.ts b/package/src/paymentHandler.ts index bbd8df7..9f8e772 100644 --- a/package/src/paymentHandler.ts +++ b/package/src/paymentHandler.ts @@ -1,5 +1,6 @@ import { NitroModules } from 'react-native-nitro-modules' import type { PaymentHandler } from './specs/PaymentHandler.nitro' +import type { PaymentResult } from './types' /** * Error returned when `startPayment` is called while another payment is @@ -7,6 +8,17 @@ import type { PaymentHandler } from './specs/PaymentHandler.nitro' */ export const PAYMENT_IN_PROGRESS_ERROR = 'A payment is already in progress' +/** + * Result of `startPayment` while another payment is in flight, as the native + * handlers return it. Copy it before handing it out. + */ +export const PAYMENT_IN_PROGRESS_RESULT: Readonly = { + status: 'failed', + code: 'IN_PROGRESS', + success: false, + error: PAYMENT_IN_PROGRESS_ERROR, +} + let paymentHandler: PaymentHandler | undefined /** diff --git a/package/src/types/Payment.ts b/package/src/types/Payment.ts index b5152c9..7a6d067 100644 --- a/package/src/types/Payment.ts +++ b/package/src/types/Payment.ts @@ -159,7 +159,9 @@ export interface PaymentMethod { export interface PaymentToken { paymentMethod: PaymentMethod - transactionIdentifier: string + // Apple's transaction identifier on iOS. Missing on Android: Google Pay + // doesn't return one. + transactionIdentifier?: string paymentData: string // Base64 encoded Data from PKPaymentToken } export interface PaymentRequest { @@ -252,10 +254,46 @@ export interface PaymentDetails { shippingMethod?: ShippingMethod } +/** + * How a payment ended. `'cancelled'` means the user closed the sheet before + * authorizing; it is not an error. + */ +export type PaymentStatus = 'success' | 'cancelled' | 'failed' + +/** + * Why a payment did not succeed. Set on every result whose `status` is not + * `'success'`. + * + * - `'CANCELLED'`: the user closed the sheet before authorizing. + * - `'IN_PROGRESS'`: another payment is still in flight. No sheet was shown. + * - `'CONFIGURATION'`: the request or the app's setup is invalid, such as a + * missing merchant ID or an invalid amount. Retrying won't help. + * - `'NOT_AVAILABLE'`: the device can't show the payment sheet right now. + * - `'PROVIDER_ERROR'`: Apple Pay, Google Pay or your `onAuthorize` reported a + * failure, including an `onAuthorize` timeout. + * - `'UNKNOWN'`: anything else. + */ +export type PaymentErrorCode = + | 'CANCELLED' + | 'IN_PROGRESS' + | 'CONFIGURATION' + | 'NOT_AVAILABLE' + | 'PROVIDER_ERROR' + | 'UNKNOWN' + export interface PaymentResult extends PaymentDetails { + status: PaymentStatus + code?: PaymentErrorCode + // `status === 'success'`. Kept for compatibility. success: boolean + /** + * @deprecated A random ID generated on the device for each successful + * result. It doesn't come from Apple, Google or your gateway and changes on + * every attempt, so don't use it as an idempotency key: use your order ID. + */ transactionId?: string token?: PaymentToken + // A message for logs. Also set when `status` is `'cancelled'`. error?: string } @@ -267,7 +305,8 @@ export type PaymentAuthorizationStatus = 'success' | 'failure' */ export interface PaymentAuthorizationResult { status: PaymentAuthorizationStatus - // Reported as `PaymentResult.error` when `status` is `'failure'`. + // Reported as `PaymentResult.error`, with code `'PROVIDER_ERROR'`, when + // `status` is `'failure'`. error?: string }