AWS SAM集成Stripe Webhook时rawBody返回undefined问题排查
问题原因与解决方案
核心问题:你使用了**AWS_PROXY(Lambda代理集成)**类型,但同时配置了RequestTemplates,这两者冲突。Lambda代理集成会自动传递标准化的请求结构到Lambda,忽略自定义的请求模板,因此你定义的rawBody字段不会出现在Lambda的event中。
解决方案一:改用非代理集成(AWS类型)
修改template.yaml中StripeWebhookMethod的集成配置,将Type从AWS_PROXY改为AWS,这样自定义的请求模板会生效:
StripeWebhookMethod: Type: AWS::ApiGateway::Method Properties: AuthorizationType: NONE HttpMethod: POST ResourceId: !Ref StripeWebhookResource RestApiId: !Ref ApiGatewayRestApi Integration: IntegrationHttpMethod: POST Type: AWS # 修改为AWS类型 Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${stripeWebhookFunction.Arn}/invocations RequestTemplates: application/json: | { "method": "$context.httpMethod", "body": $input.json('$'), "rawBody": "$util.escapeJavaScript($input.body).replaceAll(\"\\'\", \"'\")", "headers": { #foreach($param in $input.params().header.keySet()) "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end #end } } IntegrationResponses: - StatusCode: 200 ResponseTemplates: application/json: "{}" PassthroughBehavior: NEVER # 强制使用自定义模板 MethodResponses: - StatusCode: 200
修改后重新执行sam deploy部署应用,Lambda即可正常获取rawBody字段。
解决方案二:保留Lambda代理集成,直接从event提取原始请求体
如果想继续使用AWS_PROXY,无需配置RequestTemplates,直接从Lambda的event中提取原始请求体即可。Stripe Webhook发送的是application/json格式,Lambda代理集成会将原始请求体字符串放在event.body中,可直接用于签名验证:
修改Lambda代码:
export const stripeWebhookHandler = async (event) => { // 直接使用event.body作为原始请求体 const rawBody = event.body; const headers = event.headers; const signature = headers["Stripe-Signature"]; const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; console.log("rawBody: ", rawBody); console.log("headers: ", headers); console.log("signature: ", signature); let stripeEvent; // 验证Stripe事件合法性 try { stripeEvent = stripe.webhooks.constructEvent( rawBody, signature, webhookSecret, ); } catch (err) { console.error(`Webhook签名验证失败: ${err.message}`); return formatResponse(400, { error: err.message }); } // 后续业务逻辑保持不变... };
额外排查步骤
- 打印完整event日志:在Lambda中打印整个
event对象,确认实际接收的结构,排查字段异常 - 确认部署更新:修改配置后重新执行
sam deploy,确保API Gateway的部署已同步更新 - 禁用请求验证:若API Gateway方法启用了请求验证,可能会修改原始请求体,建议暂时禁用后测试
- 用Stripe CLI测试:使用Stripe CLI发送测试webhook,同时查看API Gateway的CloudWatch日志,确认请求体是否完整传递
内容的提问来源于stack exchange,提问作者Jonny Ortiz
相关产品推荐
相关产品推荐

