Sunday, July 5, 2020

Webbooks introduction & Implementation

Webhook 

Webhooks are also sometimes referred to as “Reverse APIs”. In APIs, the client-side application calls (consumes) the server-side application. Whereas, in case of web hooks it is the server-side that calls (consumes) the web hook (the end-point URL provided by the client-side application), i.e. it is the server-side application that calls the client-side application.

Webhooks operate on the concept of “event reaction” (don’t call me, I’ll call you if I have something new), and thus avoids the need for constant polling of the server-side application by the client-side application. Thus, rather than the client-side application constantly polling the server-side application to check for new events, the server-side application calls the client-side application (by invoking a client provided webhook URL) anytime the server-side has something new to report to the client.

This is the core concept of the Webhook.

----------------------------------------------------------------------------------------------------------------

What WebHooks are used for

Webhooks are "user-defined HTTP callbacks". They are usually triggered by some event, such as pushing code to a repository or a comment being posted to a blog. When that event occurs, the source site makes an HTTP request to the URI configured for the webhook. Users can configure them to cause events on one site to invoke behaviour on another. The action taken may be anything. Common uses are to trigger builds with continuous integration systems or to notify bug tracking systems. Since they use HTTP, they can be integrated into web services without adding new infrastructure.

----------------------------------------------------------------------------------------------------------------

How it works

When a webHook is triggered it will send an HTTPS POST request to the attached URLs, containing a JSON-serialized Update (the one specified when you call the trigger method).

-----------------------------------------------------------------------------------------------------------------------------

Implementation using node.js


Step 1 - Create a new Node.js project
npm init // creates package.json
npm install express body-parser --save // installs using dependencies

Step 2 - Create a HTTP server
Add the below code to index.js and put your verification token into token variable, 
Note : Token should be used to verify if the request comes from a trusted source. It’s optional and can be empty.

index.js

const express = require('express');
const bodyparser = require('body-parser');
const app = express().use(bodyparser.json()); // creates http server
const token = 'yourtoken'; // type here your verification token

app.listen(8888, () => console.log('Listening'));


var router= function (app) {
  
  app.use("/event", function (req, res) {
    var payload = JSON.stringify(req.body);
    var signature = req.get("x-api-key");   

    // if signature is empty return 401
    if (!signature) {
      return res.status(401).send("FORBIDDEN");
    }

    // if payload is empty, don't do anything
    if (!payload) {
      return res.status(200).send("success");
    }
    // validate signature
    if (util.isValidPayload(signature, payload)) {
      // add to queue
      queue.addToQueue(payload);
      return res.status(200).send("success");
    } else {
      return res.status(401).send("FORBIDDEN");
    }
  });
}

module.exports = router;

app.js

var async = require("async"); // for queue implementation
/**
 * Manages a queue and executes a single async thread to process
 * the queue whenever an item is added to the queue
 *
 */

// creating a queue with concurrency 1
var q = async.queue(function (task, callback) {
  processTask(task);
  callback();
}, 1);

function addToQueue(payload) {
  q.push(payload);
}

async function processTask(params) {
  var data = JSON.parse(params);
}
}



No comments:

Post a Comment

Webbooks introduction & Implementation

Webhook  Webhooks are also sometimes referred to as  “Reverse APIs” . In APIs,  the client-side application calls (consumes) the server-side...