How to use paypal on PWA with Ionic 5 ?

In this tutorial, i will show you how to integrate Paypal with Ionic 5, to enable payments on your PWA version.

The source code repository

To integrate paypal in a Ionic 5 application will allow users to make payments using their paypal account or by entering credit card detail information.

Reminder this tutorial is not about using paypal mobile SDK in an iOS or Android Ionic application, but using Paypal javascript SDK on your Ionic PWA version (running on web).

Let’s create our Ionic 5 application with command:

ionic start paypal blank --capacitor --project-id=paypal --package-id=com.ionicanddjangotutorials.paypal

Then we need to edit the index.html file of our ionic application, to load the Paypal javascript sdk

<script src="https://www.paypal.com/sdk/js?client-id=YOUR-CLIENT-ID&currency=EUR"></script>

Just replace the YOUR-CLIENT-ID with your sandbox/live environment client id.

Now we will modify our home.page.html file to integrate a Paypal button

<ion-header>
  <ion-toolbar>
    <ion-title>Paypal Demo</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="page-flex-align" padding>
    <div class="top-content">
      <h1>Would you like to pay {{price}} ? </h1>
      <p>
      </p>
      <div id="paypal-button"></div>
   </div>
  </div>
</ion-content>

Nothing really complicated. We display the amount that the user will pay, then to integrate a Paypal button, the important line is :

<div id="paypal-button"></div>

The paypal code will be injected automatically from our home.page.ts using the Paypal javascript library.

So let’s write our home.page.ts

import { Component } from '@angular/core';
declare var paypal: any;
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  price;
  priceToPay = 10;
  payPalConfig: any;

  PAYPAL_CLIENT_ID_TEST = "YOURDEVKEY"
  PAYPAL_CLIENT_ID_LIVE = "YOURLIVEKEY"

  PAYPAL_CLIENT_ID = this.PAYPAL_CLIENT_ID_TEST

  constructor() {

    this.price = this.priceToPay + " €"
    let enviroment = ""
    if (this.PAYPAL_CLIENT_ID == this.PAYPAL_CLIENT_ID_TEST) {
      enviroment = "sandbox"
    }
    else {
      enviroment = "live"
    }

    this.payPalConfig = {
      env: enviroment,
      client: {
        sandbox: this.PAYPAL_CLIENT_ID,
      },
      commit: false,
       createOrder: (data, actions)=> {
        return actions.order.create({
            purchase_units: [{
                amount: {
                    value: this.module.prix,
                    currency: 'EUR' 
                }
            }]
        });
    },
      // Finalize the transaction
      onApprove: (data, actions) => {
        //console.log(data)
        //console.log(actions)
        return actions.order.capture()
          .then((details) => {
            // Show a success message to the buyer
            console.log(details)
            let status = details["status"]
            let id = details["id"]
            if (status == "COMPLETED") {
              this.validPurchase(id)
            }
            else {
              //Status not completed...
            }
            console.log('Transaction completed by ' + details.payer.name.given_name + '!');
          })
          .catch(err => {
            console.log(err);
            // deal with error
          })
      }
      ,
      onError: (err) => {
        // Show an error page here, when an error occurs
        console.log(err)
        // deal with error
      }
    }
  }

  validPurchase(id) {
    // Purchase confirm 
    //Do whatever you want to do
  }

  ionViewDidEnter() {
    paypal.Buttons(this.payPalConfig).render('#paypal-button');
  }


  ngOnInit() {
  }

}

Use paypal javscript sdk with Ionic 5

First we need to declare the paypal sdk

declare var paypal: any;

Then we can configure our paypal api keys

PAYPAL_CLIENT_ID_TEST = "YOURDEVKEY"
PAYPAL_CLIENT_ID_LIVE = "YOURLIVEKEY"

PAYPAL_CLIENT_ID = this.PAYPAL_CLIENT_ID_TEST

And set the paypal environment to use (sandbox or live) based on the key

 let enviroment = ""
    if (this.PAYPAL_CLIENT_ID == this.PAYPAL_CLIENT_ID_TEST) {
      enviroment = "sandbox"
    }
    else {
      enviroment = "live"
    }

Now, we will configure the most important piece of the sdk, a paypal configuration object :

 this.payPalConfig = {
      env: enviroment,
      client: {
        sandbox: this.PAYPAL_CLIENT_ID,
      },
      commit: false,
       createOrder: (data, actions)=> {
        return actions.order.create({
            purchase_units: [{
                amount: {
                    value: this.module.prix,
                    currency: 'EUR' 
                }
            }]
        });
    },
      // Finalize the transaction
      onApprove: (data, actions) => {
        //console.log(data)
        //console.log(actions)
        return actions.order.capture()
          .then((details) => {
            // Show a success message to the buyer
            console.log(details)
            let status = details["status"]
            let id = details["id"]
            if (status == "COMPLETED") {
              this.validPurchase(id)
            }
            else {
              //Status not completed...
            }
            console.log('Transaction completed by ' + details.payer.name.given_name + '!');
          })
          .catch(err => {
            console.log(err);
            // deal with error
          })
      }
      ,
      onError: (err) => {
        // Show an error page here, when an error occurs
        console.log(err)
        // deal with error
      }
    }

The createOrder method will set the amout and the currency that the user needs to pay

  createOrder: (data, actions)=> {
        return actions.order.create({
            purchase_units: [{
                amount: {
                    value: this.module.prix,
                    currency: 'EUR' 
                }
            }]
        });
    },

The onApprove method will be fired once the payment has been made.

We just need to check the value of status variable to know if the payment has been successfull or not. If status is not COMPLETED or an error occurs, we just need to deal with the error.

 onApprove: (data, actions) => {
        //console.log(data)
        //console.log(actions)
        return actions.order.capture()
          .then((details) => {
            // Show a success message to the buyer
            console.log(details)
            let status = details["status"]
            let id = details["id"]
            if (status == "COMPLETED") {
              this.validPurchase(id)
            }
            else {
              //Status not completed...
            }
            console.log('Transaction completed by ' + details.payer.name.given_name + '!');
          })
          .catch(err => {
            console.log(err);
            // deal with error
          })
      }

We can also configure the style of our paypal button. We just need to pass a style configuration to our paypalConfig dictionnary.

Et voila. We are now able to use paypal to pay on the web in our Ionic 5 application.

Christophe Surbier