Flask集成Cashfree API时Payload中None值的处理问题
解决方案:Cashfree支付Payload空值/None处理
核心问题定位
Cashfree支付API对数值类型字段有严格校验,不接受None、空字符串这类非数值类型值——哪怕替换成空字符串也不行,必须传入合法的数值类型(int/float)。
后端强制兜底处理(关键)
在Flask后端组装请求Payload前,对所有涉数字段做统一的数值转换处理,确保无非法值:
修改后的Flask后端代码片段
# 处理列表类型金额字段 def sanitize_amount_list(amount_list): if not amount_list: return [] return [float(item) if item is not None and item != '' else 0.0 for item in amount_list] # 处理单个金额字段 def sanitize_single_amount(amount): if amount is None or amount == '': return 0.0 try: return float(amount) except ValueError: return 0.0 # 组装请求Payload时调用处理函数 payload = { # 其他字段... "f_r_amounts": sanitize_amount_list(request.json.get("f_r_amounts")), "s_r_amounts": sanitize_amount_list(request.json.get("s_r_amounts")), "f_hou_amount": sanitize_single_amount(request.json.get("f_hou_amount")), "s_hou_amount": sanitize_single_amount(request.json.get("s_hou_amount")), # 其他字段... } # 发起Cashfree API请求 response = requests.post(cashfree_api_url, json=payload, headers=headers)
前端参数校验优化
在Flutter前端发起请求前,提前将空值/null替换为0,减少后端处理负担:
修改后的Flutter前端代码片段
// 处理列表类型金额 List<double> sanitizeAmountList(List<dynamic>? list) { if (list == null) return []; return list.map((item) => item == null || item == '' ? 0.0 : double.parse(item.toString())).toList(); } // 处理单个金额 double sanitizeSingleAmount(dynamic amount) { if (amount == null || amount == '') return 0.0; try { return double.parse(amount.toString()); } catch (e) { return 0.0; } } // 组装请求参数 var requestBody = { // 其他字段... 'f_r_amounts': sanitizeAmountList(_formData['f_r_amounts']), 's_r_amounts': sanitizeAmountList(_formData['s_r_amounts']), 'f_hou_amount': sanitizeSingleAmount(_formData['f_hou_amount']), 's_hou_amount': sanitizeSingleAmount(_formData['s_hou_amount']), // 其他字段... }; // 向后端发起请求 var response = await http.post(Uri.parse(your_flask_api_url), body: json.encode(requestBody));
错误排查补充
如果问题仍存在,打印Cashfree API返回的完整响应(response.json()),根据具体错误提示调整:
示例错误响应:{"status":"ERROR","message":"Invalid value for field f_r_amounts[0], expected number got string"}
这类提示说明字段类型不匹配,需确保最终传入的是数值而非字符串类型。
内容的提问来源于stack exchange,提问作者Swarup Nama
相关产品推荐
相关产品推荐

