我有一个通过 API 网关调用 AWS Lambda 的条带 Webhook 端点。在这个函数中我需要验证并验证事件的签名。这是代码:
const AWS = require('aws-sdk');
AWS.config.update({ region: "us-east-1" });
let stripe = require('stripe')('sk_test_#####');
exports.handler = async (req) => {
console.log('hit')
let event;
let response;
try {
event = stripe.webhooks.constructEvent(
req.body,
req.headers['Stripe-Signature'],
process.env.STRIPE_WEBHOOK_SECRET
);
console.log(event)
} catch (err) {
console.log(err);
console.log(`⚠️ Webhook signature verification failed.`);
console.log(
`⚠️ Check the env file and enter the correct webhook secret.`
);
response = {
statusCode: 400,
headers: {
"Content-Type": "application/json",
"access-control-allow-origin": "*"
},
};
return response
}
// Extract the object from the event.
const dataObject = event.data.object;
// Handle the event
// Review important events for Billing webhooks
// https://stripe.com/docs/billing/webhooks
// Remove comment to see the various objects sent for this sample
switch (event.type) {
case 'invoice.paid':
// Used to provision services after the trial has ended.
// The status of the invoice will show up as paid. Store the status in your
// database to reference when a user accesses your service to avoid hitting rate limits.
break;
case 'invoice.payment_failed':
// If the payment fails or the customer does not have a valid payment method,
// an invoice.payment_failed event is sent, the subscription becomes past_due.
// Use this webhook to notify your user that their payment has
// failed and to retrieve new card details.
break;
case 'customer.subscription.deleted':
if (event.request != null) {
// handle a subscription cancelled by your request
// from above.
} else {
// handle subscription cancelled automatically based
// upon your subscription settings.
}
break;
default:
// Unexpected event type
}
response = {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"access-control-allow-origin": "*"
},
};
return response;
};
但是我收到此错误:StripeSignatureVerificationError:未找到与有效负载的预期签名匹配的签名
所以这里的问题是
req.headers['Stripe-Signature']
您要传递给
stripe.webhooks.constructEvent(
req.body,
req.headers['Stripe-Signature'],
process.env.STRIPE_WEBHOOK_SECRET
)
将是
undefined
因此,您需要按照本文档中的说明在 API 网关中配置自定义标头 使用自定义 Lambda 集成通过 API Gateway 将自定义标头配置到 Lambda 函数
配置完成后,您将在
req
对象中看到如下值
{
"body": {
// Stripe body content goes here
},
"headers": {
"Accept": "*/*; q=0.5, application/xml",
"Cache-Control": "no-cache",
"Content-Type": "application/json; charset=utf-8",
"Host": "udpou*****",
"Stripe-Signature": "t=*,v1=*,v0=*",
"User-Agent": "Stripe/1.0 (+https://stripe.com/docs/webhooks)",
"X-Amzn-Trace-Id": "*",
"X-Forwarded-For": "*",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
}
}
现在您可以访问标题中的
'Stripe-Signature'
并将其传递给 stripe.webhooks.constructEvent()
方法。
如果这有效,请在评论中告诉我。