Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js Asp.net Core C C#
      DotNet HTML/CSS Java JavaScript Node.js
      Python React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET MVC
  4. Implement Stripe Payment Gateway In ASP.NET MVC

Implement Stripe Payment Gateway In ASP.NET MVC

Date- Jun 26,2022

Updated Mar 2026

20381

Free Download Pay & Download
Stripe Payment Gateway AspNet

Overview of Stripe Payment Gateway

Stripe has become a go-to solution for businesses looking to accept online payments due to its robust features and ease of integration. With Stripe, you can accept various payment methods, including credit cards, debit cards, and even digital wallets like Apple Pay and Google Pay. This flexibility makes it suitable for businesses of all sizes, from startups to large enterprises.

Implementing a payment gateway is crucial for any online business, as it directly impacts user experience, conversion rates, and overall revenue. Stripe's Checkout feature simplifies this process by providing a pre-built, customizable payment page that adheres to PCI compliance standards, allowing you to focus on building your application without worrying about security.

In this tutorial, we will guide you through the process of integrating Stripe Checkout in an ASP.NET Core application. We will cover everything from project setup to handling payment processing, ensuring you have a comprehensive understanding of the implementation.

Stripe Payment Gateway

Prerequisites

Before you begin, ensure you have the following prerequisites:

  • Visual Studio 2022: You should have Visual Studio 2022 installed on your machine.
  • ASP.NET Core Knowledge: Familiarity with ASP.NET Core and MVC architecture is beneficial.
  • Stripe Account: Sign up for a Stripe account at stripe.com to obtain your API keys.
  • NuGet Package Manager: Ensure you have access to NuGet Package Manager to install the Stripe.net package.

Step 1: Create the Project

To get started, you need to create a new ASP.NET Core MVC project in Visual Studio:

  1. Open Visual Studio 2022 and click on Create a new Project.
  2. Search for MVC and select ASP.NET Core Web App (Model-View-Controller).
  3. Give your project a name and select a location for it.
  4. Select .NET 6 as the framework, leave other selections as default, and click on Create.
Implement Stripe Payment Gateway In ASPNET MVC

Step 2: Add the Stripe.net Package to Your Project

Next, you will need to add the Stripe.net package to your project. This package provides the necessary libraries to interact with the Stripe API.

Install-Package Stripe.net

To do this, navigate to Manage NuGet Packages in your project, search for Stripe.net, and install the latest version.

Step 3: Configure Stripe API Keys in Web Config

In this step, you will add your Stripe API keys to the Web.config file. These keys are essential for authenticating requests to the Stripe API.

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="StripeSecretKey" value="sk_test_your_secret_key" />
    <add key="StripePublishableKey" value="pk_test_your_publishable_key" />
</appSettings>

Replace sk_test_your_secret_key and pk_test_your_publishable_key with your actual keys obtained from the Stripe dashboard.

Implement Stripe Payment Gateway In ASPNET MVC 2

Step 4: Set Up Global.asax.cs

Now, you need to configure the Stripe API by modifying the Global.asax.cs file. This file allows you to set up application-wide settings.

using System.Web.Configuration;
using Stripe;

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    var secretKey = WebConfigurationManager.AppSettings["StripeSecretKey"];
    StripeConfiguration.SetApiKey(secretKey);
}

Step 5: Create the Payment Web Page

Next, create a new web page called Payment.cshtml where users can enter the payment amount and initiate the checkout process.

<form action="/Home/CreateCheckoutSession" method="POST">
    <input type="text" id="TextBox1" placeholder="amount" name="amount" /><br />
    <button type="submit">Checkout</button>
</form>
Implement Stripe Payment Gateway In ASPNET MVC 3

Step 6: Create the Checkout Session

In this step, you will implement the action method CreateCheckoutSession in your Payment Controller. This method will handle the payment request and create a session with Stripe.

[HttpPost]
public ActionResult CreateCheckoutSession(string amount) {
    var options = new Stripe.Checkout.SessionCreateOptions {
        PaymentMethodTypes = new List<string> { "card" },
        LineItems = new List<Stripe.Checkout.SessionLineItemOptions> {
            new Stripe.Checkout.SessionLineItemOptions {
                PriceData = new Stripe.Checkout.SessionLineItemPriceDataOptions {
                    Currency = "usd",
                    ProductData = new Stripe.Checkout.SessionLineItemProductDataOptions {
                        Name = "Sample Product",
                    },
                    UnitAmount = long.Parse(amount) * 100,
                },
                Quantity = 1,
            },
        },
        Mode = "payment",
        SuccessUrl = "https://yourdomain.com/success",
        CancelUrl = "https://yourdomain.com/cancel",
    };
    var service = new Stripe.Checkout.SessionService();
    Stripe.Checkout.Session session = service.Create(options);
    return Json(new { id = session.Id });
}
Implement Stripe Payment Gateway In ASPNET MVC 4

