Integrating Apple Pay in IOS Application (Part I)

Pranjal Vyas
7 min readAug 14, 2023

--

In today’s digital landscape, the integration of technology has become increasingly vital for a seamless user experience. Among the frontrunners in this domain is Apple, which offers a comprehensive suite of services that can be effortlessly integrated into iOS applications. In this article, we’ll dive into the world of Apple integration on iOS, exploring the key services available, their benefits, and how developers can leverage them to create exceptional user experiences.

Benefits of Apple Integration

  • Seamless User Experience: Integration of Apple services ensures a consistent and user-friendly experience, as users are already familiar with these services.
  • Enhanced Security and Privacy: Apple’s emphasis on security and privacy translates into safer transactions and protected user data.
  • Efficient Authentication: Apple’s authentication methods, such as Apple Sign-In, streamline the login process and reduce friction for users.
  • Leveraging Hardware Capabilities: Developers can tap into device-specific features like Touch ID, Face ID for innovative app functionalities.
  • Cross-Device Syncing: Apple’s ecosystem allows users to seamlessly transition between devices while maintaining their data and preferences.

Prerequisites

  1. Apple Developer Account: You need an active Apple Developer account to access the necessary tools, documentation, and resources for integrating Apple Pay and other services into your app.
  2. Payment Processing Account: You need to have a merchant account or payment processing service to handle transactions made through Apple Pay. This could be a bank account, payment gateway, or third-party payment processor.

Lets Go

Enough of chitter chatter , lets get our hands dirty, but alas, before we get into code we need to do some setup to please our Apple Gods.

  1. Merchant ID creation: We need to add a merchant id to proceed with apple pay integration. For this move to identifiers page and add an identifier by selecting merchant id

Add a valid merchant id , best practice is to add your bundle id after merchant. Eg. merchant.com.sample.app

Click continue and register and you are done !!

2. Certificate creation : First things first, to generate a certificate we need a csr file, to generate this hit cmd+space , type in keychain access and open it up.

Click on Keychain Access in tool bar and select Certificate Assistant >> Request a certificate from a Certificate Authority

Add a email id and Common name , leave CA email address as blank and don’t forget to select saved to disk. Click Continue

Thats it save the csr file to any location. Keep this in handy , we will need it!

Now head back to our identifier tab, click on the identifier we created in step 1.

You will see there is an option to create certificate. Click on that button.

Next you would be asked the following question, Will payments associated with this Merchant ID be processed exclusively in China mainland?

Answer it according to your use case . Click Continue.

Upload the csr certificate you just created and click continue and then download this certificate. Store this certificate for future use.

That it! Done with the certificate creation.

3. Adding Capability

Finally we can move to XCode , sigh, cant start with coding as of yet. One more step to go before we get to tipitty tap part.

Move to your target , select your app as your target. Click on Signing & Capabilities . Click on the + icon and select apple pay, if all went well , you will see your merchant id already, if its not selected select it. Easy Peasy right?

4. Code Integration

Yay! Tipitty Tap time!

Open the ViewController where you want to invoke apple pay, will not go into the logic for making an eCommerce app, you might have different use cases. Lets take an example of buying a video game !

User can select a video game and pay by apple pay. Basic Scenario right?

Lets make a helper class to handle the apple pay stuff. Naming it ApplePayHelper. Add a method pay to handle the payment

func pay(label : String,amount : NSDecimalNumber){
let paymentItem = PKPaymentSummaryItem.init(label: label, amount: amount) //1
var paymentNetworks = [PKPaymentNetwork.amex, .discover, .masterCard, .visa] //2

if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) { //3
let request = PKPaymentRequest() //4
request.currencyCode = "USD"
request.countryCode = "US"
request.merchantIdentifier = "merchant.com.sample.app"
request.merchantCapabilities = PKMerchantCapability.capability3DS
request.supportedNetworks = paymentNetworks
request.paymentSummaryItems = [paymentItem]


guard let paymentVC = PKPaymentAuthorizationViewController(paymentRequest: request) else {
displayDefaultAlert(title: "Error", message: "Unable to present Apple Pay authorization.")
return
}
paymentVC.delegate = viewController as! any PKPaymentAuthorizationViewControllerDelegate
viewController!.present(paymentVC, animated: true, completion: nil)

} else {
displayDefaultAlert(title: "Error", message: "Unable to make Apple Pay transaction.")
}

}

