How to Implement Stripe Payment Gateway in ASP.NET Core
By FoxLearn 2/17/2025 9:28:16 AM 276
We'll walk through setting up your Stripe account, configuring the application, and using Stripe Checkout for payment processing.
Prerequisites
- Stripe Account: You need to have a Stripe account. If you don’t have one, sign up at Stripe.
- ASP.NET Core SDK: Make sure you have the latest .NET SDK installed.
- IDE: Use Visual Studio
Step 1: Create a Stripe Account and Get API Keys
- Go to Stripe and create an account.
- After signing in, go to Developers > API Keys in the Stripe Dashboard.
- Copy your Publishable Key and Secret Key.
Step 2: Create a New ASP.NET Core MVC Project
- Open Visual Studio (or any IDE) and create a new ASP.NET Core MVC Web Application project.
- Select ASP.NET Core Web App (Model-View-Controller).
- Choose .NET 8.0 (or later) as the framework version.
Step 3: Install Stripe NuGet Package
- Open NuGet Package Manager or the Package Manager Console in Visual Studio.
- Run the following command to install the Stripe .NET library:
Install-Package Stripe.net
Step 4: Configure Stripe API Keys in appsettings.json
Add your Stripe API keys to the appsettings.json
file:
{ "Stripe": { "PublishableKey": "YOUR_STRIPE_PUBLISHED_KEY", "SecretKey": "YOUR_SECRET_KEY" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
Step 5: Set Up Stripe in Program.cs
Configure Stripe in your Program.cs
file by reading the API keys from appsettings.json
.
using Stripe; namespace YourAppNamespace { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Read the Stripe secret key StripeConfiguration.ApiKey = builder.Configuration["Stripe:SecretKey"]; // Add services to the container builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); } } }
Step 6: Create a Payment Controller
Create a new controller called PaymentController.cs
. This controller will handle the payment flow.
using Microsoft.AspNetCore.Mvc; using Stripe.Checkout; namespace YourAppNamespace.Controllers { public class PaymentController : Controller { private readonly IConfiguration _configuration; public PaymentController(IConfiguration configuration) { _configuration = configuration; } public IActionResult Checkout() { // Pass the Stripe Publishable Key to the view ViewBag.StripePublishableKey = _configuration["Stripe:PublishableKey"]; return View(); } [HttpPost] public async Task<IActionResult> CreateCheckoutSession() { // Create a Stripe Checkout Session var options = new SessionCreateOptions { PaymentMethodTypes = new List<string> { "card" }, LineItems = new List<SessionLineItemOptions> { new SessionLineItemOptions { PriceData = new SessionLineItemPriceDataOptions { Currency = "usd", ProductData = new SessionLineItemPriceDataProductDataOptions { Name = "Test Product", }, UnitAmount = 2000, // $20.00 in cents }, Quantity = 1, }, }, Mode = "payment", SuccessUrl = Url.Action("Success", "Payment", null, Request.Scheme), CancelUrl = Url.Action("Cancel", "Payment", null, Request.Scheme), }; var service = new SessionService(); var session = await service.CreateAsync(options); // Redirect to Stripe Checkout return Redirect(session.Url); } public IActionResult Success() { return View(); } public IActionResult Cancel() { return View(); } } }
Step 7: Create Views
Create the views for the payment process.
Checkout View (Views/Payment/Checkout.cshtml
):
@{ ViewData["Title"] = "Checkout"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>Checkout</h1> <form asp-action="CreateCheckoutSession" method="post"> <button type="submit" class="btn btn-primary">Pay with Stripe</button> </form>
Success View (Views/Payment/Success.cshtml
):
@{ ViewData["Title"] = "Payment Successful"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>Payment Successful</h1> <p>Thank you for your payment!</p>
Cancel View (Views/Payment/Cancel.cshtml
):
@{ ViewData["Title"] = "Payment Canceled"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>Payment Canceled</h1> <p>Your payment was canceled.</p>
Step 8: Run and Test the Application
- Run the application using
dotnet run
or the IDE's run command. - Go to
/Payment/Checkout
in your browser. - Click the Pay with Stripe button, which will redirect you to the Stripe Checkout page.
- Use test card details to make a payment:
- Card Number:
4242 4242 4242 4242
- Expiration Date: Any future date
- CVC: Any 3 digits
- ZIP Code: Any value
- Card Number:
Step 9: Handle Webhooks for Payment Events
To listen for payment events (like successful payments), set up a webhook to handle Stripe events such as CheckoutSessionCompleted
.
Set up a Webhook Endpoint in Stripe Dashboard:
- Go to Developers > Webhooks in the Stripe Dashboard.
- Add a new endpoint with your server's URL (e.g.,
https://yourdomain.com/Payment/Webhook
).
Add Webhook Handling in PaymentController.cs
:
using Stripe; using Microsoft.AspNetCore.Mvc; public class PaymentController : Controller { private readonly IConfiguration _configuration; public PaymentController(IConfiguration configuration) { _configuration = configuration; } [HttpPost] public async Task<IActionResult> Webhook() { var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(); var stripeEvent = EventUtility.ConstructEvent( json, Request.Headers["Stripe-Signature"], _configuration["Stripe:WebhookSecret"] ); if (stripeEvent.Type == Events.CheckoutSessionCompleted) { var session = stripeEvent.Data.Object as Session; // Handle the payment confirmation } return Ok(); } }
Add Webhook Secret to appsettings.json
:
{ "Stripe": { "WebhookSecret": "your_webhook_secret_here" } }
We’ve successfully integrated the Stripe Payment Gateway into an ASP.NET Core MVC application! This implementation uses Stripe Checkout for easy setup and secure transactions. You can further enhance the system by adding features like custom payment forms, storing payment details, and sending email confirmations.
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core
- How to Create a custom model validation attribute in ASP.NET Core
- How to disable ModelStateInvalidFilter in ASP.NET Core
- How to fix LoginPath not working in ASP.NET Core
- Synchronous operations are disallowed