DEV Community

Cover image for Payment Gateway Solutions in Ionic 4 - Paypal, Apple Pay, Stripe and others
Abhijeet Rathore for Enappd

Posted on • Originally published at enappd.com

Payment Gateway Solutions in Ionic 4 - Paypal, Apple Pay, Stripe and others


A reliable payment plugin requirement is indispensable for selling your products or services through your app. Ionic payment plugins come with several different features and capabilities. You need to choose the one that best suits your business needs and seamlessly integrates with your site. Let’s take a look at the best Ionic payment plugins you can use on your app:

1. Apple Pay


Apple Pay

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. The service is supported on iPhone 6 and newer, iPad Air 2 and newer, Macs with Touch ID, and all Apple Watches. Users with the iPhone 5 and 5C can use the service through an Apple Watch.

To use Apple Pay, you need to install the plugin using following commands

ionic cordova plugin add cordova-plugin-applepay
npm install @ionic-native/apple-pay

After installing the plugin, you can use following code-piece to implement the Apple Pay (code for Ionic 4)

// import ApplePay in the component
import { ApplePay } from '@ionic-native/apple-pay/ngx';

constructor(private applePay: ApplePay) { }

async applePay() {

try {
const applePayTransaction = await this.applePay.makePaymentRequest({
items,
shippingMethods,
merchantIdentifier,
currencyCode,
countryCode,
billingAddressRequirement: ['name', 'email', 'phone'],
shippingAddressRequirement: 'none',
shippingType: 'shipping'
});
    const transactionStatus = await completeTransactionWithMerchant(applePayTransaction);
await this.applePay.completeLastTransaction(transactionStatus);
} catch {
// handle payment request error
}
}

To build the app with Apple Pay for App store release, you need to enable Apple Pay in XCode capabilities tab. You can find more details here

2. Apple Wallet

Apple Wallet is a mobile app included with the iOS operating system that allows users to store Wallet-passes, meaning coupons, boarding passes, student ID cards, event tickets, movie tickets, public transportation tickets, store cards, (and starting with iOS 8.1) credit cards, debit cards, prepaid cards, and loyalty cards via Apple Pay.

To add Apple Wallet plugin, use following commands

ionic cordova plugin add cordova-apple-wallet
npm install @ionic-native/apple-wallet

Import the installed plugin with

import { AppleWallet } from '@ionic-native/apple-wallet/ngx';

Check if Apple Wallet is available

this.appleWallet.available()
.then((status) => {
// status is a boolean value, either true or false
console.log("Is Apple Wallet available? ", status);
})
.catch((message) => {
console.error("ERROR >> ", message);
});

Start adding a card using this method

let data = {
cardholderName: 'Test User',
primaryAccountNumberSuffix: '1234',
localizedDescription: 'Description of payment card',
paymentNetwork: 'VISA'
}
AppleWallet.startAddPaymentPass(data)
.then((res) => {
/**
* User proceed and successfully asked to add card to his wallet
* Use the callback response JSON payload to complete addition process
* Expect
* res = {
* "certificateSubCA":"Base64 string represents certificateSubCA",
* "certificateLeaf":"Base64 string represents certificateLeaf"
* "nonce":"Base64 string represents nonce",
* "nonceSignature":"Base64 string represents nonceSignature",
* }
*/
})
.catch((err) => {
// Error or user cancelled.
});

And complete the card addition, taking a callback from above function

let encryptedData = {
activationData: "encoded Base64 activationData ",
encryptedPassData: "encoded Base64 encryptedPassData ",
wrappedKey: "encoded Base64 wrappedKey"
}
AppleWallet.completeAddPaymentPass(encryptedData)
.then((res) => {
// A success callback response means card has been added successfully
})
.catch((err) => {
// Error and can not add the card
});

For more information, please check Apple Developer documentation from here.

3. PayPal

For details of Paypal integration in Ionic 4, read our blog — IONIC 4 PAYPAL PAYMENT INTEGRATION

PayPal Holdings, Inc. is an American company operating a worldwide online payments system that supports online money transfers and serves as an electronic alternative to traditional paper methods like checks and money orders. The company operates as a payment processor for online vendors, auction sites, and many other commercial users, for which it charges a fee in exchange for benefits such as one-click transactions and password memory.

Paypal is one of the biggest and most popular payment gateway for mobile and web-apps. Good news is — it can be used for both iOS and Android. To install Paypal plugin for Ionic, use

ionic cordova plugin add com.paypal.cordova.mobilesdk
npm install @ionic-native/paypal

Import Paypal into your component using

import { PayPal, PayPalPayment, PayPalConfiguration } from '@ionic-native/paypal/ngx';

Use the following command to initiate a payment. You will require you client_id from your Paypal account. (How to get my credentials from Paypal account)

this.payPal.init({
PayPalEnvironmentProduction: 'YOUR_PRODUCTION_CLIENT_ID',
PayPalEnvironmentSandbox: 'YOUR_SANDBOX_CLIENT_ID'
}).then(() => {
// Environments: PayPalEnvironmentNoNetwork, PayPalEnvironmentSandbox, PayPalEnvironmentProduction
this.payPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({
// Only needed if you get an "Internal Service Error" after PayPal login!
//payPalShippingAddressOption: 2 // PayPalShippingAddressOptionPayPal
})).then(() => {
let payment = new PayPalPayment('3.33', 'USD', 'Description', 'sale');
this.payPal.renderSinglePaymentUI(payment).then(() => {
// Successfully paid
}, () => {
// Error or render dialog closed without being successful
});
}, () => {
// Error in configuration
});
}, () => {
// Error in initialization, maybe PayPal isn't supported or something else
});

