我'm struggling a bit with the integration of an automated workflow when a user purchases a product and pays by stripe. I'm使用 Firestore 和 Cloud 功能 .
Workflow
-
用户通过Stripe Checkout.js购买产品
-
付款存储在“付款”集合中
{ product:<uid of the product> '...', user:<uid of the user> '..', method: 'stripe', token:< Stripe token> {..} }
-
触发 Cloud 功能(onWrite用于付款收集)
-
TODO:从'products'获取产品DocRef(检索产品价格)
-
TODO:在“用户”集合的文档中将“文档”添加到“购买”集合
-
付费
我已经实现了这个工作流程,但步骤4和5除外,因为我不知道如何在Cloud Functions中从Firestore检索和添加DocRef(Firebase Docs提供了很多关于它如何与RT数据库一起工作的示例)
functions/index.js
exports.stripeCharge = functions.firestore
.document('/payments/{payment}')
.onWrite(event => {
const paymentId = event.params.payment;
const payment = event.data.data();
if (!payment || payment.method !== 'stripe' || payment.charge) return;
// 4. Get Product's Price
firestore.collection('products').doc(payment.product).then(product => {
const idempotency_key = paymentId;
const charge = {
amount: product.price,
currency: 'chf',
source: payment.token.id
};
stripe.charges.create(charge, {idempotency_key}).then(charge => {
// 5. Update User Purchases
firestore.collection('users').doc(payment.user).collection('purchases').add({
product: payment.product,
payment: paymentId,
date: new Date()
});
// Updated Charge
event.data.ref.update({charge});
});
});
Admin SDK 我想我必须使用Admin SDK来实现这个目标,但我不知道这应该如何与Firestore一起使用
1 回答
从Admin SDK访问Firestore非常类似于从Admin SDK访问任何其他Firebase产品:例如
admin.firestore()...
见https://firebase.google.com/docs/reference/admin/node/admin.firestore .当您尝试访问该文档时,您错过了一个
get()
调用:如果您之前没有使用过JavaScript的Firestore,那么Cloud Functions并不是开始使用它的最简单方法 . 我建议阅读docs for JavaScript/web users,然后选择Firestore codelab for web developers .