Skip to content

Instantly share code, notes, and snippets.

@SidShetye
Created October 25, 2012 04:36
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save SidShetye/3950433 to your computer and use it in GitHub Desktop.
Save SidShetye/3950433 to your computer and use it in GitHub Desktop.
Receiving Stripe.com's Webhooks in ASP.NET C#, MVC4
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Stripe; // you need this library https://github.com/jaymedavis/stripe.net
using System.Net;
namespace StripeSampleMVC.Controllers
{
public class StripeWebhookController : Controller
{
[HttpPost]
public ActionResult Index()
{
// MVC3/4: Since Content-Type is application/json in HTTP POST from Stripe
// we need to pull POST body from request stream directly
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
StripeEvent stripeEvent = null;
try
{
// as in header, you need https://github.com/jaymedavis/stripe.net
// it's a great library that should have been offered by Stripe directly
stripeEvent = StripeEventUtility.ParseEvent(json);
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest,"Unable to parse incoming event");
}
if (stripeEvent ==null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Incoming event empty");
switch (stripeEvent.Type)
{
case "charge.refunded":
// do work
break;
case "customer.subscription.updated":
case "customer.subscription.deleted":
case "customer.subscription.created":
// do work
break;
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
}
@jmichas
Copy link

jmichas commented Nov 3, 2013

You might want to add something like this before the switch statement:

var obj = JObject.Parse(json);
var dataObj = obj.SelectToken("data.object"); //this gets the event data object payload only

and then in the cases you can use something like this:

case "customer.subscription.created":
var subscription = Mapper<StripeSubscription>.MapFromJson(dataObj.ToString());
....

This way you can have a strongly typed object to work with instead of the data.object dynamic class of the stripeEvent. For each case the payload would be a different type, so you can check the stripe api and create objects that are easier to work with in your code. (I was unaware that there was a Mapper<> in Stripe.net, made things easy because it converts the unix dates from the json properly)

@d668
Copy link

d668 commented Jan 29, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment