Skip to main content

Webhook Implementation Guide

Overview

Kid Smart AI supports webhooks for asynchronous delivery of assessment results. This guide covers implementation details and best practices.

Webhook Format

Request Headers

Content-Type: application/json
X-KidSmart-Signature: {hmac_signature}
X-KidSmart-Timestamp: {unix_timestamp}

Security Verification

To verify webhook authenticity:

import hmac
import hashlib

def verify_webhook(signature, timestamp, payload, secret):
# Combine timestamp and payload
message = f"{timestamp}.{payload}"

# Calculate expected signature
expected = hmac.new(
secret.encode('utf-8'),
message.encode('utf-8'),
hashlib.sha256
).hexdigest()

return hmac.compare_digest(signature, expected)

Implementation Examples

Python Flask Example

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def handle_webhook():
# Get headers
signature = request.headers.get('X-KidSmart-Signature')
timestamp = request.headers.get('X-KidSmart-Timestamp')

# Verify webhook
if not verify_webhook(signature, timestamp, request.data, WEBHOOK_SECRET):
return jsonify({'error': 'Invalid signature'}), 401

# Process the webhook data
data = request.json

# Handle based on assessment type
if data.get('type') == 'fluency':
process_fluency_result(data)
elif data.get('type') == 'pronunciation':
process_pronunciation_result(data)
elif data.get('type') == 'recognition':
process_recognition_result(data)

return jsonify({'status': 'success'}), 200

Node.js Express Example

const express = require('express');
const crypto = require('crypto');
const app = express();

app.post('/webhook', express.json(), (req, res) => {
const signature = req.headers['x-kidsmart-signature'];
const timestamp = req.headers['x-kidsmart-timestamp'];

// Verify webhook
const isValid = verifyWebhook(signature, timestamp, JSON.stringify(req.body));
if (!isValid) {
return res.status(401).json({ error: 'Invalid signature' });
}

// Process webhook data
const data = req.body;

// Handle based on assessment type
switch(data.type) {
case 'fluency':
processFluencyResult(data);
break;
case 'pronunciation':
processPronunciationResult(data);
break;
case 'recognition':
processRecognitionResult(data);
break;
}

res.json({ status: 'success' });
});

Best Practices

  1. Quick Response: Return a 2xx status code quickly, process the webhook data asynchronously
  2. Idempotency: Handle duplicate webhooks gracefully using the assessment_id
  3. Retry Logic: Implement exponential backoff if your processing fails
  4. Logging: Log all webhook requests for debugging
  5. Security:
    • Validate webhook signatures
    • Use HTTPS endpoints
    • Keep webhook secret secure
    • Validate request timestamps (prevent replay attacks)

Common Issues

  1. Missing Results:

    • Ensure webhook URL is accessible from the internet
    • Check firewall rules
    • Verify URL format in API request
  2. Invalid Signatures:

    • Verify webhook secret is correct
    • Check timestamp format
    • Ensure payload is raw JSON string when verifying
  3. Timeout Issues:

    • Process webhooks asynchronously
    • Return response quickly
    • Implement proper error handling

Testing Webhooks

  1. Use tools like webhook.site for initial testing
  2. Implement a test endpoint in your development environment

Need help? Contact our support team at support@kidsmart.ai