Reputation: 5354
I have implemented Apple Pay in my SwiftUI app and it's working fine. However I need to handle error cases. Let's say the user has not enough money or something else happens. I need this so I can cancel the purchase and show a message.
Also I need a confirmation that the payment was successful.
From what I have seen none of the PKPaymentAuthorizationControllerDelegate
methods covers these cases.
Any idea how to get success/ errors confirmations?
func paymentAuthorizationController(_ controller: PKPaymentAuthorizationController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
completion(.success)
}
func paymentAuthorizationControllerDidFinish(_ controller: PKPaymentAuthorizationController) {
controller.dismiss(completion: nil)
}
Upvotes: 0
Views: 1030
Reputation: 1215
Yo have to implement some network code for payment processing and work with it's response in case of errors and so on. Here some basic code you can use and improve for your cases:
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)
}
}
And here method I used above, to produce some error object, in my case I say what provided phone number is wrong.
// 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])
}
Upvotes: 1