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

Angular Stripe Payments Part 2 - Firebase Cloud Functions Backend

Episode 25 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 Angular Stripe Payments Part 1, we collected the token from stripe and saved it to Firebase. In this lesson, we will send that token back to Stripe with a Firebase Cloud Function to charge the card. The function will receive the charge response from Stripe, then save it to the database.

Side Note: You will need a paid Firebase account for this cloud function to work. Firebase blocks external API requests on the free “Spark” plan.

Configure Stripe with Cloud Functions

If you don’t have functions initialized, run firebase init functions, then cd functions.

Run npm install stripe --save from the functions directory to install the Stripe in the cloud function.

Configuring Stripe with Environment Variables

Set the stripe API key to your cloud function environment like so:

firebase functions:config:set stripe.testkey="YOUR_STRIPE_TEST_KEY"

Then verify it worked

firebase functions:config:get

Stripe Cloud Function Step by Step

I’m going to break the cloud function down step by step in the index.js file.

Step 1 - onWrite Setup

Our function will execute when data is written to the specified path. The event returned from this function is contains the data at this database location, which should have an amount and token that was saved in Part 1.

We set a few variables, then return if the the payment is missing or it has already been charged.

const functions = require('firebase-functions')
const admin = require('firebase-admin')

admin.initializeApp();

const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
const stripe = require('stripe')(firebaseConfig.stripe.testkey)

exports.stripeCharge = functions.database
.ref('/payments/{userId}/{paymentId}')
.onWrite(event => {

const payment = event.after.val();
const userId = event.params.userId;
const paymentId = event.params.paymentId;

if (!payment || payment.charge) return;


});

Step 2 - Get the User

This step is not necessary at this point, but I am including it because it is needed if you want to save user payment data for future checkouts. I will cover user management in stripe in greater detail in the next section.

return admin.database()
.ref(`/users/${userId}`)
.once('value')
.then(snapshot => {
return snapshot.val();
})

Step 3 - Create the Stripe Charge

Now its time to charge the card. Stripe only needs the amount, currency code, and token ID. We also send the paymentId, which is a Firebase push key, to enforce an idempotent operation. This just means that multiple POST requests on this resources will not change result - in other words, it prevents duplicate charges to the card.

.then(customer => {

const amount = payment.amount;
const idempotency_key = paymentId;
const source = payment.token.id;
const currency = 'usd';
const charge = {amount, currency, source};


return stripe.charges.create(charge, { idempotency_key });

})

Step 4 - Update the Firebase Database

When the charge is returned, we save it to the database. The charge object contains all sorts of useful information that we will use in the next section when designing a payment history component.

.then(charge => {
admin.database()
.ref(`/payments/${userId}/${paymentId}/charge`)
.set(charge)
})

The Full Stripe Charge Cloud Function

Gist

Next Steps

The covers the basic process of charging Stripe customers with Firebase Base Cloud Functions. In the next section we will create payment history component in Angular. We will also create some digital products so user’s can spend their money.