Created
July 21, 2017 05:17
-
-
Save dmurawsky/ff0c2c9f5fee181df9328017d79e6966 to your computer and use it in GitHub Desktop.
A gist for creating Stripe users with Firebase and Google 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
import { databse } from 'firebase' | |
const userRef = database().ref('users/' + uid) // Assumes you have the users uid | |
userRef.update({ token, lastFour }) // Assumes you've used Stripe.js to get a card token and lastFour | |
userRef.child('stripeCustomerId').on('value', snap => { | |
let stripeCustomerId = snap.val() | |
if (stripeCustomerId) { | |
userRef.child('charges').push({ | |
amount: 4000, // $40 | |
currency: 'usd', | |
description: 'Example charge', | |
customer: stripeCustomerId | |
}) | |
userRef.child('stripeCustomerId').off('value') | |
} | |
}) |
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 stripe = require('stripe')(functions.config().stripe.sk) | |
// Add secret key to config by running this command on the command line: | |
// $ firebase functions:config:set stripe.sk="sk_live_f7ag7agaslkflkjasdfjkla" | |
exports.updateCard = functions.database.ref('/users/{uid}/token').onWrite(event => { | |
let token = event.data.val() | |
if (token) { | |
let userRef = event.data.ref.parent | |
return userRef.once('value', snap => { | |
let user = snap.val() | |
if (token && user.stripeCustomerId) { | |
// If the user is already registered with Stripe just update the card | |
return stripe.customers.update(user.stripeCustomerId, { source: token }) | |
} else if (token) { | |
// Otherwise, create a new Stripe customer and save the customer id to firebase | |
return stripe.customers.create({ | |
description: 'User ' + user.email, | |
source: token, | |
email: user.email | |
}).then(stripeCustomer => userRef.update({ stripeCustomerId: stripeCustomer.id }) | |
} | |
}) | |
} | |
}) | |
exports.chargeUser = functions.database.ref('/users/{uid}/charges/{chargeId}').onWrite(event => { | |
let charge = event.data.val() | |
// Make sure the charge object you save is the correct format for Stripe charges like on lines 8-13 in frontend/app.js above | |
stripe.charges.create(charge).then(() => event.data.ref.update({ charged: true })) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment