Browse Source

Adding initial Stripe example

Change-Id: I4ab9c7b106106eb632bffc488e75f6c7fbd2a65b
katowulf-pr-tpl
James Daniels 8 years ago
parent
commit
5a2163c25d
  1. 6
      stripe/database.rules.json
  2. 5
      stripe/firebase.json
  3. 43
      stripe/functions/index.js
  4. 9
      stripe/functions/package.json

6
stripe/database.rules.json

@ -0,0 +1,6 @@
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}

5
stripe/firebase.json

@ -0,0 +1,5 @@
{
"database": {
"rules": "database.rules.json"
}
}

43
stripe/functions/index.js

@ -0,0 +1,43 @@
const functions = require('firebase-functions'),
admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const stripe = require('stripe')(functions.config().stripe.token),
currency = functions.config().stripe.currency || 'USD';
exports.createStripeCharge = functions.database.ref('/users/{userId}/charges/{id}').onWrite(event => {
const val = event.data.val();
if (val === null || val.id || val.error) return null;
return admin.database().ref(`stripe_customers/${event.params.userId}`).once('value').then(snapshot => {
return snapshot.val();
}).then(customer => {
const amount = val.amount;
const idempotency_key = event.params.id;
return stripe.charges.create({amount, currency, customer}, {idempotency_key});
}).then(response => {
return event.data.ref.set(response);
}, error => {
return event.data.ref.child('error').set(error.message);
}
);
});
exports.createStripeCustomer = functions.auth.user().onCreate(event => {
const data = event.data;
return stripe.customers.create({
email: data.email,
}).then(customer => {
return admin.database().ref(`/stripe_customers/${data.uid}`).set(customer.id);
});
});
exports.cleanupUser = functions.auth.user().onDelete(event => {
return admin.database().ref(`/stripe_customers/${event.data.uid}`).once('value').then(snapshot => {
return snapshot.val();
}).then(customer => {
return stripe.customers.del(customer);
}).then(() => {
return admin.database().ref(`/stripe_customers/${event.data.uid}`).remove();
});
});

9
stripe/functions/package.json

@ -0,0 +1,9 @@
{
"name": "functions",
"description": "Firebase Functions",
"dependencies": {
"firebase-admin": "^4.0.5",
"firebase-functions": "https://storage.googleapis.com/firebase-preview-drop/node/firebase-functions/firebase-functions-preview.latest.tar.gz",
"stripe": "^4.15.0"
}
}
Loading…
Cancel
Save