You need to enable JavaScript to run this app. 如何从.NET C#后端传参调用前端JS完成Stripe支付身份验证
优惠活动
大模型
产品
解决方案
定价
更多

如何从.NET C#后端传参调用前端JS完成Stripe支付身份验证

.NET 后端对接前端完成Stripe二次验证支付实现方案

整个流程的核心是后端捕获OffSession支付的身份验证/确认需求,把前端调用stripe.confirmCardPayment所需的必要字段返回给客户端,由前端完成用户侧的验证交互,最终完成支付。

后端C#改造说明

现有代码在捕获到card_error类型的支付异常时,仅打印了paymentIntent.Id,未将前端需要的字段返回,无法触发前端的确认流程。
前端调用stripe.confirmCardPayment需要两个核心字段,均可从捕获到的PaymentIntent对象中获取:

  • client_secret:PaymentIntent的客户端密钥,是前端调用Stripe JS接口的必填参数
  • last_payment_error.payment_method.id:上次失败的支付方法ID,可避免用户重复输入卡片信息

改造后后端代码示例

try
{
  var service = new PaymentIntentService();
  var options = new PaymentIntentCreateOptions
  {
    Amount = 1099,
    Currency = "usd",
    Customer = "{{CUSTOMER_ID}}",
    PaymentMethod = "{{PAYMENT_METHOD_ID}}",
    Confirm = true,
    OffSession = true,
  };
  service.Create(options);
}
catch (StripeException e)
{
  switch (e.StripeError.ErrorType)
  {
    case "card_error":
      // 错误码为authentication_required时说明需要前端完成验证
      Console.WriteLine("Error code: " + e.StripeError.Code);
      var paymentIntentId = e.StripeError.PaymentIntent.Id;
      var service = new PaymentIntentService();
      // 获取完整的PaymentIntent对象
      var paymentIntent = service.Get(paymentIntentId);

      // 封装前端所需字段返回,无需暴露完整PaymentIntent
      var frontendPayload = new 
      {
        clientSecret = paymentIntent.ClientSecret,
        paymentMethodId = paymentIntent.LastPaymentError.PaymentMethod.Id,
        errorCode = e.StripeError.Code
      };
      // 替换为对应项目的响应返回逻辑,如ASP.NET Core可直接Ok(frontendPayload)
      return frontendPayload;
  }
}

前端JS对接逻辑

从后端接口响应中获取上述两个字段后,直接调用Stripe前端API即可:

// 调用后端接口获取支付参数
const { clientSecret, paymentMethodId } = await fetch('/api/your-payment-create-endpoint').then(res => res.json())

// 完成支付确认
stripe.confirmCardPayment(clientSecret, {
  payment_method: paymentMethodId
}).then(function(result) {
  if (result.error) {
    // 展示错误信息给用户
    console.log(result.error.message);
  } else {
    if (result.paymentIntent.status === 'succeeded') {
      // 支付完成,执行业务后续逻辑
    }
  }
});

注意事项

  • 前端调用前需完成Stripe初始化,确保已通过公钥获取到全局stripe实例
  • 仅返回前端所需的两个字段即可,无需暴露完整PaymentIntent对象,符合安全规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 04:15:03