Examples to receive the response from webhooks


Listed below are different coding language examples to recevice the response from webhooks:

  • PHP

  • <?php
    $pepipost = array();
    $http_data = file_get_contents("php://input");
    $parts = explode('&', $http_data);
    foreach ( $parts as $part ) {
      list($key, $value) = explode('=', $part, 2);
      $pepipost[$key] = $value;
    }
    foreach($pepipost as $key=>$value) {
      file_put_contents('/tmp/test', "$key\n", FILE_APPEND);
    }
    echo "Success";
    ?>
    

  • Node.js

  • var http = require('http');
    fs = require('fs');
    http.createServer(function (req, res) {
    var path = '/tmp/pepipost_webhooks.log';
     console.dir(req.param);
    
        if (req.method == 'POST') {
            console.log("POST");
            var body = '';
            req.on('data', function (data) {
            fs.appendFile(path, data, function(error) {
                 if (error) {
              console.error("write error:  " + error.message);
         } else {
           console.log("Successful Write to " + path);
         }
    });
            });
            req.on('end', function () {
                console.log("Body: " + body);
            });
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end('post received');
        }
        {
         res.end("not recevice");
        }
    
  • Python

  • from threading import Thread
    from SocketServer import ThreadingMixIn
    from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
    from urlparse import urlparse
    import urllib
    import datetime,traceback,sys
    import imp
    from Queue import Queue
    import psLogging as log
    
    my_logger = log.init_logger('/tmp/masterServer.log','Master Server')
    
    thread = 40 
    q = Queue()
    putCounter=0
    getCounter=0
    
    moduleHsh = {}
    def importMe(moduleName):
      my_logger.info('Modlue Hash - %s ' % moduleHsh)
      my_logger.info('Modlue Name - %s ' % moduleName)
      try:
        if not moduleName in moduleHsh:
          f, filename, data = imp.find_module(moduleName)
          importedModule = imp.load_module(moduleName, f, filename, data )
          moduleHsh[moduleName] = importedModule
        return moduleHsh[moduleName]
      except:
        errortrace =  ''.join(traceback.format_exception(*sys.exc_info()))
        my_logger.error("Unexpected error: %s" % (errortrace,))
    
    def dequeMe(i,q):
      while True:
        try:
          my_logger.info('%s: Waiting for next call' % i)
          params = q.get()
          global getCounter
          getCounter += 1
          my_logger.info("Get Counter => %s " % (getCounter))
          my_logger.info('%s: Got call with params: %s' % (i, params))
          module = params.get('module')
          m = importMe(params.get('module')) 
          c = m.MissedCallHandler()
          r = c.processMe(params)
          my_logger.info("Response %s " % (r))
          q.task_done()
        except:
          errortrace =  ''.join(traceback.format_exception(*sys.exc_info()))
          my_logger.error("Unexpected error: %s" % (errortrace,))
    
    # Worker Function which initiate the de-queue process.
    for i in range(thread):
        worker = Thread(target=dequeMe, args=(i, q,))
        worker.setDaemon(True)
        worker.start()
    
    class AdminHandler(BaseHTTPRequestHandler):
      def do_POST(self):
        # Doesn't do anything with posted data
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself
        print post_data
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
    
    def shutdown():
      my_logger.info('IN SHUTDOWN')
      HTTPServer.server_close(HTTPSERVER)
      my_logger.info('OUT SHUTDOWN')
    
    class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
      pass
    
    HTTPSERVER = ThreadingHTTPServer(("0.0.0.0",80), AdminHandler)
    
    if __name__ == '__main__':
      my_logger.info('Starting master Server')