如何检测Stripe支付的成功与失败?代码执行疑问解析
问题解答
支付失败时的代码行为
Stripe的.NET SDK在API返回402这类错误状态码时,会直接抛出StripeException异常,不会返回null。你需要通过try-catch块捕获并处理这类错误,而非判断返回值是否为空。
如何获取支付失败原因
捕获StripeException后,可通过异常对象的属性获取详细失败信息:
ex.Message:错误的简要描述ex.StripeError:结构化错误详情,核心字段包括:StripeError.Code:错误类型码(比如payment_method_declined表示支付方式被拒绝)StripeError.DeclineCode:具体拒绝码(比如insufficient_funds表示余额不足)StripeError.Message:更详细的失败原因说明
处理失败的代码示例
PaymentIntent paymentIntent = null; try { var paymentIntentCreateOptions = new PaymentIntentCreateOptions { Customer = customerId, PaymentMethod = paymentMethodId, Amount = 123400, Currency = "usd", OffSession = true, Confirm = true, }; var paymentIntentService = new PaymentIntentService(); paymentIntent = paymentIntentService.Create(paymentIntentCreateOptions); } catch (StripeException ex) { // 处理支付失败逻辑 string errorCode = ex.StripeError.Code; string declineCode = ex.StripeError.DeclineCode; string errorMessage = ex.StripeError.Message; // 可根据错误类型执行后续操作,比如记录日志、提示用户更新支付方式等 }
补充说明
文档提到的PaymentIntent状态为requires_payment_method,是支付失败后该支付意图的状态值——但仅当API请求成功返回(无异常抛出)时,才能从返回的PaymentIntent对象中获取该状态。而支付失败导致的402错误会触发SDK抛出异常,此时需从异常的StripeError中分析原因,再决定是否重新创建支付意图或引导用户更新支付方式。
内容的提问来源于stack exchange,提问作者Jonathan Wood
相关产品推荐
相关产品推荐

