Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Collect Payments With Angular, Stripe Checkout, and Firebase

Episode 24 written by Jeff Delaney
full courses for pro members

Health Check: This lesson was last reviewed on and tested with these packages:

  • Angular v4.2
  • AngularFire2 v4

Update Notes: Serious about Stripe Payments in your Angular Firebase app? Check out the Full Stack Stripe Payments course.

Find an issue? Let's fix it

In this lesson, we are going to build a payment collection system, that will enable users to make credit card payments with Stripe Checkout. This first part covers how to use Angular 4 to collect the Stripe charge token and save it to Firebase.

  • Angular 4.2
  • Stripe Checkout
  • Firebase

This is part one of a multipart series on Angular payment collection.

Stripe Lesson Series Contents

  • Use Stripe Checkout to collect the Charge Token (You are Here)
  • Create a Stripe Charge with Firebase Cloud Functions
  • Selling Digital Products
  • Custom Payment Form with Stripe Elements PRO (in development)
  • Create and Manage Subscriptions PRO (in development)
  • Create a Marketplace and Payout Users with Stripe Connect PRO (in development)
  • Advanced Techniques - Logging, Security, and Webhooks. (in development)

demo of stripe checkout in angular 4

Prerequisites

You need to have user authentication enabled in your Angular app with AngularFire2. You also need a Stripe account.

Generate the Resources

We are going to put payments in their own NgModule. The payment feature will grow more complex throughout this series, so it is a good idea to extract it into a module now.

ng g module payments/payment
ng g service payments/payment --module payments/payment
ng g component payments/make-payment --module payments/payment

Your NgModule should look like this

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { MakePaymentComponent } from './make-payment/make-payment.component';
import { PaymentService } from './payment.service';

@NgModule({
imports: [
CommonModule
],
declarations: [
MakePaymentComponent
],
providers: [
PaymentService
]
})
export class PaymentModule { }

Then import the module in the app.module or wherever you plan on using Stripe.

Initial Setup

Before doing anything, get your Stripe account setup and not the test API key.

How Stripe Payments Work in Angular with Firebase

  • User triggers the checkout window, enters card details
  • Stripe returns the charge token
  • Token is saved to the Firebase database
  • Cloud function processes the actual charge and updates the database.

Include the Stripe Library in Angular TypeScript

We need the stripe checkout library in our project. Stripe recommends making this script global to enable better fraud detection, so let’s add it the head of the index.html. In fact, it must be loaded directly from Stripe - using a local NPM package is not possible/supported.

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

Register with TypeScript

The StripeCheckout class is not known to TypeScript, so we need declare it in typings.d.ts

declare var StripeCheckout:any;

Add API Key to Environment

Lastly, you should add your Stripe API keys to your environment files. Here I am adding the test key to the development environment.

export const environment = {
production: false,
stripeKey: 'YOUR_STRIPE_TEST_KEY',
// Your Firebase Config {}

};

Database Design

Stripe returns the data for the token and charge as JSON. Each payment will be nested under the UserId.

payments
$userId
$paymentId
amount: number
token: object
charge: object

The Make Payment Component

The user can click a button to in the MakePaymentComponent that will trigger the stripe checkout window to collect the user’s credit card information. In order for it to work, we need to convert the Stripe JavaScript custom integration code into Angular-style TypeScript.

make-payment.component.html

<button (click)="handlePayment()">
Add Credits to your Account
</button>

make-payment.component.ts

The handler is defined during ngOnInit. We pass it the test key from our environment and set a default image. When stripe returns the token, it will trigger the service to save the data.

Next, a click handler is created to open the checkout modal. The @HostListener decorator is used to listen for the window:popstate event, which will occur if the user clicks the back button or navigates to a new page.

Stripe amounts are based equal to 1/100th of the base currency, so an amount of 500 equals $5.00.

import { Component, OnInit, HostListener } from '@angular/core';
import { PaymentService } from '../payment.service';
import { environment } from '../../../environments/environment';

@Component({
selector: 'make-payment',
templateUrl: './make-payment.component.html',
styleUrls: ['./make-payment.component.scss']
})
export class MakePaymentComponent implements OnInit {

handler: any;
amount = 500;

constructor(private paymentSvc: PaymentService ) { }

ngOnInit() {
this.handler = StripeCheckout.configure({
key: environment.stripeKey,
image: '/your/awesome/logo.jpg',
locale: 'auto',
token: token => {
this.paymentSvc.processPayment(token, this.amount)
}
});
}

handlePayment() {
this.handler.open({
name: 'FireStarter',
excerpt: 'Deposit Funds to Account',
amount: this.amount
});
}

@HostListener('window:popstate')
onPopstate() {
this.handler.close()
}

}

Payment Service

The service just needs to get the current user’s ID, then save the stripe token to the database.

payment.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';


@Injectable()
export class PaymentService {

userId: string;

constructor(private db: AngularFireDatabase, private afAuth: AngularFireAuth) {
this.afAuth.authState.subscribe((auth) => {
if (auth) this.userId = auth.uid
});
}


processPayment(token: any, amount: number) {
const payment = { token, amount }
return this.db.list(`/payments/${this.userId}`).push(payment)
}

}

Next Steps

That’s it for Part 1 of Stripe Checkout in Angular. At this point, the card has NOT actually been charged. We just have a token that needs to be processed on a backend server. In the next section, we will setup the backend with Firebase Cloud Functions to get you paid!