Integrate Stripe with Angular 10

Virti Shah
Bitontree
Published in
4 min readNov 6, 2020

Stripe provides several JavaScript libraries — Stripe Elements & Checkout — that make it convenient to collect and validate payment sources like credit cards, bank accounts, and more. With Stripe.js, you can also tokenize sensitive information, integrate with Checkout, and handle 3D Secure authentication.

What are Stripe Elements?

Stripe Elements are a set of pre-built UI components, like inputs and buttons, for building your checkout flow.

Elements include features like:

  • Formatting card information automatically as it is entered
  • Translating placeholders into your customer’s preferred language
  • Using responsive design to fit the width of your customer’s screen or mobile device
  • Customizing the styling to match the look and feel of your checkout flow

Prerequisites

  • Node installed on your machine
  • NPM installed on your machine
  • Installing Angular CLI 10: npm install -g @angular/cli
  • Creating your Angular 8 Project: ng new angular-example

Now we will create a simple Payment form using Angular Reactive Forms.

Setup

  1. Include Stripe.js in the <head> tag of index.html file.
<script src="https://js.stripe.com/v3/"></script>

2. Configure Stripe using the following snippet.

var handler = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
locale: 'auto',
email: 'stripey@mcstripeface.com',
token: function (token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
}
});

Or, we can use the available npm package for Stripe using the following command.

For npm => npm install @stripe/stripe-js
For yarn => yarn add @stripe/stripe-js

The next step is to initialize Stripe using loadStripe function provided by the package.

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

Using the Payment Gateway in your Application

According to the plan selected, the screen will redirect to the Stripe payment gateway screen.

  1. Creating the Payment Form.

Use the following code in your component.html

<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>

And this in your component.ts

const stripe = Stripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
const elements = stripe.elements();

You can now 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');

2. Customize the card element.

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` <div>.
card.mount('#card-element');

3. Handle events and errors.

Elements also provide specific information about validation errors in real-time, 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 = '';
}
});

4. Create Token for security on form submit

Pass the createToken() method as its first argument to generate a token for payment checkout. Add the code belowin 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();
});

5. Pass the secure token with the amount to API for checkout

By using Http, call the Backend API and pass the token with the amount for the checkout process.

stripe.redirectToCheckout({
sessionId: token
});

Add more features to your stripe configuration =>

You can add additional parameters in the shortcode to customize your Stripe checkout button.button_text – The text displayed inside the button (e.g. button_text=”Pay Now”). The default is “Buy Now”.
success_url – The URL to which Stripe will redirect upon completion of a successful payment (e.g. success_url=”https://example.com/success”). The default is the Return URL specified in the settings.
cancel_url – The URL to which Stripe will redirect after a payment is canceled. (e.g. cancel_url=”https://example.com/payment-canceled”). The default is the home URL for your site.
mode – The mode of the checkout (e.g. mode=”subscription”). The default is “payment”.

--

--