Stripe.NET 使用教程
项目介绍
Stripe.NET 是一个用于与 Stripe API 进行交互的 .NET 客户端库。它支持同步和异步操作,适用于 .NET 4.6.1 及以上版本。Stripe.NET 提供了对 Stripe API 的全面支持,包括支付处理、订阅管理、发票生成等功能。
项目快速启动
安装
你可以通过 NuGet 安装 Stripe.NET:
nuget install Stripe.net
或者使用 Package Manager Console:
Install-Package Stripe.net
初始化
在你的项目中初始化 Stripe.NET:
using Stripe;
class Program
{
static void Main(string[] args)
{
StripeConfiguration.ApiKey = "你的 Stripe 密钥";
}
}
创建客户
以下是一个创建客户的示例:
var options = new CustomerCreateOptions
{
Email = "jenny.rosen@example.com",
Description = "Jenny Rosen (jenny.rosen@example.com)"
};
var service = new CustomerService();
Customer customer = service.Create(options);
Console.WriteLine(customer.Id);
应用案例和最佳实践
支付处理
Stripe.NET 可以轻松处理支付:
var options = new ChargeCreateOptions
{
Amount = 2000,
Currency = "usd",
Source = "tok_visa", // 从 Stripe.js 获取的令牌
Description = "Charge for jenny.rosen@example.com"
};
var service = new ChargeService();
Charge charge = service.Create(options);
Console.WriteLine(charge.Id);
订阅管理
创建和管理订阅:
var options = new SubscriptionCreateOptions
{
Customer = "cus_12345",
Items = new List<SubscriptionItemOptions>
{
new SubscriptionItemOptions
{
Plan = "plan_12345"
}
}
};
var service = new SubscriptionService();
Subscription subscription = service.Create(options);
Console.WriteLine(subscription.Id);
典型生态项目
Stripe Checkout
Stripe Checkout 是一个预构建的支付页面,可以快速集成到你的网站中。你可以使用 Stripe.NET 来处理 Checkout 会话:
var options = new SessionCreateOptions
{
PaymentMethodTypes = new List<string>
{
"card"
},
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
Price = "price_12345",
Quantity = 1
}
},
Mode = "payment",
SuccessUrl = "https://example.com/success",
CancelUrl = "https://example.com/cancel"
};
var service = new SessionService();
Session session = service.Create(options);
Console.WriteLine(session.Id);
Stripe Elements
Stripe Elements 是一组自定义 UI 组件,用于构建安全的支付表单。你可以使用 Stripe.NET 来处理 Elements 提交的支付信息:
var options = new PaymentIntentCreateOptions
{
Amount = 2000,
Currency = "usd",
PaymentMethodTypes = new List<string>
{
"card"
}
};
var service = new PaymentIntentService();
PaymentIntent paymentIntent = service.Create(options);
Console.WriteLine(paymentIntent.ClientSecret);
通过这些示例,你可以快速上手并使用 Stripe.NET 进行支付处理、订阅管理等操作。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考