Remember the mail man scenario we shared earlier in comparison with how webhooks work. Imagine you are the busy kind of person, and you receive quite a lot of parcels. We believe you cannot identify who sent what parcel (JSON Data) by just looking at the envelope.
Yeah, there is always a signature that acknowledges the sender. Our webhooks work like that too.
Moreover, who knows? An unfriendly person might be cooking something unhealthy for you.
Handling WebHook Requests
Our notifications often carry a x-browpay-signature header. This header is a HMAC SHA512 signature that is signed using your secret key.
It is important to verify your webhook requests against fake or unrelated data before it is processed for security purposes.
constcrypto=require('crypto');constsecret= your-secret-key;// Using ExpressJSapp.post("/your-server/webhook-endpoint", (req, res) => {//validate event consthash=crypto.createHmac('sha512', secret).update(JSON.stringify(req.body)).digest('hex');if (hash ==req.headers['x-browpay-signature']) {// bodyconstevent=req.body;// you may use the data here }// do nothingres.send(200);});
import hmacimport hashlibfrom http.server import BaseHTTPRequestHandler, HTTPServerclassWebhookHandler(BaseHTTPRequestHandler):defdo_POST(self): secret =b'your-secret-key' content_length =int(self.headers['Content-Length']) content = self.rfile.read(content_length)# validate event hash_signature = hmac.new(secret, content, hashlib.sha512).hexdigest()if hash_signature == self.headers.get('x-browpay-signature'):# process the event event = content.decode('utf-8')# use the data here# do nothing self.send_response(200) self.end_headers() self.wfile.write(b'OK')if__name__=='__main__': server_address = ('',8000) httpd =HTTPServer(server_address, WebhookHandler) httpd.serve_forever()
importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.InetSocketAddress;importcom.sun.net.httpserver.HttpExchange;importcom.sun.net.httpserver.HttpHandler;importcom.sun.net.httpserver.HttpServer;publicclassMinimalWebhookHandler {publicstaticvoidmain(String[] args) throwsIOException {int port =8080;HttpServer server =HttpServer.create(newInetSocketAddress(port),0);server.createContext("/your-server/webhook-endpoint",newWebhookHandler());server.setExecutor(null); // creates a default executorserver.start(); }staticclassWebhookHandlerimplementsHttpHandler { @Overridepublicvoidhandle(HttpExchange exchange) throwsIOException {InputStream requestBody =exchange.getRequestBody();byte[] buffer =newbyte[1024];int bytesRead;StringBuilder content =newStringBuilder();while ((bytesRead =requestBody.read(buffer)) !=-1) {content.append(newString(buffer,0, bytesRead)); }requestBody.close();// Your secret keyString secret ="your-secret-key";// validate eventString hash =generateHash(content.toString(), secret);if (hash.equals(exchange.getRequestHeaders().getFirst("x-browpay-signature"))) {// process the eventString event =content.toString();// use the data here }// do nothingexchange.sendResponseHeaders(200,0);OutputStream os =exchange.getResponseBody();os.close(); }privateStringgenerateHash(String data,String secret) {// Implement your HMAC generation logic herereturn""; // Replace with your actual implementation } }}
<?php$secret ='your-secret-key';$content =file_get_contents('php://input');$hash_signature =hash_hmac('sha512', $content, $secret);if ($hash_signature == $_SERVER['HTTP_X_BROWPAY_SIGNATURE']) {// process the event $event = $content;// use the data here}// do nothinghttp_response_code(200);echo'OK';
packagemainimport ("crypto/hmac""crypto/sha512""encoding/base64""io/ioutil""net/http")funcmain() { secret :="your-secret-key" http.HandleFunc("/your-server/webhook-endpoint", func(w http.ResponseWriter, r *http.Request) { content, _ := ioutil.ReadAll(r.Body)defer r.Body.Close()// validate event hash :=generateHash(content, []byte(secret))if hash == r.Header.Get("x-browpay-signature") {// process the event event :=string(content)// use the data here }// do nothing w.WriteHeader(http.StatusOK) }) http.ListenAndServe(":8080", nil)}funcgenerateHash(data []byte, secret []byte) string { h := hmac.New(sha512.New, secret) h.Write(data) hashBytes := h.Sum(nil)return base64.StdEncoding.EncodeToString(hashBytes)}
We however added an extra layer of data security to protect you and the notification you receive from us. It is not recommended if you are satisfied with validating the signature.