Webhook Examples

Mailigen's built in Webhooks function as an easy way to get automated events and data updates sent to your web service. Assuming you have read about Mailigen Webhook data format, you can use various tools to send test requests while developing connection with Mailigen.

Example Webhook listener in PHP

define('SIGNATURE_HEADER', 'HTTP_X_MAILIGEN_SIGNATURE');

// If Webhook is configured with secret, provide it here
$secret = 'EXAMPLE_SECRET';

// Example function of signature validation
function validateSignature($secret, $body) {

    // Check if the header is set
    if (empty($_SERVER[SIGNATURE_HEADER]) === false) {

        // Extract algorithm and signature parts
        list($algo, $signature) = explode('=', $_SERVER[SIGNATURE_HEADER]);

        // Validate algorithm
        if (empty($signature) === true || in_array($algo, hash_hmac_algos()) === false) {
            return false;
        }

        // Calculate and compare if signature matches
        return $secret === hash_hmac($algo, $body, $secret);
    }

    return false;
}

// Get the POST request body
$body = file_get_contents('php://input');

// If Webhook is configured with secret, validate the request signature
if (empty($secret) === false && validateSignature($secret, $body) === false) {
    http_response_code(401);
    die('401 Unauthorized');
}

// Convert POST request to PHP array
$request = json_decode($body);

// Display contents of POST request
var_dump($request);

Testing Webhooks with cURL

cURL - command line tool and library for transferring data with URLs. Available for most of platforms.

  • Linux - can be installed with package installer.
  • macOS - Homebrew or MacPorts
  • Windows - download binary file and unpack it to some directory and add it to PATH.

Example request with cURL would look similar to this:

curl -H "Content-Type: application/json" -X POST -d '{"timestamp": 1541609146, "events": [{"type": "contact.subscribe", "data": { ... }}]}' https://www.example.com/webhook-listener/
  • -H "Content-Type: application/json" - header that tells server that you are sending JSON data
  • -X POST - use POST method
  • -d '{"timestamp": 1541609146, "events": [{"type": "contact.subscribe", "data": { ... }}]}' - adds data to request

Using Requestb.in Service

If you don't have public URL that accepts Webhook requests yet, you can use requestb.in or similar tool to get temporary URL and see received data.
You can even add it to Mailigen's Webhook Settings page.

© 2010-2018 Mailigen. All rights reserved.