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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ All notable changes to this project are documented in this file.
- **Android: `GooglePayButton`'s `radius` is in dp, as documented.** It was passed to Google Pay as
pixels, so corners were about a third of the requested size on a typical phone. Apps that
enlarged `radius` to compensate should set it back.
- **iOS: a payment no longer hangs when the Apple Pay sheet cannot stay on screen.** The sheet
was presented from the app's top view controller. When `startPayment()` ran while that view
controller was being dismissed, for example while a modal closed, UIKit closed the sheet with
it, or refused to show it, and PassKit never called back. The promise never settled, and every
later call returned "A payment is already in progress" until the app restarted. The sheet now
opens in its own window (`PKPaymentAuthorizationController`), so the app's view controllers
cannot refuse or close it. If PassKit still cannot show it, `startPayment` resolves with
`status: 'failed'`, `code: 'NOT_AVAILABLE'` and
`error: 'Unable to present payment authorization'`, and the next call opens a new sheet.
- **Android: `supportedNetworks` limits the cards the payer can choose.** Android ignored it and
always offered Visa, Mastercard, Amex and Discover, so a merchant whose gateway refuses Amex
still received Amex tokens, and JCB or Interac could not be enabled. The payment request, the
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 @@ -86,7 +86,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 (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`. |
| `'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
4 changes: 4 additions & 0 deletions docs/docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ npx expo prebuild --clean

See [Apple Pay button not showing](#apple-pay-button-not-showing) for the full checklist.

### "Unable to present payment authorization"

`startPayment` resolves with `status: 'failed'`, `code: 'NOT_AVAILABLE'` and this `error` when PassKit could not show the Apple Pay sheet. No sheet appeared and nothing was charged. The payment has ended, so the next `startPayment` call opens a new sheet. If you see it while the app is in the foreground, [open an issue](https://github.com/gmi-software/react-native-pay/issues) with the iOS version and what was on screen.

### "Unknown merchant capability"

The payment fails with `code: 'CONFIGURATION'` and `Unknown merchant capability "<value>". 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).
Expand Down
162 changes: 103 additions & 59 deletions package/ios/HybridPaymentHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -431,9 +431,67 @@ private enum PaymentResultFactory {
}
}

// MARK: - Payment Sheet

/// What the handler needs from `PKPaymentAuthorizationController`, so the
/// unit tests can stand in a sheet that PassKit refuses to present.
protocol PaymentSheet: AnyObject {
var delegate: PKPaymentAuthorizationControllerDelegate? { get set }
func present(completion: (@Sendable (Bool) -> Void)?)
}

extension PKPaymentAuthorizationController: PaymentSheet {}

/// Presents the Apple Pay sheet and holds it until `release()`: the sheet's
/// delegate is weak, and no view controller owns it. Main thread only.
/// Internal, not private, so the NitroPay unit tests can reach it.
final class PaymentSheetPresenter {
private let makeSheet: (PKPaymentRequest) -> PaymentSheet?
private var sheet: PaymentSheet?

init(makeSheet: @escaping (PKPaymentRequest) -> PaymentSheet? = PaymentSheetPresenter.makePassKitSheet) {
self.makeSheet = makeSheet
}

/// Calls `onFailure` when there is no sheet. PassKit then calls no
/// delegate method, so `onFailure` is the payment's only chance to settle.
func present(
_ request: PKPaymentRequest,
delegate: PKPaymentAuthorizationControllerDelegate,
onFailure: @escaping (PaymentFailure) -> Void
) {
guard let sheet = makeSheet(request) else {
onFailure(PaymentFailure(code: .notAvailable, message: ErrorMessage.unableToCreate))
return
}
sheet.delegate = delegate
self.sheet = sheet
sheet.present { presented in
guard !presented else { return }
// PassKit does not say which thread this runs on.
DispatchQueue.main.async {
onFailure(PaymentFailure(code: .notAvailable, message: ErrorMessage.unableToPresent))
}
}
}

func release() {
sheet = nil
}

static func makePassKitSheet(for request: PKPaymentRequest) -> PaymentSheet? {
// The controller's initializer never fails, but the view controller's
// returns nil when the device cannot pay or the request is invalid.
guard PKPaymentAuthorizationViewController(paymentRequest: request) != nil else {
return nil
}
return PKPaymentAuthorizationController(paymentRequest: request)
}
}

// MARK: - Payment Delegate

private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDelegate {
private class PaymentDelegate: NSObject, PKPaymentAuthorizationControllerDelegate {
private weak var paymentHandler: HybridPaymentHandler?
private let request: PaymentRequest
private let paymentRequest: PKPaymentRequest
Expand All @@ -459,9 +517,9 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel
self.summaryItems = paymentRequest.paymentSummaryItems
}

func paymentAuthorizationViewController(
_ controller: PKPaymentAuthorizationViewController,
didSelect shippingMethod: PKShippingMethod,
func paymentAuthorizationController(
_ controller: PKPaymentAuthorizationController,
didSelectShippingMethod shippingMethod: PKShippingMethod,
handler completion: @escaping (PKPaymentRequestShippingMethodUpdate) -> Void
) {
selectedShippingMethodIdentifier = shippingMethod.identifier
Expand All @@ -476,8 +534,8 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel
completion(PKPaymentRequestShippingMethodUpdate(paymentSummaryItems: summaryItems))
}

func paymentAuthorizationViewController(
_ controller: PKPaymentAuthorizationViewController,
func paymentAuthorizationController(
_ controller: PKPaymentAuthorizationController,
didAuthorizePayment payment: PKPayment,
handler completion: @escaping (PKPaymentAuthorizationResult) -> Void
) {
Expand Down Expand Up @@ -538,17 +596,30 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel
return request.shippingMethods?.first { $0.identifier == identifier }
}

func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
controller.dismiss(animated: true) {
// Report the merchant's outcome, not a cancellation, once it arrives.
if self.isAuthorizing {
self.finishedWhileAuthorizing = true
return
func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) {
controller.dismiss {
// PassKit does not say which thread this runs on.
DispatchQueue.main.async {
// Report the merchant's outcome, not a cancellation, once it arrives.
if self.isAuthorizing {
self.finishedWhileAuthorizing = true
return
}
self.reportResult()
}
self.reportResult()
}
}

// Required on visionOS. PassKit shows the sheet on this window's scene. A
// scene is still foregroundInactive right after a system alert closes.
func presentationWindow(for controller: PKPaymentAuthorizationController) -> UIWindow? {
let windows = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.filter { $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive }
.flatMap(\.windows)
return windows.first(where: \.isKeyWindow) ?? windows.first
}

private func reportResult() {
if paymentAuthorized, let authorizedResult {
paymentHandler?.handlePaymentResult(authorizedResult)
Expand All @@ -568,8 +639,14 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel
class HybridPaymentHandler: HybridPaymentHandlerSpec {
private let pendingPayment = PendingPayment<PaymentResult>()
// Main thread only
private let sheetPresenter: PaymentSheetPresenter
private var delegate: PaymentDelegate?


init(sheetPresenter: PaymentSheetPresenter = PaymentSheetPresenter()) {
self.sheetPresenter = sheetPresenter
super.init()
}

// MARK: - Public Methods

// PassKit asks the Wallet service, so both checks run off the JS thread.
Expand Down Expand Up @@ -628,6 +705,7 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec {

func handlePaymentResult(_ result: PaymentResult) {
delegate = nil
sheetPresenter.release()
// One-shot settle: Nitro Promise crashes on a second resolve/reject.
pendingPayment.settle(result)
}
Expand All @@ -636,55 +714,21 @@ class HybridPaymentHandler: HybridPaymentHandlerSpec {

private func performPayment(request: PaymentRequest, onAuthorize: AuthorizeCallback?) throws {
let paymentRequest = try PaymentRequestBuilder.build(from: request)
delegate = PaymentDelegate(

let delegate = PaymentDelegate(
paymentHandler: self,
request: request,
paymentRequest: paymentRequest,
onAuthorize: onAuthorize
)

guard let paymentAuthVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest) else {
throw PaymentFailure(code: .notAvailable, message: ErrorMessage.unableToCreate)
}

paymentAuthVC.delegate = delegate

guard let rootViewController = getRootViewController() else {
throw PaymentFailure(code: .notAvailable, message: ErrorMessage.unableToPresent)
}

rootViewController.present(paymentAuthVC, animated: true)
}

private func getRootViewController() -> UIViewController? {
let scenes = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.filter { $0.activationState == .foregroundActive }

let rootViewController = scenes
.flatMap(\.windows)
.first(where: \.isKeyWindow)?
.rootViewController

return topViewController(from: rootViewController)
}

private func topViewController(from viewController: UIViewController?) -> UIViewController? {
guard let viewController else { return nil }

if let navigationController = viewController as? UINavigationController {
return topViewController(from: navigationController.visibleViewController)
}

if let tabBarController = viewController as? UITabBarController {
return topViewController(from: tabBarController.selectedViewController)
}

if let presentedViewController = viewController.presentedViewController {
return topViewController(from: presentedViewController)
}

return viewController
self.delegate = delegate

// The sheet has its own window, so a view controller of the app that
// is busy presenting or dismissing can neither refuse nor close it.
sheetPresenter.present(
paymentRequest,
delegate: delegate,
onFailure: { self.handlePaymentResult(PaymentResultFactory.failure($0)) }
)
}
}
Loading
Loading