Implement Stripe Payment Gateway In ASP.NET
Hello guys and welcome to Code2Night. In this tutorial demonstrates how to integrate Stripe Payment Gateway In an ASP.NET application built with C# and WebForms. The application uses Checkout to accept credit cards from the end user and send tokens to a back-end API. The back-end controller uses the Stripe .NET library to create a charge. There are four steps: Create the project and configure dependencies, Create the payment Web Form, Create a page to perform the charge, and Run the application.
Step 1: Create the project
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.
- Start Visual Studio 2017 or 2015.
- Create a new project -> Web -> Visual Studio 2017.
- Select ASP.NET Web Application(.Net Framework).
- Provide the Name and Location for the project and click Next.
- 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"];
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 is 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 the future expiry date. Submit the form and see if the application correctly displays the successful charge page.