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

如何将Cashfree支付网关的GET请求改为POST并实现动态支付?

解决方案

1. 调整接口请求方式为POST

确保你的后端路由配置为接收POST请求(以Express框架为例):

app.post('/api/payment/initiate', paymentinitiate);

2. 从请求体获取动态数据

前端发起POST请求时,将用户信息、购物车数据、订单金额等参数放在请求体中,后端直接读取这些动态值,替换原有的静态字段。

3. 修改后的完整服务端代码

const crypto = require('crypto');
const Cashfree = require('cashfree-pg');

Cashfree.XClientId = process.env.CASH_API_ID;
Cashfree.XClientSecret = process.env.CASH_SECRET;
Cashfree.XEnvironment = Cashfree.Environment.SANDBOX;

function generateOrderId() {
  const uniqueId = crypto.randomBytes(16).toString("hex");
  const hash = crypto.createHash("sha256");
  hash.update(uniqueId);
  const orderId = hash.digest("hex");
  return orderId.substr(0, 12);
}

export const paymentinitiate = async (req, res) => {
  try {
    // 从POST请求体读取动态数据
    const { userInfo, cartItems, totalAmount } = req.body;

    // 构造Cashfree订单请求参数
    const request = {
      order_amount: totalAmount,
      order_currency: "INR",
      order_id: await generateOrderId(),
      customer_details: {
        customer_id: userInfo.id,
        customer_phone: userInfo.phone,
        customer_email: userInfo.email
      },
      order_items: cartItems.map(item => ({
        item_id: item.id,
        item_name: item.name,
        item_price: item.price,
        item_quantity: item.quantity
      })),
      order_meta: {
        return_url: `https://your-domain.com/payment-success?order_id={order_id}`,
        notify_url: `https://your-domain.com/payment-webhook`
      },
    };

    // 调用Cashfree创建订单API(SDK内部已处理POST请求)
    const response = await Cashfree.PGCreateOrder(request);

    // 返回会话信息给前端唤起支付
    res.status(200).json({
      success: true,
      sessionId: response.data.session_id,
      orderId: request.order_id
    });
  } catch (error) {
    console.error('支付订单创建失败:', error);
    res.status(500).json({
      success: false,
      message: '支付初始化失败,请重试'
    });
  }
};

关键修改说明

  • 动态数据注入:通过req.body获取前端传递的用户信息、购物车列表、订单总金额,彻底替换静态值。
  • 购物车数据传输:新增order_items字段,将购物车商品转为Cashfree要求的格式,解决GET无法传输复杂数据的问题。
  • Cashfree API调用:使用官方SDK的PGCreateOrder方法创建订单,内部已封装POST请求逻辑,无需手动处理HTTP细节。
  • 回调地址配置:替换return_url为你的业务域名下的支付结果页面,notify_url用于接收Cashfree异步支付结果通知。

前端请求示例

前端需通过POST请求传递动态数据:

async function initPayment() {
  const userInfo = { id: 'user_123', phone: '13800138000', email: 'user@example.com' };
  const cartItems = [
    { id: 'item_001', name: '商品A', price: 99.99, quantity: 1 },
    { id: 'item_002', name: '商品B', price: 49.99, quantity: 2 }
  ];
  const totalAmount = 199.97;

  const response = await fetch('/api/payment/initiate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ userInfo, cartItems, totalAmount })
  });

  const data = await response.json();
  // 使用sessionId唤起Cashfree支付组件
  Cashfree.Checkout({
    sessionId: data.sessionId,
    returnUrl: 'https://your-domain.com/payment-success'
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 10:11:13