Integrating Stripe into your ionic project

in #utopian-io5 years ago

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


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="" async></script>

And the whole file should look something like this

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <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>

  (html comment removed:  add to homescreen for ios )
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <script src="" async></script>

  (html comment removed:  cordova.js required for cordova apps (remove if not needed) )
  <script src="cordova.js"></script>

  (html comment removed:  un-comment this code to enable service worker
    if ('serviceWorker' in navigator) {
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));

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


  (html comment removed:  Ionic's root component and where the app will load )

  (html comment removed:  The polyfills js is generated during the build process )
  <script src="build/polyfills.js"></script>

  (html comment removed:  The vendor js is generated during the build process
       It contains all of the dependencies in node_modules )
  <script src="build/vendor.js"></script>

  (html comment removed:  The main bundle js is generated during the build process )
  <script src="build/main.js"></script>


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
  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-title>Stripe Payment</ion-title>
    <form action="/" method="post" id="payment-form">
      <div class="form-row">
        <div id="card-element">
          (html comment removed:  a Stripe Element will be inserted here. )
        (html comment removed:  Used to display Element errors )
        <div id="card-errors" role="alert"></div>
    <button ion-button block large>Add Card</button>

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

        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;
  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() {
    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.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 => {
      // 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 {

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';
  providers: [
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

///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


Thank you for your contribution @yalzeee.
We suggest the following points below:

  • We suggest you put some picture on what you are developing. A tutorial with only text and code becomes very monotonous and unattractive for the reader to read to the end.

  • Nice work on the explanations of your code, although adding a bit more comments to the code can be helpful as well.

Thank you for your good work in developing this tutorial. We are waiting for more tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.

Need help? Write a ticket on
Chat with us on Discord.

Thank you for your review, @portugalcoin! Keep up the good work!

Hello! I find your post valuable for the wafrica community! Thanks for the great post! We encourage and support quality contents and projects from the West African region.
Do you have a suggestion, concern or want to appear as a guest author on WAfrica, join our discord server and discuss with a member of our curation team.
Don't forget to join us every Sunday by 20:30GMT for our Sunday WAFRO party on our discord channel. Thank you.

Hi @yalzeee!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @yalzeee!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support!
Simply set as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.26
TRX 0.10
JST 0.031
BTC 37959.48
ETH 2052.04
USDT 1.00
SBD 5.37