Angular 13.2.0 + .NET 6集成Stripe支付时的CORS问题求助
解决Stripe Checkout集成中的CORS重定向问题
问题根源
你的问题出在AJAX请求跟随重定向到Stripe域名上:浏览器的XMLHttpRequest/fetch会自动跟随后端返回的303重定向,但Stripe的Checkout页面不会返回Access-Control-Allow-Origin头——因为Stripe Checkout是设计给用户直接跳转访问的,不是给AJAX请求调用的,所以浏览器会因为CORS策略拦截这个跨域请求。
正确解决方案
不要让后端返回303重定向,而是让后端返回Stripe Session的URL,前端接收到URL后直接用页面跳转的方式打开Stripe Checkout。
1. 修改.NET后端接口
将原来返回303的逻辑改为返回包含Checkout URL的JSON响应:
public IActionResult Create() { var domain = "http://localhost:4200"; var priceOptions = new PriceCreateOptions { Product = "prod_someProd", UnitAmount = 2000, Currency = "GBP", }; var priceService = new PriceService(); Price price = priceService.Create(priceOptions); var options = new SessionCreateOptions { LineItems = new List<SessionLineItemOptions> { new SessionLineItemOptions { Price = price.Id, Quantity = 1, }, }, Mode = "payment", SuccessUrl = domain + "/payments", CancelUrl = domain + "/payments", }; var service = new SessionService(); Session session = service.Create(options); // 返回Checkout URL而非重定向 return Ok(new { checkoutUrl = session.Url }); }
2. 修改Angular前端逻辑
调用接口获取URL后,用window.location.href进行页面跳转,而非AJAX请求跟随重定向:
// 示例Angular组件代码 import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-payment', templateUrl: './payment.component.html', }) export class PaymentComponent { constructor(private http: HttpClient) {} initCheckout() { this.http.get('/api/payment').subscribe((response: any) => { // 直接跳转到Stripe Checkout页面 window.location.href = response.checkoutUrl; }); } }
额外说明
- 你之前配置的.NET CORS规则是正确的,但问题不在后端,而是重定向后的Stripe域名不支持AJAX跨域请求,所以调整交互方式才是根本解决办法。
- 页面跳转是浏览器的原生行为,不受CORS策略限制,完全符合Stripe Checkout的使用设计。
内容的提问来源于stack exchange,提问作者Michał Sawicki
相关产品推荐
相关产品推荐

