Created
July 10, 2017 16:03
-
-
Save codediodeio/a814e073c7bd92e092edd00dec7407d0 to your computer and use it in GitHub Desktop.
Simple Stripe Payments with Firebase Cloud Functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "functions", | |
"description": "Cloud Functions for Firebase", | |
"dependencies": { | |
"firebase-admin": "^4.1.2", | |
"firebase-functions": "^0.5", | |
"stripe": "^4.23.1" | |
}, | |
"private": true | |
} |
You set It with the firebase cli by entering firebase functions:config:set stripe.testKey="YOUR STRIPE SECRET KEY" on the command line.
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
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
Small question, where do you set the keys for stripe?