Stripe Webhook in C# (Asp.net)
Stripe is a payment platform that allows some finer-grained control over payments than paypal does. However, it’s a good bit more complex, but the extra work should pay off..
So, lets see what’s involved with a payment; first you do a bit of JavaScript as follows
<a class=”btn btn-primary btn-lg” role=”button” id=”customButton”>Purchase</a>
<script>
var handler = StripeCheckout.configure({
key: ‘pk_test_uhSAMkhrXb9GP6MqtCzL09hd’,
image: ‘/img/documentation/checkout/marketplace.png’,
token: function (token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
alert(token.id);
$.get(“/pages/ProcessStripePayment.aspx?token=” + token.id, function (data) {
alert(data);
});
}
});$(‘#customButton’).on(‘click’, function (e) {
// Open Checkout with further options
handler.open({
name: ‘Demo Site’,
description: ‘2 widgets’,
currency: “gbp”,
amount: 2000
});
e.preventDefault();
});// Close Checkout on page navigation
$(window).on(‘popstate’, function () {
handler.close();
});
</script>
Note the Ajax call with the token? this means we have to add some server side code to process the charge, once the credit card details have been captured.
You need to then do a NuGet “Install-Package Stripe”, then use this code to convert the token to a charge;
protected void Page_Load(object sender, EventArgs e)
{
string token = Request.QueryString[“token”];
var apiKey = “sk_test_NYqtadezpWaohbRKmY9y2R8a”; // can be found here https://manage.stripe.com/#account/apikeys
var api = new StripeClient(apiKey); // you can learn more about the api here https://stripe.com/docs/apiStripeObject charge = api.CreateChargeWithToken(20.00m, token);
// need to query paid
if (Convert.ToBoolean(charge[“paid”]) == true)
{
Response.Write(“OK”);
}
else
{
Response.Write(“Fail”);
}
}
And that’t the charge made.
I did add another bit of code, purely for diagnostics at this stage, but a webhook that gets called when a charge is made, and this is implemented on the server as follows –
<%@ WebHandler Language=”C#” Class=”StripeMerchant.StripeHook” %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;using System.Web.Script.Serialization;
namespace StripeMerchant {
[Serializable]
public class StripeHookResponse {
public long Created { get; set; }
public string Type { get; set; }
public bool LiveMode { get; set; }
public string Id { get; set; }
public StripeDataObj Data { get; set; }
}[Serializable]
public class StripeDataObj {
public StripeData Object { get; set; }
}[Serializable]
public class StripeData {
public double Amount { get; set; }
public StripeCard Card { get; set; }
}[Serializable]
public class StripeCard {
public string Country { get; set; }
public int Exp_Month { get; set; }
public int Exp_Year { get; set; }
public string Id { get; set; }
public int Last4 { get; set; }
public string Object { get; set; }
public string Type { get; set; }
}/// <summary>
/// Summary description for StripeHook
/// </summary>
public class StripeHook : IHttpHandler {public void ProcessRequest(HttpContext context) {
string sPathName = context.Server.MapPath(“log.txt”);
StreamWriter sw = new StreamWriter(sPathName,true);
sw.WriteLine(“—————————————————“);
sw.WriteLine(DateTime.Now);
sw.WriteLine(“—————————————————“);try {
JavaScriptSerializer js = new JavaScriptSerializer();StringBuilder sb = new StringBuilder();
int streamLength;
int streamRead;
Stream s = context.Request.InputStream;
streamLength = Convert.ToInt32(s.Length);
sw.WriteLine(“Length:” + streamLength);
Byte[] streamArray = new Byte[streamLength];streamRead = s.Read(streamArray, 0, streamLength);
for (int i = 0; i < streamLength; i++) {
sb.Append(Convert.ToChar(streamArray[i]));
}string raw = sb.ToString();
sw.WriteLine(raw);StripeHookResponse stripeResponse = (StripeHookResponse)js.Deserialize(raw, typeof(StripeHookResponse));
//handle the data received from Stripe
context.Response.ContentType = “text/plain”;
context.Response.StatusCode = 200;} catch (Exception e) {
//handle error and tell Stripe that a fault occurred
context.Response.ContentType = “text/plain”;
context.Response.StatusCode = 301; //Let Stripe know that this failed
}
sw.Flush();
sw.Close();}
public bool IsReusable {
get {
return false;
}
}
}
}
Hi,
Nice doc. Can you please let me know how to test this on Dev phase. what is the to call back url need to be set in Stripe in order to make this work. Did the application needs to be hosted on Local IIS or somewhere. I have tried with “htttp://my global ip/Domain: port/Handler.ashx” but getting 503 error in Test webhook connection ., But my project is not hosted anywhere yet. Thannks in advance
LikeLike
I got the transaction status at page level, so why i need to call handler or set webhook
LikeLike
As per code
if (Convert.ToBoolean(charge[“paid”]) == true)
{
Response.Write(“OK”);
}
else
{
Response.Write(“Fail”);
}
}
I had to get transaction status then why we need to call handler or set webhooks?
LikeLike
If you are looking the latest solution of Stripe payment gateway integration in ASP.NET Web Forms Web App or ASP.NET Core MVC Web App, check out the demo ==> https://techtolia.com/Stripe/
Receive payments from credit or debit cards, Alipay, WeChat Pay, Bancontact, EPS, giropay, iDEAL, Multibanco, Przelewy24, SOFORT, Secure Remote Commerce and Payment Request Button (Apple Pay, Google Pay, Microsoft Pay, and the browser Payment Request API) via Stripe.
LikeLike