ReOTP.
Security and Synchronization/Webhooks and HMAC
1 min read

Webhooks and HMAC

Learn how to receive secure instant notifications upon phone number verification.

The Webhooks are the fastest and most secure way to know that a user has successfully verified without the need for Polling.

When the user sends the message and it is successfully matched, our system sends a POST request to a URL that you specify in advance in your project settings.

Webhook Security (HMAC Signature)

To ensure that requests are truly coming from our servers and are not fake attacks, we sign every request using the HMAC-SHA256 algorithm.

1. Go to project settings and generate a Webhook Secret.

2. An encrypted signature will be attached in the request Header named x-webhook-signature.

3. You must calculate the signature on your server using the same Secret of yours and compare it to the sent signature.

Integration Code (SDKs)
const express = require('express');
const crypto = require('crypto');
const app = express();

const WEBHOOK_SECRET = 'your_webhook_secret_here';

// Must parse raw body to verify signature correctly
app.use(express.json());

app.post('/webhook/reotp', (req, res) => {
  const signatureHeader = req.headers['x-webhook-signature'];
  const payloadString = JSON.stringify(req.body);

  // Calculate HMAC SHA256
  const expectedSignature = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(payloadString)
    .digest('hex');

  // Securely compare signatures
  if (signatureHeader !== expectedSignature) {
    return res.status(401).send('Invalid signature');
  }

  // Handle successful verification
  const { event, phoneNumber, requestId } = req.body;
  if (event === 'verification.success') {
    console.log(`User ${phoneNumber} verified! (ID: ${requestId})`);
    // Login user, create session, update DB, etc.
  }

  // Must return 200 OK so we know it was delivered
  res.status(200).send('OK');
});

app.listen(3000, () => console.log('Listening for Webhooks...'));