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

Posted

技术标签:

【中文标题】Apple Pay 处理错误 资金不足或其他极端情况【英文标题】:Apple Pay handle errors Insufficient funds or other edge cases 【发布时间】:2021-01-07 14:41:17 【问题描述】:

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

我还需要确认付款成功。

据我所知,PKPaymentAuthorizationControllerDelegate 方法都没有涵盖这些情况。

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

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


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

【问题讨论】:

【参考方案1】:

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

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)
    

这里我使用上面的方法来产生一些错误对象,在我的例子中,我说提供的电话号码是错误的。

// 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])

【讨论】:

以上是关于Apple Pay 处理错误 资金不足或其他极端情况的主要内容,如果未能解决你的问题,请参考以下文章

iOS App集成Apple Pay教程(附示例代码)

苹果会强迫您通过Apple Pay进行应用内购买和订阅吗?

Samsung Pay/Apple Pay/Android Pay支付技术大比拼

设置Apple Pay发生错误怎么办

Apple Pay - 支付后端服务器 - iOS

gas 资金不足 * 价格 + 价值