Apple Pay Payments Integration
You can follow Offering Apple Pay in Your App to implement Apple Pay within your app.
func present() {
items = [
PKPaymentSummaryItem(label: "Moyasar", amount: 1.00, type: .final)
]
let request = PKPaymentRequest()
request.paymentSummaryItems = items
request.merchantIdentifier = "merchant.mysr.fghurayri"
request.countryCode = "SA"
request.currencyCode = "SAR"
request.supportedNetworks = [ .amex, .masterCard, .visa, .mada ]
request.merchantCapabilities = [
.capability3DS,
.capabilityCredit,
.capabilityDebit
]
controller = PKPaymentAuthorizationController(paymentRequest: request)
controller?.delegate = self
controller?.present(completion: {(p: Bool) in // OR add your custom navigation as needed .
print("Presented: " + (p ? "Yes" : "No"))
})
}
info
If you want to know how to use apply pay button please check the component section in this docs .
- When the user authorizes the payment using Face ID or Touch ID on their iOS device, the
didAuthorizePayment
event will be dispatched. In this step, you must pass thetoken
toApplePayService
found within thePKPayment
object. Here is an example:
func paymentAuthorizationController(_ controller: PKPaymentAuthorizationController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
Task {
do {
let apiPaymentResult = try await applePayService!.authorizePayment(request: paymentRequest, token: payment.token)
handleCompletedPaymentResult(apiPaymentResult, handler: completion)
} catch {
// Handle the error case
print(error)
completion(PKPaymentAuthorizationResult(status: .failure, errors: [error]))
}
}
}
func handleCompletedPaymentResult(_ apiPaymentResult: ApiPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
print("Got payment, status: \(apiPaymentResult.status)")
print(apiPaymentResult.status)
print(apiPaymentResult.id)
switch (apiPaymentResult.status) {
case .paid:
completion(PKPaymentAuthorizationResult(status: .success, errors: []))
case .failed:
let message: String = if case let .applePay(source) = apiPaymentResult.source {
source.message ?? "unspecified"
} else {
"Returned API source is not Apple Pay"
}
completion(PKPaymentAuthorizationResult(status: .failure, errors: [DemoError.paymentError(message)]))
default:
completion(PKPaymentAuthorizationResult(status: .failure, errors: [DemoError.paymentError("Unexpected status returned by API")]))
}
}
info
- Don't forget:
- Call the
completion
. If, for some reason, the closure is not called, it would result in the Apple Pay sheet hanging or other unexpected behavior. Therefore, it's crucial to ensure that the completion is always called, regardless of the payment process outcome. - Import
PassKit
.
- Call the
- An error will be printed if the API key format is incorrect.
- After the payment is finished, the
paymentAuthorizationControllerDidFinish
delegate function will be called; allowing you todismiss
the controller within it.