This content originally appeared on DEV Community and was authored by Adrián Bailador
This guide will walk you through the process of integrating Stripe into a .NET application, from initial setup to implementing payment functionality.
Prerequisites
- Visual Studio Code installed on your machine.
- .NET SDK installed (preferably the latest version).
- A Stripe account. Sign up at Stripe and obtain your API keys.
Step 1: Create a New .NET Project
Open Visual Studio Code and create a new ASP.NET Core MVC project.
dotnet new mvc -n StripeIntegrationDemo
cd StripeIntegrationDemo
Step 2: Install the Stripe Package
Install the Stripe.Net package from NuGet.
dotnet add package Stripe.net
Step 3: Configure Stripe API Keys
-
Add API Keys in
appsettings.json
:
Open the appsettings.json
file and add the Stripe configuration section:
```json
{
"Stripe": {
"SecretKey": "your_secret_key_here",
"PublishableKey": "your_publishable_key_here"
}
}
```
Step 4: Create the Stripe Configuration Model
Create a StripeSettings
class in the Models
folder to handle Stripe configurations.
namespace StripeIntegrationDemo.Models
{
public class StripeSettings
{
public string SecretKey { get; set; }
public string PublishableKey { get; set; }
}
}
Step 5: Update Program.cs
Configure Program.cs
to use StripeSettings
and register Stripe keys.
using Microsoft.Extensions.Options;
using StripeIntegrationDemo.Models;
using Stripe;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Configure StripeSettings using values from appsettings.json
builder.Services.Configure<StripeSettings>(builder.Configuration.GetSection("Stripe"));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// Configure Stripe secret key from configuration
StripeConfiguration.ApiKey = builder.Configuration.GetSection("Stripe")["SecretKey"];
app.Run();
Step 6: Create the Payment Controller
Add a PaymentController
to handle payment operations. Include error handling and comments for clarity.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Stripe;
using Stripe.Checkout;
using StripeIntegrationDemo.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
public class PaymentController : Controller
{
private readonly StripeSettings _stripeSettings;
public PaymentController(IOptions<StripeSettings> stripeSettings)
{
_stripeSettings = stripeSettings.Value;
}
[HttpGet]
public IActionResult Checkout()
{
ViewBag.PublishableKey = _stripeSettings.PublishableKey;
return View();
}
[HttpPost]
public async Task<IActionResult> CreateCheckoutSession()
{
var options = new SessionCreateOptions
{
PaymentMethodTypes = new List<string> { "card" },
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
PriceData = new SessionLineItemPriceDataOptions
{
UnitAmount = 2000,
Currency = "eur",
ProductData = new SessionLineItemPriceDataProductDataOptions
{
Name = "Test Product",
},
},
Quantity = 1,
},
},
Mode = "payment",
SuccessUrl = Url.Action("Success", "Payment", null, Request.Scheme),
CancelUrl = Url.Action("Cancel", "Payment", null, Request.Scheme),
};
try
{
var service = new SessionService();
Session session = await service.CreateAsync(options);
return Json(new { id = session.Id });
}
catch (StripeException e)
{
return BadRequest(new { error = e.Message });
}
}
public IActionResult Success()
{
return View();
}
public IActionResult Cancel()
{
return View();
}
}
Step 7: Create Payment Views
Checkout.cshtml
This view shows the button to start the payment process with Stripe.
@{
ViewBag.Title = "Checkout";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container">
<div class="py-5 text-center">
<h2>Checkout</h2>
<p class="lead">Click the button below to proceed with your payment using Stripe.</p>
<button type="button" id="checkout-button" class="btn btn-primary">Pay with Stripe</button>
</div>
</div>
<script src="https://js.stripe.com/v3/"></script>
<script>
var stripe = Stripe('@ViewBag.PublishableKey');
var checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', function () {
fetch('/payment/createcheckoutsession', {
method: 'POST',
})
.then(function (response) {
return response.json();
})
.then(function (sessionId) {
return stripe.redirectToCheckout({ sessionId: sessionId.id });
})
.then(function (result) {
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error('Error:', error);
});
});
</script>
</body>
</html>
Success.cshtml
This view displays a success message when the payment completes successfully.
@{
ViewBag.Title = "Payment Successful";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container">
<div class="py-5 text-center">
<h2 class="text-success">Payment Successful!</h2>
<p class="lead">Thank you for your purchase.</p>
<button onclick="window.location.href='/'" class="btn btn-primary">Return to Home</button>
</div>
</div>
</body>
</html>
Cancel.cshtml
This view displays a message when the user cancels the payment.
@{
ViewBag.Title = "Payment Cancelled";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container">
<div class="py-5 text-center">
<h2 class="text-danger">Payment Cancelled</h2>
<p class="lead">We're sorry, your payment could not be completed.</p>
<button onclick="window.location.href='/'" class="btn btn-primary">Return to Home</button>
</div>
</div>
</body>
</html>
Step 8: Add the Button to Navigate to the Payment Page
Update Views/Home/Index.cshtml
to include a button that redirects to the payment page.
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center mt-5">
<h1 class="display-4">Welcome, Codú!</h1>
<a href="/payment/checkout" class="btn btn-primary">Go to Payment Page</a>
</div>
Step 9: Run the Application
Run the application using the command:
dotnet run
Conclusion
You have successfully integrated Stripe into a .NET application. You can now handle payments using Stripe Checkout. Thisguide includes API key configuration, creating a payment controller, implementing payment views, and handling success or cancellation responses.
Useful Links:
This content originally appeared on DEV Community and was authored by Adrián Bailador
Adrián Bailador | Sciencx (2024-07-17T14:57:04+00:00) Complete Guide to Integrating Stripe in a .NET Application. Retrieved from https://www.scien.cx/2024/07/17/complete-guide-to-integrating-stripe-in-a-net-application/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.