Click here to Skip to main content
15,886,806 members
Articles / Programming Languages / C#

How to Integrate Stripe Payments into a .NET Web Forms Project

Rate me:
Please Sign up or sign in to vote.
4.98/5 (13 votes)
25 Jun 2017CPOL4 min read 39.3K   1.8K   12   4
Describes how to integrate Stripe payments into a .NET webforms application

Introduction

This article describes a way of integrating the Stripe payments API with a .NET webforms project.

Background

If you were to create a new web application of any complexity you probably wouldn’t want to use .NET webforms to create it.

These days you’d choose to utilise MVC. However, there are lots of legacy ecommerce sites out there built on webforms which may want to take advantage of the excellent Stripe payment processing facilities.

Stripe documentation itself doesn’t give much, or in fact any, help for integrating their platform in .NET webforms applications.

This article describes how to do that.

Using the code

Open your Stripe account

If you haven’t done so already visit www.stripe.com to open your account.

You’ll then need your API publishable and secret keys provided with your Stripe account.

Install Stripe.net into your project

Stripe.net is a sync/async .NET 4.5+ client, and a portable class library for stripe.com, written by jaymedavis.

Either download it from Github here: https://github.com/jaymedavis/stripe.net or install it via Nuget: Install-Package Stripe.net

Your payment page

The key difference in this process is that we are not going to use .NET server controls for our inputs. We need to use normal client side HTML input fields. So the part of your payment page containing the card detail input fields and PAY button will look something like this:

HTML
<div>
	<asp:Label runat="server" Width="180">Card Number</asp:Label>
	<input type="text" id="txtCardNumber" name="txtCardNumber" />
</div>
<div>
	<asp:Label runat="server" Width="180">Expiry Date</asp:Label>
	<input type="text" id="txtCardExpiryMonth" name="txtCardExpiryMonth" />
	/
	<input type="text" id="txtCardExpiryYear" name="txtCardExpiryYear" />
</div>
<div>
   <asp:Label runat="server" Width="180">Security Code</asp:Label>
   <input type="text" id="txtCardSecurityCode" name="txtCardSecurityCode" />
</div>
<div>
	<asp:Label runat="server" Width="180">Card Number</asp:Label>
	<input type="text" id="txtCardNumber" name="txtCardNumber" />
</div>
// Pay Button
<div>
	<input type="submit" id="btnPay" name="btnPay" value="Pay Now" />
</div>

The Stripe token

Stripe uses a tokenised system, where the cardholders details are sent direct from the client to Stripe, they never hit your server, which is how using Stripe avoids any PCI compliance issues.

We need a hidden field somewhere on the page to accept the token that Stripe sends us on successful authorisation. This token can then be shared with the server when you do any processing in your application after payment has been made.

<input type="hidden" name="hfStripeToken" id="hfStripeToken" />

The JavaScript provided by Stripe

The process uses JavaScript provided by Stripe, included in the <head> section of your payment page, like this:

<script type="text/javascript" src="https://js.stripe.com/v2/</script>

Then, also in the <head> section of your payment page, include this JavaScript:

<script type="text/javascript">

	$('document').ready(function () {
		Stripe.setPublishableKey(your_Stripe_publishable_key);

			$('#btnPay').on('click', function (e) {
				e.preventDefault();
       	    e.stopPropagation();

			Stripe.card.createToken({
				number: $('#txtCardNumber').val(), 
				cvc: $('#txtCardSecurityCode').val(),
				exp_month: $('#txtCardExpiryMonth').val(),
				exp_year: $('#txtCardExpiryYear').val()
			}, stripeResponseHandler);
		});


		function stripeResponseHandler(status, response) {
			var $form = $('#form1');
			if (response.error) {
				// Show the errors on the form
				alert(response.error.message);
			} else {
				// response contains id and card, which contains additional card details 
				var token = response.id;
				// Insert the token into the form so it gets submitted to the server
				$('#hfStripeToken').val(token);
				// and submit
				$form.get(0).submit();
			}
		}
	});
