Use Discourse webhooks with PHP

I recently wrote a PHP script that receives data from a Discourse webhook every time a new topic or reply is posted. I thought I’d share the foundation for the code so that other developers can quickly get started working with the event data sent by their Discourse webhooks.

If you have any questions or improvements for this code, let me know!

<?php

// Immediately verify the authenticity of the request.
if (array_key_exists('HTTP_X_DISCOURSE_EVENT_SIGNATURE', $_SERVER)) {
    $discourse_payload_raw = file_get_contents('php://input');
    $discourse_payload_sha256 = substr($_SERVER['HTTP_X_DISCOURSE_EVENT_SIGNATURE'], 7);
    
    // For security, configure the webhook with a secret in Discourse and set it below.
    $discourse_payload_secret = '';
    
    // Verify that the request was sent from an authorized webhook.
    if (hash_hmac('sha256', $discourse_payload_raw, $discourse_payload_secret) == $discourse_payload_sha256) {
        echo 'received';
    }
    else {
        die('authentication failed');
    }
}
else {
    die('access denied');
}

// Prepare the payload for use in the PHP script.
$discourse_json = json_decode($discourse_payload_raw);

// Below here, do whatever you want with the JSON.
print_r($discourse_json);

?>
16 Likes

Thanks for that! It took me a while to figure out how to get this to work with the WordPress REST API. Here’s a basic skeleton plugin for adding a custom endpoint to WordPress for processing a Discourse webhook request.
https://github.com/scossar/wp-discourse-custom-webhook-request

4 Likes

Thanks for sharing this snippet!