0

我正在尝试收听 Stripe webhook 调用,然后执行一些操作,例如发送电子邮件。我的网站在 Netlify 上,我修改了在教程中找到的一些代码:

这在本地有效,但当我将它作为 Netlify 函数(基本上是 lambda)运行时则无效。基本上,来自“client.getSpace..”的部分似乎根本没有运行。我怀疑这与在异步函数中使用这些 .then 承诺有关,但我不确定。

require('dotenv').config();
     const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    
     const contentful = require('contentful-management');
     const client = contentful.createClient({
      accessToken: 
    process.env.CONTENTFUL_CONTENT_MANAGEMENT_ACCESS_TOKEN
    });
    
    var postmark = require("postmark");
    var serverToken = process.env.POSTMARK_SERVER_TOKEN;
    var postmark_client = new postmark.ServerClient(serverToken);
    
    exports.handler = async ({ body, headers }) => {
    try {
      const stripeEvent = stripe.webhooks.constructEvent(
        body,
        headers['stripe-signature'],
        process.env.STRIPE_WEBHOOK_SECRET
      );
    
      if (stripeEvent.type === 'checkout.session.completed') {
      	console.log('confirm checkout session completed');
        const eventObject = stripeEvent.data.object;
        const entryId = eventObject.client_reference_id;
        let email = "";
        let secret = "";
    
      client.getSpace(process.env.WEBSITE_CONTENTFUL_SPACE_ID)
      	.then(space => space.getEnvironment('master'))
          .then(environment => environment.getEntry(entryId))
          .then(entry => {
          	entry.fields.paymentStatus['en-GB'] = 'Paid';
          	email = entry.fields.email['en-GB'];
          	return entry.update();
          })
          .then(entry => entry.publish())
      	.then(entry => postmark_client.sendEmailWithTemplate({
              "From": "x@test.com",
              "To": email,
              "TemplateId": 12345678,
              "TemplateModel": {
                  "abc": "xyz"
               }
            }))
          .catch(console.error)
    
      }
    
      return {
        statusCode: 200,
        body: JSON.stringify({ received: true }),
      };
      } catch (err) {
      console.log(`Stripe webhook failed with ${err}`);
    
      return {
        statusCode: 400,
        body: `Webhook Error: ${err.message}`,
      };
    }
    };

4

1 回答 1

0

对于您和遇到此问题的任何其他人来说,这有什么价值。我在 Vercel 上使用 NextJS 时遇到了类似的问题。我使用 async/await 重写了 .then 语法,到目前为止,问题似乎已经解决。我不是专家,但我认为在这种情况下你会先替换

  client.getSpace(process.env.WEBSITE_CONTENTFUL_SPACE_ID)
    .then(space => space.getEnvironment('master'))

有类似的东西

       const send = await client.getSpace(process.env.WEBSITE_CONTENTFUL_SPACE_ID)
       const getEnvironment = await space.getEnvironment('master')

等等等等。我不确定您将如何重写其他所有内容,或者这是否会有所帮助,但这让我重回正轨。

于 2021-01-10T14:31:13.367 回答