Skip to content

Instantly share code, notes, and snippets.

@drexel-ue
Created March 16, 2019 20:16
Show Gist options
  • Save drexel-ue/6666172dd0c6d426cd434f2585e448b1 to your computer and use it in GitHub Desktop.
Save drexel-ue/6666172dd0c6d426cd434f2585e448b1 to your computer and use it in GitHub Desktop.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const firestore = admin.firestore();
const settings = {timestampInSnapshots: true};
firestore.settings(settings);
const stripe = require('stripe')(functions.config().stripe.token);
const currency = functions.config().stripe.currency || 'USD';
// Adds a customer's card information to Stripe for later billing.
// Returns the encrypted card information for processing on our end.
exports.addStripeSource = functions.firestore
.document('cards/{userId}/tokens/{tokenId}')
.onCreate(async (tokenSnap, context) => {
var customer;
const data = tokenSnap.data();
if(data == null) {
return null
}
const token = data.tokenId;
const snapshot = await firestore.collection('cards')
.doc(context.params.userId).get();
const customerId = snapshot.data().custId;
const customerEmail = snapshot.data().email;
if(customerId == 'new') {
customer = await stripe.customers.create({
email: customerEmail,
});
firestore.collection('cards').doc(context.params.userId).update({
custId: customer.id
});
}
else {
customer = await stripe.customers.retrieve(customerId);
}
const customerSource = await stripe.customers
.createSource(customer.id, {source: token});
return firestore.collection('cards').doc(context.params.userId)
.collection('sources').doc(customerSource.fingerprint)
.set(customerSource, {merge: true});
}
)
// When a user deletes their account, clean up after them
exports.cleanupUser = functions.auth.user().onDelete(async (user) => {
const snapshot = await admin.firestore().collection('cards')
.doc(user.uid).get();
const customer = snapshot.data();
await stripe.customers.del(customer.custId);
firestore.collection('users').doc(user.email).delete();
return firestore.collection('cards').doc(user.uid).delete();
});
@AarthifChristina
Copy link

does this work for you

@AarthifChristina
Copy link

becuase for me it says the below error caan u please fix this out for me
TypeError: Cannot read property 'custId' of undefined
at exports.addStripeSource.functions.firestore.document.onCreate (/srv/index.js:21:43)

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