5 steps to add Stripe.js to Angular CLI project

Last updated: 25 March 2020

1. Install Angular CLI

npm install -g @angular/cli

2. Create your first Stripe.js Angular CLI project

ng new my-first-stripe-js-project
cd new my-first-stripe-js-project

3. Install Stripe.js

npm install @stripe/stripe-js

4. Include Stripe.js script tag in index.html

<!-- Somewhere in index.html <head> tag -->
<script src="https://js.stripe.com/v3" async></script>

5. Add 3 snippets of code to app.component.html

import {Component} from '@angular/core';

// *** To Do #1 of 3: Add this
import {loadStripe} from '@stripe/stripe-js';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

// *** To Do #2 of 3: Add this
async checkout() {

// Replace with your own publishable key: https://dashboard.stripe.com/test/apikeys
const PUBLISHABLE_KEY = 'pk_1234';

// Replace with the domain you want your users to be redirected back to after payment
const DOMAIN = window.location.hostname;

// Replace with a SKU for your own product (created either in the Stripe Dashboard or with the API)
const SUBSCRIPTION_BASIC_PLAN_ID = 'plan_1234';

try {
const stripe = await loadStripe(PUBLISHABLE_KEY);
stripe.redirectToCheckout({
items: [{plan: SUBSCRIPTION_BASIC_PLAN_ID, quantity: 1}],
successUrl:
'https://' +
DOMAIN +
'/success.html?session_id={CHECKOUT_SESSION_ID}',
cancelUrl: 'https://' + DOMAIN + '/canceled.html'
})
.then(this.handleResult);
} catch (error) {
console.error('checkout() try catch error', error);
}

}

// *** To Do #3 of 3: Add this
handleResult(result) {
console.log('handleResult()', result);
}

}

Done!

  1. Serve it over HTTPS
  2. Change PUBLISHABLE_KEY
  3. Change SUBSCRIPTION_BASIC_PLAN_ID

Love writing my thoughts, reading biographies, and meeting like-minded friends to talk on B2B software sales, engineering & cloud solution architecture.