Topics

#196: Apple Pay Basics 💰

Topics

Today we'll take a look at how to add Apple Pay to an app, letting users buy things. Let's begin.

Our first step is to go to Project > Capabilities > Apple Pay and flip the switch to "on". This will configure our project to use Apple Pay and create a Merchant ID for us automatically (We'll use this later when configuring our payment request). Then, we'll importing PassKit, and add a button to kick off the process:

let paymentButton = PKPaymentButton(type:.Buy, style: .Black)
paymentButton.addTarget(self, action: "paymentButtonTapped", forControlEvents: .TouchUpInside)

Next, inside paymentButtonTapped, we'll create a payment request, andan authorization view controller.

func paymentButtonTapped() {
  let request = PKPaymentRequest()

  request.merchantIdentifier = "merchant.com.magnus.apple-samplecode.apple-pay.Emporium"

  request.countryCode = "US"
  request.currencyCode = "USD"

  request.supportedNetworks = [PKPaymentNetworkVisa, PKPaymentNetworkMasterCard]
  request.merchantCapabilities = .Capability3DS // 3DS or EMV

  request.paymentSummaryItems = [
    PKPaymentSummaryItem(label: "Little Bites of Cocoa Volume 1", amount: NSDecimalNumber(double: 39.99), type: .Final),
    PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(double: 5.99), type: .Final),
    PKPaymentSummaryItem(label: "Tax", amount: NSDecimalNumber(double: 3.79), type: .Final),
    PKPaymentSummaryItem(label: "Total", amount: NSDecimalNumber(double: 49.77), type: .Final)
  ]

  let authVC = PKPaymentAuthorizationViewController(paymentRequest: request)
  authVC.delegate = self
  presentViewController(authVC, animated: true, completion: nil)
}

Then we'll implement the authorized delegate function:

func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: (PKPaymentAuthorizationStatus) -> Void) {
  print(payment.token)
  completion(.Success)
}

Now that we've got the groundwork laid, we can sign up for a payment provide like Stripe.

Essentially we'll just send the payment.token we got to them, wait for them to process, then call the given completion closure with their result.