PayPal Payment Integration using Braintree in Ionic 5 apps
In this tutorial, we will go through PayPal payment using Braintree in Ionic 5. Previously Paypal supported the Cordova PayPal Plugin, which is no more maintained by PayPal, hence it has issues while making payment using PayPal Login. PayPal now recommends using Braintree for mobile payments, while web payment still works fine with the generic PayPal JS script. You can read more about the web integration in our blog — PayPal integration in Ionic PWA.
For ease of development, it is recommended to have same payment method i.e. Braintree for both mobile and web, instead of PayPal for web and Braintree for mobile.
This type of integration requires a Backend (server) to generate several tokens and final transaction is also done by the server. For this tutorial, we will be using a Node JS server and will be calling APIs from Ionic app using HTTP client.
We will follow below steps to implement PayPal integration using Braintree.
Steps to Implement PayPal Integration Using Braintree :-
- Create Braintree sandbox account and get the required keys
- Setup Ionic 5 project
- Setup Node JS project
- Creating Node JS API’s for Braintree
- Braintree/PayPal integration in Ionic app using Node JS API’s
- Testing
Before we proceed, a little bit about Ionic and Braintree
What is Braintree ?
Braintree offers a variety of products that make it easy for users to accept payments in their apps or website. Think of Braintree as the credit card terminal you swipe your card through at the grocery store. Braintree supports following major types of payment methods
- ACH Direct Debit
- Apple Pay
- Google Pay
- PayPal
- Samsung Pay
- Credit / Debit cards
- Union Pay
- Venmo
What is Ionic ?
Ionic framework is a mobile app framework, which supports other front-end frameworks like Angular, React, Vue and Vanilla JS, and builds apps for both Android and iOS from same code.
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 Ionic you can write a single piece of code for your app that can run on both iOS and Android and web (as PWA), that too with the simplicity of HTML, CSS, and JS.
It is important to note the contribution of Cordova/Capacitor in this. Ionic is only a UI wrapper made up of HTML, CSS and JS. So, by default, Ionic cannot run as an app in an iOS or Android device. Cordova/Capacitor is the build environment that containerizes (sort of) this Ionic web app and converts it into a device installable app, along with providing this app access to native APIs like Camera, web access etc.
Ionic and Payment Gateways
Ionic can create a wide variety of apps, and hence a wide variety of payment gateways can be implemented in Ionic apps. The popular ones are PayPal, Stripe, Braintree, in-app purchase etc. For more details on payment gateways, you can read our blogs on Payment Gateway Solutions in Ionic, Stripe integration in Ionic, Apple pay in Ionic etc.
Also, there are different types of Ionic Apps you can build for same functionality. Most popular ones are :
- Front-end: Angular | Build environment : Cordova
- Front-end: Angular | Build environment : Capacitor ✅
- Front-end: React | Build environment : Capacitor
- Front-end: Vue | Build environment : Capacitor
PayPal can be integrated in websites as well as mobile apps. In this blog we’ll learn how to integrate PayPal payment gateway in Angular/Capacitor Ionic 5 apps using Braintree.
OK, enough of talking, let’s start building our PayPal Braintree Payment System.
Step 1 :- Create Braintree sandbox account and get the required keys
This steps is required to proceed further, we will be needing several keys to integrate PayPal in Ionic 5 app as well as in Node JS script. To get these keys go to Braintree Sandbox Account. Once you login, you can go to settings and select API.
In API section, scroll down and you will get the Required API key. We need three keys to initialize Braintree in Node JS scripts
- Merchant Id
- Public Key and
- Private Key
Save these IDs, we will use them in initializing the Braintree on server-side.
Step 2 — Setup Ionic 5 project
In this part, we will create and configure Ionic 5 Project and also setup new Node JS Script.
Creating and configuring the Ionic 5 application.
To create new Ionic 5 project, run the below command :-
$ ionic start PayPal --blank --type=angular
This will create blank app in the working directory and if you want to know more about creating the Ionic 5 project, go to Ionic 5 Beginners Blog. Now once we have created the Ionic app, we can configure the app for Braintree, to do that flow the below steps.
a) Add CDN to index.html
file
How will Ionic app know we want to use Braintree ? Currently there is no Cordova or Capacitor plugin for Braintree. Hence we will add the CDN to parent file i.e. index.html, below is the CDN for Braintree JavaScript SDK.
<script src="https://js.braintreegateway.com/js/braintree-2.32.1.min.js"></script>
By adding this SDK CDN, Braintree will be available throughout the application. We can simply use it in any of the pages in our Ionic app.
b) Using Braintree variable in Ionic 5 application
Once we import the SDK CDN, we can use the Braintree variable in any page by using below defined syntax
declare const braintree;
Now later in Payment-gateway page, we will use this variable to setup the Client side application for successful payment.
Step 3 — Setup Node JS project
Create a separate folder for node server. To create Node JS script, we will run npm init
in the working directory .
$ npm init
Above command will ask few basic questions and creates the package.json
file in working directory. Now you can create the index.js
file (All logic will be contained in index file because we’re making a simple server). Once you have run the above commands, the project structure will look like this
We have to install some of the libraries that will help in implementing node script. To install the libraries run the below command :-
$ npm install cors express braintree body-parser
To know more about cors, express, body-parser and braintree you can follow the links. You can also check official Ionic documentation on CORS which we believe is very good for understanding.
Now we have all the basic requirements to start our node script.
Note — Check your project’s package.json
file, it should contain the value stated below in scripts section. If it doesn’t, just add manually :-
Step 4 — Creating Node JS APIs for Braintree
Creating Braintree APIs will allow us to get the Client ID requested from client side. We will use Braintree package to implement those APIs. First of all, import the Braintree using below command in index.js
file
const braintree = require("braintree");
Now using Braintree object to initialize the Braintree Gateway. This initialization requires those keys (which we have saved in step 2) and environment value (i.e. for now we are using Sandbox, later you can use production value). Use the below command to initialize the Gateway.
const gateway = new braintree.BraintreeGateway({ environment: braintree.Environment.Sandbox, merchantId: "USE_YOUR_MERCHENT_ID", publicKey: "USE_YOUR_PUBLIC_KEY", privateKey: "USE_YOUR_PRIVATE_KEY" });
This Gateway object will be used to get the Client ID and used in doing transaction.
Payment Flow with Braintree
The following flowchart will get you up to speed with the payment flow. With this in mind, you’ll be able to better follow the code steps given further
First our Ionic application will call the Node JS API that will return the CLIENT ID generated using API mentioned below :-
app.get("/brainTreeClientToken", (req, res) => { gateway.clientToken.generate({}).then((response) => { console.log('Token', response); res.send(response); }); });
‘/brainTreeClientToken’ API will be called from Ionic app using HTTP Client (later we will see in step 4). Once client side (Ionic app-side) gets the token it will setup the Braintree using setup call (will see in step 4). After setup, client will initiate payment using Pay with PayPal button. Clicking PayPal button will open In App Browser and sandbox will create a random user and provide info containing nonce (token string used in making transaction successful).
For making transaction, we will create Node JS API that will checkout payment using amount and nonce. Below is the transaction API :-
app.post("/checkoutWithPayment", jsonParser, (req, res) => { const nonceFromTheClient = req.body.nonceFromTheClient; const payment = req.body.paymentAmount; gateway.transaction.sale({ amount: payment, paymentMethodNonce: nonceFromTheClient, options: { submitForSettlement: true } }).then((result) => { res.send(result); }); });
In above API nonceFromTheClient and paymentAmount will be passed through Ionic 5 app and using gateway object will make a transaction. This will return a transaction status containing complete info about customer, payment and also contains status of payment. This will complete the flow of payment using PayPal. Below is the complete script code :-
Note
- In the above script, you can replace
route
in theapp.listen
with the port3000
. So it becomesapp.listen(3000,()=>...
- You can also create
.catch
for the.generate
and.sale
methods in the server. This way, if you get any error from Braintree server, you will be able to see that in node server terminal
Run the server using npm start
or if you want to deploy code to some cloud server you can do that as well. If you’re running the server in local system, the APIs will have a localhost
URL. You can test web payments directly in local system. For phone payments you might have to deploy the node server on a cloud.
Step 5 — Braintree integration in Ionic App using Node JS APIs
In this part we will go through client side (Ionic app) integration, using which we can make the PayPal transaction. We have seen how to initialize Braintree in Ionic app (stated in step 2).
declare const braintree
Following method can be used to retrieve client ID from server. This method will be called during Braintree setup.
async getClientTokenForPaypal() { return await this.http.get('http://localhost:3000/brainTreeClientToken').toPromise(); }
Now we can setup Braintree using below code. Notice that the .setup
is the function which defines for the first time that we are going to use PayPal as the payment gateway, using Braintree as the provider.
Keep in mind this setup will require the CLIENT_ID that will be generated by server API (mentioned in Step 3). So first we will call the server API and then pass the CLIENT_ID to setup method. You can call this function when page loads ( i.e. in ngOnInit() or ionViewWillEnter() methods).
initalizeBrainTree() { const that = this; this.getClientTokenForPaypal().then((res: any) => { let checkout; braintree.setup(res.clientToken, 'custom', { paypal: { container: 'paypal-container', }, onReady: function (integration) { checkout = integration; }, onCancelled: (obj) => { console.log('Cancelled', obj); checkout.teardown(() => { checkout = null }); }, onPaymentMethodReceived: (obj) => { checkout.teardown(() => { checkout = null; that.handleBraintreePayment(obj.nonce); }); } }); }); }
In above method, first we call the getClientTokenForPaypal()
method that will call the Node JS server brainTreeClientToken
API and returns the token. Once we get client token, we can setup Braintree using it. This setup method will initialize the PayPal-container that will be used to render the PayPal button in HTML file.
Once the client token is obtained, Paypal button will be automatically rendered in HTML file in this place. Make sure you have this in your HTML file
<ion-button class="paypalBtn" id="paypal-container"></ion-button>
This will render the Paypal button in Page view and will look like below screen :-
Now we have completed the setup and we can make payment using this button. When we click the button it will open the In-app Browser and sandbox will handle the payment and users info. This will return the nonce value in the callback defined in setup call.
One more thing we have to keep in mind that sometimes, PayPal payment screen does not go off when we make a payment (due to some screen refresh angular issues). To remove it manually, we have to use teardown() method defined in checkout variable (initialized on onReady() callback).
onReady: function (integration) { checkout = integration; },
Below is the callback that will handle the nonce token and pass on to other method that will handle the transaction.
onPaymentMethodReceived: (obj) => { checkout.teardown(() => { checkout = null; that.handleBraintreePayment(obj.nonce); }); }
We will pass the nonce value to handleBraintreePayment() method that will further call the transaction API defined in Node JS server. Here you can console the final response after payment.
async handleBraintreePayment(nonce) { this.api.makePaymentRequest(this.payableAmount, nonce).then((transaction) => { console.log('Transaction', transaction); }) }
Above makePaymentRequest() method will call the transaction API defined in Node JS server, that will make the original payment using Braintree. Below is the function call :-
async makePaymentRequest(amount, nonce) { const paymentDetails = { paymentAmount: amount, nonceFromTheClient: nonce } return await this.http.post('http://localhost:3000/checkoutWithPayment', paymentDetails).toPromise(); }
Above function will contain the paymentAmount and nonce value and will passed them to the server API. That will return the transaction object and we can decide the client end logic according to the response that we get from server. This will complete the PayPal Braintree integration from both client side and server side.
Step 6 — Testing
As mentioned earlier, it is easy to test this setup in a web domain, because the server can run on localhost, and the Ionic app can call the server while running with ionic serve
. Here how the payment flow looks
To test it in your device, you will need to deploy the server on a cloud so you can call the APIs from the app. If there is a way you can call localhost APIs from your app (I don’t know any), that should work as well !
Troubleshooting
>> braintree is not defined
Check if you included the Braintree script in index.html
>> Authentication error in API
Check if you have entered correct API keys and Merchant Id in node server. Also check if you are using Production keys in Sandbox, or vice versa
Conclusion :-
Congratulations !! 🎉 You just learnt how to integrate the awesome Braintree payment system to make payments using PayPal.
You can make payments using both PayPal account and Debit / Credit Cards. This way of integration can work both in Web view and mobile apps. If you want to know more about any feature integration, you can check out our amazing tutorials at Enappd Blogs.
Happy coding !