Ionic 4/5 Stripe integration in Ionic & Angular Apps and PWA Ionic 5

Stripe is the best famous and fastest-growing way to accept payments on your website or app. It works with a lot of different payment methods and is quickly spreading around the world. Stripe can handle almost all of your app and website payment needs.

What is Ionic ?

Ionic is probably something you already know about, but I'm putting it here for people who don't. made Ionic, a full open-source SDK for making hybrid mobile apps, in 2013. Ionic offers tools and services for making hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Using Cordova, apps created with these Web technologies can be shared through native app stores and installed on devices.

Ionic 4 and Stripe Payment: There are two main ways to integrate Stripe into an Ionic application.


You can use the Ionic Native implementation, a wrapper around the Stripe native SDKs for iOS and Android. Cordova-plugin-stripe makes this work. The downside of this plugin is that it can only be used to earn tokens for one-time payments. The limitation is in the plugin and could change in the future.

The other option is to use Stripe.js, which is Stripe's implementation of its functionality in JavaScript. It is simple to use and quick to set up because it is written in JavaScript, and web technologies power Ionic at its core. The functionality is added to the page on the fly, and both one-time and recurring payments can be made.

Prerequisites

Create a basic Ionic 4 app

Creating a basic Ionic 4 app is very easy. Assuming you have all basic requirements installed in your system, run

$ ionic start stripe blank

This creates your app with titleMyApp and blank template.

Navigate to the folder using:

$ cd stripe

Setup your Stripe profile and retrieve your API key


Visit Stripe.com and create an account. Stripe payment services are currently unavailable in few countries. Full detail shown on this page.

Once you are inside Stripe Dashboard, look for the Developer Tab -> API keys. For more guide, retrieve your API keys by following the instructions here.


The first thing in Ionic/Stripe integration you will need to do is to create all the necessary pages in ionic application.

Run the following commands to create the pages:

$ ionic g page StripeJavaScript --spec false
$ ionic g page StripeNative --spec false


Open up your home.html file and update code with the code below. It easier to test the different versions of Stripe in Ionic application we are integrating.

<ion-header>
    <ion-toolbar color="success">
        <ion-title text-center>
            Learn Stripe
        </ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>
  <ion-button (click)="openJavaScript()">Stripe JavaScript</ion-button>
<ion-button (click)="openNative()">Stripe Native</ion-button>
</ion-content>

Now let’s add the functions that the buttons are calling to your home.ts file. Add the code below, this will handle the button click events and it will also ensure that the correct pages are being loaded.

import { Component } from '@angular/core';
import { Router} from '@angular/router';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public router: Router) {

  }

  openJavaScript(){
    this.router.navigate(['/stripe-java-script']);
  }

  openNative(){
    this.router.navigate(['/stripe-native']);
  }

}

Connect Stripe into your Ionic/Angular project


Let’s start by adding the Stripe.js script file to your index.html. Add this:

<script src="https://js.stripe.com/v3/" async></script>

With that step completed we can start by making the changes we need to StripeJavaScriptPage().

Open up stripe-java-script.page.html and update your code with the following amendments to it.

<ion-content>

    <form id="payment-form">
    
      <div class="form-row">
        <div id="card-element">
          <!-- a Stripe Element will be inserted here. -->
        </div>
  
        <!-- Used to display Element errors -->
        <div id="card-errors" role="alert"></div>
      </div>
  
    <ion-button expand="block" size="large">Add Card</ion-button>
      
    </form>

</ion-content>

We are using Stripe Elements to bootstrap our payment form. This will be bound together in stripe-java-script.page.ts. The Stripe form will be loaded/injected in the project when ready. Keep in mind that the form id is being used to bind everything together.

Before we move on we are going to add some generic styles to our stripe-java-script.page.scss.

.StripeElement--webkit-autofill {
background-color: #fefde5; // Specify background color
}
.StripeElement {
-webkit-transition: box-shadow 150ms ease;
transition: box-shadow 150ms ease;
border-radius: 4px;
box-shadow: 0 1px 3px 0 #e6ebf1;
border: 1px solid transparent;
background-color: white;
padding: 8px 12px;
}
.form-row {
padding: 10px;
}
.StripeElement--focus {
box-shadow : 0 1px 3px 0 #cfd7df; // box shadow
}

.StripeElement--invalid {
border-color: #fa755a;
}

Now we can start working on the stripe-java-script.page.ts. This is the page where the functionality needs to be implemented. First, amend your code in stripe-java-script.page.ts to match the following:

import { Component, OnInit } from '@angular/core';

declare var Stripe;

@Component({
  selector: 'app-stripe-java-script',
  templateUrl: './stripe-java-script.page.html',
  styleUrls: ['./stripe-java-script.page.scss'],
})
export class StripeJavaScriptPage {

