Apple Pay 处理错误资金不足或其他极端情况

Apple Pay handle errors Insufficient funds or other edge cases

我已经在我的 SwiftUI 应用程序中实现了 Apple Pay,并且运行良好。但是我需要处理错误情况。假设用户没有足够的钱或发生其他事情。我需要这个,这样我就可以取消购买并显示消息。

我还需要确认付款成功。

据我所知,PKPaymentAuthorizationControllerDelegate 方法中的 none 涵盖了这些情况。

知道如何获得成功/错误确认吗?

func paymentAuthorizationController(_ controller: PKPaymentAuthorizationController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
    completion(.success)
}

func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) {
    controller.dismiss(completion: nil)
    
}

您必须实施一些用于支付处理的网络代码,并在出现错误等情况下使用它的响应。这里有一些基本代码,您可以为您的案例使用和改进:

func paymentAuthorizationViewController(
    _ controller: PKPaymentAuthorizationViewController,
    didAuthorizePayment payment: PKPayment,
    handler completion: @escaping (PKPaymentAuthorizationResult) -> Void
) {
    // some network code you have to process for payment with payment token and all data what you need
    // it produce some NETWORK_RESPONSE yo can now use - it's up to you what format it will have

    if NETWORK_RESPONSE.success {
        let successResult = PKPaymentAuthorizationResult(status: .success, errors: nil)
        completion(successResult)
    } else if let someErrors = NETWORK_RESPONSE.errors {
        let errorResult = responsePrepared(with: error)
        completion(errorResult)
    } else {
        let defaultFailureResult = PKPaymentAuthorizationResult(status: .failure, errors: nil)
        completion(defaultFailureResult)
    }
}

我在上面使用的方法来生成一些错误对象,在我的例子中,我说提供的 phone 数字是错误的。

// it's up to you to produce here the error response object with error messages and pointing
func responsePrepared(with error: Error) -> PKPaymentAuthorizationResult{
    let phoneNumberError = NSError.init(
        domain: PKPaymentErrorDomain,
        code: PKPaymentError.shippingContactInvalidError.rawValue,
        userInfo: [
            NSLocalizedDescriptionKey: message,
            PKPaymentErrorKey.contactFieldUserInfoKey.rawValue: PKContactField.phoneNumber
        ])

    return PKPaymentAuthorizationResult(status: .failure, errors: [phoneNumberError])
}