Stripe PaymentMethod API创建报错求助(附代码及错误信息)
解决Stripe创建PaymentMethod时的CardException错误
你的问题核心是错误地把测试PaymentMethod ID(pm_card_visa)当成卡号传入了setNumber方法。pm_card_visa是Stripe预先生成的测试PaymentMethod资源,不是卡号,用这种方式调用创建接口会触发PCI合规的安全校验,导致报错。
以下是两种可行的解决方案:
方案一:直接使用预先生成的测试PaymentMethod
既然pm_card_visa本身就是现成的测试PaymentMethod,不需要调用创建接口,直接通过ID获取即可:
import com.stripe.Stripe; import com.stripe.exception.StripeException; import com.stripe.model.PaymentMethod; public class Main { public static void main(String[] args) throws StripeException { Stripe.apiKey = "sk_test_你的测试密钥"; // 直接获取预先生成的测试PaymentMethod PaymentMethod paymentMethod = PaymentMethod.retrieve("pm_card_visa"); System.out.println(paymentMethod); } }
方案二:使用测试卡号创建PaymentMethod(需开启权限)
如果一定要通过卡号创建PaymentMethod,步骤如下:
- 先在Stripe后台开启测试模式下的「原始卡号数据API访问」权限
- 使用Stripe官方提供的测试卡号(比如Visa测试卡号
4242424242424242),而非pm_card_visa
修改后的代码:
import com.stripe.Stripe; import com.stripe.exception.StripeException; import com.stripe.model.PaymentMethod; import com.stripe.param.PaymentMethodCreateParams; public class Main { public static void main(String[] args) throws StripeException { Stripe.apiKey = "sk_test_你的测试密钥"; PaymentMethodCreateParams params = PaymentMethodCreateParams.builder() .setType(PaymentMethodCreateParams.Type.CARD) .setCard( PaymentMethodCreateParams.CardDetails.builder() .setNumber("4242424242424242") // 官方测试Visa卡号 .setExpMonth(8L) .setExpYear(2026L) .setCvc("314") .build() ) .build(); PaymentMethod paymentMethod = PaymentMethod.create(params); System.out.println("done!"); } }
关键说明
pm_card_visa是Stripe提供的预先生成的测试PaymentMethod资源ID,不是卡号。当你调用PaymentMethod.create传入卡号字段时,Stripe会判定为发送原始卡号数据,触发安全校验——哪怕你填的是令牌ID也会被拦截,这就是报错的原因。
内容的提问来源于stack exchange,提问作者Gulam Samdani
相关产品推荐
相关产品推荐

