Integrating Stripe Payment Gateway in ASP.NET Core MVC

In this article, we’ll walk through the complete process of integrating the Stripe Payment Gateway into an ASP.NET Core MVC application. By the end of this guide, you’ll have a fully functional payment system that allows users to make payments using Stripe’s secure checkout.

Introduction

Stripe is a popular payment gateway that allows businesses to accept payments online. It supports credit cards, debit cards, and other payment methods. Stripe provides a secure and easy-to-integrate API for developers.

In this article, we’ll use Stripe Checkout, which is a pre-built payment page hosted by Stripe. This approach is secure and requires minimal setup.

Prerequisites

Before starting, ensure you have the following.

  • Stripe Account: Sign up at Stripe.
  • .NET SDK: Install the latest .NET SDK from here.
  • IDE: Use Visual Studio, Visual Studio Code, or any preferred IDE.
  • Stripe API Keys: Retrieve your Publishable Key and Secret Key from the Stripe Dashboard.

Step 1. Create a Stripe Account

  1. Go to Stripe and sign up for an account.
  2. Once logged in, navigate to Developers > API Keys.
  3. Copy your publishable key and secret key. These will be used in your ASP.NET Core application.

Step 2. Set Up an ASP.NET Core MVC Project

  1. Open Visual Studio or your preferred IDE.
  2. Create a new ASP.NET Core Web App (Model-View-Controller) project.
    • Name the project (e.g., StripePaymentDemo).
    • Select .NET 6.0 or later as the framework.
  3. Build and run the project to ensure it’s set up correctly.

Step 3. Install Stripe.NET NuGet Package

Stripe provides an official .NET library to interact with its API. Install it via the Package Manager Console.

Install-Package Stripe.net

Step 4. Configure Stripe in appsettings.json

Add your Stripe API keys to the appsettings.json file.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Stripe": {
    "PublishableKey": "YOUR_STRIPE_PUBLISHED_KEY",
    "SecretKey": "YOUR_SECRET_KEY"
  },
  "AllowedHosts": "*"
}

Step 5. Configure Stripe in the Program.cs

Configure Stripe in the Program.cs file.

using Stripe;

namespace StripePaymentDemoApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            // Add services to the container
            builder.Services.AddControllersWithViews();
            StripeConfiguration.ApiKey = builder.Configuration["Stripe:SecretKey"];
            var app = builder.Build();
            // Configure the HTTP request pipeline
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, 
                // see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            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 named: PaymentController.cs.

using Microsoft.AspNetCore.Mvc;
using Stripe.Checkout;

namespace StripePaymentDemoApp.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

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

  1. Run the application using dotnet run or your IDE’s run command.
  2. Navigate to /Payment/Checkout in your browser.
  3. Click the "Pay with Stripe" button to be redirected to the Stripe Checkout page.
  4. Use the following test card details.
    • Card Number: 4242 4242 4242 4242.
    • Expiration Date: Any future date.
    • CVC: Any 3 digits.
    • ZIP Code: Any value.

Let's run the application and start the payments with Stripe.

Application

Click the Pay with Stripe Button.

Stripe button

Fill in the payment details with test credentials and click the pay button.

Test credentials

Let's check the Stripe dashboard for our latest transactions.

Latest transactions

Step 9. Handle Webhooks (Optional)

To handle payment confirmation and other events, set up a webhook endpoint.

  1. Create a Webhook Endpoint in the 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).
  2. Add Webhook Secret to:appsettings.json.
    {
      "Stripe": {
        "WebhookSecret": "your_webhook_secret_here"
      }
    }
    
  3. Add Webhook Handler in:PaymentController.cs.
    [HttpPost]
    public async Task<IActionResult> Webhook()
    {
        var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
        
        try
        {
            var stripeEvent = EventUtility.ConstructEvent(
                json,
                Request.Headers["Stripe-Signature"],
                _configuration["Stripe:WebhookSecret"]
            );
            // Handle events
            if (stripeEvent.Type == Events.CheckoutSessionCompleted)
            {
                var session = stripeEvent.Data.Object as Session;
                // Handle successful payment
            }
            return Ok();
        }
        catch (StripeException e)
        {
            return BadRequest();
        }
    }
    

Conclusion

We’ve successfully integrated the Stripe Payment Gateway into our ASP.NET Core MVC application! This solution uses Stripe Checkout, which is secure and easy to implement. You can extend this by adding more features like:

  • Custom payment forms using Stripe Elements.
  • Storing payment details in a database.
  • Sending email confirmations to users.

For more information, refer to the Stripe Documentation.