Ionic 2 – Payment processing with Stripe

Hi Friends,

Hope you are all well. In this post we’ll discuss about Payment Processing in your Ionic 2 apps. This has been requested by a lot of our friends. We’ll be using an external library called stripe to achieve this.

Let’s begin.

A video screencast of this post

 

The complete code for this post can be found below

Backend (nodejs) – here.

Frontend (Ionic 2) – here.

This post will constitute of two sections. The back-end using Node.js and the app using Ionic 2.

Go to stripe.com and signup for an account. Once you have signed up and logged in, click on the API option available in the left side of the dashboard. You will see 2 sets of keys with 2 keys each namely a test set and a production set. Copy both the keys in the test set.

First let’s deal with the Node.js code.

Initialize a node project with npm init.

Then use the below command to install dependencies.

Now create a new file called index.js in your project directory and type the below code in it.

Replace the sk_test with your test secret key (obtained from stripe.com).

We are simply creating a REST endpoint which when hit will obtain the stripetoken and amount to be charged from the request body and then create a charge. If successful then it will simply return a json.

The Ionic 2 Part:

Install the cordova-plugin-stripe using the below commands.

Open up the ionic app. Use the below command to create a new page where we will be getting the card details.

(You could simply use a prompt alert to get the card details as well).

Now open up app.module.ts and import everything as shown below.

Now open up home.html and add a button

Open up home.ts and wire this up

Now open card.html and add the below code in-between the <ion-content> tags.

The above code is pretty much self explanatory. We are simply creating four input fields and a button.

Open up card.ts and add the below code in it.

Please paste the test publishable key (obtained from stripe.com) in the this.stripe.setPublishableKey() line.

We are simply creating a token from the card details and passing it along with the amount to be charged to the backend server (our Node.js app) and then if the transaction is successful i.e., if the charge is created successfully then the alert shows up.

That’s it guys. Stripe has several options available which you can make use of.

To test the above code, you could simply run your node.js app on a hosting provider like heroku, then replace the post request URL with the url provided by heroku and try making a payment request from your client applications.

All your client applications will have the publishable key in them. (Never use the server key in your client-side code).

Hope this helped you guys. If it did, kindly share it with someone and help them too.

Thanks for reading. Peace.. :)

 

Liked it? Take a second to support admin on Patreon!