Webhooks : exemples

Dans cette section, vous trouverez quelques exemples de code sur la façon de consommer les événements webhook. Chaque requête faite à votre point de terminaison webhook sera de type POST.

Nous avons des exemples dans ces langues :

PHP (5.0+)

$json = file_get_contents('php://input');
$body = json_decode($json, true);

if (is_null($body) or !isset($body['eventName'])) {
    // When something goes wrong, return an invalid status code
    // such as 400 BadRequest.
    header('HTTP/1.1 400 Bad Request');
    return;
}

switch ($body['eventName']) {
    case 'order.completed':
        // This is an order:completed event
        // do what needs to be done here.
        break;
}

// Return a valid status code such as 200 OK.
header('HTTP/1.1 200 OK');

C# ASP.NET MVC

using System.IO;
using System.Net;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace MyApplication.Controllers
{
    public class WebhooksController : Controller
    {
        [HttpPost]
        public ActionResult Receive()
        {
            Request.InputStream.Position = 0;
            Request.InputStream.Seek(0, SeekOrigin.Begin);
            using(var reader = new StreamReader(Request.InputStream))
            {
                var json = reader.ReadToEnd();
                var body = JsonConvert.DeserializeObject<dynamic>(json);
                try
                {
                    switch ((string)body.eventName)
                    {
                        case "order.completed":
                            // This is an order:completed event
                            // do what needs to be done here.
                            break;
                    }
                    // Return a valid status code such as 200 OK.
                    return new HttpStatusCodeResult(HttpStatusCode.OK);
                }
                catch
                {
                    // When something goes wrong, return an invalid status code
                    // such as 400 BadRequest.
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
            }
        }
    }
}

Ruby (Rails)

class WebhookController < ApplicationController
    def event
        begin
            data = ActiveSupport::JSON.decode(request.body.read)
            case data[:eventName]
            when 'order.completed'
            # This is an order:completed event
            # do what needs to be done here.
            end
        rescue
            # When something goes wrong, return an invalid status code
            # such as 400 BadRequest.
            head :bad_request
        else
            # Return a valid status code such as 200 OK.
            head :ok
        end
    end
end