Slim v3.2 PHP Stripe Checkout无法获取URL参数求助
解决Slim v3.2中无法获取URL参数并传递给Stripe支付会话的问题
我来帮你梳理下问题所在,并且给出具体的修复步骤:
核心问题分析
- Slim版本API差异:你用的
$app->request()->get('price')是Slim 2的写法,Slim 3已经完全重构了请求处理逻辑,需要通过注入到路由闭包的Request对象来获取参数。 - 中间件写法错误:你的
middleware1不符合Slim 3的中间件规范,而且变量作用域有问题——中间件里的$price无法传递到后续的路由处理函数中。 - 变量作用域问题:即使中间件能获取到
price,当前写法也无法把这个变量传递到/create-session的路由闭包里。
具体修复方案
步骤1:正确获取参数(两种场景)
根据你的请求URL,price是作为GET参数传递的,分两种情况处理:
场景A:/create-session是POST请求,但参数通过URL的GET参数传递
直接在路由闭包里用Slim 3的Request对象获取:
$app->post('/create-session', function(Request $request, Response $response) { // 获取URL中的GET参数price $price = $request->getQueryParam('price'); // 参数校验:避免空值或非法值 if(!$price || !is_numeric($price)){ return $response->withJson(['error' => 'Invalid price parameter'], 400); } try { $session = \Stripe\Checkout\Session::create([ 'payment_method_types' => ['card'], 'line_items' => [[ 'name' => 'Order', 'description' => 'ORDER ID: 123456789A', 'images' => ['testimage'], 'amount' => $price, 'currency' => 'aud', 'quantity' => 1, ]], 'success_url' => 'http://localhost:4242/success?session_id={CHECKOUT_SESSION_ID}', 'cancel_url' => 'http://localhost:4242/cancel', ]); createSession($session->id); } catch (Exception $e) { return $response->withJson($e->getJsonBody(), 400); } return $response->withJson($session); });
场景B:/create-session的POST请求体中包含price参数(更推荐的POST传参方式)
如果你的前端是通过POST请求体(比如JSON或表单)传递price,用以下方式获取:
// 获取POST请求体中的参数(JSON/表单格式通用) $params = $request->getParsedBody(); $price = $params['price'] ?? null; // 同样需要参数校验 if(!$price || !is_numeric($price)){ return $response->withJson(['error' => 'Invalid price parameter'], 400); }
步骤2:移除错误的中间件
你原来的middleware1写法不符合Slim 3的规范,而且没有实际作用,直接删掉即可。如果确实需要中间件处理参数,正确的Slim 3中间件写法如下(示例):
$app->add(function (Request $request, Response $response, $next) { // 在中间件中获取参数 $price = $request->getQueryParam('price'); // 将参数存入request属性,传递给后续路由 $request = $request->withAttribute('price', $price); return $next($request, $response); }); // 后续路由中获取参数 $app->post('/create-session', function(Request $request, Response $response) { $price = $request->getAttribute('price'); // 后续逻辑同上... });
步骤3:参数校验(重要)
无论哪种方式,都要对price进行校验:确保它是数字、不为空,并且符合Stripe的金额要求(比如AUD是以分为单位,5770代表57.70澳元,要确认你的数值是否正确)。
额外注意事项
- 你原来的代码中路由闭包里的
use ($app)是多余的,Slim 3的路由闭包已经通过注入Request和Response处理请求,不需要依赖全局的$app对象。 - 测试时可以先在路由里输出
$price确认是否获取成功,比如var_dump($price); exit;,再集成到Stripe的会话创建逻辑中。
内容的提问来源于stack exchange,提问作者AnonPHPcoder
相关产品推荐
相关产品推荐

