使用Stripe API创建计划报错求助(Stripe.net v15.6.1)
看起来你在使用Stripe.net v15.6.1创建Plan的环节遇到了报错,虽然你提到通过JSON获取的userId、price、priceId等参数都有有效值,但还是有几个常见的排查方向可以帮你定位问题:
1. 确认SDK与Stripe API版本的兼容性
Stripe.net的版本和Stripe官方API版本是绑定的,v15.6.1对应的API版本通常是2020-08-27。如果你的Stripe Dashboard中设置的默认API版本高于这个值,很可能会出现参数或端点不兼容的问题。建议在代码中显式指定匹配的API版本:
StripeConfiguration.ApiVersion = "2020-08-27"; StripeConfiguration.ApiKey = Settings.ConstName.StripeAPIKeyTest; // 注意你原代码里的"Strinp"可能是拼写错误
2. 检查StripePlanCreateOptions的必填参数是否完整
在Stripe.net v15.x版本中,创建Plan的必填参数包括:
Name:计划名称(不能为空)Interval:计费周期(可选值:month/week/year/day)Amount或AmountDecimal:金额(单位为分,比如$9.99对应999;用AmountDecimal则直接传9.99m)Currency:货币代码(比如usd/eur)
如果遗漏了这些必填项,Stripe会直接返回参数错误。你可以对照自己的代码检查是否都填全了:
var planOptions = new StripePlanCreateOptions { Name = "Premium Monthly Plan", Interval = "month", Amount = 1999, // $19.99 Currency = "usd", // 其他自定义参数,比如ProductId、Metadata等 }; var planService = new PlanService(Settings.ConstName.StripeAPIKeyTest); var plan = planService.Create(planOptions);
3. 捕获并查看具体的Stripe异常信息
你现在没有给出具体的报错内容,这是定位问题最关键的信息。建议在代码中添加异常捕获,打印Stripe返回的详细错误:
[HttpPost] public IActionResult Post([FromBody] JObject token) { var apiKey = Settings.ConstName.StripeAPIKeyTest; StripeConfiguration.ApiKey = apiKey; StripeConfiguration.ApiVersion = "2020-08-27"; try { var planOptions = new StripePlanCreateOptions { // 你的参数配置 PlanId = abn.PriceValueUnikId }; var planService = new PlanService(apiKey); var plan = planService.Create(planOptions); return Ok(plan); } catch (StripeException ex) { // 打印详细错误信息,包括错误码、参数提示 Console.WriteLine($"Stripe Error Message: {ex.Message}"); Console.WriteLine($"Stripe Error Code: {ex.StripeError.Code}"); Console.WriteLine($"Affected Parameter: {ex.StripeError.Param}"); return BadRequest(new { error = ex.StripeError.Message }); } }
Stripe的异常会明确告诉你是参数格式错误、权限不足还是API版本不兼容等问题,这能帮你快速锁定根源。
4. 验证API密钥的权限与拼写
注意你原代码中的StrinpAPIKeyTest可能是拼写错误(应该是StripeAPIKeyTest),如果密钥拼写错误,会直接返回权限验证失败。另外,要确认你使用的测试密钥(pk_test_开头)有创建Plan的权限,可以登录Stripe Dashboard,进入【Developers】->【API Keys】查看测试密钥的权限设置,确保没有被限制。
5. 检查自定义PlanId的格式
你设置的PlanId = abn.PriceValueUnikId需要符合Stripe的ID格式要求:只能包含小写字母、数字、-、_、.、=,且长度不超过50个字符。如果格式不符合,Stripe会返回参数无效的错误。
内容的提问来源于stack exchange,提问作者J. Petersen

