Abhijeet Rathore
Posted on September 20, 2019
Apple Pay is a mobile payment and digital wallet service by Apple Inc. that allows users to make payments in person, in iOS apps, and on the web. It is supported on the iPhone, Apple Watch, iPad, and Mac. It digitizes and can replace a credit or debit card chip and PIN transaction at a contactless-capable point-of-sale terminal. Apple Pay does not require Apple Pay-specific contactless payment terminals; it works with any merchant that accepts contactless payments. It supports authentication via passcode, touchID as well as face recognition.
This post is related to Apple Pay integration in Ionic 4 apps. Just like we integrate Stripe, PayPal etc payment gateways in our apps, we can integrate Apple Pay in the apps as well. Benefits of Apple Pay is
- Quick payment using just the phone
- Saving all your cards in the phone, and paying as you like
- Authentication managed by the phone itself
- Keeping your cards in Apple wallet also allows you to pay cashless on payment terminals.
What is Ionic 4?
You probably already know about Ionic, but I’m putting it here just for the sake of beginners. Ionic is a complete open-source SDK for hybrid mobile app development created by Max Lynch, Ben Sperry and Adam Bradley of Drifty Co. in 2013. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices by leveraging Cordova.
So, in other words — If you create Native apps in Android, you code in Java. If you create Native apps in iOS, you code in Obj-C or Swift. Both of these are powerful but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS.
Ionic 4 and Payment Gateways
Ionic 4 can create a wide variety of apps, and hence a wide variety of payment gateways can be implemented in Ionic 4 apps. The popular ones are PayPal, Stripe, Razorpay, Braintree, in-app purchase etc. For more details on payment gateways, you can read my overview blog on Payment Gateway Solutions in Ionic 4 or detailed blogs on PayPal , Stripe and Razorpay.
Apple Pay can be integrated in websites as well as mobile apps. In this blog we’ll learn how to integrate Apple Pay in Ionic 4 apps.
Adding a card in Apple Pay
Before you can use Apple Pay in your apps, you need to have a card added in your Apple wallet. For development purpose, to test the demo flow, you don’t need to add a card. But to test the live payment mode of the app, you will need a card in your app. The process of this is not programmatic, but just for information purpose, you can add a card following this video
Integrating Apple Pay in Ionic 4 apps is very simple and straightforward. It makes use of Ionic native Apple pay plugin, and it works in iOS apps only.
Let’s start step-by-step
Complete source code of this tutorial is available in the Ionic4-applepay Github repository.
Prerequisites
- Create an Ionic 4 app for Apple Payintegration
- Apple Merchant ID and certificate (required for publishing app)
Creating a basic Ionic 4 app is very easy. Assuming you have all basic requirements installed in your system, run
$ ionic start MyApp blank
This creates your app with titleMyApp
and blank template.
For more details on how to create a basic Ionic 4 app, refer to my blog How to create an Ionic 4 app
With minor modifications, my homepage looks like this.
The whole cart-like view is not really necessary for Apple Pay integration, but I have shown it here just for a better understanding of the things. One might want to show this data on their cart page for users to understand clearly (in a better UI of course 😜 )
The file structure looks something like this, just for an idea
The full HTML code can be found in the home.page.html
file in the repository.
Apple Pay Merchant ID and Certificate
If you have done some iOS development, you are aware of Apple’s love for certificates. So, for Apple Pay as well, you need to get a Merchant ID and a Payment Processing Certificate from Apple developer account (you need to have an Apple developer account for this)
- Merchant ID — An identifier you register with Apple that uniquely identifies your business as a merchant able to accept payments. This ID never expires, and can be used in multiple websites and iOS apps. See Create a merchant identifier for the setup steps.
- Payment Processing Certificate — A certificate associated with your merchant ID, used to secure transaction data. Apple Pay servers use the certificate’s public key to encrypt payment data. You (or your payment service provider) use the private key to decrypt the data to process payments. See Create a payment processing certificate for the setup steps.
Integrate Apple Pay plugin in Ionic 4 App
To include Apple Pay functionality in your Ionic 4 app, you need to install Apple Pay plugin. Install the plugin with following commands
$ ionic cordova plugin add cordova-plugin-applepay
$ npm install @ionic-native/apple-pay
After installation completes, import Apple Pay in your app.module.ts
import { ApplePay } from '@ionic-native/apple-pay/ngx';
and include it in the providers
list
Similarly, import Apple Pay in your home.page.ts
and define it in constructor
constructor(private applePay: ApplePay) { }
Methods available in Apple Pay Plugin
Apple Pay plugin is not a complete package for everything that Apple Pay can actually do. The plugin is limited in its ability, but can easily complete your basic payment flow in the app. The methods available are
- canMakePayments — Check whether the device is capable of making payments with Apple Pay
- makePaymentRequest — Create a payment request with appropriate Order
- completeLastTransaction — Mark a payment request complete once a ‘success’ or ‘failure’ is returned from the respective payment bank / card agency.
- startListeningForShippingContactSelection — This does not return a promise, but it fires the success callback upon shipping contact selection.
- updateItemsAndShippingMethods — Update Items and/or shipping methods when user changes a Shipping method / contact
- stopListeningForShippingContactSelection — You can opt to NOT listen to shipping method / contact changes
Details for listening to Shipping contact changes are mentioned in the final section at the end of the post.
1. Applepay.canMakePayments
This method is useful to check if the device supports Apple Pay, or Apple Pay is properly setup in the device. For sample purpose, we will call this method on a button click, but ideally you should call it in background, and appropriately show the user an alert to setup Apple Pay on device.
2. makePaymentRequest
Now the actual payment request !
But before that, let us understand how an Order is created in Apple Pay.
An Order consists of items, price, shipping methods etc. in Apple Pay. The following screenshot summarizes the various parts of an Apply Pay order
Let us explore the Order components one by one
- items — (Array of PKPaymentSummaryItem in swift). Items array is created in a way so that items’ price, delivery price and total price is included in the array in order. Our items array is as follows
-
shippingMethods — Is an array of various Shipping methods available with the merchant. A user can change Shipping method while making payment. You need to implement
startListeningForShippingContactSelection
andupdateItemsAndShippingMethods
to update these changes in the order.
Our sample ShippingMethods array looks like following
Notice, that we have mentioned the first Shipping method in our items
array as well
-
supportedNetworks — currently only Visa, MasterCard, American Express and Discover are accepted as config options. For the ionic plugin, these are denoted by
visa
,masterCard
,amex
anddiscover
respectively. -
merchantCapabilities — current possible values are
3ds
,debit
,credit
andemv
-
merchantIdentifier — This is the merchant ID you create in Apple developer account. It is the unique identifier to identify the merchant. For demo purpose, we will use
merchant.apple.test
-
currencyCode — 3 digit code for currency. We are using
GBP
-
countryCode — 2 digit country code. We are using
GB
-
billingAddressRequirement — The necessary information required for Billing Address. The options are
name
,email
,phone
andnone
. For demo purpose, we are using[‘name’, ‘email’, ‘phone’]
but we won’t be required to set it up, as it is a test run. But including this information in the Order is mandatory or the order will fail / app will crash -
shippingAddressRequirement — The necessary information required for Shipping Address. The options are
name
,email
,phone
andnone
. For demo purpose, we are usingnone
. Again, including this information in the Order is mandatory or the order will fail / app will crash -
shippingType — Can be one of
shipping
,delivery
,store
andservice
⭐️⭐️⭐️⭐️ IMPORTANT⭐️⭐️⭐️⭐️
Including all the parts of an Order when calling makePaymentRequest
is mandatory. Any part missed can cause a failed payment or app crash.
completeLastTransaction
After the payment request is validated, you receive a token. You can pass this token to your payment provider (bank) and wait to receive a success
or other status from the other side. Once the response
arrives, you can complete your transaction with the appropriate string in the function,
ApplePay.completeLastTransaction('success');
You can dismiss or invalidate the Apple Pay sheet by calling completeLastTransaction
with a status string which can be success
, failure
, invalid-billing-address
, invalid-shipping-address
, invalid-shipping-contact
, require-pin
, incorrect-pin
, locked-pin
.
To sum up all the points, the home.page.ts
file will look like following once you are done implementing the above steps.
Modifying Node Module
The Apple Pay Native mode module is not up to date with latest changes in iOS 12 (at the time of writing this post). So we will have to make some additions in the node module file. (sorry, no other way to do it 😓 )
Careful with these steps, as you can spoil the plugin as well 😅. This is the file we are editing. You can also jump on this by (Ctrl+click)ing on any Apple Pay function in your ts files.
- The plugin’s node module is missing required fields
merchantCapabilities
andsupportedNetworks
in the Order. We will add these in the definition. Add following lines on the top of the file (if they don’t exist)
export declare type IMerchantCapabilities = '3ds' | 'credit' | 'debit' | 'emv';
export declare type ISupportedNetworks = 'visa' | 'amex' | 'discover' | 'masterCard';
It should look like the following
2. Add the variables in Order definition
Head to the definition of IOrder
and add following lines in the end of the function
export interface IOrder extends IOrderItemsAndShippingMethods
{
....
merchantCapabilities?: IMerchantCapabilities | IMerchantCapabilities[];
supportedNetworks?: ISupportedNetworks | ISupportedNetworks[];
}
Complete function will look like following
Now, your ApplePay order should expect and accept (😛) both merchantCapabilities
and supportedNetworks
variables.
Make a Payment
To make a payment with our app, we will have to run it in …… wait for it ….. an iOS device or simulator 👏👏 of course 🙄
- Add an iOS platform in your app
$ ionic cordova platform add ios
- Prepare the iOS platform to run
$ ionic cordova prepare ios
Now, open XCode, and open your project in it. (the .xcworkspace file)
- Add an Apple Pay Entitlement to your app, or the Apple Pay won’t work at all.
Note : The plugin does not update the entitlements automatically for production app. You can define it in your config.xml
like following
Once the build is made, check if your device allows Apple Pay payments. If it does, click on Pay with Apple Pay and you will see the following flow
And our payment is complete 🎉 🎊 🎉 🎊 🎉 🎊
Conclusion
Apple Pay is a great option to include as a payment gateway for iOS apps. A simple plugin integration in Ionic 4 apps allows you to create payments from the front-end itself.
Complete source code of this tutorial is available in the Ionic4-applepay Github repository.
Stay tuned for more Ionic 4 blogs !
— — — — — — — — — — — — — — — — — — — — — — — — — — -
Buy “Ionic 4 Full Payment app Starter” today!!
— — — — — — — — — — — — — — — — — — — — — — — — — — -
FOUND THIS POST INTERESTING ?
Check out my other post on
- Ionic 4 PayPal payment integration — for Apps and PWA
- Ionic 4 Stripe payment integration — for Apps and PWA
- Ionic 4 RazorPay payment integration — for Apps and PWA
Also check out our other blog posts related to
- Firebase in Ionic 4,
- Geolocation in Ionic 4,
- QR Code and scanners in Ionic 4 and
- translations in Ionic 4
NEED FREE IONIC 4 STARTERS?
You can also find free Ionic 4 starters on our website enappd.com
You can also make your next awesome app using Ionic 4 Full App
References
Posted on September 20, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.