Laravel集成Stripe Webhook返回302重定向至登录页(路由已公开)
问题描述
本地通过Stripe CLI触发webhook事件时,Laravel返回302错误(重定向至登录页),但该路由已设置为公开,可通过隐身窗口正常访问端点,Postman测试也无异常。
相关代码如下:
\Stripe\Stripe::setApiKey( env('STRIPE_SECRET_KEY') ); // This is your Stripe CLI webhook secret for testing your endpoint locally. $endpoint_secret = 'whsec_xxxxxxxxxxxxxxxxxxxx'; $payload = @file_get_contents('php://input'); $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE']; $event = null; try { $event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $endpoint_secret ); } catch(\UnexpectedValueException $e) { // Invalid payload http_response_code(400); exit(); } catch(\Stripe\Exception\SignatureVerificationException $e) { // Invalid signature http_response_code(400); exit(); } // Handle the event switch ($event->type) { case 'payment_intent.canceled': $paymentIntent = $event->data->object; dd($paymentIntent); case 'payment_intent.payment_failed': $paymentIntent = $event->data->object; case 'payment_intent.requires_action': $paymentIntent = $event->data->object; case 'payment_intent.succeeded': $paymentIntent = $event->data->object; // ... handle other event types default: echo 'Received unknown event type ' . $event->type; } http_response_code(200);
解决方案
排除CSRF验证:Stripe的webhook请求不带CSRF令牌,必须将路由从Laravel的CSRF校验中排除。打开
app/Http/Middleware/VerifyCsrfToken.php,把webhook路由添加到$except数组:protected $except = [ '/your-webhook-endpoint', // 替换为实际的webhook路由地址 ];确认路由未被认证中间件拦截:检查路由定义,确保没有被
auth中间件包裹。运行php artisan route:list查看路由详情,确认目标路由的中间件列没有auth相关项。校验Stripe CLI的请求URL:确保Stripe CLI转发的URL和Laravel路由完全一致,包括端口号、路径前缀等。例如正确的命令格式:
stripe listen --forward-to localhost:8000/your-webhook-endpoint清除路由缓存:如果之前缓存过路由,可能导致新的路由规则未生效,执行命令:
php artisan route:clear排查自定义中间件干扰:若项目中有全局自定义中间件,可能会对请求进行认证跳转。可以临时注释全局中间件测试,或在webhook路由上明确排除认证中间件:
Route::post('/your-webhook-endpoint', [WebhookController::class, 'handle']) ->middleware('web') ->withoutMiddleware('auth');
内容的提问来源于stack exchange,提问作者Aayush Dahal
相关产品推荐
相关产品推荐

