Welcome folks today in this blog post we will be integrating stripe payment gateway
in node.js and express using the angular 14
frontend in TypeScript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new directory
as shown below
mkdir stripeproject
cd stripeproject
And now you need to make the frontend
and backend
directory as shown below
Making the Angular Frontend
mkdir frontend
ng new stripefrontend
cd stripefrontend
After that you will see the below directory
structure of the angular app as shown below
Now you need to go to app.module.ts
file and copy paste the following code
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent], }) export class AppModule {} |
As you can see we are importing the HttpClient
Module and then adding inside the imports
Array.
Now we need to go to app.component.html
file and copy paste the below html
app.component.html
1 2 3 4 5 6 7 8 9 10 |
<h2>Angular Stripe Checkout Example</h2> <button (click)="makePayment(15)">Pay With Stripe</button> <div *ngIf="success"> <h1>Your Payment is complete successfully</h1> </div> <div *ngIf="failure"> <h1>Some Error is taken place inside the payment</h1> </div> |
As you can see we have the button
to trigger the stripe
payment. And then we are invoking the method called makePayment()
method where we are passing the 15
dollars. And then we have different templates
for success
and failure
of payments.
Now we need to make the Stripe
Checkout Service by going to the command line and executing the below command as shown below
ng g service checkout
This will generate the checkout
service
Now we need to go to checkout.service.ts
file and copy paste the following code
checkout.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class CheckoutService { constructor(private http: HttpClient) { } makePayment(stripeToken: any): Observable<any>{ const url = "http://localhost:5000/checkout/" return this.http.post<any>(url,{token:stripeToken}) } } |
As you can see we are making the post
request to the checkout
url inside the express server. Now we need to import
this service inside the app.component.ts
file as shown below
Now you need to go to app.component.ts
file and copy paste the following code
app.component.ts
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 71 |
import { Component } from '@angular/core'; import { CheckoutService } from './checkout.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title="sample app" paymentHandler: any = null; success: boolean = false failure:boolean = false constructor(private checkout: CheckoutService) {} ngOnInit() { this.invokeStripe(); } makePayment(amount: number) { const paymentHandler = (<any>window).StripeCheckout.configure({ key: '##publishablekey##', locale: 'auto', token: function (stripeToken: any) { console.log(stripeToken); paymentstripe(stripeToken); }, }); const paymentstripe = (stripeToken: any) => { this.checkout.makePayment(stripeToken).subscribe((data: any) => { console.log(data); if (data.data === "success") { this.success = true } else { this.failure = true } }); }; paymentHandler.open({ name: 'Coding Shiksha', description: 'This is a sample pdf file', amount: amount * 100, }); } invokeStripe() { if (!window.document.getElementById('stripe-script')) { const script = window.document.createElement('script'); script.id = 'stripe-script'; script.type = 'text/javascript'; script.src = 'https://checkout.stripe.com/checkout.js'; script.onload = () => { this.paymentHandler = (<any>window).StripeCheckout.configure({ key: '##publishablekey##', locale: 'auto', token: function (stripeToken: any) { console.log(stripeToken); }, }); }; window.document.body.appendChild(script); } } } |
Now you need to replace the publishable
key from the stripe
dashboard and we have written the methods to make the payment
inside the stripe
Now we need to start the angular
frontend by executing the below command as shown below
ng serve
Now the angular app has started at port 4200
Making the Backend Express Server
Now we need to make the backend
directory and inside it we need to make the node.js
project as shown below
mkdir backend
cd backend
npm init -y
npm i express
npm i cors
npm i stripe
And after that you need to make an index.js
file and copy paste the following code
index.js
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 |
const express = require("express"); const bodyparser = require('body-parser') const app = express(); app.use(bodyparser.urlencoded({ extended: false })) app.use(bodyparser.json()) const stripe = require("stripe")("##yoursecretkey##"); const cors = require('cors') app.use(cors()) app.post('/checkout', async(req, res) => { try { console.log(req.body); token = req.body.token const customer = stripe.customers .create({ email: "geekygautam1997@gmail.com", source: token.id }) .then((customer) => { console.log(customer); return stripe.charges.create({ amount: 1000, description: "Test Purchase using express and Node", currency: "USD", customer: customer.id, }); }) .then((charge) => { console.log(charge); res.json({ data:"success" }) }) .catch((err) => { res.json({ data: "failure", }); }); return true; } catch (error) { return false; } }) app.listen(5000, () => { console.log("App is listening on Port 5000") }) |
Now replace the stripe secret key
from the stripe dashboard and we have starting the express
app at port 5000.
nodemon index.js