What is Angular?

Angular is a JavaScript framework for building single-page client applications using HTML and TypeScript. The following example will work with Angular version 8 till 13 (the latest at the time of publishing this article)

What is Stripe?

Stripe is the fastest and easiest way to integrate payments and financial services into your software.

How to integrate Stripe with Angular?

Before start integration of Stripe with Angular, there are some packages/software that should be installed on your system

• Node installed on your machine

• NPM installed on your machine

• Installing Angular CLI: npm install -g @angular/cli

After installing these required software, we’ll create a new angular app.
Creating your Angular Project by tying this command in your project folder:

ng new app-name

Once our app is created, we’ll go to Stripe site and create one account, after successfully account creation, Stripe will provide us secret and public key, save these keys, we’ll will provide these keys to angular app with Stripe connection.

 <script src="https://js.stripe.com/v3/"></script>

Include this script in the tag in your project root file (usually index.html). Then configure the Stripe in that component where you want to integrate Stripe,

var handler = StripeCheckout.configure({
    key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh', // your Stripe public key
    locale: 'auto',
    email: [email protected],
    token: function (token) {
        // Use the token to create the charge with a server-side script.
        // You can access the token ID with `token.id`

After that we’ll install Stripe npm package.

npm install @stripe/stripe-js

After successfully installation of Stripe package, we should have to initialize Stripe function in our desired component, and provide that public key (which was provided by stripe) to stripe function, so that stripe verify that key.

import {loadStripe} from '@stripe/stripe-js';
const stripe = await loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');

After this process we’ve to create a payment form, and we’ll use Stripe card-element to that form.

<form action="/charge" method="post" id="payment-form">
    <div class="form-row">
        <label for="card-element">
            Credit or debit card
        <div id="card-element">
            <!-- a Stripe Element will be inserted here. -->
        <!-- Used to display form errors -->
        <div id="card-errors" role="alert"></div>
    <input type="submit" class="submit" value="Submit Payment">

After inserting this, your payment form will look like this

Once, we’ve add this form to our component, after that we’ve to add this element in our .ts file.

const stripe = Stripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh'); // public key
const elements = stripe.elements();

After element initialization, now we’ve to create a card Element and add it to your page using the mount() method.

var card = elements.create('card');
// Add an instance of the card UI component into the `card-element`

If you want to customize this card element, then you can configure it like this.

const style = {
  base: {
    color: '#32325d',
    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
    fontSmoothing: 'antialiased',
    fontSize: '16px',
    '::placeholder': {
      color: '#aab7c4'
  invalid: {
    color: '#fa755a',
    iconColor: '#fa755a'
// Create an instance of the card Element.
const card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element`
. card.mount(‘#card-element’);

Elements also provide information about validation errors in real-time, which helping you communicate them to your users. Add this in your component.ts.

  var displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';

If there is any error, then I’ll be display below to that field, something like this

When user submit the form, then we’ll have to create token for security.
Add this createToken() method as its first argument to generate a token for payment checkout. Add the code below in component.ts file :

createToken() {
    if (result.error) {
      // Inform the user if there was an error
      var errorElement = document.getElementById('card-errors');
      errorElement.textContent = result.error.message;
    } else {
      // Send the token to your server
// Create a token when the form is submitted.
var form = document.getElementById('payment-form');

Once the token is successfully generated, then pass the secure token with the amount to API for checkout. Once Stripe verify everything then it will return a 200 response along with token. If you want to use that token later then you can save that token in your database or store it somewhere else.
When payment is successfully done, then you can check this payment on your Stripe account


Stripe Integration with Ngx Stripe

What is ngx-stripe

Ngx Stripe is a wrapper around Elements. With the help of this we can add Elements to any Angular app.


To install the last active version:

npm install ngx-stripe @stripe/stripe-js

To install an specific version for an older Angular major, use the lts npm tags or check the table below to pick the right version, for example, for v8:

npm install ngx-stripe@v8-lts @stripe/stripe-js

Once the package is installed successfully then we’ll setup our application.
Firstly, import the NgxStripeModule into your application.
The module will takes the parameter of API Key as the global Stripe object. Pass your stripe public API Key to this module.
Here’s is the code demo of passing API Key to NgxStripeModule.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// Import your library
import { NgxStripeModule } from 'ngx-stripe';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Once you pass your stripe key and setup the other things of your project then we’ll Mount Element functionality to our app.
Sometimes you may want to fully control the style, the loading flow or simply the provided Element Components don’t suit well for your application.
In those cases you manually mount the Stripe Element on any DOM element. In the example bellow, we are mounting a Card Element into the div with id card-element. We need to do 3 things the Card Component usually do for us:


    • Fetch the Elements Object





    • Create the Stripe Element. In this example a card element, but the same approach can be used for any other support payment method.

    • Mount the element into the DOM

Before mounting stripe element to your app, firstly you should have component where you want to mount stripe card, if you don’t have any component for stripe mount then here is the code demo for creating and setup stripe mount in your app.
I’m creating component with name of stripe mount. Open your app in vscode or your favorite editor and in terminal paste this command.

Ng g c stripe-mount

Paste this code in your stripe-mount.component.html file.

<h2>Your Heading</h2>
<button type="submit" (click)="createToken()">

After pasting code in your html file, then paste this code in your stripe-mount.component.ts file.

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

import { StripeService } from "ngx-stripe";
import {
} from '@stripe/stripe-js';

  selector: 'ngstr-stirpe-mount',
  templateUrl: '/stripe-mount.component.html'
export class StripeTestComponent implements OnInit {
  elements: StripeElements;
  card: StripeCardElement;

  cardOptions: StripeCardElementOptions = {
    style: {
      base: {
        iconColor: '#666EE8',
        color: '#31325F',
        fontWeight: '300',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSize: '18px',
        '::placeholder': {
          color: '#CFD7E0'

  elementsOptions: StripeElementsOptions = {
    locale: 'es'

  stripeTest: FormGroup;

    private fb: FormBuilder,
    private stripeService: StripeService
  ) {}

  ngOnInit() {
    this.stripeTest = this.fb.group({
      name: ['', [Validators.required]]
      .subscribe(elements => {
        this.elements = elements;
        // Only mount the element the first time
        if (!this.card) {
          this.card = this.elements.create('card', this.cardOptions);

  createToken() {
    const name = this.stripeTest.get('name').value;
      .createToken(this.card, { name })
      .subscribe((result) => {
        if (result.token) {
          // Use the token
        } else if (result.error) {
          // Error creating the token

Note: if you want to apply your own card styling, then make changes in cardOptions.style object and add your own styling object.

Once you pass your stripe key and setup the other things of your project then we’ll implement stripe checkout functionality to our app.
Stripe Checkout is a hosted payment page optimized for conversion. Whether you offer one-time purchases or subscriptions, you can use Checkout to easily and securely accept payments online.
Before implementing stripe checkout you’ve stripe checkout component, If you don’t have any component for checkout then here is the demo for creating and setup stripe checkout in your app.
I’m creating component with name of checkout. Open your app in vscode or your favorite editor and in terminal paste this command.

Ng g c checkout

After this executing this command, it’ll generate four files.
Here is the code demo of checkout.component.ts file.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { switchMap } from 'rxjs/operators';

import { StripeService } from 'ngx-stripe';

  selector: 'ngstr-checkout',
  templateUrl: './checkout.component.html'
export class CheckoutComponent {
    private http: HttpClient,
    private stripeService: StripeService
  ) {}

  checkout() {
    // Check the server.js tab to see an example implementation
    this.http.post('/create-checkout-session', {})
        switchMap(session => {
          return this.stripeService.redirectToCheckout({ sessionId: session.id })
      .subscribe(result => {
        // If `redirectToCheckout` fails due to a browser or network
        // error, you should display the localized error message to your
        // customer using `error.message`.
        if (result.error) {

Paste this code in your checkout.component.html file.

<button (click)="checkout()">
  Proceed to CHECKOUT

Once these things are done, then go to backend code and paste this code in your server.js file

// This example sets up an endpoint using the Express framework.
// Watch this video to get started: https://youtu.be/rPR2aJ6XnAc.

const express = require('express');
const app = express();
const stripe = require('stripe')('***your secret key***');

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'T-shirt',
          unit_amount: 2000,
        quantity: 1,
    mode: 'payment',
    success_url: 'https://example.com/success',
    cancel_url: 'https://example.com/cancel',

  res.json({ id: session.id });

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