How to integrate Ionic Framework & Stripe single and recurring payments

Learn how to integrate Ionic Framework & Stripe in this tutorial

Ionic Framework makes integrating Stripe a quick and easy process. Stripe is one of the world’s leading payment processors and has built a reputation for being extremely developer friendly. They are available in a number of countries and you can attempt to go the Stripe Atlas route if you fall outside of the approved countries.

There are two main ways of integrating Stripe into an Ionic application

You can either go with the Ionic Native implementation, which is a wrapper around the Stripe native SDKs for iOS and Android. This is powered by cordova-plugin-stripe. This has the limitation of only facilitating the creation of tokens for once off payments. The limitation is within the plugin and could change in the future.

The alternative approach is to use Stripe.js which is Stripe’s JavaScript implementation of their functionality. This is easy to use and quick to implement as this is implemented in JavaScript and Ionic at its core is powered by web technologies. The functionality is delivered dynamically into the page and supports both single and recurring payments.

After we complete this tutorial you will be able to integrate Ionic with Stripe and create tokens that you can use to charge your users with either a once off amount or a recurring payment.

The final payment processing will need to be integrated into your backend as a separate task. This tutorial will focus primarily on the creation of the tokens necessary to charge the user.

Subscribe to receive my latest Ionic Framework content, courses and tutorials. You will also gain access to exclusive newsletter only bonus content on the site.

Getting Started

Let’s start by setting up your Ionic installation. Navigate to where you would like to install this project using your terminal and enter the following:

Shell

1

ionic start stripe blank

Enter an appropriate project name, for example, stripe as I’ve done, and select Y to add the Cordova native platforms to this project when the question is presented.

Navigate to the folder using:

Shell

1

cdstripe

Setup your Stripe profile and retrieve your API key

Stripe provides you with both testing and live API keys that you will need to use to complete the integration. Firstly, sign up for a Stripe account, and then retrieve your API keys by following the instructions here.

You should not have an issue signing up for a Stripe account even if you reside outside of their list of approved countries. The challenge occurs when you attempt to transact live payments. The test key will be sufficient for this tutorial.

Create the pages, add the plugins and connect them all

The first thing you will need to do is to create all the necessary pages you will need and add them to your app.module.ts.

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

Open up stripe-java-script.html and make the following amendments to it.

stripe-java-script.html

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<ion-header>

<ion-navbar>

<ion-title>JavaScript</ion-title>

</ion-navbar>

</ion-header>

<ion-content>

<form action="/"method="post"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>

<button ion-buttonblocklarge>Add Card</button>

</form>

</ion-content>

We are using Stripe Elements to bootstrap our payment form. This will be bound together in stripe-java-script.ts and the Stripe form will be injected in when ready. The form id will be used to bind everything together.

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

stripe-java-script.scss

Sass

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

page-stripe-java-script {

.form-row{

padding:10px;

}

.StripeElement {

background-color:white;

padding:8px12px;

border-radius:4px;

border:1pxsolidtransparent;

box-shadow:01px3px0#e6ebf1;

-webkit-transition:box-shadow150msease;

transition:box-shadow150msease;

}

.StripeElement--focus {

box-shadow:01px3px0#cfd7df;

}

.StripeElement--invalid {

border-color:#fa755a;

}

.StripeElement--webkit-autofill {

background-color:#fefde5!important;

}

}

Now we can start working on the stripe-java-script.ts. This where all the action takes place. First, amend your code in stripe-java-script.ts to match the following and then we can walk through it together.

stripe-java-script.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

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

import{NavController,NavParams}from'ionic-angular';

declarevarStripe;

@Component({

selector:'page-stripe-java-script',

templateUrl:'stripe-java-script.html',

})

exportclassStripeJavaScriptPage{

stripe=Stripe('YOUR_API_KEY');

card:any;

constructor(public navCtrl:NavController,public navParams:NavParams){

}

ionViewDidLoad(){

this.setupStripe();

}

setupStripe(){

let elements=this.stripe.elements();

varstyle={

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=>{

vardisplayError=document.getElementById('card-errors');

if(event.error){

displayError.textContent=event.error.message;

}else{

displayError.textContent='';

}

});

varform=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){

varerrorElement=document.getElementById('card-errors');

errorElement.textContent=result.error.message;

}else{

console.log(result);

}

});

});

}

}

The first step we are doing is to declare a Stripe variable that will stop the compiler from complaining about a missing object.

Then we new up a Stripe object using your Stripe API key and create a variable to hold the Stripe Elements object.

stripe-java-script.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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

import{NavController,NavParams}from'ionic-angular';

declarevarStripe;

@Component({

selector:'page-stripe-java-script',

templateUrl:'stripe-java-script.html',

})

exportclassStripeJavaScriptPage{

stripe=Stripe('YOUR_API_KEY');

card:any;

constructor(public navCtrl:NavController,public navParams:NavParams){

}

The code that sets up the Stripe Element and the handlers for the events that comes back from the Stripe element is setup using the ionViewDidLoad() lifecycle event.

stripe-java-script.ts

JavaScript

1

2

3

ionViewDidLoad(){

this.setupStripe();

}

The majority of the work for this functionality takes place in the setupStripe() function.

stripe-java-script.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

setupStripe(){

let elements=this.stripe.elements();

varstyle={

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=>{

vardisplayError=document.getElementById('card-errors');

if(event.error){

displayError.textContent=event.error.message;

}else{

displayError.textContent='';

}

});

varform=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){

varerrorElement=document.getElementById('card-errors');

errorElement.textContent=result.error.message;

}else{

console.log(result);

}

});

});

}

The function does quite a bit and it would be better to separate the setup and binding code from the setup of the event handlers but this is sufficient for what we are attempting to do.

We first set up a Stripe Element, add some base styles, create a card and then mount it onto the view.

stripe-java-script.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

let elements=this.stripe.elements();

varstyle={

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');

With the card created we can now listen to errors from the card and add a listener for submit events. We prevent the default from taking place on submit and then select either createToken() or createSource() to authorise the card for future charges.

Use createToken() if you need to make a once off payment or createSource() to create a card that can be billed multiple times in the future.

When the promise resolves you will receive an object back that has everything you need to make payments with this card. This is where you would integrate an API call to your server to send through the source id, last 4 digits etc

stripe-java-script.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

this.card.addEventListener('change',event=>{

vardisplayError=document.getElementById('card-errors');

if(event.error){

displayError.textContent=event.error.message;

}else{

displayError.textContent='';

}

});

varform=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){

varerrorElement=document.getElementById('card-errors');

errorElement.textContent=result.error.message;

}else{

console.log(result);

}

});

});

Integrate Stripe Native SDKs ie iOS & Android into your Ionic project

To integrate the native Stripe implementation into Ionic we start with adding the Cordova plugin and then add the Ionic Native wrapper to make working with it easier.

Shell

1

2

ionic cordova plugin add cordova-plugin-stripe

npm install--save@ionic-native/stripe

Once this is completed we need to add the Ionic Native Stripe helper to your app.module.ts.

app.module.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

...

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

@NgModule({

...

providers:[

...

Stripe,

...

]

})

exportclassAppModule{}

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

I’ve opted to make this as simple as possible for the purpose of showing you how to do the foundational setup. I’m just binding variables to the view using ngModel instead of using a reactive form that will make firing some inline validation easier for the sake of simplicity.

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

Your stripe-native.ts will handle the legwork of validating the card details and 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.ts file to reflect the code below and we can walk through it together afterwards.

Now we set the Stripe key on the object when the view loads. Once again, we are using the ionViewDidLoad() lifecycle hook. This step would be better suited done in your app.component.ts when the application boots up but I’ve done it here for simplicity.

stripe-native.ts

JavaScript

1

2

3

ionViewDidLoad(){

this.stripe.setPublishableKey('YOUR_API_KEY');

}

Finally, we call our validateCard() function which only creates the Stripe card object and then fires off the captured card details to Stripe. When the promise resolves you would retrieve the data and then communicate with your own API to actually bill the card.

It’s important to actually validate the card details before attempting to create the token. The Ionic Native Stripe documentation includes all the available functions that you can use to validate the card number, cvv etc.

stripe-native.ts

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

validateCard(){

let card={

number:this.cardNumber,

expMonth:this.cardMonth,

expYear:this.cardYear,

cvc:this.cardCVV

};

// Run card validation here and then attempt to tokenise

this.stripe.createCardToken(card)

.then(token=>console.log(token))

.catch(error=>console.error(error));

}

Unfortunately, the Native implementation only supports creating card tokens and bank account tokens for once-off payments. If you want to bill the card more than once in the future then you will need to use the Stripe.js integration and create a payment source.

Conclusion: Ionic Framework & Stripe

We’ve learnt how to do two different ways of integrating Stripe into an Ionic project. You can use both in the same 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 once you’ve completed the integration of the frontend of the application as you will need to bill the payment source from your server.

Subscribe to receive my latest Ionic Framework content, courses and tutorials. You will also gain access to exclusive newsletter only bonus content on the site.

How to integrate Ionic Framework & Stripe single and recurring payments2018-01-262018-01-31https://baadiersydow.com/content/uploads/2017/12/logo-1.pngBaadier Sydowhttps://baadiersydow.com/content/uploads/2018/01/ionic-framework-stripe.jpg200px200px

Hi, I'm Baadier Sydow. I author this blog and work as a developer in Cape Town, South Africa. I spend most of my time developing hybrid mobile applications and working with Ionic, Angular, WordPress and Laravel. I'm excited to see what Progressive Web Apps can do for the future of the web.

Hey Baddier. Thanks for the tutorial. I have been implementing something similar with stripe.js in an ionic app and have had no trouble with Stripe in test mode. However I havent tried it with an activated stripe account. When I run the app in the browser with ionic serve it says testing works with http but production requires https. Testing is also working in the ionic app. But im concerned… Will my ionic app use https so it still works when i activate the stripe account?