Yalzeee avatar

Integrating Stripe into your ionic project

yalzeee

Published: 23 Nov 2018 › Updated: 23 Nov 2018Integrating Stripe into your ionic project

Integrating Stripe into your ionic project

ionic.jpg
image source

Repository: Ionic Github Repository

Software Requirements:
Visual Studio Code(Or any preferred code editor)

What you will learn:
In this tutorial you would learning about payment processing using stripe. I would be covering these major concepts

  • How to integrate the stripe.js library into your ionic application
  • How to send get a stripe token using your publishable key
  • How to use ionic's cordova plugin to get a stripe token

Difficulty: Intermediate

Tutorial

In this tutorial i would walk through simplifying the best method of monetizing your app which will be with stripe. Stripe is an awesome platform which helps you to take charges from bank accounts through debit or credit cards that they are linked to. To see more about this you can follow This.

Understanding stripe means getting through some basic concept which i would be enumerating.
Firstly, you need to understand the two processes by which payments are made

  1. Getting the stripe token for a card
  2. Billing the card on a secure 'https' server.

The first is what we will cover and can be done on you ionic application but the second needs to be done on your backend. Ionic has an inbuild cordova plugin which makes getting a token for a card way easier but this has its downsides which i would state as we get to that. The more suitable method would be to use the 'Stripe.js' library which is gives you full access to all the methods you may need.

Integrating Stripe.Js to your project

Lets create a new project and call it 'newProject'

ionic start newProject blank

After this you can navigate to your index.html document which is the entry point for our application and add the stripe.js library to it.
Add this line

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

And the whole file should look something like this

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">
  <style rel="stylesheet" href="app/app.scss"></style>

  
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

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

  
  <script src="cordova.js"></script>

  

  <link href="build/main.css" rel="stylesheet">
  <link href="assets/css/font-awesome.min.css" rel="stylesheet"/>

</head>
<body>

  
  <ion-app></ion-app>

  
  <script src="build/polyfills.js"></script>

  
  <script src="build/vendor.js"></script>

  
  <script src="build/main.js"></script>

</body>
</html>

How to get a token from stripe

Since we arent using an npm package, we would need to declare a stripe variable so our compiler would know that stripe is declared elsewhere. So generate a new page using.

ionic g page stripePayment

And in the page declare a variable like this

import { NavController, NavParams } from 'ionic-angular';
 
declare var Stripe;//This is where we declare the stripe variable
 
@Component({
  selector: 'page-stripe-payment',
  templateUrl: 'stripe-payment.html',
})
export class StripePaymentPage {
 
  stripe = Stripe('YOUR_API_KEY');//We also use our publishable key from stripe
  card: any;//Declare this variable for later
 
  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

If you don't have a stripe account you should probably create one. Head to the link i gave above and create an account there. When you do you can use the publishable key on your dashboard as stated in the code above.

Stripe has a set of css styling preset when you use their library so you can just easily create a nice template for you users to input details with a simple amount of code .Since were using the library simply add a form to your html content.

<ion-header>
 
  <ion-navbar>
    <ion-title>Stripe Payment</ion-title>
  </ion-navbar>
 
</ion-header>
 
 
<ion-content>
 
    <form action="/" method="post" id="payment-form">
    
      <div class="form-row">
        <div id="card-element">
          
        </div>
  
        
        <div id="card-errors" role="alert"></div>
      </div>
  
    <button ion-button block large>Add Card</button>
      
    </form>
 
</ion-content>

This would give stripe a wrapper for the template to be created in .You can preset some styling techniques as defined in your css like this

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

and then for our final .ts for our page

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
 
declare var Stripe;
 
@Component({
  selector: 'page-stripe-java-script',
  templateUrl: 'stripe-java-script.html',
})
export class StripeJavaScriptPage {
 
  stripe = Stripe('YOUR_API_KEY');
  card: any;
 
  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }
 
  ionViewDidLoad() {
    this.setupStripe();
  }
 
  setupStripe(){
    let elements = this.stripe.elements();
    var style = {
      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 = elements.create('card', { style: style });
 
    this.card.mount('#card-element');
 
    this.card.addEventListener('change', event => {
      var displayError = document.getElementById('card-errors');
      if (event.error) {
        displayError.textContent = event.error.message;
      } else {
        displayError.textContent = '';
      }
    });
 
    var form = document.getElementById('payment-form');
    form.addEventListener('submit', event => {
      event.preventDefault();
 
      // this.stripe.createToken(this.card)
      this.stripe.createSource(this.card).then(result => {
        if (result.error) {
          var errorElement = document.getElementById('card-errors');
          errorElement.textContent = result.error.message;
        } else {
          console.log(result);
        }
      });
    });
  }
 
}

We are done with this now and you can simply run

ionic serve

To see your project and test it out
In you console you would see the token data that stripe returns.

Stripe Native

As stated earlier cordova has its own plugin for stripe so to use it simply use the cordova plugin and npm package by installing them as stated in the documentation

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

After this you would need to add it to your app.module.ts file and it should look like this after

import { Stripe } from '@ionic-native/stripe';
 
@NgModule({
  ...
  providers: [
    ...
    Stripe,
    ...
  ]
})
export class AppModule {}

Use these commands one after the other to install the cordova plugin and when you have collected the card details as in the example above use this rather than using the stripe.js library

createCardToken(params){
///Use the card params as stated in the example for the ts file above

}

This function will return a promise which would contain the card details.

You can find the code for this tutorial in my github page
Click to go to the github repository

Leave Integrating Stripe into your ionic project to:

Written by

Crypto investor, movie freak, Graphic Designer, and a Believer

Read more #utopian-io posts


Best Posts From Yalzeee

We have not curated any of yalzeee's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Yalzeee