Follow

Webhook URL in PHP/Python

Is there a sample code to check webhook URL in PHP or Python?

 

You may use any of the following files mentioned below (PHP or Python) to test the webhook notification system.

To use this, copy the file mentioned below  to the server where you're testing your webhook. Change the output file name from /tmp/webhook_data.txt to any other file name that your webserver can write to and that you can read.

Now, copy the link to the script and paste it under the Webhook URL field of your Instamojo link's edit page. Now, make a transaction. After the purchase is done, open the output text file. You should see the webhook data in this file.

You may modify the file according to your needs.

 

webhook_receiver.php

 

<?php

$data = $_POST;
$mac_provided = $data['mac'];  // Get the MAC from the POST data
unset($data['mac']);  // Remove the MAC key from the data.

$ver = explode('.', phpversion());
$major = (int) $ver[0];
$minor = (int) $ver[1];

if($major >= 5 and $minor >= 4){
     ksort($data, SORT_STRING | SORT_FLAG_CASE);
}
else{
     uksort($data, 'strcasecmp');
}

// You can get the 'salt' from Instamojo's developers page(make sure to log in first): https://www.instamojo.com/developers
// Pass the 'salt' without the <>. $mac_calculated = hash_hmac("sha1", implode("|", $data), "<YOUR_SALT>"); if($mac_provided == $mac_calculated){ echo "MAC is fine"; // Do something here
if($data['status'] == "Credit"){
// Payment was successful, mark it as completed in your database
}
else{
// Payment was unsuccessful, mark it as failed in your database
}
}
else{
echo "Invalid MAC passed";
}
?>

 

webhook_receiver.py

 

import hmac

import hashlib 

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

import urlparse

PORT = 8000

FILENAME = '/tmp/webhook_data.txt'

 

class MojoHandler(BaseHTTPRequestHandler):

  def do_POST(self):

      content_length = int(self.headers['content-length'])

      querystring = self.rfile.read(content_length)

      data = urlparse.parse_qs(querystring)

      mac_provided = data.pop('mac')

      message = "|".join(v for k, v in sorted(data.items(), key=lambda x: x[0].lower()))

      # Pass the 'salt' without the <>.

      mac_calculated = hmac.new("<YOUR_SALT>", message, hashlib.sha1).hexdigest()

      if mac_provided == mac_calculated:

          if data['status'] == "Credit":

              # Payment was successful, mark it as completed in your database.

          else:

              # Payment was unsuccessful, mark it as failed in your database.

          self.send_response(200)

      else:

          self.send_response(400)

      self.send_header('Content-type', 'text/html')

      self.end_headers()

httpd = HTTPServer(('', PORT), MojoHandler)

httpd.serve_forever()



Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.