How to Implement Stripe Payment Gateway in ASP.NET Core

By FoxLearn 2/17/2025 9:28:16 AM   31
To implement the Stripe Payment Gateway in an ASP.NET Core application, follow these steps to integrate a simple payment system using Stripe's secure payment methods.

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

  1. Go to Stripe and create an account.
  2. After signing in, go to Developers > API Keys in the Stripe Dashboard.
  3. Copy your Publishable Key and Secret Key.

Step 2: Create a New ASP.NET Core MVC Project

  1. Open Visual Studio (or any IDE) and create a new ASP.NET Core MVC Web Application project.
  2. Select ASP.NET Core Web App (Model-View-Controller).
  3. Choose .NET 8.0 (or later) as the framework version.

Step 3: Install Stripe NuGet Package

  1. Open NuGet Package Manager or the Package Manager Console in Visual Studio.
  2. 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

  1. Run the application using dotnet run or the IDE's run command.
  2. Go to /Payment/Checkout in your browser.
  3. Click the Pay with Stripe button, which will redirect you to the Stripe Checkout page.
  4. 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

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.