You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET Core MVC 8中集成Stripe支付组件?

Stripe支付集成问题解答

问题清单

  • 官方文档中的Server.cs应放置何处?是否属于控制器?
  • 是否需要配置Product模型?
  • Stripe后台已注册的产品是否需要先在项目中添加才能正常运行?

你的项目信息

Program.cs代码

using CoffeeShop.Data;
using CoffeeShop.Models.Interfaces;
using CoffeeShop.Models.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Stripe;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();

builder.Services.AddDbContext<CoffeeShopDBContext>(option => 
    option.UseSqlServer(builder.Configuration.GetConnectionString("CoffeeShopDbConnection")));

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddEntityFrameworkStores<CoffeeShopDBContext>();
builder.Services.AddScoped<IShoppingCartRepository, ShoppingCartRepository>(s => ShoppingCartRepository.GetCart(s));

builder.Services.AddSession(); 
builder.Services.AddHttpContextAccessor();
builder.Services.AddRazorPages(); 

var app = builder.Build();

app.UseSession(); 

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.MapRazorPages(); 

app.UseRouting();

StripeConfiguration.ApiKey = builder.Configuration.GetSection("Stripe:SecretKey").Get<string>(); 

app.UseAuthentication(); 
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

项目结构

项目结构截图


解答

1. Server.cs的位置与定位

Stripe快速启动中的Server.cs是示例后端逻辑集合,并非ASP.NET Core标准控制器。结合你的项目结构,有两种处理方式:

  • 整合到控制器:在Controllers文件夹下新建StripeController.cs,将Server.cs中的支付创建、Webhook处理等逻辑作为控制器的Action方法实现(比如CreatePaymentIntent、HandleStripeWebhook)。
  • 抽离为服务:在Models/Services文件夹下创建StripePaymentService.cs,封装支付核心逻辑,然后在现有控制器(比如OrderController)中依赖注入该服务,调用相关方法。这种方式更符合你现有项目的分层设计。

2. Product模型配置

需要结合你的现有业务决定:

  • 你项目中已有IProductRepository,说明存在本地产品管理逻辑,无需照搬Stripe的Product结构,但建议在本地Product模型中添加StripeProductId字段,用于关联Stripe后台的产品ID。
  • 若完全依赖Stripe后台管理产品,可直接通过Stripe API查询产品信息,但这种方式灵活性差,不推荐。优先保留本地产品模型并关联Stripe ID。

3. Stripe后台产品的项目关联

不需要在项目中重复创建产品实体,但需在业务逻辑中关联Stripe产品ID:

  • 用户发起支付时,从本地购物车或产品数据中取出对应的StripeProductId,调用Stripe API创建PaymentIntent/CheckoutSession时传入该ID,即可关联Stripe后台已注册的产品。
  • 使用Stripe Checkout链接时,直接在链接参数中指定Stripe产品ID即可,无需提前在项目中添加产品数据。

内容的提问来源于stack exchange,提问作者TheHollyRoller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 03:56:18