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()); } }
关键说明
- 必须同时传Payment Method和Customer:你的Payment Method已经关联到客户,Stripe需要通过Customer确认支付方式的归属,防止非法使用。
setConfirm(true)的作用:新版Payment Method要求支付必须经过确认才能完成,设置该参数会在创建Charge时自动触发确认流程,无需额外调用确认接口。- 若Payment Method尚未关联到Customer,需先执行附加操作:
PaymentMethodAttachParams attachParams = PaymentMethodAttachParams.builder() .setCustomer(customerId) .build(); PaymentMethod.retrieve(paymentMethodId).attach(attachParams);
内容的提问来源于stack exchange,提问作者Youzef
相关产品推荐
相关产品推荐

