Use Discourse webhooks with PHP

AI-generated summary

Using Discourse Webhooks with PHP

In this discussion, users are sharing code snippets and resources for working with Discourse webhooks in PHP. DanielMarquard provided a PHP script that verifies the authenticity of a webhook request and decodes the JSON payload. The script can be used as a foundation for processing event data sent by Discourse webhooks.

simon shared a WordPress plugin that adds a custom endpoint for processing Discourse webhook requests, built on top of DanielMarquard’s code. The plugin is available on GitHub: https://github.com/scossar/wp-discourse-custom-webhook-request.

Other users, such as pnoeric, have expressed gratitude for the shared code snippets, which should help developers get started with working with Discourse webhooks in 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.
GitHub - scossar/wp-discourse-custom-webhook-request: A skeleton plugin for processing a webhook request to a custom endpoint from Discourse to WordPress. · GitHub

4 Likes

Thanks for sharing this snippet!