From af73ba765096d06734f3f48914851b0bfd65f1bf Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Tue, 27 Oct 2026 15:02:54 +0100 Subject: [PATCH] fix(ios): present the Apple Pay sheet in its own window startPayment presented PKPaymentAuthorizationViewController from the app's top view controller. When that view controller was being dismissed, for example while a modal closed, UIKit closed the sheet with it or refused to show it, and no delegate method ran. The promise never settled, and every later call returned "A payment is already in progress" until the app restarted. Present with PKPaymentAuthorizationController instead, which has its own window, and settle the payment with "Unable to present payment authorization" when PassKit reports that it could not show the sheet. Implement presentationWindow(for:), which visionOS requires. Fixes #20 --- CHANGELOG.md | 9 + docs/docs/payment-flow.md | 2 +- docs/docs/troubleshooting.md | 4 + package/ios/HybridPaymentHandler.swift | 162 ++++++++++------- .../Tests/PaymentSheetPresenterTests.swift | 164 ++++++++++++++++++ 5 files changed, 281 insertions(+), 60 deletions(-) create mode 100644 package/ios/Tests/PaymentSheetPresenterTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 03a5f01..99627e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/docs/payment-flow.md b/docs/docs/payment-flow.md index 5a577d3..7267b8b 100644 --- a/docs/docs/payment-flow.md +++ b/docs/docs/payment-flow.md @@ -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`. | diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index aca3a9e..78ef84d 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -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 "". 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). diff --git a/package/ios/HybridPaymentHandler.swift b/package/ios/HybridPaymentHandler.swift index baa4f82..037eae6 100644 --- a/package/ios/HybridPaymentHandler.swift +++ b/package/ios/HybridPaymentHandler.swift @@ -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 @@ -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 @@ -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 ) { @@ -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) @@ -568,8 +639,14 @@ private class PaymentDelegate: NSObject, PKPaymentAuthorizationViewControllerDel class HybridPaymentHandler: HybridPaymentHandlerSpec { private let pendingPayment = PendingPayment() // 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. @@ -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) } @@ -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)) } + ) } } diff --git a/package/ios/Tests/PaymentSheetPresenterTests.swift b/package/ios/Tests/PaymentSheetPresenterTests.swift new file mode 100644 index 0000000..5383d05 --- /dev/null +++ b/package/ios/Tests/PaymentSheetPresenterTests.swift @@ -0,0 +1,164 @@ +import PassKit +import XCTest +@testable import NitroPay + +/// Answers `present` the way the test asks, on the queue it names. +private final class FakeSheet: PaymentSheet { + weak var delegate: PKPaymentAuthorizationControllerDelegate? + private let presents: Bool + private let queue: DispatchQueue? + private(set) var presentCount = 0 + + init(presents: Bool, answeringOn queue: DispatchQueue? = nil) { + self.presents = presents + self.queue = queue + } + + func present(completion: (@Sendable (Bool) -> Void)?) { + presentCount += 1 + let presents = self.presents + if let queue { + queue.async { completion?(presents) } + } else { + completion?(presents) + } + } +} + +private final class SheetDelegate: NSObject, PKPaymentAuthorizationControllerDelegate { + func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) {} + + func presentationWindow(for controller: PKPaymentAuthorizationController) -> UIWindow? { + return nil + } +} + +final class PaymentSheetPresenterTests: XCTestCase { + + private let delegate = SheetDelegate() + + /// What the presenter reported once its work on the main queue has run. + private func reportedFailure(from presenter: PaymentSheetPresenter) -> PaymentFailure? { + var failure: PaymentFailure? + presenter.present(PKPaymentRequest(), delegate: delegate) { failure = $0 } + let drained = expectation(description: "main queue drained") + DispatchQueue.main.async { drained.fulfill() } + wait(for: [drained], timeout: 1) + return failure + } + + func testReportsARefusedSheet() { + let presenter = PaymentSheetPresenter { _ in FakeSheet(presents: false) } + + let failure = reportedFailure(from: presenter) + + XCTAssertEqual(failure?.code, .notAvailable) + XCTAssertEqual(failure?.message, "Unable to present payment authorization") + } + + func testReportsNothingForAPresentedSheet() { + let sheet = FakeSheet(presents: true) + let presenter = PaymentSheetPresenter { _ in sheet } + + XCTAssertNil(reportedFailure(from: presenter)) + XCTAssertEqual(sheet.presentCount, 1) + XCTAssertTrue(sheet.delegate === delegate) + } + + func testReportsARequestPassKitCannotShow() { + let presenter = PaymentSheetPresenter { _ in nil } + + let failure = reportedFailure(from: presenter) + + XCTAssertEqual(failure?.code, .notAvailable) + XCTAssertEqual(failure?.message, "Unable to create payment authorization") + } + + func testReportsARefusalOnTheMainThreadWhenPassKitAnswersOffIt() { + let presenter = PaymentSheetPresenter { _ in + FakeSheet(presents: false, answeringOn: .global()) + } + let reported = expectation(description: "refusal reported") + var reportedOnMain: Bool? + + presenter.present(PKPaymentRequest(), delegate: delegate) { _ in + reportedOnMain = Thread.isMainThread + reported.fulfill() + } + wait(for: [reported], timeout: 1) + + XCTAssertEqual(reportedOnMain, true) + } + + func testHoldsTheSheetUntilReleased() { + weak var weakSheet: FakeSheet? + let presenter = PaymentSheetPresenter { _ in + let sheet = FakeSheet(presents: true) + weakSheet = sheet + return sheet + } + + _ = reportedFailure(from: presenter) + XCTAssertNotNil(weakSheet) + + presenter.release() + XCTAssertNil(weakSheet) + } +} + +/// Runs `startPayment` with a sheet PassKit refuses, as in issue #20. +final class RefusedPaymentSheetTests: XCTestCase { + + private func paymentRequest() -> PaymentRequest { + return PaymentRequest( + applePayMerchantIdentifier: "merchant.com.example", + merchantName: "Example", + countryCode: "US", + currencyCode: "USD", + paymentItems: [PaymentItem(label: "Coffee", amount: .second("4.99"), type: .final)], + merchantCapabilities: ["3DS"], + supportedNetworks: ["visa"], + shippingType: nil, + shippingMethods: nil, + billingContactRequired: nil, + shippingContactRequired: nil, + emailRequired: nil, + phoneNumberRequired: nil, + googlePayMerchantId: nil, + googlePayEnvironment: nil, + googlePayGateway: nil, + googlePayGatewayMerchantId: nil, + googlePayAllowedAuthMethods: nil + ) + } + + func testSettlesThePaymentAndLetsTheNextOneStart() throws { + var sheets: [FakeSheet] = [] + let handler = HybridPaymentHandler(sheetPresenter: PaymentSheetPresenter { _ in + let sheet = FakeSheet(presents: false) + sheets.append(sheet) + return sheet + }) + + for attempt in 1...2 { + let settled = expectation(description: "payment \(attempt) settled") + var status: PaymentStatus? + var code: PaymentErrorCode? + var error: String? + try handler.startPayment(request: paymentRequest(), options: nil).then { result in + status = result.status + code = result.code + error = result.error + settled.fulfill() + } + wait(for: [settled], timeout: 1) + + XCTAssertEqual(status, .failed) + XCTAssertEqual(code, .notAvailable) + XCTAssertEqual(error, "Unable to present payment authorization") + XCTAssertFalse(try handler.isPaymentInProgress()) + } + // The second payment reached PassKit instead of "already in progress". + XCTAssertEqual(sheets.map(\.presentCount), [1, 1]) + } +}