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

Stripe Payment Intent创建时前后端金额传递400错误求助

解决Stripe支付Intent创建时的JSON反序列化错误

问题场景

使用Stripe、React和C#开发支付功能,创建Payment Intent时将金额从前端传递到后端,收到400 Bad Request错误,错误信息显示无法将JSON对象反序列化为System.Int64类型。

错误原因

前端发送的是包含amount字段的JSON对象(格式为{"amount": 数值}),但后端接口的参数声明为[FromBody] long amount,期望接收的是JSON原始值(如直接传递数值1000),数据格式不匹配导致反序列化失败。

解决方案

方案一:修改前端,直接传递金额原始值

调整前端代码,将计算后的金额以原始数值形式发送,而非包裹在对象中。同时注意Stripe要求金额使用最小货币单位(例如美元需传入分,1美元对应100),需将计算结果转成整数:

// 计算总金额并转为最小货币单位(美元→分)
const totalAmount = Math.round(
  (cart.CartPrice + cart.CartPrice * 0.06625 + props.fee + props.tipAmount.amount) * 100
);

// 创建PaymentIntent
axios.post(
  "https://localhost:5001/api/Checkout/create-payment-intent",
  totalAmount, // 直接传递数值,而非对象
  {
    headers: {
      "Content-Type": "application/json",
    },
  }
).then((res) => res.json())
.then(({ clientSecret }) => setClientSecret(clientSecret));

注:前端原代码中的JSON.stringify(amount);未生效(未赋值给变量),axios会自动处理数据序列化,无需手动调用。

方案二:修改后端,创建接收模型

后端定义一个类来匹配前端发送的JSON对象结构,再从模型中获取金额:

  1. 创建请求模型类:
public class PaymentIntentRequest
{
    public long Amount { get; set; }
}
  1. 修改控制器接口参数:
[HttpPost("create-payment-intent")]
public async Task<ActionResult> CreateCheckoutSession([FromBody] PaymentIntentRequest request)
{
    try
    {
        var service = new PaymentIntentService();
        var paymentIntent = await service.CreateAsync(new PaymentIntentCreateOptions
        {
            Amount = request.Amount, // 从请求模型中获取金额
            Currency = "usd",
            PaymentMethodTypes = new List<string> {"card", "us_bank_account"},
        });

        return Ok(new { ClientSecret = paymentIntent.ClientSecret });
    }
    catch (StripeException e)
    {
        return BadRequest(new { error = new { message = e.StripeError.Message }});
    }
}

额外注意事项

  • 确保前端计算的金额为整数,Stripe不接受小数金额,必须转换为最小货币单位(如美元×100取整)。
  • 若使用方案一,后端无需修改,保持原[FromBody] long amount参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:17:45