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

Flutter对接Cashfree API无法获取响应值,支付网关无法启动

Cashfree测试API获取order_token失败问题排查与修复

我正尝试从Cashfree测试API获取响应中的order_token,用于创建支付网关会话。在Postman中调用该API能正常获取响应,但代码里返回值为null,支付网关无法打开,打印响应也为空。以下是我的原始代码:

CFEnvironment environment = CFEnvironment.SANDBOX;

Future<dynamic> createOrder() async {
  var response = await http.post(
    Uri.https('https://sandbox.cashfree.com/pg/orders'),
    headers: {
      'Content-Type': 'application/json',
      'x-client-id': 'your x-client-id',
      'x-client-secret': 'your x-client-secret',
      'x-api-version': '2022-01-01',
      'x-request-id': 'developer_name',
    },
    body: jsonEncode(
      {
        "order_id": widget.cartId,
        "order_amount": widget.grandTotal,
        "order_currency": "INR",
        "order_note": "Additional order info",
        "customer_details": {
          "customer_id": widget.address.id,
          "customer_name": "name",
          "customer_email": widget.email,
          "customer_phone": widget.address.phone,
        }
      },
    ),
  );
  if (response.statusCode == 200) {
    if (jsonDecode(response.body)['status'] == 'OK') {
      debugPrint(jsonDecode(response.body)['order_id']);
      debugPrint('log');
      Logger.i(response.body);
      
      return jsonDecode(response.body)['order_id'];
    }
  }
  return '';
}


createSession() {
  createOrder().then((value) {
     try {
    var session = CFSessionBuilder()
        .setEnvironment(environment)
        .setOrderId(widget.cartId!)
        .setOrderToken(value)
        .build();
    return session;
  } on CFException catch (e) {
    debugPrint(e.message);
  }

  });
 
  return null;
}

错误原因分析

  • Uri构造错误:Uri.https的第一个参数应该是主机名(如sandbox.cashfree.com),传入完整URL会导致请求地址无效,无法正确调用API。
  • 返回值错误:createOrder方法返回的是order_id,但创建支付会话需要的是响应中的order_token,参数不匹配导致会话创建失败。
  • 异步处理不当:createSession方法中使用then处理异步请求,但直接返回null,此时会话还未创建完成,最终返回值始终为null。
  • 缺少错误日志:未处理非200状态码的响应,也未捕获网络异常,无法排查API调用失败的具体原因。

修正后的代码

修正createOrder方法

CFEnvironment environment = CFEnvironment.SANDBOX;

Future<String> createOrder() async {
  try {
    var response = await http.post(
      // 正确构造Uri:主机名 + 路径
      Uri.https('sandbox.cashfree.com', '/pg/orders'),
      headers: {
        'Content-Type': 'application/json',
        'x-client-id': 'your x-client-id', // 替换为实际测试环境client id
        'x-client-secret': 'your x-client-secret', // 替换为实际测试环境secret
        'x-api-version': '2022-01-01',
        'x-request-id': 'developer_name',
      },
      body: jsonEncode(
        {
          "order_id": widget.cartId,
          "order_amount": widget.grandTotal,
          "order_currency": "INR",
          "order_note": "Additional order info",
          "customer_details": {
            "customer_id": widget.address.id,
            "customer_name": "name",
            "customer_email": widget.email,
            "customer_phone": widget.address.phone,
          }
        },
      ),
    );

    // 打印所有状态码和响应,方便排查问题
    debugPrint('Response status code: ${response.statusCode}');
    debugPrint('Response body: ${response.body}');

    if (response.statusCode == 200) {
      final responseData = jsonDecode(response.body);
      if (responseData['status'] == 'OK') {
        // 返回正确的order_token
        return responseData['order_token'] ?? '';
      }
    }
    return '';
  } catch (e) {
    // 捕获网络请求异常
    debugPrint('Request error: $e');
    return '';
  }
}

修正createSession方法

Future<CFSession?> createSession() async {
  try {
    // 用await等待异步请求完成,确保拿到order_token后再创建会话
    String orderToken = await createOrder();
    if (orderToken.isEmpty) {
      debugPrint('Failed to retrieve valid order token');
      return null;
    }
    return CFSessionBuilder()
        .setEnvironment(environment)
        .setOrderId(widget.cartId!)
        .setOrderToken(orderToken)
        .build();
  } on CFException catch (e) {
    debugPrint('Cashfree session error: ${e.message}');
    return null;
  } catch (e) {
    debugPrint('Session creation error: $e');
    return null;
  }
}

额外注意事项

  • 确保替换x-client-id和x-client-secret为Cashfree提供的测试环境有效凭证。
  • 检查widget.cartId、widget.grandTotal等参数是否非空且格式正确,避免传入无效数据导致API请求失败。
  • 调用createSession时也需要使用await,确保会话创建完成后再进行后续支付操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:35:17