Now dissecting the code

  1. PKPaymentSummaryItemwould require the label . Label can be the name of the game in our case . EG. “Baldur’s Gate 3”. And it need the amount as a decimal number, eg. if its $20.54 would need to send 20.54

2. PKPaymentNetwork needs to be added, it is basically whitelisting the options you allow your users to go for in payment.

3.PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) this line is very important for us to check whether the user can even do a payment , it can happen so that user doesn’t have apple pay authorized in their respective country , or the user has not added the valid payment method we mentioned in step 2. If this returns false , you can gracefully handle this condition and show some error message to the user.

4. PKPaymentRequest is where we generate a payment request for our use case , you can add shipping address, billing address etc here as well. Check here for further details. We have added country and currency code , the merchant identifier that we created early on. capability3DS is just the cryptographic payment protocol channel we selected.

Present the PKPaymentAuthorizationViewController and we are done. This should open up the apple pay bottom modal. But our work here is not done. We need to get some details back from apple right? Or else how would the actual transaction happen?

For this we need to add delegate to our calling ViewController

extension ViewController : PKPaymentAuthorizationViewControllerDelegate{
func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
dismiss(animated: true, completion: nil)
}
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
dismiss(animated: true, completion: nil)
print("SUCCES APPLE PAY")
let token = payment.token
let paymentData = token.paymentData
let paymentMethod = token.paymentMethod
let transactionIdentifier = token.transactionIdentifier


let json = (try? JSONSerialization.jsonObject(with: paymentData, options: [])) as? NSDictionary
print(json ?? "Empty Data")

var paymentMethodString = ""

switch(paymentMethod.type.rawValue){
case 0 :
paymentMethodString = "unknown"
break
case 1 :
paymentMethodString = "debit"
break
case 2 :
paymentMethodString = "credit"
break
case 3 :
paymentMethodString = "prepaid"
break
case 4 :
paymentMethodString = "store"
break
case 5 :
paymentMethodString = "eMoney"
break
default:
paymentMethodString = "unknown"
break
}

var paymentMethodDictionary = [
"displayName" : paymentMethod.displayName!,
"network" : paymentMethod.network!.rawValue,
"type" : paymentMethodString
] as NSDictionary
print(paymentMethodDictionary)
print(transactionIdentifier)
// Use this data depending on the merchant you are going to use , the merchant may need these data
}
}

paymentAuthorizationViewControllerDidFinish : in this method you can dismiss the apple modal

paymentAuthorizationViewController : Here is where you get the payment token. Depending on the merchant, you might need to share this token with the merchant or you would need to extract the data from the token and then share it.

Some questions must be popping up for someone integrating apple pay for the first time

  1. Q: What is this merchant you keep talking about? A : Apple on its own doesn’t do the transaction , it will give you this token , you need to signup with a merchant to enable you to do the payment from the details capture from apple and also transfer the money to your account. You can use Visa, or Stripe
  2. Q: How do i test this? I can’t use my actual card to do the payment A: You can use sandbox environment which apple provides where you can add some dummy cards to test.
  3. Q: I can’t test , the country where I live doesn’t have apple Pay A: Same as 2, the sandbox account you create , you can set its country as USA for example and proceed with testing.

We will discuss in details the Sandbox environment setup in part 2. I hope this article was helpful for you.

If you enjoyed this article, please click the 👏 button and share to help others find it! Feel free to leave a comment below.

--

--

Pranjal Vyas

Passionate iOS, Android, and Flutter developer creating seamless mobile experiences. Backend explorer diving into Node.js and Rust for robust APIs.