← All posts

How to Integrate Stripe into an Angular Application

Integrating Stripe into an Angular application involves several steps, from setting up the Stripe account to configuring both the client-side Angular application and the server-side Node.js application. Here’s a detailed walkthrough with additional information:

Stripe Account

To get started, you need to create a Stripe account. This account allows you to manage your payments, view transactions, and access developer tools. Once you’ve registered your Stripe account, navigate to the developer mode. Here, you’ll find your test publishable and secret keys. These keys are important for secure communication between your Angular application and Stripe.

Angular Application

To work with Stripe in your Angular app, you should install the ngx-stripe npm package. It's a wrapper for Stripe Elements that simplifies the integration process. Here is the full documentation.

npm install ngx-stripe @stripe/stripe-js

In your app.module.ts, import and configure the NgxStripeModule to provide access to Stripe Elements.

import {NgxStripeModule} from "ngx-stripe";

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgxStripeModule.forRoot()
],
bootstrap: [AppComponent]
})

export class AppModule { }

Next, you need to create StripePaymentComponent:

// stripe-payment.component.html

<div class="stripe-payment-container">
<div class="stripe-payment-form">
<h5>Stripe Payment</h5>
<mat-form-field >
<input matInput [(ngModel)]="stripeAmount" type="number" required/>
<span matPrefix>$&nbsp;</span>
</mat-form-field>
<button mat-raised-button color="primary" type="submit" (click)="checkout()">
Checkout
</button>
</div>

</div>
// stripe-payment.component.ts

import {Component, OnDestroy, OnInit} from '@angular/core';
import { CommonModule } from '@angular/common';

import {NgxStripeModule, StripeCardComponent, StripeFactoryService, StripeInstance, StripeService,} from "ngx-stripe";
import {Subscription, switchMap} from "rxjs";

import {MatButtonModule} from "@angular/material/button";
import {MatInputModule} from "@angular/material/input";
import {HttpClient, HttpResponse} from "@angular/common/http";
import {FormsModule} from "@angular/forms";

@Component({
selector: 'app-stripe-payment',
standalone: true,
imports: [CommonModule, StripeCardComponent, NgxStripeModule, MatInputModule, MatButtonModule, FormsModule],
templateUrl: './stripe-payment.component.html',
styleUrls: ['./stripe-payment.component.scss']
})
export class StripePaymentComponent implements OnInit, OnDestroy{

public stripe!: StripeInstance;
public stripeAmount!: number;
public stripePublicKey = 'key';

private subscriptions: Subscription;

constructor(
private http: HttpClient,
private stripeFactory: StripeFactoryService,
) {
this.subscriptions = new Subscription();
}

ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}

ngOnInit(): void {
// dynamically load the stripe script
this.stripe = this.stripeFactory.create(this.stripePublicKey);
// stripe amount is in cents, you should multiply your amount by 100
this.stripeAmount = 100;
}

checkout() {
const host = 'http://localhost:3000';
const checkout: Subscription = this.http.post(host + '/create-checkout-session', {data: {amount: this.stripeAmount * 100}}, {observe: 'response'})
.pipe(
switchMap((response: HttpResponse<Object>) => {
const session: IStripeSession = response.body as IStripeSession;
return this.stripe.redirectToCheckout({ sessionId: session.id });
})
)
.subscribe(result => {
// If `redirectToCheckout` fails due to a browser or network
if (result.error) {
console.log(result.error)
}
});
this.subscriptions.add(checkout);
}
}

interface IStripeSession {
id: string;
}

This component integrates with the Stripe payment gateway, allowing users to make secure and convenient payments using their credit cards.

  1. On initialization, the component dynamically loads the Stripe script and sets up a Stripe instance. It also defines the payment amount, which is specified in cents (and should be multiplied by 100 for proper conversion).
  2. The checkout() method is triggered when the user initiates a payment. It sends a request to the server to create a checkout session with the specified amount. The server responds with a session ID, and the component uses this ID to redirect the user to the Stripe checkout page, where they can complete the payment securely.
  3. The component imports various Angular and third-party modules and services, including Angular’s HttpClient, Stripe-related modules from “ngx-stripe,” and Angular Material components for input fields and buttons. This ensures that the necessary dependencies are available for Stripe payment processing.
  4. The stripePublicKey variable is set to the Stripe public key. This key is essential for securely communicating with the Stripe API. You can find this key in your Stripe account.

Node.js Server Application

Firstly, in your Node.js project, you need to install the stripe npm package. The Stripe Node library provides convenient access to the Stripe API from applications written in server-side JavaScript.

npm install stripe

Next, you need to create the Stripe API Server sets up an Express.js application to handle payment transactions through the Stripe payment gateway.

// create http server for stripe api
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const port = 3000;
const Stripe = require('stripe');
const stripeSecretKey = 'sk_test_51MluWcAoB9wLi1FKqlSfoiOWGTATimIw9Y6QQ8thXODlp3qya8on6KSokrH7zPzxUIsy71Bu5gISQtIyjGbGMGrr'
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods','OPTIONS,GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});
app.post('/create-checkout-session', async (req, res) => {
const stripe = Stripe(stripeSecretKey);
const domain = `http://localhost:${port}`;
//get amount
const amount = req.body?.data?.amount || 1000;
try {
//create stripe session
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'Test payment',
},
unit_amount: amount,
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${domain}/stripe-successful-payment?hash=hash`,
cancel_url: `${domain}/stripe-canceled-payment?hash=hash`,
expand: ['payment_intent']
});

return res.send(session);
} catch (err) {
console.log('stripe error', err);
}
});

app.listen(port, () => console.log(`Listening on port ${port}!`));

Here is the detailed description of the code above:

  1. The server initializes an Express.js application, creating a robust foundation for handling HTTP requests and managing routes.
  2. The server integrates with the Stripe payment gateway using the Stripe library. This enables users to make payments securely using credit cards.
  3. To handle Cross-Origin Resource Sharing (CORS), the server is configured to allow requests from a specific origin (http://localhost:4200). This is crucial for enabling secure communication with the frontend of a web application.
  4. The server defines a POST endpoint (/create-checkout-session) responsible for creating a Stripe checkout session. This endpoint expects a JSON payload containing payment-related data, such as the payment amount.
  5. Upon receiving a request to create a checkout session, the server utilizes the Stripe library to create a session with relevant details, such as accepted payment methods, line items, and success/cancel URLs.
  6. Upon successful creation of a Stripe checkout session, the server responds with the session details, allowing the client application to proceed with the payment process.
  7. The server securely configures the Stripe secret key (stripeSecretKey), a critical component for establishing a secure and authenticated connection with the Stripe API. You can find this key in your Stripe account.

Testing Your Application

To see your payment system in action, launch both the Angular application and the Node.js server. Make sure they are both running.

Angular application

When using your Angular application, users will be able to make payments securely through the Stripe checkout.

Stripe checkout

In summary, by following these steps and implementing the provided code, you can seamlessly integrate Stripe payments into your Angular application. This provides a secure and convenient way for your users to make payments using their credit cards.

Documentation links:

  1. https://stripe.com/docs;
  2. https://ngx-stripe.dev/docs/checkout;
  3. https://www.npmjs.com/package/stripe;
  4. https://www.npmjs.com/package/ngx-stripe

And there we have it. I hope you have found this useful. Thank you for reading. If you have any questions you can find me on LinkedIn. You can also see my previous articles:

In Plain English

Thank you for being a part of our community! Before you go: