- Updated: March 20, 2026
- 8 min read
Adding a Custom Webhook to OpenClaw Rating API with Serverless Functions
You can add a custom webhook to the OpenClaw Rating API and enrich rating payloads in real‑time using a serverless function on AWS Lambda, Azure Functions, or Cloudflare Workers.
Introduction
Developers building rating‑centric applications often need to react instantly when a new rating arrives. The OpenClaw Rating API supports webhooks, but a raw webhook payload may lack the contextual data your downstream services require. By coupling the webhook with a serverless function you can transform, augment, and route the data without managing any servers.
In this guide we’ll walk through the entire process—from creating a secure endpoint to enriching the payload with user profile information—using three popular serverless platforms: AWS Lambda, Azure Functions, and Cloudflare Workers. The examples are written in JavaScript/Node.js, which aligns with the majority of modern web stacks.
Before diving in, you might want to explore the UBOS platform overview to see how UBOS can host and manage your serverless workloads alongside other AI‑driven services.
Overview of OpenClaw Rating API Webhooks
The OpenClaw Rating API emits a POST request to a URL you configure whenever a new rating is submitted. The default payload looks like this:
{
"ratingId": "abc123",
"productId": "prod-456",
"score": 4,
"comment": "Great product!",
"timestamp": "2024-03-20T12:34:56Z"
}While this data is useful, many applications also need:
- Customer demographic details (age, location, loyalty tier)
- Product metadata (category, price, inventory status)
- Real‑time sentiment analysis of the comment
Serverless functions let you fetch this extra information from your databases or third‑party APIs, merge it with the original payload, and forward the enriched object to downstream services such as analytics pipelines, CRM systems, or notification engines.
Setting Up a Custom Webhook Endpoint
All three platforms share a common pattern:
- Expose an HTTP endpoint that validates the incoming request.
- Fetch additional data (e.g., user profile) using async calls.
- Combine the original rating with the fetched data.
- Return a 200 status to acknowledge receipt.
Below are concrete implementations for each environment.
AWS Lambda Example
We’ll use AWS Lambda behind an API Gateway trigger. Create a new Lambda function named openclawWebhookHandler and attach the following code:
exports.handler = async (event) => {
// 1️⃣ Verify that the request is from OpenClaw (shared secret header)
const secret = process.env.OPENCLAW_SECRET;
if (event.headers['x-openclaw-signature'] !== secret) {
return { statusCode: 401, body: 'Invalid signature' };
}
// 2️⃣ Parse the incoming rating payload
const rating = JSON.parse(event.body);
// 3️⃣ Enrich with user profile (mocked async call)
const userProfile = await getUserProfile(rating.userId);
// 4️⃣ Enrich with product metadata
const productInfo = await getProductInfo(rating.productId);
// 5️⃣ Combine everything
const enrichedPayload = {
...rating,
user: userProfile,
product: productInfo,
enrichedAt: new Date().toISOString()
};
// 6️⃣ Forward to downstream service (e.g., analytics endpoint)
await forwardToAnalytics(enrichedPayload);
// 7️⃣ Respond to OpenClaw
return { statusCode: 200, body: 'OK' };
};
// Mock helper functions
async function getUserProfile(userId) {
// Replace with real DB call
return { id: userId, age: 29, country: 'US', tier: 'Gold' };
}
async function getProductInfo(productId) {
// Replace with real API call
return { id: productId, category: 'Electronics', price: 199.99 };
}
async function forwardToAnalytics(payload) {
const https = require('https');
const data = JSON.stringify(payload);
const options = {
hostname: 'analytics.example.com',
path: '/ingest',
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': data.length }
};
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
res.on('data', () => {});
res.on('end', resolve);
});
req.on('error', reject);
req.write(data);
req.end();
});
}
Deploy the function, then configure an API Gateway with a POST /openclaw/webhook route that points to this Lambda. In the OpenClaw dashboard, set the webhook URL to the API Gateway endpoint and provide the shared secret.
Azure Functions Example
For Azure, create an HTTP‑triggered Function App named OpenClawWebhook. Use the following index.js:
module.exports = async function (context, req) {
// 1️⃣ Validate secret
const secret = process.env["OPENCLAW_SECRET"];
if (req.headers['x-openclaw-signature'] !== secret) {
context.res = { status: 401, body: 'Invalid signature' };
return;
}
// 2️⃣ Parse payload
const rating = req.body;
// 3️⃣ Parallel enrichment calls
const [userProfile, productInfo] = await Promise.all([
getUserProfile(rating.userId),
getProductInfo(rating.productId)
]);
// 4️⃣ Build enriched object
const enriched = {
...rating,
user: userProfile,
product: productInfo,
enrichedAt: new Date().toISOString()
};
// 5️⃣ Send to downstream (e.g., Event Hub)
await sendToEventHub(enriched);
// 6️⃣ Respond
context.res = { status: 200, body: 'OK' };
};
async function getUserProfile(userId) {
// Simulated DB call
return { id: userId, age: 34, country: 'CA', tier: 'Silver' };
}
async function getProductInfo(productId) {
// Simulated API call
return { id: productId, category: 'Books', price: 24.99 };
}
async function sendToEventHub(payload) {
const { EventHubProducerClient } = require("@azure/event-hubs");
const client = new EventHubProducerClient(process.env.EVENT_HUB_CONNECTION, "ratings");
const batch = await client.createBatch();
batch.tryAdd({ body: payload });
await client.sendBatch(batch);
await client.close();
}
After publishing the function, copy its URL (e.g., https://myfuncapp.azurewebsites.net/api/OpenClawWebhook) into the OpenClaw webhook configuration. The Workflow automation studio can later be used to orchestrate additional steps such as Slack notifications or CRM updates.
Cloudflare Workers Example
Cloudflare Workers run at the edge, giving you sub‑millisecond latency. Create a new Worker named openclaw-webhook and paste the following script:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
// 1️⃣ Verify secret header
const secret = OPENCLAW_SECRET; // Set as a secret in Workers KV
const signature = request.headers.get('x-openclaw-signature');
if (signature !== secret) {
return new Response('Invalid signature', { status: 401 });
}
// 2️⃣ Parse JSON body
const rating = await request.json();
// 3️⃣ Enrich data (parallel fetches)
const [userProfile, productInfo] = await Promise.all([
fetchUserProfile(rating.userId),
fetchProductInfo(rating.productId)
]);
// 4️⃣ Build enriched payload
const enriched = {
...rating,
user: userProfile,
product: productInfo,
enrichedAt: new Date().toISOString()
};
// 5️⃣ Forward to downstream (e.g., KV store or external API)
await forwardEnriched(enriched);
// 6️⃣ Respond to OpenClaw
return new Response('OK', { status: 200 });
}
async function fetchUserProfile(userId) {
// Example: call an external user service
const resp = await fetch(`https://api.example.com/users/${userId}`);
return resp.json();
}
async function fetchProductInfo(productId) {
const resp = await fetch(`https://api.example.com/products/${productId}`);
return resp.json();
}
async function forwardEnriched(payload) {
// Store in a KV namespace called ENRICHED_RATINGS
await ENRICHED_RATINGS.put(payload.ratingId, JSON.stringify(payload));
}
Deploy the Worker, then set the webhook URL in OpenClaw to the Worker’s endpoint (e.g., https://openclaw.example.workers.dev). Because Workers execute at the edge, the enrichment step can be performed close to the user, reducing overall latency.
Enriching Rating Payloads in Real‑Time
Enrichment is more than just data lookup; it’s an opportunity to apply AI services that add predictive value. UBOS offers a suite of AI integrations that can be called from any of the serverless functions above:
- OpenAI ChatGPT integration – run sentiment analysis on the
commentfield. - Chroma DB integration – store vector embeddings for future similarity searches.
- ElevenLabs AI voice integration – generate an audio summary for internal dashboards.
Below is a snippet showing how to call the ChatGPT API from the AWS Lambda example to add a sentiment field:
async function analyzeSentiment(text) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: `Classify the sentiment of this review: "${text}"` }],
temperature: 0
})
});
const data = await response.json();
return data.choices[0].message.content.trim(); // Expected "Positive", "Neutral", or "Negative"
}
// Inside the Lambda handler, after fetching rating:
const sentiment = await analyzeSentiment(rating.comment);
enrichedPayload.sentiment = sentiment;
Similar calls can be made from Azure Functions or Cloudflare Workers using their native fetch APIs. By embedding AI‑driven insights directly into the webhook flow, downstream services receive a richer, ready‑to‑use dataset.
Deployment Checklist
Before you go live, run through this concise checklist. Each item is essential for security, reliability, and performance.
- ✅ Secure the webhook endpoint – validate the
x-openclaw-signatureheader against a secret stored in environment variables. - ✅ Set up proper IAM roles – grant the function least‑privilege access to databases, external APIs, and logging services.
- ✅ Enable retries and dead‑letter queues – ensure no rating is lost if downstream services are temporarily unavailable.
- ✅ Configure rate limiting – protect against burst traffic or malicious spikes.
- ✅ Log structured JSON – use a consistent schema for observability (e.g., CloudWatch, Azure Monitor, or Workers KV).
- ✅ Test with a sandbox OpenClaw account – send sample ratings and verify enrichment results.
- ✅ Monitor latency – aim for sub‑500 ms total processing time.
- ✅ Review UBOS pricing plans for any additional AI services you consume.
- ✅ Document the endpoint URL and secret in a secure vault (e.g., AWS Secrets Manager, Azure Key Vault).
- ✅ Enable alerting for error rates > 1 % or latency spikes.
Conclusion and Next Steps
By following the patterns above, you can turn a simple OpenClaw rating webhook into a powerful, real‑time data enrichment pipeline that leverages serverless scalability and AI intelligence. The modular code snippets make it easy to swap out data sources, add new AI analyses, or switch cloud providers without rewriting the entire flow.
If you’re ready to spin up a production‑grade OpenClaw instance, the host OpenClaw page provides step‑by‑step deployment guides, managed hosting options, and best‑practice security recommendations.
Looking ahead, consider integrating the enriched ratings with UBOS’s AI marketing agents to automatically trigger personalized email campaigns, or feed the data into the Enterprise AI platform by UBOS for advanced analytics and predictive modeling.
Happy coding, and may your webhook pipelines be ever‑responsive!
For further reading, see the original announcement of the OpenClaw webhook feature.