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

Stripe Java后端通过Payment Method创建Charge报错,求解决方案

解决Stripe Java后端用Payment Method创建Charge的错误问题

问题原因

你当前代码用setSource()传入pm_开头的Payment Method ID是错误的——setSource()仅支持旧版的Source(src_xxx)、Token(tok_xxx)或Card ID(card_xxx),不兼容新版的Payment Method对象。而且关联到客户的Payment Method在创建Charge时,必须同时指定Payment Method ID和所属的Customer ID。

修正后的代码

调整方法参数,传入Payment Method ID和对应的Customer ID,用setPaymentMethod()替代setSource(),并添加必要的确认参数:

public Charge chargeWithPaymentMethod(String paymentMethodId, String customerId, double amount) throws EtAuthException {
    if (amount == 0) {
        throw new EtAuthException("Enter a valid amount");
    }
    // 将金额转换为分,用Math.round保证金额精度更准确
    long amountInCents = Math.round(amount * 100);
    try {
        ChargeCreateParams chargeParams = ChargeCreateParams.builder()
                .setAmount(amountInCents)
                .setCurrency("usd")
                .setPaymentMethod(paymentMethodId) // 指定Payment Method ID
                .setCustomer(customerId) // 指定该Payment Method所属的Customer
                .setConfirm(true) // 自动确认扣款,触发必要的验证流程(如3D Secure)
                .build();

        return Charge.create(chargeParams);
    } catch (StripeException e) {
        throw new EtAuthException("chargeWithPaymentMethod: " + e.getMessage());
    }
}

关键说明

  1. 必须同时传Payment Method和Customer:你的Payment Method已经关联到客户,Stripe需要通过Customer确认支付方式的归属,防止非法使用。
  2. setConfirm(true)的作用:新版Payment Method要求支付必须经过确认才能完成,设置该参数会在创建Charge时自动触发确认流程,无需额外调用确认接口。
  3. 若Payment Method尚未关联到Customer,需先执行附加操作:
    PaymentMethodAttachParams attachParams = PaymentMethodAttachParams.builder()
            .setCustomer(customerId)
            .build();
    PaymentMethod.retrieve(paymentMethodId).attach(attachParams);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:45:05