Stripe payment with Angular6 and NodeJs (Express)

We are on git also : 

So , today we are going to see how to make stripe payment with the help of Angular6. For this first of all we have to create a account in stripe (https://stripe.com) .

Now after creating the account in stripe , Go to the dashboard. Here we can find the Developers->API keys. 

Now follow the below steps :

1)Create a new Angular6 project

2)Install ngx-stripe

npm install ngx-stripe@next –save

3)Now open app.module.ts .

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { NgxStripeModule } from 'ngx-stripe';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule,
NgxStripeModule.forRoot('pk_test_6GD8IOeqFvFby4EuW982mVHS')
],
providers: [MessageService],
bootstrap: [AppComponent]
})
export class AppModule { }

Note : NgxStripeModule.forRoot(‘pk_test_6GD8IOeqFvFby4EuW982mVHS‘)

forRoot() method contains the your-stripe-publishable key. (We can find inside API Keys)

4)Now create a Card payment form inside the app.component.html

<div class="container">
<form novalidate (ngSubmit)="buy($event)" [formGroup]="stripeTest">
<div class="col-lg-6">
<input class="form-control" type="text" formControlName="name" placeholder="Jane Doe">
</div>
<div class="col-lg-6">
<div id="card-element" class="field"></div>
</div>
<div class="col-lg-12">
<button class="btn btn-success" type="submit">
BUY
</button>
</div>
</form>
</div>

5)Now inside the app.component.ts , we need to create a buy() method. This buy() method gets called once customer clicks over the Buy button. Inside buy() method we are creating the stripe token. We will send this token to the server for making charges

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

import { StripeService, Elements, Element as StripeElement, ElementsOptions } from "ngx-stripe";
import { Http} from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
elements: Elements;
card: StripeElement;

// optional parameters
elementsOptions: ElementsOptions = {
locale: 'es'
};

stripeTest: FormGroup;

constructor(
private http : Http,
private fb: FormBuilder,
private stripeService: StripeService) {}

ngOnInit() {
this.stripeTest = this.fb.group({
name: ['', [Validators.required]]
});
this.stripeService.elements(this.elementsOptions)
.subscribe(elements => {
this.elements = elements;
// Only mount the element the first time
if (!this.card) {
this.card = this.elements.create('card', {
style: {
base: {
iconColor: '#666EE8',
color: '#31325F',
lineHeight: '40px',
fontWeight: 300,
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSize: '18px',
'::placeholder': {
color: '#CFD7E0'
}
}
}
});
this.card.mount('#card-element');
}
});
}

buy() {
const name = this.stripeTest.get('name').value;

this.stripeService
.createToken(this.card, { name })
.subscribe(obj => {
if (obj) {
console.log("Token is --> ",obj.token.id);

this.http.post("http://localhost:3000/payme",{
token : obj.token.id
}).subscribe(
(res)=>{
console.log("The response from server is ",res);
console.log('Payment Done')
},
(err)=>{
console.log('The error is ',err)
})



} else {
// Error creating the token
console.log("Error comes ");
}
});
}
}

Note : In above code we can see that after getting the token , we are sending it to the server. (http://localhost:3000/payme) through post method

Express Code for stripe payment :

var express = require('express');
var stripe = require('stripe')('sk_test_xJYsnTIczDoCpOJ591lv6FkQ');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
//cross origin start
var cors = require('cors');
var originsWhitelist = [
'http://localhost:4200'
];
var corsOptions = {
origin: function(origin, callback){
var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
callback(null, isWhitelisted);
},
credentials:true
}
app.use(cors(corsOptions));
//cross origin end
app.post('/payme',(req,res)=>{
console.log('The body is ',req.body);
varcharge=stripe.charges.create({
amount:230000,
currency:'gbp',
source:req.body.token
},(err,charge)=>{
if(err){
throwerr;
}
res.json({
success :true,
message :"Payment Done"
})
});
})

 
app.listen(3000,()=>{
console.log('Server starts at port 3000');
});

Note : Once we click on buy button , a charge will be requested to the stripe payment gateway. Once done we will se a Payment Done message on console

By Pankaj Kumar Agarwal

Leave a reply:

Your email address will not be published.