You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter集成Laravel后端Stripe支付时json.decode报<!doctype html>错误

解决Flutter解析Laravel后端Stripe支付响应时的FormatException错误

这个错误的核心原因很明确:你的Laravel后端没有返回预期的JSON数据,而是返回了HTML错误页面(就是报错里的<!doctype html>),导致Flutter端用json.decode()解析时直接抛出格式异常。下面一步步排查和解决:

1. 先修复Laravel后端的致命语法错误

看你的后端代码,所有$request-input('xxx')都是语法错误——PHP里调用对象方法应该用->,不是-。这个错误会直接触发PHP语法异常,Laravel会自动渲染HTML错误页面,而不是返回JSON。

同时,你还需要添加异常捕获和明确的JSON响应,避免Stripe操作失败时再次返回HTML。修正后的代码如下:

public function makePayment(Request $request) {
  \Stripe\Stripe::setApiKey('sk_test_7422pw1lMsdRfN2FaPmfFKlt00AtiIJD9O');
  
  try {
    // 修复语法错误:$request->input 替代 $request-input
    $token = Token::create([
      'card'=>[
        'number'=>$request->input('cardNumber'),
        'exp_month'=>$request->input('expiryMonth'),
        'exp_year'=>$request->input('expiryYear'),
        'cvc'=>$request->input('cvcNumber')
      ]
    ]);
    
    \Stripe\PaymentIntent::create([
      'amount' => 1000,
      'currency' => 'inr',
      'source' => $token,
      'receipt_email' => $request->input('email'),
    ]);
    
    // 明确返回成功的JSON响应
    return response()->json(['result' => true, 'message' => 'Payment completed successfully']);
  } catch (\Exception $e) {
    // 捕获Stripe异常(比如卡号无效、过期)或其他服务器错误,返回错误JSON
    return response()->json(['result' => false, 'message' => $e->getMessage()], 400);
  }
}

2. 增强Flutter端的错误处理逻辑

即使后端修复了,也可能出现网络异常、非JSON响应的情况,所以要在Flutter端添加防御性代码,避免未处理的异常:

void _makePayment(BuildContext context, Payment payment) async {
  PaymentService _paymentService = PaymentService();
  try {
    var paymentData = await _paymentService.makePayment(payment);
    
    // 先检查响应是否为JSON格式
    if (paymentData.headers['content-type']?.contains('application/json') == true) {
      var result = json.decode(paymentData.body);
      if (result['result'] == true) {
        CartService _cartService = CartService();
        this.widget.cartItems.forEach((cartItem){
          _cartService.deleteCartItemById(cartItem.productId);
        });
        _showPaymentSuccessMessage(context);
        Timer(Duration(seconds: 2), () {
          Navigator.pop(context);
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => HomeScreen()));
        });
      } else {
        // 处理后端返回的业务错误
        _showErrorMessage(context, result['message'] ?? 'Payment failed');
      }
    } else {
      // 后端返回非JSON(比如HTML错误页)
      _showErrorMessage(context, 'Server error: Invalid response received');
    }
  } catch (e) {
    // 捕获解析错误、网络错误等所有异常
    _showErrorMessage(context, 'Payment failed: ${e.toString()}');
  }
}

3. 调试验证后端接口

如果还是有问题,建议先用Postman或curl直接调用你的make-payment接口,传入Stripe测试卡号(4242424242424242,过期年月设为未来日期,CVC填123),确认返回的是标准JSON:

curl -X POST http://你的LaravelAPI地址/make-payment \
  -H "Content-Type: application/json" \
  -d '{"cardNumber":"4242424242424242","expiryMonth":"12","expiryYear":"2025","cvcNumber":"123","email":"test@example.com","name":"Test User"}'

这样能快速定位后端是否还有其他问题,比如路由配置错误、CSRF验证拦截等。

内容的提问来源于stack exchange,提问作者chetan suri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:17:31