JavaScript Google Cloud Function:将Stripe值写入Firebase

时间:2019-07-02 04:39:15

标签: javascript firebase firebase-realtime-database google-cloud-functions stripe-payments

我是JavaScript新手,并且在各种资源的帮助下编写了以下JS Google Cloud Function。

此函数处理Stripe invoice.payment_succeeded事件,而不是编写整个data,而是尝试将发送的period_startperiod_end值都保存回正确的位置在我的Firebase数据库中的位置(请参见下面的结构)。

如何在同一函数调用中写入这两个值?

exports.reocurringPaymentWebhook = functions.https.onRequest((req, res) => {

  const hook  = req.body.type;
  const data  = req.body.data.object;
  const status = req.body.data.object.status;
  const customer = req.body.data.object.customer;
  const period_start = req.body.data.object.period_start;
  const period_end = req.body.data.object.period_end;

  console.log('customer', customer);
  console.log('hook:', hook);
  console.log('status', status);
  console.log('data:', data);
  console.log('period_start:', period_start);
  console.log('period_end:', period_end);


return admin.database().ref(`/stripe_ids/${customer}`).once('value').then(snapshot => snapshot.val()).then((userId) => {
  const ref = admin.database().ref(`/stripe_customers/${userId}/subscription/response`)
    return ref.set(data);
})
.then(() => res.status(200).send(`(200 OK) - successfully handled ${hook}`))
.catch((error) => {
  // We want to capture errors and render them in a user-friendly way, while
  // still logging an exception with StackDriver
  return snap.ref.child('error').set(userFacingMessage(error));
})
.then((error) => {
  return reportError(error, {user: context.params.userId});
});

});//End

enter image description here

2 个答案:

答案 0 :(得分:1)

HTTP类型的函数在发送响应后立即终止。在您的代码中,您正在发送响应,然后在此之后尝试做更多的工作。发送响应之前,您必须做所有工作,否则可能会中断响应。

答案 1 :(得分:0)

如果您只想保存period_startperiod_end值,而不是整个data对象,则可以使用update()方法(请参见https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields)。

然后,您应按以下步骤修改代码。 (请注意,不清楚从何处接收到userId值,因为您没有在问题中显示stripe_ids数据库节点。我假设它是该值在/stripe_ids/${customer}。您可以修改。

exports.reocurringPaymentWebhook = functions.https.onRequest((req, res) => {

  const hook  = req.body.type;
  const data  = req.body.data.object;
  const status = req.body.data.object.status;
  const customer = req.body.data.object.customer;
  const period_start = req.body.data.object.period_start;
  const period_end = req.body.data.object.period_end;


  admin.database().ref(`/stripe_ids/${customer}`).once('value')
  .then(snapshot => {
     const userId = snapshot.val();
     let updates = {};
     updates[`/stripe_customers/${userId}/subscription/response/period_start`] = period_start;
     updates[`/stripe_customers/${userId}/subscription/response/period_end`] = period_end;

     return admin.database().ref().update(updates);
  })
  .then(() => res.status(200).send(`(200 OK) - successfully handled ${hook}`))
  .catch((error) => {...});

});