Handling webhook deliveries

Modified on Fri, 14 Jun at 12:46 PM


Introduction


When you create a webhook, you specify a URL and subscribe to event types. When an event that your webhook is subscribed to occurs, Fluid will send an HTTP request with data about the event to the URL that you specified. If your server is set up to listen for webhook deliveries at that URL, it can take action when it receives one.


This article describes how to write code to let your server listen for and respond to webhook deliveries. You will test your code by using your computer as a local server.



Write code to handle webhook deliveries

In order to handle webhook deliveries, you need to write code that will:


  • Initialize your server to listen for requests to your webhook URL
  • Read the HTTP headers and body from the request
  • Take the desired action in response to the request


You can use any programming language that you can run on your server.


The following examples print a message when a webhook delivery is received. However, you can modify the code to take another action, such as making a request to the Fluid API or sending a Slack message.



Node.JS 


This example uses Node.js and the Express library to define routes and handle HTTP requests. For more information, see expressjs.com


This example requires your computer to run Node.js version 12 or greater and npm version 6.12.0 or greater. For more information, see nodejs.org


To use this example, you must install node.js and the express library in your Node.js project. For example:


npm install nodejs


install express


npm install express


Node.js example: Write the code


const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');

const app = express();
const port = 3000;

// Middleware to parse JSON bodies as text,
// so we dont get issues like "prop":1.0 being changed to "prop":1
// as the payload is used for signature-256 validation
app.use(bodyParser.text({
   type: 'application/json'
}))

// Function to validate the X-Hub-Signature header
function validateSignature(req, res, next) {
  
    const sharedSecret = '#######'; // Replace with your shared secret
    const signature = req.headers['x-hub-signature-256'];
    const payload = req.body;
  
    if (!signature) {
    console.log(`X-Hub-Signature header missing`); 
        return res.status(400).send('X-Hub-Signature-256 header missing');
    }

  const hmac = crypto.createHmac('sha256', sharedSecret);
  const calculatedSignature = hmac.update(payload).digest('hex');

     if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from('sha256=' + calculatedSignature))) {
      console.log(`X-Hub-Signature-256 is VALID`);
        next();
    } else {
    console.log(`X-Hub-Signature-256 is INVALID`);
        return res.status(403).send('Invalid X-Hub-Signature-256');
    }
}

  app.post('/', validateSignature, (req, res) => {

  const jsonData = JSON.parse(req.body);
  const prettifiedJson = JSON.stringify(jsonData, null, 2);

  console.log('Received VALID POST request with body:', prettifiedJson);

  res.json(prettifiedJson); // Echo back the request body
});

// Start the server
app.listen(port, () => {
    console.log(`Server is listening at http://localhost:${port}`);
});


Test the code


To test your webhook, you can use your computer to act as a local server. If you have trouble with these steps, see  Troubleshooting webhooks.


node FILE_NAME


Replace FILE_NAME with the name of your file, eg server.js You should see output that says Server is running on port 3000.



Testing

In order to test your webhook locally, you can use a webhook proxy URL to forward webhooks from Fluid to your computer. This article uses ngrok https://ngrok.com to provide a webhook proxy URL and forward webhooks.



ngrok Setup


1. follow the instuctions at https://ngrok.com/download to install the correct version of ngrok for your OS. Signup for ngrok is free.


Once you have signed up, log into the dashboard and make note of the authentication token https://dashboard.ngrok.com/get-started/your-authtoken, you'll need this as part of your install.


You can also follow their own webhook getting started guide here https://ngrok.com/docs/integrations/hostedhooks/webhooks for additional information.


Below details are for installation on windows.


2. Open a windows cmd shell and run the following command.


choco install ngrok


3. Authenticate ngrok, your token can found here https://dashboard.ngrok.com/get-started/your-authtoken after ngrok sign-up.


ngrok config add-authtoken <### Token ###>


4. To receive forwarded webhooks from ngrok, run the following command in your terminal. Replace PORT with the port where your local server is listening.


ngrok http PORT


5. To confirm configuration of ngrok, browse to the the local ngrok dashboard http://localhost:4040 here you'll find information about you ngrok instance, status, inspect incoming requests and locate your public webhook url.



6. Take note of the ngrok URL value (highlighted in the screenshot above), this is the public URL that you will be using to configure Webhooks to Fluid boards. These events that are sent to this URL will now be forwarded to your local server listening on port 3000.  In this example the url is "https://a346-185-245-255-247.ngrok-free.app"



Note: Each time you run ngrok http PORT you will receive a new public URL, you will need to update Fluid webhook configuration settings accordingly. see How to configure Webooks to Fluid Boards integration



Create a webhook

Create a webhook with the following settings. For more information, see How to configure Webooks to Fluid Boards integration



1. Trigger your webhook. For example, if you configured your action webhook to subscribe to the create event, create a new action. 


2. Navigate to your  the ngrok dashboard at http://localhost:4040. Under the inspect tab, you should see an event that corresponds to the event that you triggered. This indicates that Fluid successfully sent a webhook delivery to the URL that you specified in config. You can also inspect the Http header details and sent by Fluid and/or replay the message again.




3. In the terminal window where you ran node FILE_NAME, you should see the event message corresponding to the event that was sent.


4. In both terminal windows, enter Ctrl+C to stop your local server and stop listening for forwarded webhooks.


Now that you have tested out your code locally, you can make changes to use your webhook in production. For more information, see "Next steps." If you had trouble testing your code, try the steps in Troubleshooting webhooks



Troubleshooting

If you don't see the expected results described in the testing steps, try the following:



  • Make sure that your webhook uses the JSON content type.


  • Make sure that both the ngrok client and your local server are running. You will have these processes running in two separate terminal windows.


  • Make sure that your server is listening to the same port where ngrok is forwarding webhooks. All of the examples in this article use port 3000.


  • Check for error messages in the terminal windows where you are running the ngrok client and your local server.


  • Check your webhook proxy URL on ngrok. You should see an event that corresponds to the event that you triggered. This indicates that Fluid successfully sent a webhook delivery to the payload URL that you specified.



Next steps

This article demonstrated how to write code to handle webhook deliveries. It also demonstrated how to test your code by using your computer or codespace as a local server and by forwarding webhook deliveries from Fluid to your local server via ngrok.com. Once you are done testing your code, you might want to modify the code and deploy your code to a server.


Modify the code

This article gave basic examples that print a message when a webhook delivery is received. You may want to modify the code to take some other action. For example, you could modify the code to:


  • Send a message on Slack


  • Log events


  • Update an external tool


Verify that the delivery is from Fluid

In your code that handles webhook deliveries, you should validate that the delivery is from Fluid  before processing the delivery further. For more information, see Validating Webhooks


Deploy your code to a server

This article demonstrated how to use your computer or codespace as a server while you develop your code. Once the code is ready for production use, you should deploy your code to a dedicated server.


When you do so, you may need to update your code to reflect the host and port where your server is listening.


Update the webhook URL

Once you have a server that is set up to receive webhook traffic from Fluid, update the URL in your fluid board webhook  config settings. You may need to update the route that your code handles to match the path portion of the new URL. 


You should not use ngrok.com to forward your webhooks in production.


Follow best practices

You should aim to follow best practices with your webhooks. For more information, see Webhook best practices


Further reading

Troubleshooting webhooks

Webhook best practices

Webhook events and payloads


Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article