Step 7: Implement Frontend Logic to Handle Checkout

To handle the checkout process on the frontend, you will need to include the Stripe.js library and implement a function that calls your CreateCheckoutSession method and redirects the user to the Stripe Checkout page.

<script src="https://js.stripe.com/v3/"></script>
<script>
    const stripe = Stripe('pk_test_your_publishable_key');

    const form = document.querySelector('form');
    form.addEventListener('submit', async (event) => {
        event.preventDefault();
        const { id } = await fetch('/Home/CreateCheckoutSession', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ amount: document.getElementById('TextBox1').value })
        }).then((r) => r.json());
        const { error } = await stripe.redirectToCheckout({ sessionId: id });
        if (error) {
            console.error(error);
        }
    });
</script>
Implement Stripe Payment Gateway In ASPNET MVC 5

Edge Cases & Gotchas

When implementing Stripe, it's essential to be aware of potential edge cases and gotchas that may arise:

  • Currency Handling: Ensure that your application handles multiple currencies if you plan to sell internationally. Stripe supports various currencies, but you need to specify them correctly in your checkout session.
  • Amount Validation: Always validate the amount entered by the user before processing. For instance, ensure that it is a positive integer and within acceptable limits.
  • Network Issues: Be prepared to handle network issues that may occur during the payment process. Implement retry logic and graceful error handling to enhance user experience.

Performance & Best Practices

To ensure optimal performance and security when implementing Stripe, consider the following best practices:

  • Use Webhooks: Implement webhooks to handle events such as successful payments, refunds, or subscription updates. This allows your application to respond to changes in payment status in real time.
  • Secure Your API Keys: Never expose your secret keys in client-side code. Always store them securely on the server side.
  • Test Your Integration: Use Stripe's test mode to simulate various payment scenarios. This helps ensure that your integration works as expected before going live.
  • Optimize User Experience: Make the payment process as seamless as possible. Use Stripe's pre-built UI components to minimize friction during checkout.
Implement Stripe Payment Gateway In ASPNET MVC 6

Conclusion

Integrating Stripe Payment Gateway into your ASP.NET Core application can significantly enhance your online payment processing capabilities. By following the steps outlined in this tutorial, you can set up a secure and efficient payment system that meets your business needs.

  • Stripe provides a flexible and secure payment processing platform.
  • Ensure you handle API keys securely and validate user inputs.
  • Implement webhooks for real-time updates on payment status.
  • Test thoroughly before going live to ensure a smooth user experience.
Implement Stripe Payment Gateway In ASPNET MVC 7 Implement Stripe Payment Gateway In ASPNET MVC 8 Implement Stripe Payment Gateway In ASPNET MVC 9

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Implement Stripe Payment Gateway In ASP.NET Core
Jul 01, 2023
Integrate Stripe Payment Gateway In ASP.NET Core 8.0
Nov 23, 2023
Integrate Stripe Payment Gateway In ASP.NET Core 7.0
Jul 22, 2023
Get random number in asp.net C#
Dec 23, 2023
Previous in ASP.NET MVC
Import Excel in Asp.net MVC using OLE DB
Next in ASP.NET MVC
Linkedin Sign In using LinkedinLogin Nuget package in Asp-Net MVC

Comments

On this page

🎯

Interview Prep

Ace your ASP.NET MVC interview with curated Q&As for all levels.

View ASP.NET MVC Interview Q&As

More in ASP.NET MVC

  • Implement Stripe Payment Gateway In ASP.NET 58652 views
  • Jquery Full Calender Integrated With ASP.NET 39558 views
  • Microsoft Outlook Add Appointment and Get Appointment using … 27504 views
  • How to implement JWT Token Authentication and Validate JWT T… 25188 views
  • Payumoney Integration With Asp.Net MVC 23148 views
View all ASP.NET MVC posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • Asp.net Core
  • C
  • C#
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor