A Complete Guide to Integrate Apple Payment Method in iOS App – 1

After the launch of Apple pay, Apple took a huge step into the world of mobile payments. It has brought a new Apple payment method for developers to handle mobile payments and its process is as easy as a touch of a finger.

You can basically use Apple pay in two ways: one is at the point of sale with NFC (Near Field Communication). It allows shoppers to pay using their iPhones if the store owner has installed NFC terminals. And second is, users can use Apple pay within your iOS app.

In this Apple pay tutorial, we’re going to show how to integrate Apple pay in your native iOS app. And in the next part, we’ll show how to add Stripe payment gateway in the Apple pay feature.

Let’s Get Started!

First Register a Merchant ID in your developer account by following steps.

  • In Member Center, select Certificates, Identifiers & Profiles.

ApplePay1

  • Under Identifiers, select Merchant IDs.

ApplePay2

  • Click the Add button (+) in the upper-right corner.

ApplePay3

  • Enter a description and identifier, and click Continue.
  • Review the settings, and click Register.

Now to configure Merchant ID follow below steps.

  • In Member Center, select Certificates, Identifiers & Profiles.
  • Under Identifiers, select Merchant IDs.
  • Select the merchant ID from the list, and click Edit.
  • Click Create Certificate, follow the instructions to obtain or generate your certificate signing request (CSR), and click Continue.
  • Click Choose File, select your CSR, and click Generate.
  • Download the certificate by clicking Download, and click Done.

Next, create a project in XCode.

  • Create a new project under file menu and select “Single View Application”.

ApplePay4

  • In the next tab, name your iOS project. Here, we’re naming it as “SOApplePay”.

ApplePay5

Create an object of product list and for selected items in “ViewController.swift”.

//Array of product with price
var quotesArray : NSMutableArray = [
["Product": "Shirt", "Price": "20", "Note": "Nice Shirt"],
["Product": "Shoes", "Price": "12", "Note": "Nice Shoes"],
]
var items : NSMutableDictionary = NSMutableDictionary()
  • Once you create the object, Set outlet of UITableView for show list of product.
@IBOutlet weak var tblShopping: UITableView!
  • Set PKPayment Authorization ViewController Delegate in “ViewController.swift”
class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate
  • Add a Apple pay button in “ViewController.swift” in viewDidLoad()
let btnApplePay: PKPaymentButton
if PKPaymentAuthorizationViewController.canMakePayments() {
btnApplePay = PKPaymentButton(type: .Buy, style: .Black)
} else {
btnApplePay = PKPaymentButton(type: .SetUp, style: .Black)
}

btnApplePay.addTarget(self, action: #selector(ViewController.payByApplePay), forControlEvents: .TouchUpInside)
btnApplePay.frame = CGRectMake(40, view.frame.size.height - 60, view.frame.size.width - 80,  40)
view.addSubview(btnApplePay)
  • Create a shopping list in UITableView and show the list by set DataSource and Delegate of tableview.
//MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return quotesArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
configureCell(cell, forRowAtIndexPath: indexPath)
return cell
}

func configureCell(cell: UITableViewCell, forRowAtIndexPath: NSIndexPath) {
let lblProduct : UILabel = cell.contentView.viewWithTag(1) as! UILabel
let lblPrice : UILabel = cell.contentView.viewWithTag(2) as! UILabel
let lblNote : UILabel = cell.contentView.viewWithTag(3) as! UILabel

let dict : NSDictionary = quotesArray.objectAtIndex(forRowAtIndexPath.row) as! NSDictionary
lblProduct.text = dict.valueForKey("Product") as? String
lblPrice.text = "$" + (dict.valueForKey("Price") as! String)
lblNote.text = dict.valueForKey("Note") as? String
}

ApplePay6

  • When user select any of product by clicking on list, it will be added to “items”
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
items.addEntriesFromDictionary(quotesArray.objectAtIndex(indexPath.row) as! [NSObject : AnyObject])
}

ApplePay7

  • Now tap on Apple pay button for payment process.