</script>

This code attaches a click function to your PAY button which, when clicked, sends the contents of the card details fields to Stripe to obtain a token which you can later use to make the payment charge itself.

If there are any errors in the card input it displays a JavaScript alert to inform your visitor that something has been mistyped or is incorrect.

Once the visitor has entered a valid card number, valid expiry date and valid security Code (CSC) this JavaScript gets a token from the Stripe servers which it places in your hidden field before (re)submitting the form, this time to your server.

Note that in our example it's submitting the form with id="form1" which is the default ASP.NET form name for a webforms web page, but it may be different in your project.

Handling the postback from Stripe

Normally in .NET we use events attached to buttons to handle clicks such as: protected void btn_Click(object sender, EventArgs e) { // Process the click } . Then subsequently protected void Page_PreRender(object sender, EventArgs e) { } is executed.

However, because we haven't used server controls for the button or input fields we have to handle the postback from Stripe right at the beginning of the Page_Load() event:

protected void Page_Load(object sender, EventArgs e)
{
	if (IsPostBack)
	{
		// Handle Stripe payments
		NameValueCollection nvc = Request.Form; 
		string hfStripeToken = nvc["hfStripeToken"];
		if (!string.IsNullOrEmpty(hfStripeToken)) 
		{
			btnPay_Click(hfStripeToken);
		}
	} 

	//  continue your regular Page_load() processing...
}

We have to distinguish between postbacks triggered by our PAY button (which are being posted back to us by Stripe) and postbacks triggered by any other buttons or clickable elements on our payment page.

We know that if Stripe has placed it's token in our hidden field then this postback MUST have been initially triggered by a click of our PAY button, and that this form submission has been triggered by Stripe.

Confirming the payment from the server

In the function we have called btnPay_Click(), we use the token that Stripe has sent us to make the actual payment.

If the payment fails for some reason, such as the card being declined, as well as other reponse information giving details of the error, Stripe returns an HTML error code, so the attempted charge must be in a Try { } Catch { } block to catch the "error".

private void btnPay_Click(string stripeToken)
{
	var myCharge = new StripeChargeCreateOptions
	{
		// convert the amount of £15.95 to pennies i.e. 1595
		Amount = (int)(amount_to_charge * 100),
		Currency = "gbp", // or whatever currency your dealing in
		Description = your_unique_identifier, // for example an order ID
		SourceTokenOrExistingSourceId = stripeToken
	};
    
   var chargeService = new StripeChargeService(your_Stripe_secret_key);
    
   try
 	{
		stripeCharge = chargeService.Create(myCharge);
	}
	catch (StripeException ex)
	{
		StripeError stripeError = ex.StripeError;
		// Handle error
		return;
   } 


	// Successfully Authorised, do your post-succesful payment processing here...
}

StripeError holds information about the failed payment, probably a declined card, you can use the information provided by this to send details of the failed payment to your payment page for your visitor.

If no error occurred than you can assume the payment was made successfully, you can then process the payment, such a saving your order to a database and displaying a thank you page to your visitor.

Points of Interest

Use this code on legacy webforms systems only! New projects of any significant size should, of course, be created using ASP.NET MVC.

History

v1: 21/06/2017
v2: 23/06/2017

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionIntegrate Stripe Payments Pin
Member 119990855-Jun-18 0:43
Member 119990855-Jun-18 0:43 
Bugdownload link not working. Pin
Bryian Tan25-Jun-17 13:22
professionalBryian Tan25-Jun-17 13:22 
GeneralRe: download link not working. Pin
mrOneness26-Jun-17 11:18
mrOneness26-Jun-17 11:18 
GeneralRe: download link not working. Pin
Bryian Tan26-Jun-17 11:51
professionalBryian Tan26-Jun-17 11:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.