Apple Pay Tutorial: Getting Started

Enter the world of mobile payments on iOS in this Apple Pay tutorial! You’ll learn how to implement Apple Pay in your iOS apps to collect payment for physical goods and services. By Erik Kerber.

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 6 of this article. Click here to view the first page.

Creating a Payment Request

Open BuySwagViewController.swift and add the following import to the top of the file:

import PassKit

The Apple Pay classes are actually part of PassKit, so you need that import to do anything useful.

Next, locate purchase(sender:); you execute this when the user attempts to purchase an item. To do this, you’ll need to create a PKPaymentRequest and a PKPaymentAuthorizationViewController.

Add the following code to the body of purchase(sender:):

let request = PKPaymentRequest()
let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request)
self.presentViewController(applePayController, animated: true, completion: nil)

This code creates a simple PKPaymentRequest object that represents a single Apple Pay payment, as well as the creation of a PKPaymentAuthorizationViewController constructed with the PKPaymentRequest instance responsible for displaying the Apple Pay payment sheet. Finally, the BuySwagViewController presents the PKPaymentAuthorizationViewController.

You’ll need to populate the required elements of PKPaymentRequest next to see your Apple Pay sheet in action.

Populating PKPaymentRequest

Add the following code just under the IBOutlet properties of BuySwagViewController:

let SupportedPaymentNetworks = [PKPaymentNetworkVisa, PKPaymentNetworkMasterCard, PKPaymentNetworkAmex]
let ApplePaySwagMerchantID = "merchant.com.YOURDOMAIN.ApplePaySwag" // Fill in your merchant ID here!

SupportedPaymentNetworks defines an array of payment networks you are able to accept. You set these depending on your ability to process each of these payment networks; in this tutorial you’ll accept all three. ApplePaySwagMerchantID is a string that matches the merchant ID you created on the developer portal and set in your app’s Capabilities.

It would be a good idea to hide the Apple Pay button if the user isn’t able to make payments for some reason, such as parental control settings or not having the right hardware. In that case, you’ll just let them window shop.

Add the following code to viewDidLoad():

applePayButton.hidden = !PKPaymentAuthorizationViewController.canMakePaymentsUsingNetworks(SupportedPaymentNetworks)

canMakePaymentsUsingNetworks returns a Boolean if the user can make payments, so you negate this value with ! to set whether the button should be hidden or not.

Add the following lines to purchase(sender:), below the point where you instantiate PKPaymentRequest:

request.merchantIdentifier = ApplePaySwagMerchantID
request.supportedNetworks = SupportedPaymentNetworks
request.merchantCapabilities = PKMerchantCapability.Capability3DS
request.countryCode = "US"
request.currencyCode = "USD"

These five fields tell the payment request about the capabilities of your transaction:

  1. merchantIdentifier is your merchant ID. This is used to decrypt the cryptogram on the backend.
  2. supportedNetworks tells the request which networks you support. This affects which of your user’s cards show up in the Apple Pay sheet.
  3. merchantCapabilities is the security standard you want to use. The details of this are outside the scope of this tutorial, but for now you’ll use 3DS which is the most popular standard in the US.
  4. countryCode is the 2-character country code where your transaction takes place. For now, this is set to US as it is the only supported country at the time this tutorial was published; more countries will be available in the future.
  5. currencyCode is the currency of your transaction; since you set countryCode to US, set this to USD.

Now you’ll add some code specific to the swag that will tell the customer the most important detail of this interaction — how much this swag is going to cost them! :]

Add the following code below the PKPaymentRequest setup code you just added:

request.paymentSummaryItems = [
    PKPaymentSummaryItem(label: swag.title, amount: swag.price),
    PKPaymentSummaryItem(label: "Razeware", amount: swag.price)
]

Here, you create an array of PKPaymentSummaryItem objects that provide the user with a breakdown the items they’re purchasing. You might notice that the same price is repeated with different labels. When creating arrays of PKPaymentSummaryItem, the last summary item will be the amount charged and the label will be prepended with the text PAY TO.

Build and run your app on a physical device; select your swag of choice and press the Apple Pay button. You should see the Apple Pay sheet pop up on the screen like so:

ApplePay-Lite

It’s exciting to see that fingerprint icon on the screen! Scan your programmed-finger-of-choice on the touch ID sensor, and remember, your account won’t be charged. Instead, you’ll see the wait spinner spin forever; tap Cancel to exit out of this state.

Nothing happens here because there’s more interaction you’ll need to handle using a delegate on the PKPaymentAuthorizationViewController named PKPaymentAuthorizationViewControllerDelegate.

Implementing Delegates to Handle Payment Requests

In BuySwagViewController.swift, add the following extension to BuySwagViewController that implements PKPaymentAuthorizationViewControllerDelegate:

extension BuySwagViewController: PKPaymentAuthorizationViewControllerDelegate {
  func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController!, didAuthorizePayment payment: PKPayment!, completion: ((PKPaymentAuthorizationStatus) -> Void)!) {
    completion(PKPaymentAuthorizationStatus.Success)
  }
  
  func paymentAuthorizationViewControllerDidFinish(controller: PKPaymentAuthorizationViewController!) {
    controller.dismissViewControllerAnimated(true, completion: nil)
  }
}

This implements the two required methods of PKPaymentAuthorizationViewControllerDelegate:

  • paymentAuthorizationViewController(controller:didAuthorizePayment:completion:): This handles the user authorization to complete the purchase.
  • paymentAuthorizationViewControllerDidFinish(controller:): This is called when the payment request completes.

The PKPayment object holds the Apple Pay authorization token, as well as final shipping, billing, and contact information for the order, which you’ll handle later in this tutorial.

paymentAuthorizationViewController(controller:didAuthorizePayment:completion:) is where you’ll eventually send the payment request to your backend for processing. This is also why you saw the spinner spin indefinitely. The Apple Pay sheet will remain in place until you invoke the completion handler; this gives you the amount of time you need to complete the transaction. For now though, you simply hardcode the parameter to the completion block with PKPaymentAuthorizationStatus.Success.

The responsibility of paymentAuthorizationViewControllerDidFinish(controller:), for now, is simply to dismiss the view controller when finished.

Add the following line to purchase(sender:) right after the creation of your PKPaymentAuthorizationViewController to set its delegate:

applePayController.delegate = self

Build and run your project; select a piece of swag and tap the Apple Pay button one more time. Scan your finger on the Touch ID and… darn, an error alert!

Not Available

You thought you had everything set up properly for Apple Pay — so why the error?

Your app is not currently permitted to use Apple Pay because you haven’t yet added a certificate from your payment provider — you’ll do that a bit later in the tutorial.

The Apple Pay sheet you present to the user is fairly simple; it only has a method to select which credit card to use to complete the payment. That’s sufficient for payment purposes — but not enough information for your shipping department to send the user the swag they just purchased! You’ll need to tell PKPaymentRequest what kind of information you require from the user to complete the transaction.

Erik Kerber

Contributors

Erik Kerber

Author

Over 300 content creators. Join our team.