
What is stripe angular integration?
In this article, we will discuss about the stripe angular integration, first we will discuss about the angular. Angular is a JavaScript framework for building single-page client applications using HTML and TypeScript. The following stripe integration example will work with Angular version 8 till 13 (the latest at the time of publishing this article) and now we will discuss about the stripe, Stripe is the fastest and easiest way to integrate payments and financial services into your software. This article will help the developer while stripe angular integration because it is one of the most used method in payments form.
How to do stripe angular integration?
1. Before starting the stripe angular integration, there are some packages/software that should be installed on your system, these are as:
• Node installed on your machine
• NPM installed on your machine
• Installing Angular CLI: npm install -g @angular/cli
2. The step, after the installation of these required software, we’ll create a new angular app, now we’ll start with angular integration example as it will help you more in better understanding of angular stripe integration method.
3. Start by creating your Angular Project by tying this command in your project folder:
ng new app-name
4. As 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 so save these keys because we’ll will provide these keys to angular app with Stripe connection.

<script src="https://js.stripe.com/v3/"></script>
5. 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`
}
});
6. So the next step is that we’ll install Stripe npm package.
npm install @stripe/stripe-js
7. On the successful 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');
Creation of payment form
8. Then, we’ve to create a payment form, and we’ll use Stripe element to that form.
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- a Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors -->
<div id="card-errors" role="alert"></div>
</div>
<input type="submit" class="submit" value="Submit Payment">
</form>
9. Insertion is completed now, your payment form will look like this

10. We’ve added 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();
11. Element initialization is now completed, 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`
card.mount('#card-element');
12. 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`
13. Elements also provide information about validation errors in real-time, which helping you communicate them to your users. Add this in your component.ts.
card.addEventListener('change',(event)=>{
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
14. In case of any error, It’ll display below to that field, something like this

15. When user submit the form, then we’ll have to create token for security.
16. Add this createToken() method as its first argument to generate a token for payment checkout. Add the code below in component.ts file :
createToken() {
stripe.createToken(card).then((result)=>{
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
stripeTokenHandler(result.token);
}
});
};
// Create a token when the form is submitted.
var form = document.getElementById('payment-form');
form.addEventListener('submit',(event)=>{
event.preventDefault();
createToken();
});
17. 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

How to do 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.
Installation
1. To install the last active version:
npm install ngx-stripe @stripe/stripe-js
1.2. If you want to install any 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
2. As the package is installed successfully then we’ll setup our application.
3. Firstly, import the NgxStripeModule into your application.
4. 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';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
NgxStripeModule.forRoot('***your-stripe-publishable-key***'),
LibraryModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
5. Now you have to pass your stripe key and setup the other things of your project then we’ll Mount Element functionality to our app.
6. 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
7. 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.
8. 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
9. Use this code in your stripe-mount.component.html file.
<h2>Your Heading</h2>
<ngx-stripe-card
[options]="cardOptions"
[elementsOptions]="elementsOptions"
></ngx-stripe-card>
<button type="submit" (click)="createToken()">
Submit
</button>
Stripe mount component
10. 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 {
StripeElements,
StripeCardElement,
StripeCardElementOptions,
StripeElementsOptions
} from '@stripe/stripe-js';
@Component({
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;
constructor(
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', this.cardOptions);
this.card.mount('#card-element');
}
});
}
createToken() {
const name = this.stripeTest.get('name').value;
this.stripeService
.createToken(this.card, { name })
.subscribe((result) => {
if (result.token) {
// Use the token
console.log(result.token.id);
} else if (result.error) {
// Error creating the token
console.log(result.error.message);
}
});
}
}
Note: if you want to apply your own card styling, then make changes in cardOptions.style object and add your own styling object.
11. 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.
12. 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.
13. 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
14. After this executing this command, it’ll generate four files.
Checkout component
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';
@Component({
selector: 'ngstr-checkout',
templateUrl: './checkout.component.html'
})
export class CheckoutComponent {
constructor(
private http: HttpClient,
private stripeService: StripeService
) {}
checkout() {
// Check the server.js tab to see an example implementation
this.http.post('/create-checkout-session', {})
.pipe(
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) {
alert(result.error.message);
}
});
}
}
15. Copy and paste this code in your checkout.component.html file.
<button (click)="checkout()">
Proceed to CHECKOUT
</button>
16. As soon as these steps are completed, 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}!`));
Conclusion:
We have discussed about the stripe and how can we integrate stripe payment method with angular by implementing with an example of by using payment form. Further more, we have also discussed the integration of stripe with ngx stripe with an example. This will help the developer to better understand the integration of stripe with angular and integration of stripe with ngx stripe. You can also read about the integration of stripe on demanding app and integrating apple pay with stripe.