Apple Pay
Client-Side Implementation
Once your Certificate and Merchant ID are set up, you can add Apple Pay to your app.
Apple Pay user experience
Apple Pay has specific user experience and identity guidelines, which Apple may enforce during the App Store review process. Please consult these guidelines as well as Apple's developer information when designing your Apple Pay user experience.
Get the SDK
Custom UI Integration
CocoaPods
Include Braintree/ApplePay in your podfile:
- Ruby
pod 'Braintree/ApplePay'
Carthage
Include the BraintreeApplePay and BraintreeCore frameworks.
Drop-in UI Integration
No additional steps are required to fetch the BraintreeApplePay module once BraintreeDropIn has been included in your project.
Initialization
Like all Braintree SDK integrations, you will first need to initialize the Braintree SDK client:
- Swift
var braintreeClient: BTAPIClient?
// BTAPIClient can be initialized in a couple different ways, here's one example:
braintreeClient = BTAPIClient(authorization: CLIENT_AUTHORIZATION)
Your app will submit an Apple Pay authorization to Braintree and receive a payment method nonce in return, which can be used for server-side processing.
PassKit integration and payment tokenization
- To integrate Apple Pay, follow the Apple Pay Programming Guide (
PKPaymentRequest
,PKPaymentAuthorizationViewController
, etc.) - Use our SDK to tokenize the resulting
PKPayment
- You are responsible for coordinating Apple Pay (PKPaymentRequest) and Braintree configurations
Set up your Apple Pay button
Apple provides an Apple Pay button, PKPaymentButton
. See their brand guidelines for more information.
- Swift
func applePayButton() -> UIButton {
let button = PKPaymentButton(type: PKPaymentButtonType.buy, style: PKPaymentButtonStyle.black)
button?.addTarget(self, action: #selector(tappedApplePay), for: UIControlEvents.touchUpInside)
return button!
}
Custom UI
Apple Pay is only available on certain iOS devices. Before presenting the Apple Pay option to the current user, you should determine whether Apple Pay is available.
- Swift
import PassKit
// Add BraintreeApplePay.h to bridging header
class MyCheckoutViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {
// ...
override func viewDidLoad() {
super.viewDidLoad()
// Conditionally show Apple Pay button based on device availability
if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: [PKPaymentNetwork.visa, PKPaymentNetwork.masterCard, PKPaymentNetwork.amex, PKPaymentNetwork.discover]) {
let button = self.applePayButton()
// TODO: Set button constraints/frame...
self.view.addSubview(button)
}
}
// ...
}
Drop-in UI
First, you must properly configure the Drop-in UI.
If your customer selects Apple Pay via the Drop-in, the result.paymentMethodType == .applePay and result.paymentMethod will be nil. If Apple Pay was selected, you must now show a PKPaymentButton.
- Swift
let dropIn = BTDropInController(authorization: clientTokenOrTokenizationKey, request: request) {
(controller, result, error) in
if (result?.paymentMethodType == .applePay) {
// Display PKPaymentButton
let button = self.applePayButton()
// TODO: Set button constraints/frame...
// self.view.addSubview(button)
}
}
Create a PKPaymentRequest
Before you can initiate a user-facing Apple Pay experience, you will need to initialize a payment request:
- Swift
func setupPaymentRequest(completion: @escaping (PKPaymentRequest?, Error?) -> Void) {
let applePayClient = BTApplePayClient(apiClient: self.braintreeApiClient)
// You can use the following helper method to create a PKPaymentRequest which will set the 'countryCode',
// 'currencyCode', 'merchantIdentifier', and 'supportedNetworks' properties.
// You can also create the PKPaymentRequest manually. Be aware that you'll need to keep these in
// sync with the gateway settings if you go this route.
applePayClient.paymentRequest { (paymentRequest, error) in
guard let paymentRequest = paymentRequest else {
completion(nil, error)
return
}
// We recommend collecting billing address information, at minimum
// billing postal code, and passing that billing postal code with all
// Apple Pay transactions as a best practice.
paymentRequest.requiredBillingContactFields = [.postalAddress]
// Set other PKPaymentRequest properties here
paymentRequest.merchantCapabilities = .capability3DS
paymentRequest.paymentSummaryItems =
[
PKPaymentSummaryItem(label: "<#ITEM_NAME#>", amount: NSDecimalNumber(string: "<#PRICE#>")),
// Add add'l payment summary items...
PKPaymentSummaryItem(label: "<#COMPANY NAME#>", amount: NSDecimalNumber(string: "<#GRAND TOTAL#>")),
]
completion(paymentRequest, nil)
}
}
Here are some Braintree-specific recommendations about the various fields in the PKPaymentRequest:
- countryCode: We suggest using the country where your business is located
- currencyCode: This value must correspond to your Braintree merchant account's currency
- merchantCapabilities: Please use PKMerchantCapability3DS (PKMerchantCapabilityEMV corresponds to in-store purchasing only)
- merchantIdentifier: This value must match up with the merchantIdentifier and certificate on file in both Apple's developer center and Braintree's Control Panel
- paymentSummaryItems: This value is required, and the grand total amount should not exceed the amount that is authorized or submitted for settlement
- supportedNetworks: This value must match up with your merchant account's accepted payment methods
- requiredBillingContactFields: We recommend including PKContactFieldPostalAddress as a best practice
In order to be prepared to make changes without re-releasing your app, you should consider setting these values dynamically based on a response from your server.
In particular, you should be careful about keeping the PKPaymentRequest in sync with server environment (production vs. sandbox), as well as with your merchant account configuration and Apple Pay configuration. Self-service certificate management can be found in the Control Panel by clicking the gear icon in the top right corner, selecting Processing from the drop-down menu, scrolling to Apple Pay, and clicking the Options link.
Present a PKPaymentAuthorizationViewController
When your user taps on your Apple Pay UI, present a PKPaymentAuthorizationViewController to initiate Apple Pay:
- Swift
func tappedApplePay() {
self.setupPaymentRequest { (paymentRequest, error)
guard error == nil else {
// Handle error
return
}
// Example: Promote PKPaymentAuthorizationViewController to optional so that we can verify
// that our paymentRequest is valid. Otherwise, an invalid paymentRequest would crash our app.
if let vc = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
as PKPaymentAuthorizationViewController?
{
vc.delegate = self
present(vc, animated: true, completion: nil)
} else {
print("Error: Payment request is invalid.")
}
}
}
Implement PKPaymentAuthorizationViewControllerDelegate
Implement the PKPaymentAuthorizationViewControllerDelegate protocol methods. In your implementation of paymentAuthorizationViewController:didAuthorizePayment:handler:, create a nonce by tokenizing the PKPayment via the Braintree SDK:
- Swift
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
didAuthorizePayment payment: PKPayment,
handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
// Tokenize the Apple Pay payment
braintree!.tokenizeApplePay(payment) { (nonce, error) in
if error != nil {
// Received an error from Braintree.
// Indicate failure via the completion callback.
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil)
return
}
// TODO: On success, send nonce to your server for processing.
// If requested, address information is accessible in 'payment' and may
// also be sent to your server.
// Then indicate success or failure based on the server side result of Transaction.sale
// via the completion callback.
// e.g. If the Transaction.sale was successful
completion(PKPaymentAuthorizationResult(status: .success, errors: nil))
}
}
You must also implement the paymentAuthorizationViewControllerDidFinish(_:)
delegate method to handle the dismissal of the Apple Pay sheet upon Apple Payment finishing.
- Swift
func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
// Apple Payment finished
dismiss(animated: true)
}
Next Page: Server-side →