symfony - Symfony 5,测试条带时得到 403
问题描述
我正在尝试使用 stripe 进行 symfony 5 的每月订阅。
我在我的项目中集成了条带,我正在测试一个网络书来收听诸如支付失败之类的事件。
我在控制器中创建了一个动作:
/**
* @Route("/webhook", name="webhook")
* @param Request $request
* @return Response
*/
public function webhook(Request $request) {
\Stripe\Stripe::setApiKey('sk_test_..');
$event = $request->query;
$webhookSecret = "whsec_..";
$signature = $request->headers->get('stripe-signature');
if ($webhookSecret) {
try {
$event = \Stripe\Webhook::constructEvent(
$request->getContent(),
$signature,
$webhookSecret
);
} catch (\Exception $e) {
// return new JsonResponse([['error' => $e->getMessage(),'status'=>403]]);
$response = new Response();
$response->setContent(json_encode([
'error' => $e->getMessage(),
]));
$response->headers->set('Content-Type', 'application/json');
$response->setStatusCode(403);
return $response;
}
} else {
$event = $request->query;
}
$type = $event['type'];
$object = $event['data']['object'];
switch ($type) {
case 'checkout.session.completed':
// Payment is successful and the subscription is created.
// You should provision the subscription and save the customer ID to your database.
break;
case 'invoice.paid':
// Continue to provision the subscription as payments continue to be made.
// Store the status in your database and check when a user accesses your service.
// This approach helps you avoid hitting rate limits.
break;
case 'invoice.payment_failed':
// The payment failed or the customer does not have a valid payment method.
// The subscription becomes past_due. Notify your customer and send them to the
// customer portal to update their payment information.
break;
// ... handle other event types
default:
// Unhandled event type
}
$response = new Response();
$response->setContent(json_encode([
'status' => 'success',
]));
$response->setStatusCode(200);
return $response;
}
基于条纹官方文档: https ://stripe.com/docs/billing/subscriptions/checkout
我修改了代码以使其适应 symfony,并尝试使用 postman 和 stripe cli 测试该操作:
与邮递员一起,我得到了:
无法从标头中提取时间戳和签名
使用 stripe cli,我开始使用以下命令监听路由:stripe listen --forward-to http://localhost/webhook,我使用 stripe trigger payment_intent.created 来模拟付款,但出现 403 错误
我该如何修复网络钩子?
解决方案
Postman 不是测试 Stripe webhook 的好方法,因为您的请求会丢失某些标头,例如时间戳,正如您所发现的那样。
相反,您应该使用 Stripe CLI 或仪表板来发送测试事件(CLI 更好,因为它创建了所有对象,而不是向您发送带有虚拟数据的事件)。
至于您在通过 CLI 触发事件时遇到的 403 错误,如果没有更多详细信息,我无法真正告诉您那里发生了什么。403 是“禁止”状态代码,因此您应该仔细检查您的服务器设置,确保 Webhook 端点无需身份验证即可访问 Internet。
推荐阅读
- object - 如何将对象检测标签转储到泡菜中?
- ggplot2 - 分类变量 R estudio 中的唯一值
- javascript - Javascript: how do you use multiple if else statments refering to different elements?
- python - 在 Z3Py 中定义对某些输入返回 true 对其他输入返回 false 的函数
- php - 将 shell_exec 与带有管道 ( | ) 的命令一起使用
- javascript - 'key' 未定义 no-undef setState ReactJS
- angular - Angular - 自定义内置语言环境
- python - 在python上计算以大写字母开头的单词
- azure - Sitecore 9 - 负载测试导致 502 错误
- ruby-on-rails - Rails:创建可以引用或可以是字符串的列