Code examples
Code example
Java
Java1import org.apache.commons.codec.digest.HmacAlgorithms;2import org.apache.commons.codec.digest.HmacUtils;3import org.springframework.stereotype.Controller;4import org.springframework.web.bind.annotation.PostMapping;5import org.springframework.web.bind.annotation.RequestBody;6import org.springframework.web.bind.annotation.ResponseBody;78import javax.servlet.http.HttpServletRequest;9import javax.servlet.http.HttpServletResponse;1011@Controller12public class WebhookExampleController {1314@PostMapping("/webhook/example")15@ResponseBody16public String receive(HttpServletRequest request, @RequestBody String payload, HttpServletResponse response) {1718String responseBody = "";1920StringBuilder valueToDigest = new StringBuilder();21// Get the timestamp from header22String timestamp = request.getHeader("x-timestamp");23valueToDigest.append(timestamp);24valueToDigest.append(payload);2526// Get the signature from header27String signature = request.getHeader("x-signature");2829// Get your secret30String secret = getSecret();3132// Check if calculated signature matches the signature from the request33HmacUtils hmacUtils = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secret)34if (hmacUtils.hmacHex(valueToDigest)).equals(signature)) {3536// Do something with event3738response.setStatus(HttpServletResponse.SC_OK);39} else {40// Invalid signature41response.setStatus(HttpServletResponse.SC_BAD_REQUEST);42responseBody = "failed to verify the signature";43}4445return responseBody;46}4748}
PHP
PHP1<?php2use RingCentral\Psr7\Response;34function getSecret() {5return 'whsec_CEm2XM_JZ1x5FxUUEGcZoRgIz4RZfDE';6}78function handler($request, $context): Response{9$timestamp = $request->getHeaderLine('x-timestamp');10$body = $request->getBody()->getContents();1112$secret = getSecret();13$signature = $request->getHeaderLine('x-signature');1415if (hash_hmac('sha256', $timestamp.$body, $secret) != $signature) {16return new Response(400, array(), 'failed to verify the signature');17}1819// Do something with event20return new Response(200, array(), $body);21}22
Node.js
JavaScript1// express.js2const crypto = require('crypto')34const secret = '<CLIENT_API_WEBHOOK_SECRET>'56async webhookController(ctx, next) {7 // webhook is received89 const { headers, body } = ctx.request10 const { name, accountId } = body || {} // payload1112 const ts = headers['x-timestamp']1314 const policy = `${ts}${body}`1516 const signatureHex = crypto.createHmac('sha256', secret).update(policy).digest('hex')1718 if (signatureHex === headers['x-signature']) {19 // do business logic after signature is verified2021 return next() // http response code = 200: ack the webhook22 } else {23 ctx.status = 50024 ctx.body = 'failed to verify webhook signature'25 return26 }27}
Was this page helpful?