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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ All notable changes to this project are documented in this file.
`paymentRequest.googlePayAllowPrepaidCards` gives it for the button. Omitted or `true`, the
requests are unchanged. Android only
([#87](https://github.com/gmi-software/react-native-pay/issues/87)).
- **`applePayMerchantCategoryCode`** and **`applePayLaterAvailability`** in `PaymentRequest`.
The first sets `PKPaymentRequest.merchantCategoryCode`, an ISO 18245 code from 0 to 9999, so
Apple Pay leaves out the cards that don't accept the category (iOS 18 and later). The second
(`ApplePayLaterAvailability`: `'available'`, `'itemIneligible'`, `'recurringTransaction'`) hides
Apple Pay Later and tells the payer why (iOS 17 and later). Earlier iOS versions ignore them, but
an invalid value fails with `code: 'CONFIGURATION'` on any iOS version. iOS only; Android ignores
both ([#78](https://github.com/gmi-software/react-native-pay/issues/78)).
- **`PaymentError` with a `code`.** `usePaymentCheckout` now sets `error` to a `PaymentError`, an
`Error` subclass whose `code` is a `PaymentErrorCode`: `'CONFIGURATION'` for an empty cart or an
invalid request, `'UNKNOWN'` when native code threw, and the result's `code` (`'UNKNOWN'` if it
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,8 @@ interface PaymentRequest {
automaticReload?: AutomaticReloadPaymentRequest; // top-ups, iOS 16+
applePayMultiTokenContexts?: PaymentTokenContext[]; // several merchants, iOS 16+
couponCode?: string; // iOS only, needs onCouponCodeChange
applePayMerchantCategoryCode?: number; // ISO 18245 code, iOS 18+
applePayLaterAvailability?: string; // ApplePayLaterAvailability value, iOS 17+
// Google Pay specific
googlePayMerchantId?: string;
googlePayEnvironment?: "TEST" | "PRODUCTION";
Expand Down Expand Up @@ -925,6 +927,8 @@ Google Pay accepts at most two decimal places, so three-decimal amounts (`"1.234

Google Pay can leave credit cards out, but not debit cards. On Android, `"Debit"` without `"Credit"` sends `allowCreditCards: false`, which UK gambling merchants must do; prepaid cards stay allowed. `["3DS", "Credit"]` accepts every card type on Android, so check the card on your server if you must refuse debit cards. Give `GooglePayButton` and `payServiceStatus` the same `merchantCapabilities` as the payment.

`applePayMerchantCategoryCode` (an ISO 18245 code from 0 to 9999, iOS 18+) leaves out the cards that don't accept your category. `applePayLaterAvailability` (`"available"`, `"itemIneligible"` or `"recurringTransaction"`, iOS 17+) hides Apple Pay Later and tells the payer why. Earlier iOS versions and Android ignore both; an invalid value fails the payment on iOS. See [`PaymentRequest`](https://gmi-software.github.io/react-native-pay/docs/api/types#paymentrequest).

### Shipping and contact details

Set `billingContactRequired`, `shippingContactRequired`, `emailRequired` or `phoneNumberRequired` to ask the payer for a billing address, a shipping address, an email address or a phone number. Each one fills `billingContact`, `shippingContact`, `emailAddress` or `phoneNumber` in the result and in the second argument of `onAuthorize`, on both platforms. Google Pay only collects a phone number with an address: without `shippingContactRequired`, Android asks for it with at least the billing name, country and postal code.
Expand Down
21 changes: 21 additions & 0 deletions docs/docs/api/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ interface PaymentRequest {
automaticReload?: AutomaticReloadPaymentRequest
applePayMultiTokenContexts?: PaymentTokenContext[] // several merchants, iOS 16+
couponCode?: string // iOS only, needs onCouponCodeChange
applePayMerchantCategoryCode?: number // ISO 18245 code, iOS 18+
applePayLaterAvailability?: string // ApplePayLaterAvailability value, iOS 17+
// Google Pay (Android)
googlePayMerchantId?: string
googlePayEnvironment?: 'TEST' | 'PRODUCTION'
Expand Down Expand Up @@ -122,6 +124,10 @@ Without `googlePayEnvironment`, Android uses `'TEST'`. When it is omitted, an An

`couponCode` is a code already applied, shown in the sheet's coupon field; `paymentItems` must already include its discount. It needs `StartPaymentOptions.onCouponCodeChange`, or the payment fails with `code: 'CONFIGURATION'`. iOS only; Android ignores it.

`applePayMerchantCategoryCode` is your ISO 18245 merchant category code, a whole number from 0 to 9999, for example `5411` for grocery stores. Apple Pay leaves out the cards that don't accept the category. iOS 18 and later use it; earlier versions ignore it. Another value, including a fraction, fails the payment on any iOS version: the result has `code: 'CONFIGURATION'` and `error: 'Invalid merchant category code <value>. Use a whole number from 0 to 9999'`. iOS only; Android ignores it.

`applePayLaterAvailability` takes an [`ApplePayLaterAvailability`](#applepaylateravailability) value. iOS only; Android ignores it.

---

## PaymentResult
Expand Down Expand Up @@ -483,6 +489,21 @@ For example, `'delivery'` shows "Delivery Address" instead of "Shipping Address"

---

## ApplePayLaterAvailability

Whether the payer may pay with Apple Pay Later, used in `PaymentRequest.applePayLaterAvailability` (iOS 17 and later; earlier versions and Android ignore the field).

```ts
type ApplePayLaterAvailability =
| 'available'
| 'itemIneligible'
| 'recurringTransaction'
```

`'itemIneligible'` and `'recurringTransaction'` hide Apple Pay Later, and the sheet tells the payer why: an item can't be paid over time (gift cards, for example, must not be), or the cart holds a subscription. Without the field, Apple Pay uses `'available'`. Any other value fails the payment on any iOS version: the result has `code: 'CONFIGURATION'` and `error: 'Unknown Apple Pay Later availability "<value>". Use "available", "itemIneligible" or "recurringTransaction"'`.

---

## Pass types (iOS)

These iOS-only types appear in payment-related metadata returned by Apple Pay APIs (for example pass details tied to the selected card) and are mostly useful in advanced/native-integrated flows.
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/payment-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ function describeOutcome(result: PaymentResult): string | null {
| --- | --- | --- | --- |
| `'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. Debug builds log a warning when the sheet closes within 1 second of appearing (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, a `currencyCode` or `countryCode` that isn't an upper-case ISO code, 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, `googlePayCheckoutOption: 'completeImmediatePurchase'` with a `'pending'` item, `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. |
| `'CONFIGURATION'` | The request or the app's setup is invalid. Retrying won't help. | Both: an invalid amount, a negative total, a `currencyCode` or `countryCode` that isn't an upper-case ISO code, 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` or `applePayLaterAvailability`, an `applePayMerchantCategoryCode` that isn't a whole number from 0 to 9999. Android: more than two decimal places, an unknown `googlePayAllowedAuthMethods` value, `googlePayCheckoutOption: 'completeImmediatePurchase'` with a `'pending'` item, `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 can't show it (see [Troubleshooting](/docs/troubleshooting#unable-to-present-payment-authorization)). 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`. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ internal fun paymentRequest(
automaticReload = automaticReload,
applePayMultiTokenContexts = null,
couponCode = null,
applePayMerchantCategoryCode = null,
applePayLaterAvailability = null,
googlePayMerchantId = googlePayMerchantId,
googlePayEnvironment = environment,
googlePayGateway = googlePayGateway,
Expand Down
44 changes: 44 additions & 0 deletions package/ios/HybridPaymentHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ private enum ErrorMessage {
static func unknownShippingType(_ shippingType: String) -> String {
return "Unknown shipping type \"\(shippingType)\". Use \"shipping\", \"delivery\", \"storePickup\" or \"servicePickup\""
}

static func invalidMerchantCategoryCode(_ code: Double) -> String {
// NSNumber prints 10000, not 10000.0.
return "Invalid merchant category code \(NSNumber(value: code)). Use a whole number from 0 to 9999"
}

static func unknownApplePayLaterAvailability(_ availability: String) -> String {
return "Unknown Apple Pay Later availability \"\(availability)\". Use \"available\", \"itemIneligible\" or \"recurringTransaction\""
}
}

/// Why a payment ended without success.
Expand Down Expand Up @@ -119,6 +128,9 @@ struct PaymentRequestBuilder {
paymentRequest.shippingType = try convertShippingType(shippingType)
}

try configureMerchantCategoryCode(paymentRequest, code: request.applePayMerchantCategoryCode)
try configureApplePayLater(paymentRequest, availability: request.applePayLaterAvailability)

configureContactRequirements(paymentRequest, request: request)

return paymentRequest
Expand Down Expand Up @@ -317,6 +329,38 @@ struct PaymentRequestBuilder {
}
}

/// Checks the code on every iOS version, so a bad one fails the same
/// everywhere; only iOS 18 and later can use it.
private static func configureMerchantCategoryCode(_ paymentRequest: PKPaymentRequest, code: Double?) throws {
guard let code = code else { return }
guard let rawValue = Int16(exactly: code), (0...9999).contains(rawValue) else {
throw PaymentFailure.configuration(ErrorMessage.invalidMerchantCategoryCode(code))
}
if #available(iOS 18.0, *) {
paymentRequest.merchantCategoryCode = PKPaymentRequest.MerchantCategoryCode(rawValue: rawValue)
}
}

/// The `ApplePayLaterAvailability` values, so iOS before 17 checks them too.
private enum ApplePayLater: String {
case available, itemIneligible, recurringTransaction
}

/// Checks the value on every iOS version, like the category code;
/// Apple Pay Later needs iOS 17.
private static func configureApplePayLater(_ paymentRequest: PKPaymentRequest, availability: String?) throws {
guard let availability = availability else { return }
guard let value = ApplePayLater(rawValue: availability) else {
throw PaymentFailure.configuration(ErrorMessage.unknownApplePayLaterAvailability(availability))
}
guard #available(iOS 17.0, *) else { return }
switch value {
case .available: paymentRequest.applePayLaterAvailability = .available
case .itemIneligible: paymentRequest.applePayLaterAvailability = .unavailable(.itemIneligible)
case .recurringTransaction: paymentRequest.applePayLaterAvailability = .unavailable(.recurringTransaction)
}
}

private static func configureContactRequirements(_ paymentRequest: PKPaymentRequest, request: PaymentRequest) {
if request.billingContactRequired == true {
paymentRequest.requiredBillingContactFields = [.postalAddress, .name]
Expand Down
75 changes: 75 additions & 0 deletions package/ios/Tests/PaymentRequestBuilderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,81 @@ final class PaymentRequestBuilderTests: XCTestCase {
)
}

func testSetsTheMerchantCategoryCode() throws {
let request = try PaymentRequestBuilder.build(from: paymentRequest(
items: [item("Coffee", "4.99")],
merchantCategoryCode: 5411
))

guard #available(iOS 18.0, *) else { throw XCTSkip("Needs iOS 18") }
XCTAssertEqual(request.merchantCategoryCode?.rawValue, 5411)
}

func testAcceptsTheEdgesOfTheMerchantCategoryCodeRange() throws {
for code in [0.0, 9999.0] {
let request = try PaymentRequestBuilder.build(from: paymentRequest(
items: [item("Coffee", "4.99")],
merchantCategoryCode: code
))
if #available(iOS 18.0, *) {
XCTAssertEqual(request.merchantCategoryCode?.rawValue, Int16(code))
}
}
}

func testLeavesTheMerchantCategoryCodeAloneWithoutOne() throws {
let request = try PaymentRequestBuilder.build(from: paymentRequest(items: [item("Coffee", "4.99")]))

guard #available(iOS 18.0, *) else { throw XCTSkip("Needs iOS 18") }
// PassKit's own default, which is 0000 rather than nil on iOS 26.
XCTAssertEqual(request.merchantCategoryCode, PKPaymentRequest().merchantCategoryCode)
}

func testRejectsAnInvalidMerchantCategoryCode() {
let cases: [(Double, String)] = [
(-1, "-1"),
(10000, "10000"),
(5411.5, "5411.5"),
(40000, "40000"),
(.nan, "nan"),
]
for (code, shown) in cases {
assertBuildFails(
paymentRequest(items: [item("Coffee", "4.99")], merchantCategoryCode: code),
with: "Invalid merchant category code \(shown). Use a whole number from 0 to 9999"
)
}
}

func testSetsApplePayLaterAvailability() throws {
guard #available(iOS 17.0, *) else { throw XCTSkip("Needs iOS 17") }
func availability(_ value: String) throws -> PKPaymentRequest.ApplePayLaterAvailability {
return try PaymentRequestBuilder.build(from: paymentRequest(
items: [item("Coffee", "4.99")],
applePayLaterAvailability: value
)).applePayLaterAvailability
}

guard case .available = try availability("available") else {
return XCTFail("Expected available")
}
guard case .unavailable(.itemIneligible) = try availability("itemIneligible") else {
return XCTFail("Expected unavailable(.itemIneligible)")
}
guard case .unavailable(.recurringTransaction) = try availability("recurringTransaction") else {
return XCTFail("Expected unavailable(.recurringTransaction)")
}
}

func testRejectsUnknownApplePayLaterAvailability() {
for value in ["unavailable", "ItemIneligible", ""] {
assertBuildFails(
paymentRequest(items: [item("Coffee", "4.99")], applePayLaterAvailability: value),
with: "Unknown Apple Pay Later availability \"\(value)\". Use \"available\", \"itemIneligible\" or \"recurringTransaction\""
)
}
}

func testAppendsAMerchantTotalToASingleItem() throws {
// PassKit shows the last item as the total, so one item still gets one.
let request = try PaymentRequestBuilder.build(from: paymentRequest(
Expand Down
2 changes: 2 additions & 0 deletions package/ios/Tests/PaymentSheetSessionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ final class PaymentSheetSessionTests: XCTestCase {
automaticReload: nil,
applePayMultiTokenContexts: nil,
couponCode: nil,
applePayMerchantCategoryCode: nil,
applePayLaterAvailability: nil,
googlePayMerchantId: nil,
googlePayEnvironment: nil,
googlePayGateway: nil,
Expand Down
6 changes: 5 additions & 1 deletion package/ios/Tests/TestFixtures.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ func paymentRequest(
deferred: DeferredPaymentRequest? = nil,
automaticReload: AutomaticReloadPaymentRequest? = nil,
multiTokenContexts: [PaymentTokenContext]? = nil,
couponCode: String? = nil
couponCode: String? = nil,
merchantCategoryCode: Double? = nil,
applePayLaterAvailability: String? = nil
) -> PaymentRequest {
return PaymentRequest(
applePayMerchantIdentifier: merchantIdentifier,
Expand All @@ -54,6 +56,8 @@ func paymentRequest(
automaticReload: automaticReload,
applePayMultiTokenContexts: multiTokenContexts,
couponCode: couponCode,
applePayMerchantCategoryCode: merchantCategoryCode,
applePayLaterAvailability: applePayLaterAvailability,
googlePayMerchantId: nil,
googlePayEnvironment: nil,
googlePayGateway: nil,
Expand Down
Loading
Loading