【问题标题】:Run Function when a Customer is charged using Stripe's Subscription Firebase Extension使用 Stripe 的订阅 Firebase 扩展向客户收费时运行函数
【发布时间】:2021-04-22 06:34:17
【问题描述】:

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

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

【问题讨论】:

    标签: firebase stripe-payments firebase-extensions


    【解决方案1】:

    不幸的是,扩展程序似乎无法处理正在进行的付款事件:https://github.com/stripe/stripe-firebase-extensions/blob/master/firestore-stripe-subscriptions/functions/src/index.ts#L419-L432

    您要么需要修改该代码以包含可能的 invoice.payment_succeeded - 然后适当处理 - 要么编写一个云函数来自己处理(类似于此处显示的内容)。

    【讨论】:

    【解决方案2】:

    我自己解决了这个问题,方法是从官方仓库中借用一些用于 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_succeededurl 是我刚刚创建的 Firebase 函数。

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

    【讨论】:

      猜你喜欢
      • 2022-10-21
      • 2020-04-07
      • 2020-12-01
      • 2017-06-17
      • 2016-02-19
      • 2018-06-21
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多