James Daniels
8 years ago
4 changed files with 63 additions and 0 deletions
@ -0,0 +1,6 @@ |
|||
{ |
|||
"rules": { |
|||
".read": "auth != null", |
|||
".write": "auth != null" |
|||
} |
|||
} |
@ -0,0 +1,5 @@ |
|||
{ |
|||
"database": { |
|||
"rules": "database.rules.json" |
|||
} |
|||
} |
@ -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(); |
|||
}); |
|||
}); |
@ -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…
Reference in new issue