Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Created July 10, 2017 16:03
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save codediodeio/a814e073c7bd92e092edd00dec7407d0 to your computer and use it in GitHub Desktop.
Save codediodeio/a814e073c7bd92e092edd00dec7407d0 to your computer and use it in GitHub Desktop.
Simple Stripe Payments with Firebase Cloud Functions
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase);
const stripe = require('stripe')(functions.config().stripe.testkey)
exports.stripeCharge = functions.database
.ref('/payments/{userId}/{paymentId}')
.onWrite(event => {
const payment = event.data.val();
const userId = event.params.userId;
const paymentId = event.params.paymentId;
// checks if payment exists or if it has already been charged
if (!payment || payment.charge) return;
return admin.database()
.ref(`/users/${userId}`)
.once('value')
.then(snapshot => {
return snapshot.val();
})
.then(customer => {
const amount = payment.amount;
const idempotency_key = paymentId; // prevent duplicate charges
const source = payment.token.id;
const currency = 'usd';
const charge = {amount, currency, source};
return stripe.charges.create(charge, { idempotency_key });
})
.then(charge => {
admin.database()
.ref(`/payments/${userId}/${paymentId}/charge`)
.set(charge)
})
});
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"firebase-admin": "^4.1.2",
"firebase-functions": "^0.5",
"stripe": "^4.23.1"
},
"private": true
}
@KanishkVashisht
Copy link

Small question, where do you set the keys for stripe?

@jaireddjawed
Copy link

jaireddjawed commented Jan 4, 2018

You set It with the firebase cli by entering firebase functions:config:set stripe.testKey="YOUR STRIPE SECRET KEY" on the command line.

@sabeehshah
Copy link

Hey, i have a similar function but when viewing the logs for the function i see that it says cannot read property val of undefined. I'd love some help

@AhsanNissar
Copy link

Hey, i have a similar function but when viewing the logs for the function i see that it says cannot read property val of undefined. I'd love some help

Were you able to solve this problem? If yes? then how?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment