Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
10 Sep
2020

Implement Stripe Payment Gateway In ASP.NET

by Shubham Batra

7719

Step 1: Create the project 


In this tutorial was built with Visual Studio  2017 and .NET Framework 4.6.1. To follow along, you can also use any recent version of Visual Studio. Start by creating an ASP.NET application with the Empty template. In the project creation wizard, ensure that the Web Forms checkbox is enabled.

  1. Start Visual Studio 2017 or 2015.
  2. Create a new project  -> Web -> Visual Studio 2017.
  3. Select ASP.NET Web Application(.Net Framework).
  4. Provide the Name and Location for the project and click Next.
  5. Choose an "Empty" template and check "MVC" under "Add folders & core references"  then click Ok.

Then select the Empty Choose an "Empty" template and check "MVC" under "Add folders & core references"  then click Ok.



Step 2: Add the Stripe.net package to your project from NuGet



Step 3: In the Web.config file, add an appSettings section with your publishable and secret key:


<appSettings> <add key="StripeSecretKey" value="sk_test_51HOyZnDZeDIryO9RxF7t5trgvvgfMofkDiD9879121116009703ndb5e2UOLvZ3cWtJfLZa1t5JRFBnmhEjmQG2G66xbJCtWGzKoHgwZW4D40070xvqUHe" /> <add key="StripePublishableKey" value="pk_test_51HOyZnDZehghgffdfddrsdffxhhlVXWxhO8xHPtT9Jtd6765552C2LCbyjwADWUykwcCxNsTPKHaZfanP9mzZjW1BVG3wxhewwGDFPP600YZlwGByS" /> </appSettings>

Step 4: Go to the Global.asax.cs file then on the top of the Global.asax.cs file, add the following using statements:

using System.Web.Configuration;
using Stripe;

Modify the Application_Start method in the Global.asax.cs class so that it retrieves the secret key from the application settings and passes it to the Stripe client library:

 protected void Application_Start(object sender, EventArgs e)
  {
      var secretKey = WebConfigurationManager.AppSettings["StripeSecretKey"];
      StripeConfiguration.SetApiKey(secretKey);
  }

Step 5: Create the payment Web Form

Create a new Web Form called Payment.aspx. In the file, add the following HTML markup inside of the <body> tag:

<form action="/RedirectForm.aspx" method="POST">
        
        <input type="text" id="TextBox1"  placeholder="amount" name="amount" /><br />
        <input type="text" id="TextBox2"  placeholder="name" name="name" /><br />
        <input type="text" id="TextBox3"  placeholder="description" name="description" /><br />
        <input type="text" id="TextBox4"  placeholder="locale" name="locale" /><br />
        <input type="text" id="TextBox5"  placeholder="zip-code" name="zip-code" /><br />
    <script
        src="https://checkout.stripe.com/checkout.js" class="stripe-button"
        data-key="<%= stripePublishableKey %>" 
    </script>

The HTML <script> tag loads and initializes Checkout. It adds a button to the form that the user can click to display the credit card overlay. The overlay automatically performs validation and error handling. The action attribute specifies the path of the Charge route created in the next step.

The data-key attribute of the <script> tag uses the value of a variable called stripePublishableKey. To define that variable, edit the underlying Payment.aspx.cs file and add it to the class definition, extracting the value from the configuration file:

public string stripePublishableKey = WebConfigurationManager.AppSettings["StripePublishableKey"];
Add the necessary using statement to the top of the file:
using System.Web.Configuration;

Step 6: Create a page to perform the charge

Create a new Web Form named RedirectForm.aspx to handle the charge and display a message to indicate that it completed. In RedirectForm.aspx.cs, add the following code to the Page_Load method:

if (Request.Form["stripeToken"] != null)
            {
                var customers = new StripeCustomerService();
                var charges = new StripeChargeService();

                var customer = customers.Create(new StripeCustomerCreateOptions
                {
                    Email = Request.Form["stripeEmail"],
                    SourceToken = Request.Form["stripeToken"]
                   
                });

                var charge = charges.Create(new StripeChargeCreateOptions
                {
                    Amount =Convert.ToInt32(Request.Form["amount"])*100,
                    Description = "Sample Charge",
                    Currency = "inr",
                    CustomerId = customer.Id,
                    Shipping=new StripeShippingOptions {Name="Shubham",CityOrTown="Ku",Country="India",Line1="2637",PostalCode="132103",Phone="232323",State="Haryana" }

                });

                Console.WriteLine(charge);
            }

The code in the Page_Load method handles the incoming POST request that Checkout performs on the front-end. It uses the email address and card token from the POST request body to create a Stripe customer. Next, it invokes the charges.Create method, providing the Customer ID to associate the transaction with the customer.

In this example, the application charges the user $5. Stripe expects the developer to describe charges in cents, so compute the value of the Amount parameter by multiplying the desired number of dollars by one hundred. Stripe charges also take an optional Description parameter, which is “Sample Charge” in this case.

Add the necessary using statement to the top of the file:

using Stripe;

That’s it, a complete Stripe and ASP.NET Web Forms integration built with C#.

Step 7: Run the application

To run the application, navigate to Default.aspx.cs in Visual Studio and select “Start Debugging” from the “Debug” menu. Visual Studio will run the application and launch a browser window to display the page.

In the web browser, click the button to launch the payment form. If you’re using Stripe test keys, you can test it with some dummy data. Enter the test number 4242 4242 4242 4242, a three digit 123, and a future expiry date. Submit the form and see if the application correctly displays the successful charge page.

  • |
  • Implement Stripe Payment Gateway In ASPNET , Using Checkout in an ASPNET Web Forms application , Stripe Payment , Stripe Payment Integration , Stripe Integeration

Comments

Tags

How to set Date and time format in IIS Manager
IIS Manager
IIS
Internet Information Services (IIS) Manager
Internet Information Services (IIS)
Internet Information Services
Error Handling In AspNet Core
Exception Handling Asp Net Core
Exception Handling
Exception Handling Asp Net
Aspnet
Creating Log Files in MVC
Error Handling in MVC
Exception Handling in AspNet
Handling Exceptions and Creating Error Logs in Asp net Mvc using base controller
net
Code2Tonight
Stopping Browser Reload On Save
Repository Pattern with ADONet in MVC
Repository Pattern With ASPNET MVC And AdoNet
MVC Crud Operation
Jquery Full Calender Integrated With ASPNET
Full Calendar
Jquery Calendar
Slick Slider
Slick Slider Example
responsive carousels
Entity Framework
MVC
Intergrate SummerNote Text Editor into AspNet MVC
Web Config
Auto Redirection
Redirection from Http to https
AspNet
Url Rewriting
Implement Stripe Payment Gateway In ASPNET Core
Stripe Payment Gateway
C#
AspNet Core
StripeNet
Postgre
PgAdmin4
PostgreSql
A Non Fatal Error Occured During Cluster Initialisation In Postgre SQL
Microsoft Outlook
Outlook Appointments
Microsoft Exchange Service
Send Email With HTML Template And PDF Using ASPNet C#
Send Email
Email with html template
email with pdf attachment
email with html and pdf
Microsoft Outlook Contacts
Outlook
Microsoft Exhchange Service
JSON
Convert string with dot notation to JSON
HTTP Error 5025 ANCM Out Of Process Startup Failure
Internet Information Service
Net core
Payumoney Integration With AspNet MVC
Prism js
Highlighting Syntax
Syntax Highlighting
code stylings
c#
Jquery AJax
Ajax
Jquery
Implement Stripe Payment Gateway In ASPNET
Using Checkout in an ASPNET Web Forms application
Stripe Payment
Stripe Payment Integration
Stripe Integeration
How to upload Image file using AJAX andjQuery
upload Image file using AJAX and jquery
Ajax call
file upload using ajax
file uploading using ajax and jquery
ConfigurationBuilder does not contain a definition for SetBasePath
Reading app json file in dot net core
Appsetting jso
Dot Net Core
Globalization and localization in ASPNET Core
Asp Net Core with Resource file resx
How to get the resx file strings in asp net core
Culture in Net core
Localisation in AspNet Core
Url Encryption in AspNet MVC
Url Encryption in C#
Url Encryption
Custom Helpers
Slick Slider with single slide
Slick
Vue js
Child Components
How to reload vue js child components
Net Core
Visual Studio
Net core 31
Razor
Zoom sdk
Zoom c# wrapper Inegration
zoom Integration in c#
Zoom Integration
Zoom window sdk
vue js toggle button
vue js
toggle buttons
vuejs
vue js toggle switch
SignalR
VueJs
SignalR in Net Core
Chat App in Vue js
Chat App using SignalR
AspNet Chat app
JPlayer
Html5 Audio Video Player
Music Player
QR Code Generator
QR Code
Jquery QR Code
AspNet MVC
Google Maps
Google map api
Places API
Google map Places API in AspNet
Jquery Autocomplete
Autocomplete
Jquery UI Autocomplete
ExcelDataReader
Import data from excel in AspNet
Card Number Formatting
Amex Card Format
Card Format
FCM
Cloud Messaging
Android Notifications
FCM Notifications for IOS
IOS Notifications
Angular js
apply css on child components in Angular js
Angular Mentions
Google Sign In
Google Login
Google Oauth Api
Social Login
Aspnet Mvc
Google + Api
Create and publish a package using Visual Studio (NET Framework
Windows)
Create and publish a nuget package
create your own nuget package
Image compress
Image optimization
compress Image
optimize Image
WebForm
AspNet Web Pages
Batch Script
Database backup
Powershell
ASpNet
Sql Server Backup
AspNet core 31
Aspnet core 21
HttpCookies in AspNet Core
LinkedIn Authentication
Login using LinkedIN
Social Login in AspNet
LinkedIn Authentication in AspNet MVC
LinkedIn Login in aspnet MVC
Shuffle List in c#
C#Net
Google Login in AspNet MVC
GoogleAuthentication Nuget package
Password Encryption
RFC Encryption
Encryption and Decryption
Encryption in AspNet
Base 64 Encryption
Base 64 Decryption
Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
SSRS
SSRS Report
ASPNET MVC
ASPNET MVC SSRS Report
ssrs report
XlWorkbook
ClosedXml
Excel Export
Blazor
Syncfusion
SFGrid
Syncfusion SFgrid
Net
Net core 60
DataTable to List
Extension Methods
Microsoft Access Database Engine
Ace Ole Db 120
MicrosoftACEOLEDB120
OLE DB
Aspnet MVC
Ace OLE DB

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Kurukshetra
  • [email protected]

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2022 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Json Beautifier