Introduction
In this tutorial, we will walk through the process of integrating Stripe Checkout into an ASP.NET Core NET Core 8 application. This guide will cover everything from setting up a new ASP.NET Core NET Core 8 project to creating a Stripe checkout session. This is ideal for developers looking to implement a seamless payment gateway in their web applications.
Step 1: Setting Up a New ASP.NET Core 8 Project
First, let's create a new ASP.NET Core 8 project.
Select the template ASP.NET Core Web App (Model-View-Controller). Give a project name and click Next.
Select .NET 8 and click on Create.
Step 2: Adding Stripe Library
Next, we need to add the Stripe library to our project. This will allow us to interact with the Stripe API.
Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution. Search for stripe. net and install the latest version.
Step 3: Configuring Stripe
To use Stripe, we need to configure it with our secret key. Add your Stripe secret key in the appsettings.json file.
Open appsettings.json and add the following configuration:
{
"Stripe": {
"SecretKey": "your_stripe_secret_key"
}
}
Create a StripeSettings class to represent this configuration in your application. This class should be placed in your Models or Configuration folder. I am placing this is Models:
StripeSettings.cs
namespace StripeCheckoutDemo.Models
{
public class StripeSettings
{
public string? SecretKey { get; set; }
}
}
Update Program.cs to configure Stripe:
using Stripe;
using StripeCheckoutDemo.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Configure Stripe settings
builder.Services.Configure<StripeSettings>(builder.Configuration.GetSection("Stripe"));
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.MapControllerRoute(
name: "checkout",
pattern: "checkout/{action=Index}/{id?}",
defaults: new { controller = "Checkout", action = "Index" });
app.Run();
Step 4: Creating a Model for the Form Data
Create a model to capture the form data for the Stripe checkout session.
Add a new class CheckoutFormModel.cs in the Models folder:
namespace StripeCheckoutDemo.Models
{
public class CheckoutFormModel
{
public string? ProductName { get; set; }
public string? ProductDescription { get; set; }
public long Amount { get; set; }
public string? Currency { get; set; }
}
}
Step 5: Creating the Checkout Session Endpoint
Create an endpoint to handle the form submission and create a Stripe checkout session. Also add a action methods for success and cancel.
Add a new controller CheckoutController.cs in the Controllers folder:
using Microsoft.AspNetCore.Mvc;
using Stripe.Checkout;
using Stripe;
using StripeCheckoutDemo.Models;
namespace StripeCheckoutDemo.Controllers
{
[ApiController]
[Route("[controller]")]
public class CheckoutController : Controller
{
private readonly IConfiguration _configuration;
public CheckoutController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("create-checkout-session")]
public IActionResult CreateCheckoutSession([FromBody] CheckoutFormModel model)
{
StripeConfiguration.ApiKey = _configuration["Stripe:SecretKey"];
var options = new SessionCreateOptions
{
PaymentMethodTypes = new List<string> { "card" },
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
PriceData = new SessionLineItemPriceDataOptions
{
Currency = model.Currency,
ProductData = new SessionLineItemPriceDataProductDataOptions
{
Name = model.ProductName,
Description = model.ProductDescription,
},
UnitAmount = model.Amount,
},
Quantity = 1,
},
},
Mode = "payment",
SuccessUrl = $"{Request.Scheme}://{Request.Host}/checkout/success",
CancelUrl = $"{Request.Scheme}://{Request.Host}/checkout/cancel",
};
var service = new SessionService();
var session = service.Create(options);
return Ok(new { sessionId = session.Id });
}
[HttpGet("success")]
public IActionResult Success()
{
return View();
}
[HttpGet("cancel")]
public IActionResult Cancel()
{
return View();
}
}
}
Step 6: Creating the Checkout Form
Create a simple form using Bootstrap to capture the product details and amount for the Stripe checkout.
Update the Index.cshtml file in the Views/Home folder:
@page
@model CheckoutFormModel
@using StripeCheckoutDemo.Models
<form id="payment-form">
<div class="form-group pt-2">
<label for="productName">Product Name</label>
<input type="text" class="form-control" id="productName" name="productName" placeholder="Enter product name" required>
</div>
<div class="form-group pt-2">
<label for="productDescription">Product Description</label>
<input type="text" class="form-control" id="productDescription" name="productDescription" placeholder="Enter product description" required>
</div>
<div class="form-group pt-2">
<label for="amount">Amount (in cents)</label>
<input type="number" class="form-control" id="amount" name="amount" placeholder="Enter amount" required>
</div>
<div class="form-group pt-2">
<label for="currency">Currency</label>
<select class="form-control" id="currency" name="currency" required>
<option value="inr">INR</option>
<!-- Add more currencies as needed -->
</select>
</div>
<button type="button" class="btn btn-primary mt-2" id="checkout-button">Checkout</button>
</form>
@section scripts {
<script src="https://js.stripe.com/v3/"></script>
<script>
var stripe = Stripe('enter_publishable_key');
document.getElementById('checkout-button').addEventListener('click', function () {
fetch('/checkout/create-checkout-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
productName: document.getElementById('productName').value,
productDescription: document.getElementById('productDescription').value,
amount: document.getElementById('amount').value,
currency: document.getElementById('currency').value
})
})
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.sessionId });
})
.then(function (result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error('Error:', error);
});
});
</script>
}
Step 7: Creating the Success Page
Create a simple success page which will be shown after payment is done.
Update the Success.cshtml file in the Views/Checkout folder:
@{
ViewData["Title"] = "Payment Successful";
}
<h2>Payment Successful</h2>
<p>Thank you for your purchase! Your payment has been successfully processed.</p>
Step 8: Creating the Cancel Page
Create a simple cancel page which will be shown after payment is canceled.
Update the Cancel.cshtml file in the Views/Checkout folder:
@{
ViewData["Title"] = "Payment Canceled";
}
<h2>Payment Canceled</h2>
<p>Your payment has been canceled. Please try again or contact support if you need assistance.</p>
Step 9: Running the Application
Finally, run your application to see the Stripe checkout integration in action.
Complete code on GitHub:
Please find here the complete code used in this blog.
Conclusion
You've successfully integrated Stripe Checkout into your ASP.NET Core NET Core 8 application. This guide provided step-by-step instructions to set up the project, configure Stripe, and create a checkout session. Now you can easily accept payments through Stripe in your web application.
Top comments (0)