A sample sandbox response will look like

// Example sandbox response

{
"client": {
"environment": "sandbox",
"product_name": "PayPal iOS SDK",
"paypal_sdk_version": "2.16.0",
"platform": "iOS"
},
"response_type": "payment",
"response": {
"id": "PAY-1AB23456CD789012EF34GHIJ",
"state": "approved",
"create_time": "2016-10-03T13:33:33Z",
"intent": "sale"
}
}
For details of Paypal integration in Ionic 4, read our blog — IONIC 4 PAYPAL PAYMENT INTEGRATION

4. Stripe

For details of Stripe integration in Ionic 4, read our blog — Ionic 4 Stripe Payment Integration

Stripe is a technology company. Its software allows individuals and businesses to receive payments over the Internet. Stripe provides the technical, fraud prevention, and banking infrastructure required to operate on-line payment systems.

Stripe is the fastest growing payment solution around the world. It is quickly surpassing the popularity of Paypal etc. in the mobile and web payment domains.

Stripe can be used on both iOS and Androi, as well as in an Ionic PWA !

Install Stripe using following commands

ionic cordova plugin add cordova-plugin-stripe
npm install @ionic-native/stripe

First we need to set our import Stripe in the component. Then set our publishable key from Stripe account. This can be your test or live key.

import { Stripe } from '@ionic-native/stripe/ngx';
constructor(private stripe: Stripe) { }

this.stripe.setPublishableKey('my_publishable_key');
let card = {
number: '4242424242424242',
expMonth: 12,
expYear: 2020,
cvc: '220'
}
this.stripe.createCardToken(card)
.then(token => console.log(token.id))
.catch(error => console.error(error));

Once we get a token from Stripe, we can use this token on our back-end to charge the customer. Stripe integration does not require any special capabilities in XCode.

5. Braintree

Braintree provide the global commerce tools people need to build businesses, accept payments, and enable commerce for their users. It’s a payment processor acquired by PayPal, which emphasizes “simple, robust way to accept payments”, and with features like a drop-in payment UI. It is a good choice for accepting payments via credit card, PayPal, Venmo and Apple Pay.

Braintree plugin is available for Ionic apps. This plugin enables the use of the Braintree Drop-In Payments UI in your Ionic applications on Android and iOS, using the native Drop-In UI for each platform (not the Javascript SDK).

You can install Braintree plugin using

ionic cordova plugin add cordova-plugin-braintree
npm install @ionic-native/braintree

To use this, you need to import Braintree in the component. Then you will need your Braintree Tokenization Key from the Braintree dashboard. Alternatively you can also generate this token server-side using a client ID in order to allow users to use stored payment methods. See the Braintree Client Token documentation for details.

import { Braintree, ApplePayOptions, PaymentUIOptions } from '@ionic-native/braintree/ngx';
constructor(private braintree: Braintree) { }

const BRAINTREE_TOKEN = '<YOUR_BRAINTREE_TOKEN>';
// NOTE: Do not provide this unless you have configured your Apple Developer account
// as well as your Braintree merchant account, otherwise the Braintree module will fail.
const appleOptions: ApplePayOptions = {
merchantId: '<YOUR MERCHANT ID>',
currency: 'USD',
country: 'US'
}
const paymentOptions: PaymentUIOptions = {
amount: '14.99',
primaryDescription: 'Your product or service (per /item, /month, /week, etc)',
}
this.braintree.initialize(BRAINTREE_TOKEN)
.then(() => this.braintree.setupApplePay(appleOptions))
.then(() => this.braintree.presentDropInPaymentUI(paymentOptions))
.then((result: PaymentUIResult) => {
if (result.userCancelled) {
console.log("User cancelled payment dialog.");
} else {
console.log("User successfully completed payment!");
console.log("Payment Nonce: " + result.nonce);
console.log("Payment Result.", result);
}
})
.catch((error: string) => console.error(error));

6. Alipay


Selfie for payments

Alipay is a very popular payment option in Asia and part of the Alibaba group. It’s a payment option that works like many other “eWallet” services, where you add payment methods (cards or bank accounts) to your Alipay account, and can then process orders using them.

To install Alipay, use the following commands

ionic cordova plugin add cordova-plugin-gubnoi-alipay
npm install @ionic-native/alipay

Then we need to import Alipay in the component.

import { Alipay } from '@ionic-native/alipay/ngx';
constructor(private alipay: Alipay) {
//alipayOrder is a string that has been generated and signed by the server side.
this.alipay.pay(alipayOrder)
.then(result => {
console.log(result); // Success
})
.catch(error => {
console.log(error); // Failed
});
}

More details can be found at — https://docs.open.alipay.com/204/105465/

Conclusion:

We got to know in quick fashion about the top rated payment solutions available in the market. Main code snippets for integration of these plugins are shared right in the blogpost for reference. This will give a boost to your understanding and saves time.

This blog was originally published on Enappd.

FOUND THIS POST INTERESTING ?

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 Payment gateways in Ionic 4

Also check out this interesting post on How to create games in Ionic 4 with Phaser

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

Top comments (0)