Step-by-step guide to implement webhook handling with code examples in multiple languages
Overview
This guide walks you through implementing webhook endpoints to receive real-time notifications from the Nudj platform. You’ll learn how to configure webhooks, handle incoming requests, and implement best practices for production systems.
Prerequisites
Admin API Access
You need Admin API credentials to configure webhooks
HTTPS Endpoint
Your endpoint must use HTTPS: Nudj sends your auth header with every request and does not refuse an http:// URL for you
Event Processing
A system to handle and process incoming events
Authentication
Mechanism to verify webhook authenticity
Step 1: Configure Your Webhook
First, use the Admin API to configure your webhook endpoint:
The body is your organisation’s whole webhook list under webhookConfig: it replaces every webhook you created before, so send each one you want to keep. Nudj does not sign payloads; the headers you set here (such as Authorization and X-Webhook-Source above) are sent with every request, and your endpoint checks them.
Step 2: Implement Webhook Endpoint
Create an endpoint to receive and process webhook events:
const express = require('express');const crypto = require('crypto');const app = express();// Parse JSON; Nudj does not sign payloads, so the check below compares the headers you configuredapp.use('/webhooks', express.json({ verify: (req, res, buf, encoding) => { req.rawBody = buf; }}));// Webhook endpointapp.post('/webhooks/nudj', async (req, res) => { try { // Verify the webhook is from Nudj if (!verifyWebhookSignature(req)) { return res.status(401).send('Unauthorized'); } const event = req.body; console.log('Received webhook:', event.eventSubCategory); // Process the event await processWebhookEvent(event); // Always respond with 200 for successful processing res.status(200).send('OK'); } catch (error) { console.error('Webhook processing error:', error); res.status(500).send('Internal Server Error'); }});function verifyWebhookSignature(req) { const secret = process.env.WEBHOOK_SECRET; // Refuse everything when the secret is not configured. if (!secret) return false; const expected = Buffer.from(`Bearer ${secret}`); const received = Buffer.from(req.get('Authorization') ?? ''); // Compare in constant time so the check does not leak the secret. return received.length === expected.length && crypto.timingSafeEqual(received, expected);}async function processWebhookEvent(event) { switch (event.eventSubCategory) { case 'challenge-completion': await handleChallengeCompletion(event); break; case 'achievement-completion': await handleAchievementCompletion(event); break; case 'reward-claim': await handleRewardClaim(event); break; default: console.log('Unhandled event type:', event.eventSubCategory); }}async function handleChallengeCompletion(event) { const { userId, eventSourceId, payload } = event; // Example: Send congratulatory email await sendEmail(userId, { subject: 'Challenge Completed!', template: 'challenge-completion', data: { // The payload carries ids only; fetch names and points from the API. challengeId: payload.challengeId } }); // Example: Update external system await updateExternalProfile(userId, { lastChallengeCompleted: eventSourceId, totalChallengesCompleted: await getChallengeCount(userId) + 1 });}app.listen(3000, () => { console.log('Webhook server listening on port 3000');});
from flask import Flask, request, jsonifyimport osimport hmacapp = Flask(__name__)@app.route('/webhooks/nudj', methods=['POST'])def handle_webhook(): try: # Verify the webhook is from Nudj if not verify_webhook_signature(request): return jsonify({'error': 'Unauthorized'}), 401 event = request.json print(f"Received webhook: {event.get('eventSubCategory')}") # Process the event process_webhook_event(event) return jsonify({'status': 'success'}), 200 except Exception as e: print(f"Webhook processing error: {e}") return jsonify({'error': 'Internal Server Error'}), 500def verify_webhook_signature(request): secret = os.getenv('WEBHOOK_SECRET') # Refuse everything when the secret is not configured. if not secret: return False received_auth = request.headers.get('Authorization', '') # Compare bytes in constant time so the check does not leak the secret # (compare_digest raises TypeError on a str with non-ASCII characters). return hmac.compare_digest(received_auth.encode(), f"Bearer {secret}".encode())def process_webhook_event(event): event_type = event.get('eventSubCategory') handlers = { 'challenge-completion': handle_challenge_completion, 'achievement-completion': handle_achievement_completion, 'reward-claim': handle_reward_claim } handler = handlers.get(event_type) if handler: handler(event) else: print(f"Unhandled event type: {event_type}")def handle_challenge_completion(event): user_id = event.get('userId') payload = event.get('payload', {}) # Example: Send congratulatory message send_notification(user_id, { 'type': 'challenge_completed', 'message': f"Congratulations! You completed challenge {payload.get('challengeId')}", 'challenge_id': payload.get('challengeId') }) # Example: Update user stats update_user_stats(user_id, 'challenges_completed', 1)def handle_achievement_completion(event): # Implementation for achievement completion passdef handle_reward_claim(event): # Implementation for reward claim passif __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
require 'sinatra'require 'json'set :port, 4567post '/webhooks/nudj' do begin # Verify the webhook is from Nudj unless verify_webhook_signature(request) halt 401, 'Unauthorized' end # Parse the JSON payload event = JSON.parse(request.body.read) puts "Received webhook: #{event['eventSubCategory']}" # Process the event process_webhook_event(event) status 200 body 'OK' rescue => e puts "Webhook processing error: #{e.message}" status 500 body 'Internal Server Error' endenddef verify_webhook_signature(request) secret = ENV['WEBHOOK_SECRET'] # Refuse everything when the secret is not configured. return false if secret.nil? || secret.empty? received_auth = request.env['HTTP_AUTHORIZATION'].to_s # Compare in constant time so the check does not leak the secret. Rack::Utils.secure_compare(received_auth, "Bearer #{secret}")enddef process_webhook_event(event) case event['eventSubCategory'] when 'challenge-completion' handle_challenge_completion(event) when 'achievement-completion' handle_achievement_completion(event) when 'reward-claim' handle_reward_claim(event) else puts "Unhandled event type: #{event['eventSubCategory']}" endenddef handle_challenge_completion(event) user_id = event['userId'] payload = event['payload'] # Example: Send notification send_notification(user_id, { type: 'challenge_completed', message: "You completed challenge #{payload['challengeId']}!", challenge_id: payload['challengeId'] })end
<?php// Get the raw POST data$input = file_get_contents('php://input');$event = json_decode($input, true);// Verify webhook signatureif (!verifyWebhookSignature()) { http_response_code(401); die('Unauthorized');}try { echo "Received webhook: " . $event['eventSubCategory'] . "\n"; // Process the event processWebhookEvent($event); http_response_code(200); echo 'OK';} catch (Exception $e) { error_log("Webhook processing error: " . $e->getMessage()); http_response_code(500); echo 'Internal Server Error';}function verifyWebhookSignature() { $secret = $_ENV['WEBHOOK_SECRET'] ?? ''; // Refuse everything when the secret is not configured. if ($secret === '') { return false; } $receivedAuth = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; // Compare in constant time so the check does not leak the secret. return hash_equals('Bearer ' . $secret, $receivedAuth);}function processWebhookEvent($event) { switch ($event['eventSubCategory']) { case 'challenge-completion': handleChallengeCompletion($event); break; case 'achievement-completion': handleAchievementCompletion($event); break; case 'reward-claim': handleRewardClaim($event); break; default: error_log('Unhandled event type: ' . $event['eventSubCategory']); }}function handleChallengeCompletion($event) { $userId = $event['userId']; $payload = $event['payload']; // Example: Log the completion error_log("User {$userId} completed challenge: " . $payload['challengeId']); // Example: Send notification sendNotification($userId, [ 'type' => 'challenge_completed', 'message' => "Congratulations! You completed challenge {$payload['challengeId']}", 'challenge_id' => $payload['challengeId'] ]);}function sendNotification($userId, $data) { // Implementation for sending notifications error_log("Sending notification to user {$userId}: " . json_encode($data));}?>
package mainimport ( "crypto/subtle" "encoding/json" "log" "net/http" "os" "github.com/gin-gonic/gin")type WebhookEvent struct { ID string `json:"id"` EventCategory string `json:"eventCategory"` EventSubCategory string `json:"eventSubCategory"` OrganisationID string `json:"organisationId"` CommunityID string `json:"communityId"` UserID string `json:"userId"` EventSourceID string `json:"eventSourceId"` Payload interface{} `json:"payload"` Tags []string `json:"tags"` CreatedAt string `json:"createdAt"`}func main() { r := gin.Default() r.POST("/webhooks/nudj", handleWebhook) log.Println("Webhook server starting on :8080") r.Run(":8080")}func handleWebhook(c *gin.Context) { // Verify webhook signature if !verifyWebhookSignature(c) { c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) return } var event WebhookEvent if err := c.ShouldBindJSON(&event); err != nil { log.Printf("Error parsing webhook: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON"}) return } log.Printf("Received webhook: %s", event.EventSubCategory) // Process the event if err := processWebhookEvent(event); err != nil { log.Printf("Error processing webhook: %v", err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Processing failed"}) return } c.JSON(http.StatusOK, gin.H{"status": "success"})}func verifyWebhookSignature(c *gin.Context) bool { secret := os.Getenv("WEBHOOK_SECRET") // Refuse everything when the secret is not configured. if secret == "" { return false } expectedAuth := []byte("Bearer " + secret) receivedAuth := []byte(c.GetHeader("Authorization")) // Compare in constant time so the check does not leak the secret. return subtle.ConstantTimeCompare(receivedAuth, expectedAuth) == 1}func processWebhookEvent(event WebhookEvent) error { switch event.EventSubCategory { case "challenge-completion": return handleChallengeCompletion(event) case "achievement-completion": return handleAchievementCompletion(event) case "reward-claim": return handleRewardClaim(event) default: log.Printf("Unhandled event type: %s", event.EventSubCategory) return nil }}func handleChallengeCompletion(event WebhookEvent) error { payload, _ := json.Marshal(event.Payload) log.Printf("User %s completed a challenge: %s", event.UserID, string(payload)) // Add your business logic here // - Send notifications // - Update external systems // - Trigger other processes return nil}func handleAchievementCompletion(event WebhookEvent) error { // Implementation for achievement completion return nil}func handleRewardClaim(event WebhookEvent) error { // Implementation for reward claim return nil}
Step 3: Implement Event Handlers
Create specific handlers for different event types:
async function handleChallengeCompletion(event) { // challenge-completion carries ids only: name, challengeId, communityId, // organisationId and userId. Fetch names, points or XP from the Admin API. const { userId, communityId, payload } = event; const challengeId = payload.challengeId; try { // 1. Update user statistics await updateUserStats(userId, { challengesCompleted: 1 }); // 2. Look up the challenge for a friendly message const challenge = await fetchChallenge(challengeId); await sendNotification(userId, { type: 'challenge_completed', title: 'Challenge Complete!', message: 'Great job completing "' + challenge.title + '"!', }); // 3. Update your own leaderboard await updateLeaderboard(communityId, userId, { challengesCompleted: 1 }); } catch (error) { console.error('Error handling challenge completion for user ' + userId, error); throw error; }}
async function handleRewardClaim(event) { // For reward-claim, eventSourceId is the member's reward asset; the reward // itself is payload.rewardId. The payload also carries rewardAssetId, // details, campaigns, claimedAt and expiresAt. const { userId, payload } = event; try { await logEvent('reward_claimed', { userId, rewardId: payload.rewardId, rewardAssetId: payload.rewardAssetId, claimedAt: payload.claimedAt, }); await updateUserProfile(userId, { rewardsClaimed: 1, lastRewardClaimed: { id: payload.rewardId, claimedAt: payload.claimedAt }, }); } catch (error) { console.error('Error handling reward claim for user ' + userId, error); throw error; }}
Step 4: Error Handling and Retry Logic
Implement robust error handling to ensure reliable webhook processing:
const MAX_RETRIES = 3;const RETRY_DELAY = 1000; // 1 secondasync function processWebhookEvent(event) { let attempt = 1; while (attempt <= MAX_RETRIES) { try { await processEvent(event); return; // Success, exit retry loop } catch (error) { console.error(`Attempt ${attempt} failed:`, error); if (attempt === MAX_RETRIES) { // Final attempt failed, handle accordingly await handleFinalFailure(event, error); throw error; } // Wait before retrying await sleep(RETRY_DELAY * attempt); attempt++; } }}async function handleFinalFailure(event, error) { // Log to error monitoring service console.error('Webhook processing failed after all retries:', { eventId: event.id, eventType: event.eventSubCategory, error: error.message, stack: error.stack }); // Store in dead letter queue for manual review await storeInDeadLetterQueue(event, error); // Alert operations team await sendAlert('webhook-processing-failed', { eventId: event.id, eventType: event.eventSubCategory, error: error.message });}function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms));}
// redis: a connected node-redis v4 client; crypto as in the server example above.// Claim each webhook id atomically (SET NX, 5-minute TTL) under a token only this// request holds, then keep it as "done" for 24h.const CLAIM_TTL_SECONDS = 300;// Change the key only while it still holds this request's token, so a request// that outlived its claim cannot overwrite or free a newer one.const MARK_DONE_IF_OWNER = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('SET', KEYS[1], 'done', 'EX', 86400) end return false";const RELEASE_IF_OWNER = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0";// processWebhookEvent here is the Step 2 dispatcher extended to take a second argument,// { idempotencyKey, signal }, and pass it to every side effect, for example// sendEmail(userId, message, { idempotencyKey, signal }). The Step 2 version takes only the// event, so without that change the key and the timeout below do nothing.app.post('/webhooks/nudj', async (req, res) => { // Authenticate first, so an unknown caller learns nothing. if (!verifyWebhookSignature(req)) { return res.status(401).send('Unauthorized'); } const webhookId = req.body.id; if (!webhookId) return res.status(400).send('Missing id'); const key = `nudj-webhook:${webhookId}`; const token = crypto.randomUUID(); let claimed; let state; try { // The TTL frees the id if this process dies mid-event. claimed = await redis.set(key, token, { NX: true, EX: CLAIM_TTL_SECONDS }); if (!claimed) state = await redis.get(key); } catch (error) { // Redis is unavailable: ask Nudj to try again later. console.error('Idempotency store unavailable:', error); return res.status(503).send('Try again later'); } if (!claimed) { // Done: acknowledge. Still processing: ask Nudj to try again later. return state === 'done' ? res.status(200).send('OK') : res.status(503).send('Still processing'); } try { // Stop well inside the claim's TTL (Nudj waits only 15 seconds for an answer), // and pass the id on as the idempotency key of each side effect: a retry after // a failure or an expired claim runs this handler again. await processWebhookEvent(req.body, { idempotencyKey: webhookId, signal: AbortSignal.timeout(10_000), }); } catch (error) { // Release the claim so Nudj's retry can run; if Redis fails, the TTL frees it instead. await redis .eval(RELEASE_IF_OWNER, { keys: [key], arguments: [token] }) .catch((releaseError) => console.error('Could not release the claim:', releaseError)); console.error('Webhook processing error:', error); return res.status(500).send('Internal Server Error'); } try { await redis.eval(MARK_DONE_IF_OWNER, { keys: [key], arguments: [token] }); } catch (error) { // The work is done; if the mark is lost, a later retry repeats it under the same idempotency keys. console.error('Could not mark the webhook done:', error); } res.status(200).send('OK');});
# Install ngrok for local testingnpm install -g ngrok# Start your local webhook servernode webhook-server.js &# Expose local server via ngrokngrok http 3000# Use the ngrok URL in your webhook configuration# Example: https://abc123.ngrok.io/webhooks/nudj
Step 6: Production Deployment
Security Checklist
HTTPS Configuration
Use valid SSL certificates
Enable HSTS headers
Disable HTTP fallback
Use strong cipher suites
Authentication & Authorization
Check the auth header you configured
Use environment variables for secrets
Implement rate limiting
Don’t rely on an IP allowlist: Nudj publishes no fixed IP ranges