  stripe = Stripe('YOUR_STRIPE_API_KEY');
  card: any; // any type

  constructor() {
  }

  ionViewDidLoad() {
    this.initStripe();
  }

  initStripe(){
    let ele = this.stripe.elements();
    var myStyle = {
      "base": {
        color: '#32325d',
        lineHeight: '24px',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
          color: '#aab7c4'
        }
      },
      "invalid": {
        color: '#fa755a',
        iconColor: '#fa755a'
      }
    };

    this.card = ele.create('card', { style: myStyle });

    this.card.mount('#card-element'); // mount an card element

    this.card.addEventListener('change', event => { // on change event
      var displayError = document.getElementById('card-errors');
      if (event.error) { // display error if there is any
        displayError.textContent = event.error.message;
      } else { // Successfull
        displayError.textContent = '';
      }
    });

    const myForm = document.getElementById('payment-form');
    myForm.addEventListener('submit', ev => {
      ev.preventDefault();

      // this.stripe.createToken(this.card) // create stripe token
      this.stripe.createSource(this.card).then(res => {
        if (res.error) { // error case
          var errorEle = document.getElementById('card-errors');
          errorEle.textContent = res.error.message;
        } else {
          console.log(res); // success
        }
      });
    });
  }

}}

and with that we are done!


Connect Stripe SDKs ie iOS & Android into your Ionic/Angular project


To connect or integrate the native Stripe implementation into Ionic/Angular application we first start with Stripe native plugin. For that purpose we will be adding the Cordova plugin & then add the Ionic Native wrapper to make working with stripe plugin easier.

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

Once this is finished, we need to implement the Ionic/Stripe helper to your app.module.ts.

...

import { Stripe } from '@ionic-native/stripe/ngx';

@NgModule({
  ...
  providers: [
    ...
    Stripe,
    ...
  ]
})
export class AppModule {}

We now have all the setup complete and can move onto setting up our view to host our payment form.


The view will include some Ionic inputs and a button to submit the request to Stripe.

Amend stripe-native.page.html to the following.

<ion-content>

<ion-list>

  <ion-item>
    <ion-label color="primary" stacked>Card Number</ion-label>
    <ion-input type="text" placeholder="Enter your 16 digit card number" 
    [(ngModel)]="cardNumber"></ion-input>
  </ion-item>

  <ion-item>
    <ion-label color="primary" stacked>Expiration Month</ion-label>
    <ion-input type="number" placeholder="Enter your card expiration month"
    [(ngModel)]="cardMonth"></ion-input>
  </ion-item>

  <ion-item>
    <ion-label color="primary" stacked>Expiration Year</ion-label>
    <ion-input type="number" placeholder="Enter your card expiration year"
    [(ngModel)]="cardYear"></ion-input>
  </ion-item>

  <ion-item>
    <ion-label color="primary" stacked>CVV</ion-label>
    <ion-input type="number" placeholder="Enter your CVV"
    [(ngModel)]="cardCVV"></ion-input>
  </ion-item>

</ion-list>


  <ion-button expand="block" size="large" (click)="validateCard()">Add Card</ion-button>

</ion-content>

TS file "stripe-native.page.ts" will contain the functionality and it will have the ability to handle the legwork of validating the card details & submitting it to the Stripe servers. You will be able to communicate to your own API once you receive a successful response back from Stripe with the tokenized card object.


Amend your "stripe-native.page.ts" file to update the code below and we will walk through it together afterwards.

import { Component, OnInit } from '@angular/core';
import { Stripe } from '@ionic-native/stripe/ngx';
@Component({ selector: 'app-stripe-native', templateUrl: './stripe-native.page.html', styleUrls: ['./stripe-native.page.scss'], }) export class StripeNativePage { cardNumber: string; // card number will be in string cardMonth: number; // card month will be stored as number cardYear: number; // card yea will be stored as number cardCVV: string; // card CVV will be stored as string constructor(public stripe: Stripe) { } ionViewDidLoad() { this.stripe.setPublishableKey('YOUR API KEY'); } validateCard(){ let card = { number: this.cardNumber, expMonth: this.cardMonth, expYear: this.cardYear, cvc: this.cardCVV }; // You can start card validation here & then you can attempt to tokenise this.stripe.createCardToken(card) .then(token => console.log(token)) // token created .catch(error => console.error(error)); // failed } }

With that we are done.

Conclusion Ionic/Angular & Stripe



In this article, We’ve learnt two different ways of integrating Stripe into an Ionic/Angular project. You can use both integrations ways in the same Ionic application if you wanted to though you would have to use the JavaScript integration if you want recurring payments.

You still have a fair bit of work to do in the application once you’ve completed the integration of the frontend of the application as you will need to bill the payment source from your server.

If you have any question, let me know in the comment box below, thanks!

Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !