JavaScript Google Cloud Function: записывать значения Stripe в Firebase - PullRequest
0 голосов
/ 02 июля 2019

Я новичок в JavaScript и написал следующую JS Google Cloud Function с помощью различных ресурсов.

Эта функция обрабатывает событие Stripe invoice.payment_succeeded, и вместо записи всего data я пытаюсь сохранить только отправленные значения period_start и period_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 ]

1 голос
/ 02 июля 2019

Функции типа HTTP прекращаются сразу после отправки ответа. В своем коде вы отправляете ответ, а затем пытаетесь выполнить больше работы. Вам придется выполнить всю работу до отправки ответа, иначе он может быть отключен.

0 голосов
/ 02 июля 2019

Если вы просто хотите сохранить значения period_start и period_end, вместо всего data объекта , вы можете использовать метод update() (см. https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields).

Затем вам следует изменить свой код следующим образом. ( Просто отметьте, что неясно, откуда вы получаете значение userId, так как вы не показываете узел базы данных stripe_ids в своем вопросе. Iсделайте предположение, что это значение в /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) => {...});

});
...