Laravel集成Square支付报错:Must supply amount_money求助
问题解决:Square支付提示"Must supply amount_money"错误
错误原因分析
你遇到的MISSING_REQUIRED_PARAMETER错误,核心原因有两个:
CreatePaymentRequest构造函数参数顺序完全错误:Square PHP SDK中该类的构造参数顺序为source_id、amount_money、idempotency_key,你错误地将orderId放在了第二个参数位置,导致amount_money没有被正确传入API请求。- 缺少必填的
location_id参数:创建支付请求必须关联你的Square店铺位置ID,你的代码中没有将locationId设置到请求对象中。
修正后的控制器代码
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Square\SquareClient; use Square\Exceptions\ApiException; use Square\Models\Money; use Square\Models\CreatePaymentRequest; use Square\Environment; use Illuminate\Support\Str; class SquarePaymentController extends Controller { public function initiatePayment(Request $request) { $square_client = new SquareClient([ 'accessToken' => 'xxxxxxxxx', 'environment' => 'sandbox', ]); $locationId = 'LYQ8QF8RS568Z'; $payments_api = $square_client->getPaymentsApi(); // 构建金额对象 $money = new Money(); $money->setAmount(100 * 100); // 单位为分,此处对应100美元 $money->setCurrency("USD"); $sourceToken = $request->input('token'); // 生成唯一幂等键,防止重复提交请求 $idempotencyKey = Str::uuid()->toString(); // 正确实例化CreatePaymentRequest:参数顺序为source_id, amount_money, idempotency_key $create_payment_request = new CreatePaymentRequest($sourceToken, $money, $idempotencyKey); // 设置必填的location_id $create_payment_request->setLocationId($locationId); try { $response = $payments_api->createPayment($create_payment_request); if ($response->isSuccess()) { return response()->json($response->getResult()); } else { return response()->json($response->getErrors(), 400); } } catch (ApiException $e) { return response()->json(['error' => $e->getMessage()], 500); } } }
额外优化点
- 移除了无用的
use Square\Models\createPayment;等未使用的导入,精简代码结构。 - 用
Str::uuid()生成唯一的idempotency_key,替代原来参数顺序错误的rand(9000, 1000),确保请求幂等性。 - 改用Laravel标准的
response()->json()输出响应,符合框架规范。 - 移除了重复的
Authorization请求头,避免和SDK自动生成的请求头冲突。
前端代码说明
你的前端代码已正确获取支付令牌并传递到后端,无需修改。
内容的提问来源于stack exchange,提问作者Raman Naik
相关产品推荐
相关产品推荐

