当客户使用 Stripe 的订阅 Firebase 扩展程序向客户收费时运行函数



我想每次用户通过Stripe的订阅扩展收费时运行Firebase云功能。是否有任何由该扩展生成的事件可以触发云功能,例如写入Firestore?

我的场景是,每当成功地向引用相应的User文档的用户收费时,我想在Orders集合中生成一个新文档。

我能够自己解决这个问题,从Stripe的Firebase扩展的官方回购中借用一些代码:https://github.com/stripe/stripe-firebase-extensions/blob/next/firestore-stripe-subscriptions/functions/src/index.ts

我制作了自己的Firebase函数,并将其称为handleInvoiceWebhook,该函数验证并构造了一个Stripe Invoice对象,将其映射到我使用我关心的字段制作的自定义Invoice接口,然后将其保存到invoices集合。

export const handleInvoiceWebhook = functions.https.onRequest(
async (req: functions.https.Request, resp) => {
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
req.rawBody,
req.headers['stripe-signature'] || '',
functions.config().stripe.secret
);
} catch (error) {
resp.status(401).send('Webhook Error: Invalid Secret');
return;
}
const invoice = event.data.object as Stripe.Invoice;
const customerId= invoice.customer as string;
await insertInvoiceRecord(invoice, customerId);
resp.status(200).send(invoice.id);
}
);
/**
* Create an Invoice record in Firestore when a customer's monthly subscription payment succeeds.
*/
const insertInvoiceRecord = async (
invoice: Stripe.Invoice,
customerId: string
): Promise<void> => {
// Invoice is an interface with only fields I care about
const invoiceData: Invoice = {
invoiceId: invoice.id,
...map invoice data here
};
await admin
.firestore()
.collection('invoices')
.doc(invoice.id)
.set(invoiceData);
};

部署后,我去了Stripe开发者仪表板(https://dashboard.stripe.com/test/webhooks),并添加了一个新的Webhook,监听事件类型invoice.payment_succeeded,url是我刚刚制作的Firebase函数。

注意:我必须使用以下命令为我的Firebase函数部署我的Stripe API密钥和Webhook Secret作为环境变量:firebase functions:config:set stripe.key="sk_test_123" stripe.secret="whsec_456"

不幸的是,它看起来不像扩展处理正在进行的支付事件:https://github.com/stripe/stripe-firebase-extensions/blob/master/firestore-stripe-subscriptions/functions/src/index.ts#L419-L432

您要么需要修改该代码以包含可能的发票。Payment_succeeded——然后适当地处理——或者自己编写一个云函数来处理(类似于这里所示的)。

相关内容

最新更新