// MARK: - Apple Pay
func payByApplePay() {
if items.count == 0 {
self.showAlertButtonTapped("Please Try Again", strMessage: "Please select a Product.")
return
}

// Create a PKPaymentRequest Object
let request = PKPaymentRequest()
request.supportedNetworks = [PKPaymentNetworkAmex, PKPaymentNetworkVisa]

//Set countryCode and its currency
request.countryCode = "US"
request.currencyCode = "USD"

//Keep your merchange id here (which you have created in your apple developer account)
request.merchantIdentifier = "merchant.com.soapplepay.app"

//Add merchantCapabilities (EMV, Credit, Debit)
request.merchantCapabilities = .Capability3DS

//Keep shipping address field (Email, PostalAddress, Name, Phone or All)
request.requiredShippingAddressFields = .Email

// Create shipping methods
let freeShipping = PKShippingMethod(label: "Free Shipping", amount: NSDecimalNumber(double: 0.00))
freeShipping.identifier = "free"
freeShipping.detail = "Arrive in 1-2 weeks"

let expressShipping = PKShippingMethod(label: "Express Shipping", amount: NSDecimalNumber(double: 2.99))
expressShipping.identifier = "express"
expressShipping.detail = "Arrive in 3-4 days"

request.paymentSummaryItems = getPaymentSummary(freeShipping)
request.shippingMethods = [freeShipping,expressShipping]

//Now present apple payment authorization viewController
let objApplePay = PKPaymentAuthorizationViewController(paymentRequest: request)
objApplePay.delegate = self
self.presentViewController(objApplePay, animated: true, completion: nil)
}
//Add items for purchase with shipping
func getPaymentSummary(shippingMethod: PKShippingMethod) -> [PKPaymentSummaryItem] {

//Add items summery with title and price
let objItem = PKPaymentSummaryItem(label: items.valueForKey("Product") as! String , amount: NSDecimalNumber(string: items.valueForKey("Price") as? String))

//Add shipping
let shippingChargeItem = PKPaymentSummaryItem(label: shippingMethod.label, amount: shippingMethod.amount)

//Get total of item
let cartTotal = objItem.amount.decimalNumberByAdding(shippingChargeItem.amount)
let total = PKPaymentSummaryItem(label: "Space-0", amount: cartTotal)

return [objItem, shippingChargeItem , total]
}

ApplePay8

// MARK: - PKPayment Delegate
//Change shipping method
func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController, didSelectShippingMethod shippingMethod: PKShippingMethod, completion: (PKPaymentAuthorizationStatus, [PKPaymentSummaryItem]) -> Void) {
completion(.Success, getPaymentSummary(shippingMethod))
}

ApplePay9

ApplePay10

//Handle the Payment completion status from this delegate
func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: (PKPaymentAuthorizationStatus) -> Void) {
completion(.Success)
}

ApplePay11

//Payment Authorization ViewController is dismiss in case
//Payment done or
//Payment cancelled
func paymentAuthorizationViewControllerDidFinish(controller: PKPaymentAuthorizationViewController) {
controller.dismissViewControllerAnimated(true) {

}
}

Completed! By above steps, you’ve successfully integrated Apple pay in your iOS app. If you face any problem during implementation, you can contact our developers for help!

Apple pay is one of the most convenient ways for users to make payments via mobiles and it can surely increase your sales. If you don’t know how it helps, then you should check out our How Mobile Payment Feature Strengthen Business With More Sales article & The Growth of Promising Mobile Payment Technologies article to get a clear idea.

Now that you’ve the whole idea behind adding mobile payment feature, how about you hire iPhone app developer from Space-O Technologies for implementing it in your iOS app?

We’re a leading iPhone app development company in India with 200+ highly experienced developers, who solely focus on building complete user-friendly, feature-rich, and innovative mobile apps. We’ve developed 2000+ mobile applications throughout our journey, don’t forget to check out our portfolio!

You can download a copy of Apple payment method integration code from Github.

This page was last edited on May 3rd, 2018, at 4:20.
 
 

Want to Integrate Apple Payment Method? Contact Us Now.

Get your free consultation now