हस्ताक्षरित webhook पर WhatsApp मैसेज पाएं, अपने ही कोड से आम सवालों के जवाब दें, और जब ग्राहक किसी व्यक्ति से बात करना चाहे तो चैट उसे सौंप दें।
इस गाइड में आप एक छोटा WhatsApp बॉट बनाते हैं जो आपके खुलने के समय और कीमतों के बारे में सवालों के जवाब देता है, और जब ग्राहक किसी व्यक्ति से बात करना चाहे तो चैट उसे सौंप देता है।
ग्राहक को क्या दिखता है: वे आपके WhatsApp नंबर पर लिखते हैं, उनके मैसेज पर नीले टिक आते हैं, "typing..." दिखता है, और एक सेकंड बाद जवाब आ जाता है। जब वे "can I talk to a person?" लिखते हैं, तो बॉट कहता है कि कोई व्यक्ति जवाब देगा, और उसके बाद केवल आपकी टीम जवाब देती है।
आपको क्या दिखता है: हर मैसेज और जवाब app2email के Inbox और Activity Log में, हर जवाब के डिलीवरी और रीड टिक webhook इवेंट के रूप में, और बॉट के चैट सौंपने पर चैट का सारांश।
बॉट Node.js (Express) या Python (Flask) में 100 लाइन से कम का है। यह webhook का हस्ताक्षर जांचता है, उन इवेंट को अनदेखा करता है जिन्हें वह पहले संभाल चुका है, सुरक्षित तरीके से दोबारा कोशिश करता है और 24 घंटे की जवाब विंडो का सम्मान करता है।
message.received के साथ एक हस्ताक्षरित POST भेजता है।POST /messages से जवाब भेजता है।message.status इवेंट भेजता है।आपके URL को 10 सेकंड के भीतर 2xx स्टेटस से जवाब देना होगा। अगर वह नहीं देता, तो app2email वही इवेंट बाद में दोबारा भेजता है, इसलिए थोड़ी देर की गड़बड़ी से कुछ नहीं खोता।
plan_not_allowed आता है; रुकी हुई सेवा पर 403 service_not_live। देखें शुरू करना।| Scope | बॉट को इसकी ज़रूरत क्यों है |
|---|---|
messages:send | जवाब भेजना (POST /messages), मैसेज को पढ़ा हुआ चिह्नित करना (POST /messages/read), चैट किसी व्यक्ति को सौंपना (PUT /conversations/{contact}/owner) |
messages:read | बातचीत को देखना: owner और जवाब विंडो (GET /conversations/{contact}) |
webhooks:manage | webhook को एक बार रजिस्टर करना (POST /webhooks)। आप इसे बिना कोड के API key पेज पर Webhooks के अंतर्गत भी जोड़ सकते हैं |
लाइव जाने से पहले आज़माएं। एक sandbox key (sandbox फ़्लैग वाली key, जो API key पेज पर बनती है) हर जांच आपके अपने नंबर पर चलाती है और WhatsApp को कुछ नहीं भेजती: जवाबों में "sandbox": true और wamid.SANDBOX. से शुरू होने वाले मैसेज id होते हैं, और message.status इवेंट फिर भी आते हैं। बिना किसी अकाउंट के, तुरंत मिलने वाला sandbox नकली ग्राहकों के साथ डेमो नंबर 12025550100 की key देता है: POST https://api.app2email.com/v1/account/sandbox (बिना key, बिना body) या Management MCP सर्वर का create_sandbox टूल। इसमें webhooks नहीं हैं: इवेंट इसके बजाय GET /events?wait=25 से पढ़ें (FAQ देखें)। विवरण: Sandbox।
GET /me किसी भी वैध key के साथ काम करता है और उसके scopes और सीमाएं दिखाता है। हर रिक्वेस्ट में YOUR_NUMBER वह WhatsApp नंबर है जिससे आप भेजते हैं: पहले देश कोड, सिर्फ़ अंक।
curl https://api.app2email.com/v1/YOUR_NUMBER/me \
-H "Authorization: Bearer YOUR_API_KEY"const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/me", {
headers: { Authorization: `Bearer ${process.env.API_KEY}` },
});
console.log(await res.json());import os, requests
res = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/me",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"}, timeout=10)
print(res.json())जवाब में आपको क्या मिलता है:
{
"success": true,
"request_id": "a7k3p",
"key_valid": true,
"api_version": "v1",
"number": "4976659348270",
"plan": "standard_5000",
"service_status": "LIVE",
"key": { "name": "WhatsApp bot", "scopes": ["messages:read", "messages:send"], "ip_allow": "" },
"limits": { "max_numbers_per_request": 1000, "requests_per_second": 20, "burst": 50, "rate_limit_mode": "enforce", "webhooks_max": 5 }
}service_status का LIVE होना ज़रूरी है, और key.scopes में ऊपर की तालिका के scopes होने चाहिए (या पूरी पहुंच के लिए *)।
app2email इवेंट केवल सार्वजनिक https पते पर भेज सकता है। विकास के दौरान, एक टनल आपके कंप्यूटर तक एक पता पहुंचा देता है। बॉट को पोर्ट 3000 पर शुरू करें (कोड नीचे है), फिर दूसरे टर्मिनल में:
# ngrok (https://ngrok.com)
ngrok http 3000
# or Cloudflare's cloudflared, no account needed for a quick tunnel
cloudflared tunnel --url http://localhost:3000दोनों एक https पता दिखाते हैं, जैसे https://a1b2-203-0-113-7.ngrok-free.app। आपका webhook URL वह पता और /webhook है। हो सकता है कि क्विक टनल हर बार शुरू होने पर नया पता दे: ऐसा होने पर PATCH /webhooks/{id} और नए url से webhook को अपडेट करें।
टनल संभव नहीं है? GET /events?wait=25 बिना सार्वजनिक पते के वही इवेंट ले आता है (FAQ देखें)।
एक कॉल। जवाब में signing secret (whsec_...) होता है जो हर इवेंट पर हस्ताक्षर करता है: इसे अपनी key के साथ रखें, जैसे एनवायरनमेंट वेरिएबल WEBHOOK_SECRET में।
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/webhooks", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://a1b2-203-0-113-7.ngrok-free.app/webhook" }),
});
const { webhook } = await res.json();
console.log(webhook.id, webhook.secret);import os, requests
res = requests.post("https://api.app2email.com/v1/YOUR_NUMBER/webhooks",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}, timeout=10)
webhook = res.json()["webhook"]
print(webhook["id"], webhook["secret"])जवाब में आपको क्या मिलता है (201 Created; छोटा किया गया: जवाब events में हर इवेंट प्रकार भी सूचीबद्ध करता है):
{
"success": true,
"request_id": "w8hk2",
"webhook": {
"id": "wh_a1b2c3d4e5f6g7h8",
"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook",
"secret": "whsec_...",
"created": "2026-11-21T09:00:00.000Z",
"active": true,
"format": "app2email"
}
}वही URL दोबारा रजिस्टर करने पर 200 के साथ वही id और secret मिलता है, इसलिए यह कॉल दोहराना सुरक्षित है। एक नंबर पर अधिकतम 5 webhooks हो सकते हैं, और हर webhook को हर इवेंट मिलता है: आपका कोड type से अपने संभाले जाने वाले प्रकार चुनता है और बाकी के लिए 2xx से जवाब देता है। इस गाइड के लिए format को app2email (डिफ़ॉल्ट) पर रखें।
POST /webhooks/{id}/test तुरंत एक हस्ताक्षरित नमूना भेजता है और बताता है कि आपके URL ने क्या जवाब दिया। {"type": "message.received"} के साथ आपको उसी इवेंट का नमूना मिलता है।
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks/wh_a1b2c3d4e5f6g7h8/test \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"type": "message.received"}'जवाब में आपको क्या मिलता है (छोटा किया गया):
{
"success": true,
"request_id": "t3ws9",
"delivered": true,
"http_status": 200,
"response_ms": 38
}delivered: true का मतलब है कि आपके URL ने 10 सेकंड के भीतर 2xx से जवाब दिया। टेस्ट इवेंट में "test": true और हेडर X-App2email-Test: true होता है, और उसका नमूना संपर्क गढ़ा हुआ होता है, इसलिए नीचे का बॉट हस्ताक्षर जांचता है, इवेंट को लॉग करता है और उसका जवाब नहीं देता। प्रति नंबर एक घंटे में 30 टेस्ट तक। फिर अपने ही फ़ोन से अपने नंबर पर एक असली मैसेज भेजें: बॉट जवाब देगा।
हर कॉल Authorization: Bearer YOUR_API_KEY के साथ https://api.app2email.com/v1/YOUR_NUMBER पर जाती है।
यह उस message.received इवेंट की body है जो आपके URL को मिलता है (एक टेक्स्ट मैसेज):
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "message.received",
"created": "2026-11-06T01:00:00.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"from": "61412345678",
"name": "Sample Contact",
"type": "text",
"text": "What are your opening hours?",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
"timestamp": "2026-11-06T01:00:00.000Z",
"from_user_id": "AU.1234567890123456"
}
}id (हेडर X-App2email-Delivery में भी) हर दोबारा कोशिश पर वही रहता है: इसी से आप डुप्लिकेट हटाते हैं।data.from ग्राहक का नंबर है। जो संपर्क WhatsApp username इस्तेमाल करता है, उसके साथ from_user_id आ सकता है और नंबर नहीं: यह id हर उस जगह काम करता है जहां नंबर काम करता है।data.type इनमें से एक है: text, image, audio, interactive (रिप्लाई बटन या सूची की किसी पंक्ति पर टैप, interactive.id के साथ), button (टेम्पलेट के क्विक रिप्लाई बटन पर, button.payload के साथ), और भी। बॉट टेक्स्ट और टैप का जवाब देता है और बाकी सब आपकी टीम पर छोड़ देता है।GET /conversations/{contact} (scope messages:read) बताता है कि चैट कौन संभाल रहा है और क्या अभी सादा जवाब भेजा जा सकता है।
curl https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678 \
-H "Authorization: Bearer YOUR_API_KEY"जवाब में आपको क्या मिलता है:
{
"success": true,
"request_id": "c9slm",
"contact": "61412345678",
"identity_type": "phone",
"phone": "61412345678",
"name": "John",
"window_state": "open",
"window_open": true,
"window_closes_at": "2026-11-07T00:45:00Z",
"last_inbound_at": "2026-11-06T01:00:00Z",
"messages": 12,
"owner": "",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}सामान्य संचालन में owner खाली रहता है। जब यह human या paused होता है, तब चैट किसी व्यक्ति के पास होती है और बॉट चुप रहता है; whatsapp_ai का मतलब है कि WhatsApp का अपना AI एजेंट उसे संभाल रहा है।
POST /messages/read (scope messages:send) मैसेज को पढ़ा हुआ चिह्नित करता है और, "typing": true के साथ, typing संकेतक को 25 सेकंड तक या आपका जवाब आने तक दिखाता है। यह मुफ़्त है: आपके प्लान में नहीं गिना जाता, और 24 घंटे की विंडो से बंधा नहीं है।
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages/read \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=", "typing": true}'जवाब में आपको क्या मिलता है:
{
"success": true,
"request_id": "k2rdq",
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"status": "read",
"typing_indicator": true
}POST /messages (scope messages:send) "type": "text" के साथ, जवाब विंडो खुली रहने पर, एक संपर्क को सादा मैसेज भेजता है।
| हिस्सा | क्या भरें |
|---|---|
| किसे | to: ग्राहक का नंबर (data.from), या उनका from_user_id |
| कौन-सा मैसेज | type: सामान्य जवाब के लिए text। विंडो के बाहर: template |
| वह क्या कहता है | text.body: आपका जवाब। text.preview_url: लिंक का प्रीव्यू दिखाने के लिए true |
| आपकी key | हेडर Authorization: Bearer YOUR_API_KEY |
| दोहराव नहीं | हेडर Idempotency-Key: इस जवाब के लिए अनोखा मान, जैसे text- और ग्राहक का message_id। 24 घंटे के भीतर वही key वाली वही रिक्वेस्ट दोबारा नहीं भेजी जाती |
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: text-wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=" \
-d '{"to": "61412345678", "type": "text", "text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": false}}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": `text-${messageId}`,
},
body: JSON.stringify({
to: "61412345678",
type: "text",
text: { body: "We are open Monday to Friday, 9 am to 5 pm.", preview_url: false },
}),
});
console.log(res.status, await res.json());res = requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/messages",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": f"text-{message_id}"},
json={"to": "61412345678", "type": "text",
"text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": False}},
timeout=10,
)
print(res.status_code, res.json())जवाब में आपको क्या मिलता है (200):
{
"success": true,
"request_id": "kxrkf",
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"status": "accepted",
"type": "text",
"from": "4976659348270",
"to": "61412345678",
"window_closes_at": "2026-11-07T00:45:00Z",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
"contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
}accepted का मतलब है कि WhatsApp ने मैसेज ले लिया। वह डिलीवर हुआ और पढ़ा गया या नहीं, यह बाद में message.status इवेंट के रूप में आता है। उसी Idempotency-Key के साथ दोहराई गई रिक्वेस्ट को यही जवाब फिर से मिलता है, हेडर Idempotent-Replayed: true के साथ, और कुछ भी दो बार नहीं भेजा जाता।
जब यह विफल होता है, तो जवाब में success: false और एक error ऑब्जेक्ट होता है। निर्णय error.code से लें, मैसेज के टेक्स्ट से कभी नहीं:
{
"success": false,
"request_id": "q2v8n",
"error": {
"code": "outside_24h_window",
"message": "The contact has not written to this number in the last 24 hours (or never), so only a template message can be sent.",
"how_to_fix": "Send an approved template message instead (\"type\": \"template\"). When the contact answers, normal messages work again for 24 hours.",
"documentation_url": "https://www.app2email.com/docs/api/errors#outside_24h_window",
"is_retriable": false
}
}बहुत ज़्यादा कॉल करने पर Retry-After हेडर के साथ 429 rate_limited आता है:
HTTP/1.1 429 Too Many Requests
Retry-After: 2
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 2
{"success": false, "request_id": "r5lmt", "error": {"code": "rate_limited", "message": "Too many requests for this key.", "how_to_fix": "Wait, then send again.", "documentation_url": "https://www.app2email.com/docs/api/errors#rate_limited", "is_retriable": true, "retry_after_seconds": 2}}जब ग्राहक किसी व्यक्ति से बात करना चाहे, तो PUT /conversations/{contact}/owner (scope messages:send) का इस्तेमाल करें, "owner": "human", एक छोटे reason और एक summary के साथ। तब app2email का ऑटो रिप्लाई और दूसरे एजेंट उस संपर्क को अकेला छोड़ देते हैं, जिन लोगों को मैसेज ईमेल से मिलते हैं वे सारांश देखते हैं, और हर webhook को conversation.owner_changed मिलता है। until_minutes इसे अस्थायी बनाता है: उसके बाद चैट अपने आप सामान्य संचालन पर लौट आती है।
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"owner": "human", "reason": "customer asked for a person", "summary": "Wants to move the delivery to Monday.", "until_minutes": 240}'जवाब में अपडेट की गई conversation होती है (वही फ़ील्ड जो GET /conversations/{contact} में होते हैं)।
दोनों संस्करण एक ही काम करते हैं: हस्ताक्षर सत्यापित करना, टेस्ट इवेंट और पहले संभाले जा चुके इवेंट छोड़ना, जिन चैट का owner कोई व्यक्ति है उन्हें छोड़ना, typing के साथ पढ़ा हुआ चिह्नित करना, "person" पर चैट सौंपना, कीवर्ड का जवाब देना, और विंडो बंद होने पर टेम्पलेट पर लौटना। पहले तीन एनवायरनमेंट वेरिएबल सेट करें: NUMBER (आपका WhatsApp नंबर, अंक), API_KEY और WEBHOOK_SECRET (चरण 3 का whsec_... मान)।
// Node.js 18 or newer. npm install express then node bot.mjs
import crypto from "node:crypto";
import express from "express";
const { NUMBER, API_KEY, WEBHOOK_SECRET, PORT = 3000 } = process.env;
const API = `https://api.app2email.com/v1/${NUMBER}`;
const FALLBACK = { name: "hello_world", language: { code: "en_US" } }; // an approved template without placeholders
const RETRY_LATER = new Set(["rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"]);
const done = new Set(); // handled event ids: use a database table or Redis in production
const ANSWERS = [
[/\b(hours?|open|opening|closed)\b/i, "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."],
[/\b(prices?|cost|how much)\b/i, "A standard service is $49, an express service $79. Full list: https://example.com/prices"],
];
const HUMAN = /\b(human|person|someone|staff)\b/i;
const MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team.";
function verify(raw, header, secret) {
const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]); // two during a secret change
if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = crypto.createHmac("sha256", secret).update(t + ".").update(raw).digest("hex");
return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}
async function api(method, path, body, idempotencyKey) {
for (let attempt = 1; ; attempt++) {
const res = await fetch(API + path, {
method,
signal: AbortSignal.timeout(4000),
headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json",
...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}) },
body: body ? JSON.stringify(body) : undefined,
});
const json = await res.json();
if (res.ok) return json;
const code = json.error?.code;
const wait = Number(res.headers.get("Retry-After") ?? 1);
if (code === "rate_limited" && attempt < 3 && wait <= 3) { await new Promise((r) => setTimeout(r, wait * 1000)); continue; }
if (res.status >= 500 || RETRY_LATER.has(code)) throw new Error(`${code} ${json.request_id}`);
console.warn(method, path, code, json.error?.how_to_fix, json.request_id);
return json;
}
}
async function reply(to, windowOpen, body, inReplyTo) {
if (windowOpen) {
const sent = await api("POST", "/messages", { to, type: "text", text: { body } }, `text-${inReplyTo}`);
if (sent.error?.code !== "outside_24h_window") return sent;
}
return api("POST", "/messages", { to, type: "template", template: FALLBACK }, `tpl-${inReplyTo}`);
}
async function handle(m) {
if (!["text", "interactive", "button"].includes(m.type)) return; // photos, voice notes ...: for the team
const contact = encodeURIComponent(m.from || m.from_user_id);
const text = m.interactive?.id || m.button?.payload || m.text || "";
const conv = await api("GET", `/conversations/${contact}`);
if (["human", "paused", "whatsapp_ai"].includes(conv.owner)) return; // someone else has this chat
await api("POST", "/messages/read", { message_id: m.message_id, typing: true });
const open = conv.window_open !== false;
if (HUMAN.test(text)) {
await api("PUT", `/conversations/${contact}/owner`, {
owner: "human", reason: "customer asked for a person", summary: text.slice(0, 300), until_minutes: 240 });
return reply(m.from || m.from_user_id, open, "Thanks! A person from our team will answer you here soon.", m.message_id);
}
const hit = ANSWERS.find(([pattern]) => pattern.test(text));
return reply(m.from || m.from_user_id, open, hit ? hit[1] : MENU, m.message_id);
}
const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
if (!verify(req.body, req.get("X-App2email-Signature"), WEBHOOK_SECRET)) return res.sendStatus(401);
const event = JSON.parse(req.body);
if (event.test) { console.log("test event ok:", event.type); return res.sendStatus(200); }
if (event.type !== "message.received" || done.has(event.id)) return res.sendStatus(200);
try {
await handle(event.data);
done.add(event.id); // only after it worked: a failed event comes again
res.sendStatus(200);
} catch (err) {
console.error("not handled, app2email will send it again:", event.id, err.message);
res.sendStatus(503);
}
});
app.listen(PORT, () => console.log(`bot on http://localhost:${PORT}/webhook`));# Python 3.9 or newer. pip install flask requests then flask --app bot run --port 3000
import hashlib, hmac, json, os, re, time
import requests
from flask import Flask, request
NUMBER, API_KEY, SECRET = os.environ["NUMBER"], os.environ["API_KEY"], os.environ["WEBHOOK_SECRET"]
API = f"https://api.app2email.com/v1/{NUMBER}"
FALLBACK = {"name": "hello_world", "language": {"code": "en_US"}} # an approved template without placeholders
RETRY_LATER = {"rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"}
done = set() # handled event ids: use a database table or Redis in production
ANSWERS = [
(re.compile(r"\b(hours?|open|opening|closed)\b", re.I), "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."),
(re.compile(r"\b(prices?|cost|how much)\b", re.I), "A standard service is $49, an express service $79. Full list: https://example.com/prices"),
]
HUMAN = re.compile(r"\b(human|person|someone|staff)\b", re.I)
MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team."
def verify(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "") # two during a secret change
if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
return False
expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(v, expected) for v in v1)
def api(method, path, body=None, idempotency_key=None):
headers = {"Authorization": f"Bearer {API_KEY}"}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
for attempt in (1, 2, 3):
res = requests.request(method, API + path, json=body, headers=headers, timeout=4)
data = res.json()
if res.ok:
return data
code = data.get("error", {}).get("code")
wait = int(res.headers.get("Retry-After", "1"))
if code == "rate_limited" and attempt < 3 and wait <= 3:
time.sleep(wait)
continue
if res.status_code >= 500 or code in RETRY_LATER:
raise RuntimeError(f"{code} {data.get('request_id')}")
print("not done:", method, path, code, data.get("error", {}).get("how_to_fix"), data.get("request_id"))
return data
def reply(to, window_open, body, in_reply_to):
if window_open:
sent = api("POST", "/messages", {"to": to, "type": "text", "text": {"body": body}}, f"text-{in_reply_to}")
if sent.get("error", {}).get("code") != "outside_24h_window":
return sent
return api("POST", "/messages", {"to": to, "type": "template", "template": FALLBACK}, f"tpl-{in_reply_to}")
def handle(m):
if m.get("type") not in ("text", "interactive", "button"):
return # photos, voice notes ...: for the team
contact = m.get("from") or m.get("from_user_id")
text = (m.get("interactive") or {}).get("id") or (m.get("button") or {}).get("payload") or m.get("text") or ""
conv = api("GET", f"/conversations/{contact}")
if conv.get("owner") in ("human", "paused", "whatsapp_ai"):
return # someone else has this chat
api("POST", "/messages/read", {"message_id": m["message_id"], "typing": True})
window_open = conv.get("window_open") is not False
if HUMAN.search(text):
api("PUT", f"/conversations/{contact}/owner", {"owner": "human", "reason": "customer asked for a person",
"summary": text[:300], "until_minutes": 240})
return reply(contact, window_open, "Thanks! A person from our team will answer you here soon.", m["message_id"])
answer = next((a for pattern, a in ANSWERS if pattern.search(text)), MENU)
return reply(contact, window_open, answer, m["message_id"])
app = Flask(__name__)
@app.post("/webhook")
def webhook():
raw = request.get_data()
if not verify(raw, request.headers.get("X-App2email-Signature"), SECRET):
return "bad signature", 401
event = json.loads(raw)
if event.get("test"):
print("test event ok:", event["type"])
return "", 200
if event["type"] != "message.received" or event["id"] in done:
return "", 200
try:
handle(event["data"])
except Exception as err:
print("not handled, app2email will send it again:", event["id"], err)
return "", 503
done.add(event["id"]) # only after it worked: a failed event comes again
return "", 200यह ऐसे क्यों बना है:
express.raw, request.get_data())।Idempotency-Key यह सुनिश्चित करती है कि दोबारा कोशिश कभी वही जवाब दो बार न भेजे, तब भी जब पहली कोशिश भेजने तक पहुंच गई हो।rate_limited का इंतज़ार रिक्वेस्ट के भीतर ही किया जाता है (अधिकतम 3 सेकंड, ताकि 10 सेकंड की सीमा बनी रहे)। इससे लंबी कोई भी चीज़ app2email की दोबारा कोशिशों पर छोड़ दी जाती है।how_to_fix और request_id के साथ लॉग किया जाता है, और इवेंट का जवाब 200 से दिया जाता है ताकि वह बार-बार न आता रहे।FALLBACK hello_world है क्योंकि तुरंत मिलने वाले sandbox में वह है। अपने नंबर पर, अपने किसी मंज़ूर टेम्पलेट का नाम और भाषा डालें (GET /templates उन्हें सूचीबद्ध करता है, हर एक के पूरे example_request के साथ)।message.status मिलता है: sent, फिर delivered, फिर read।{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs02",
"type": "message.status",
"created": "2026-11-06T01:00:03.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"to": "61412345678",
"status": "delivered",
"timestamp": "2026-11-06T01:00:03.000Z",
"sent_by": "api",
"whatsapp_status": "delivered"
}
}विफल जवाब status: "failed" और एक error ऑब्जेक्ट के साथ message.status के रूप में आता है (code Meta का कोड है, error_code app2email का), और message.failed के रूप में भी।
जब ग्राहक लिखता है "can I talk to a person?", तो उसे "A person from our team will answer you here soon" मिलता है, और आपके webhook को यह मिलता है:
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs03",
"type": "conversation.owner_changed",
"created": "2026-11-06T01:02:00.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"owner": "human",
"previous_owner": "",
"reason": "customer asked for a person",
"summary": "can I talk to a person?",
"until": "2026-11-06T05:02:00.000Z",
"set_by": "api",
"timestamp": "2026-11-06T01:02:00.000Z"
}
}कोई व्यक्ति Inbox से, ईमेल से, या API से जवाब देता है। बॉट अगले मैसेज पर owner human देखता है और चुप रहता है।
बॉट के पास वापसी: until_minutes के बाद owner अपने आप फिर खाली हो जाता है। कोई व्यक्ति PUT /conversations/{contact}/owner और {"owner": ""} से चैट पहले भी लौटा सकता है, जो conversation.owner_changed फिर भेजता है। जब चैट किसी व्यक्ति के पास हो, तब कोड से उसे वापस न लें।
WhatsApp आपको ग्राहक के आखिरी मैसेज के 24 घंटे बाद तक सादे मैसेज (टेक्स्ट, चित्र, बटन) भेजने देता है। app2email 15 मिनट पहले रोक देता है; window_closes_at सटीक समय है। उसके बाद केवल मंज़ूर किया हुआ टेम्पलेट ही बातचीत दोबारा शुरू कर सकता है।
जो बॉट सेकंडों में जवाब देता है, वह लगभग हमेशा विंडो के भीतर होता है। यह तब मायने रखता है जब कोई इवेंट देर से डिलीवर हो: दोबारा कोशिशें लगभग 32 घंटे चलती हैं, इसलिए कल के मैसेज के जवाब के लिए टेम्पलेट चाहिए हो सकता है। बॉट लिखने से पहले window_open जांचता है, और अगर भेजने पर 422 outside_24h_window आए तब भी टेम्पलेट पर लौट आता है।
Do Not Call सूची सादे जवाबों पर लागू नहीं होती, क्योंकि ग्राहक ने आपको लिखा है। अपवाद: जब उनका आखिरी मैसेज खुद ऑप्ट-आउट था, तब जवाब देने पर 403 recipient_opted_out आता है, जब तक वे दोबारा न लिखें।
हर इवेंट सत्यापित करें। हेडर X-App2email-Signature है t=<unix seconds>,v1=<hex>: यह टेक्स्ट t, एक बिंदु और कच्ची body का HMAC-SHA256 है, जिसमें webhook का secret (whsec_..., उपसर्ग समेत) key है। हर v1= जांचें (POST /webhooks/{id}/rotate-secret और keep_old_for_hours के बाद कुछ समय तक दो होते हैं), तुलना constant time में करें, और 5 मिनट से पुराने t को अस्वीकार करें। अगर आपका कोड पहले से Meta के webhooks जांचता है, तो X-Hub-Signature-256 (sha256= और कच्ची body का HMAC-SHA256, जैसा Meta हस्ताक्षर करता है) भी मौजूद है; इसमें समय नहीं होता और केवल मौजूदा secret होता है।
जल्दी जवाब दें। 10 सेकंड के भीतर 2xx लौटाएं। रीडायरेक्ट का पालन नहीं किया जाता। धीमे काम (डेटाबेस, AI मॉडल) के लिए, इवेंट को स्टोर करें, 200 से जवाब दें, और उसे ऐसी कतार से प्रोसेस करें जो अपने आप दोबारा कोशिश करती है।
डुप्लिकेट हटाएं। हर संभाले गए इवेंट का id (X-App2email-Delivery) कम से कम दो दिन रखें: दोबारा कोशिशें लगभग 32 घंटे चलती हैं। एक से ज़्यादा प्रोसेस चलाते समय इसे मेमोरी में नहीं, डेटाबेस या Redis में रखें। इवेंट क्रम से बाहर भी आ सकते हैं: data.timestamp इस्तेमाल करें, उनके आने का क्रम नहीं।
हर जवाब एक ही बार भेजें। हर POST /messages को ग्राहक के message_id से बनी Idempotency-Key दें। वही key और वही body 24 घंटे के भीतर: पहला जवाब Idempotent-Replayed: true के साथ लौटता है। वही key, दूसरी body: 422 idempotency_key_reused। 409 idempotency_request_in_progress: रुकें और उसी key से दोबारा कोशिश करें।
सीमाओं का सम्मान करें। हर जवाब में X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (दोबारा पूरा होने तक के सेकंड) और X-RateLimit-Policy होते हैं; GET /me आपकी key के limits दिखाता है। सीमा पार करने पर: Retry-After और error.retry_after_seconds के साथ 429 rate_limited। WhatsApp की अपनी सीमाओं (429 whatsapp_rate_limit, too_many_messages_to_recipient) में सेकंड नहीं, मिनट लगते हैं। 429 monthly_limit_reached और daily_cap_reached पर अभी दोबारा कोशिश करना बेकार है (retry_after_seconds बताता है कि कब तक): किसी व्यक्ति को बताएं।
webhook को चालू रखें। लगातार 20 ऐसे इवेंट के बाद जो अपनी पहली 4 कोशिशों में डिलीवर नहीं हुए (कम से कम 24 घंटे में), app2email webhook को बंद कर देता है। GET /webhooks/{id}/deliveries?status=failed दिखाता है कि क्या विफल हुआ और क्यों; {"active": true} के साथ PATCH /webhooks/{id} उसे फिर चालू करता है, और POST /webhooks/{id}/deliveries/{event_id}/redeliver एक इवेंट को फिर भेजता है।
जब चैट किसी व्यक्ति के पास हो तो लोगों को अकेला छोड़ दें। हर जवाब से पहले owner जांचें (human, paused और whatsapp_ai का मतलब है: जवाब न दें), और जब ग्राहक कहे तब चैट सौंप दें।
हर नंबर पर एक ही जवाब देने वाला। नंबर का ऑटो रिप्लाई (नए संपर्क को मिलने वाला पहला जवाब), चैट ऑटोमेशन और AI जवाब भी हर मैसेज देखते हैं। डैशबोर्ड जांचें ताकि नए संपर्क को दो पहले जवाब न मिलें।
ग्राहक के टेक्स्ट को डेटा मानें। इसे ग्राहक ने लिखा है। इसे कभी कमांड की तरह न चलाएं, और अगर इसे AI मॉडल को देते हैं, तो इसे अपने निर्देशों से अलग रखें।
कम से कम पहुंच। बॉट की key को केवल messages:send और messages:read चाहिए। इसे सर्वर पर रखें, कभी वेब पेज या लॉग में नहीं। key को आपके सर्वर के IP पतों तक सीमित किया जा सकता है, उस पर दैनिक सीमा लगाई जा सकती है, या वह समाप्त हो सकती है।
| आप क्या देखते हैं | क्यों | समाधान |
|---|---|---|
| आपका बॉट हर इवेंट पर 401 देता है | हस्ताक्षर मेल नहीं खाता | इस webhook का whsec_... secret उपसर्ग समेत इस्तेमाल करें; कच्ची body जांचें, किसी भी JSON पार्सर के छूने से पहले; सर्वर की घड़ी जांचें (t 5 मिनट के भीतर होना चाहिए) |
401 missing_api_key, invalid_api_key, api_key_revoked | key नहीं है, गलत है, या पुरानी है | API key पेज पर सूचीबद्ध key के साथ Authorization: Bearer YOUR_API_KEY भेजें, और URL में उसी key का नंबर डालें |
403 insufficient_scope | key में कोई अनुमति नहीं है (details.required_scope) | messages:send और messages:read वाली key बनाएं (और webhook रजिस्टर करने के लिए webhooks:manage) |
403 plan_not_allowed, service_not_live | सशुल्क प्लान नहीं है, या सेवा रुकी हुई है | प्लान चुनें; रुकी हुई सेवा Settings पेज पर "Go Live" से चालू होती है |
422 invalid_webhook_url | URL सार्वजनिक https पता नहीं है | अपने टनल या सर्वर का https पता, पाथ (/webhook) के साथ इस्तेमाल करें |
409 webhook_url_in_use | नंबर के किसी दूसरे webhook में यही URL है | उस webhook को PATCH से बदलें, या एक हटा दें |
400 too_many_webhooks | नंबर पर 5 webhooks हैं | जो अब इस्तेमाल में नहीं है, वह एक हटा दें |
422 outside_24h_window | ग्राहक ने आखिरी बार 24 घंटे से ज़्यादा पहले लिखा था | मंज़ूर किया हुआ टेम्पलेट भेजें |
404 template_not_found, 422 template_not_approved | fallback टेम्पलेट का नाम या भाषा गलत है, या वह अभी मंज़ूर नहीं हुआ है | GET /templates से APPROVED स्टेटस वाला एक चुनें |
422 template_parameters_invalid | fallback टेम्पलेट में प्लेसहोल्डर हैं | बिना प्लेसहोल्डर वाला इस्तेमाल करें, या उन्हें वैसे भरें जैसा उसका example_request दिखाता है |
403 recipient_opted_out | ग्राहक का आखिरी मैसेज ऑप्ट-आउट था | जब तक वे दोबारा न लिखें, जवाब न दें |
429 rate_limited | इस key के लिए बहुत ज़्यादा कॉल | Retry-After सेकंड रुकें, फिर दोबारा कोशिश करें |
429 whatsapp_rate_limit, too_many_messages_to_recipient | WhatsApp की सीमा | कुछ मिनट रुकें |
429 too_many_tests | एक घंटे में 30 से ज़्यादा टेस्ट इवेंट | रुकें, या अपने फ़ोन से मैसेज भेजकर टेस्ट करें |
403 not_in_instant_sandbox | डेमो नंबर में यह कॉल नहीं है (जैसे webhooks) | वहां GET /events इस्तेमाल करें, या अपने नंबर पर sandbox key |
| कोई इवेंट आता ही नहीं | webhook बंद है, या टनल का पता बदल गया | GET /webhooks active और आखिरी डिलीवरी दिखाता है; नए url या {"active": true} के साथ PATCH करें |
हर जवाब में एक request_id होता है। GET /requests/{id} दिखाता है कि उसके लिए क्या लॉग हुआ, और support@app2email.com भी उसे ढूंढ सकता है। सभी कोड: त्रुटियां।
ai.answered और ai.handover रिपोर्ट करता है। यह ग्राहक को तभी जवाब देता है जब बातचीत का कोई owner न हो और किसी ऐप या ऑटोमेशन ने जवाब न दिया हो, इसलिए हर नंबर पर एक ही जवाब देने वाला चुनें। देखें AI जवाब की सेटिंग।https://api.app2email.com/mcp में वही कॉल टूल के रूप में हैं (send_text, mark_read, get_conversation, set_conversation_owner, list_events, wait_for_message ...)। देखें MCP से AI एजेंट को अपना WhatsApp चलाने दें और MCP।हां। POST https://api.app2email.com/v1/account/sandbox (बिना key, बिना body) डेमो नंबर 12025550100 के लिए तुरंत मिलने वाली sandbox key (a2es_..., 7 दिन वैध) लौटाता है। इसके नकली ग्राहकों में Ava (12025550101, हर मैसेज का जवाब देती है) और Eve (12025550105, किसी व्यक्ति को बुलाने को कहती है) शामिल हैं। इसमें GET /conversations/{contact}, PUT /conversations/{contact}/owner, POST /messages और GET /events हैं, इसलिए बॉट का तर्क वहां चलता है, और इसमें fallback के रूप में इस्तेमाल होने वाला hello_world टेम्पलेट है। इसमें webhooks नहीं हैं: इवेंट GET /events से पढ़ें (अगला सवाल)। POST /messages/read भी वहां नहीं है; वह 403 not_in_instant_sandbox लौटाता है, जिसे बॉट लॉग करके आगे बढ़ जाता है। WhatsApp तक कुछ नहीं पहुंचता।
हां: GET /events?wait=25 (scope messages:read) कोई इवेंट आने तक, 25 सेकंड तक, जवाब रोके रखता है। हर इवेंट वही JSON है जो webhook को मिलता है, उसी id के साथ। जवाब का cursor संभालकर रखें और अगली कॉल में उसे after के रूप में दें; जिन id को आप संभाल चुके हैं उन्हें छोड़ दें, क्योंकि जवाब खो जाने के बाद कोई इवेंट दोबारा आ सकता है। types=message.received केवल आने वाले मैसेज देता है। पहली कॉल नंबर की फ़ीड को चालू कर देती है; इवेंट 72 घंटे तक रखे जाते हैं।
let after = "now";
for (;;) {
const page = await api("GET", `/events?wait=25&types=message.received&after=${after}`);
for (const event of page.events ?? []) if (!done.has(event.id)) { await handle(event.data); done.add(event.id); }
after = page.cursor ?? after;
}हां, 24 घंटे की विंडो के भीतर। "type": "interactive" के साथ 3 रिप्लाई बटन तक, या 10 पंक्तियों तक की सूची भेजें। बटनों को वही id दें जिन्हें बॉट पहले से समझता है, और टैप message.received के रूप में type interactive और interactive.id के साथ आता है:
{
"to": "61412345678",
"type": "interactive",
"interactive": {
"type": "button",
"body": { "text": "What would you like to know?" },
"action": {
"buttons": [
{ "type": "reply", "reply": { "id": "hours", "title": "Opening hours" } },
{ "type": "reply", "reply": { "id": "prices", "title": "Prices" } },
{ "type": "reply", "reply": { "id": "person", "title": "Talk to a person" } }
]
}
}
}बॉट जो भी जवाब भेजता है, वह आपके app2email प्लान का एक मैसेज गिना जाता है। पढ़ा हुआ चिह्नित करना और typing संकेतक मुफ़्त हैं। Meta आपसे सीधे बिल करता है: विंडो के भीतर के जवाब सर्विस मैसेज हैं (प्रति नंबर महीने के पहले 1,000 मुफ़्त), टेम्पलेट प्रति मैसेज के हिसाब से लगते हैं। GET /usage दिखाता है कि इस महीने कितना इस्तेमाल हुआ और कितना बचा है, Meta की श्रेणियां meta_pricing में।
वे message.received के रूप में आते हैं, type image, audio, document और इसी तरह के साथ, और एक media_url के साथ: app2email एक कॉपी रखता है, जो GET /media/{message_id} से मिलती है। ऊपर का बॉट इन्हें आपकी टीम पर छोड़ देता है; आप चाहें तो ऐसा मैसेज आते ही चैट को सौंप भी सकते हैं।
डैशबोर्ड के Inbox से, ईमेल से (जब ईमेल फ़ॉरवर्डिंग चालू हो), या API से। until_minutes खत्म होने पर चैट बॉट के पास लौट जाती है, या उससे पहले PUT /conversations/{contact}/owner और {"owner": ""} से।
हां: "format": "meta" वाले webhook को WhatsApp से जो आता है वह Meta की अपनी body (entry[].changes[]) के रूप में मिलता है, उसी तरह हस्ताक्षरित। app2email के अपने इवेंट, जैसे conversation.owner_changed, app2email का लिफ़ाफ़ा रखते हैं। यह गाइड डिफ़ॉल्ट app2email फ़ॉर्मैट इस्तेमाल करती है।
WhatsApp, business-scoped user id (जैसे AU.1234567890123456) वाले username की ओर बढ़ रहा है। ऐसे इवेंट में from_user_id हो सकता है और from नहीं। id को to में डालें: यह हर उस जगह काम करता है जहां नंबर काम करता है, /conversations/{contact} समेत। ऊपर के बॉट पहले से ऐसा करते हैं।
पुष्टि और रिमाइंडर के लिए मंज़ूर किए गए utility टेम्पलेट, डिलीवरी स्टेटस के साथ।
एक सूची या सेगमेंट को एक टेम्पलेट, सहमति के रिकॉर्ड और Do Not Call सूची के साथ।
scoped keys और मंज़ूरियों के साथ Claude या किसी दूसरे एजेंट को अपने नंबर से जोड़ें।
आपकी टीम के लिए बातचीत के owner, असाइनमेंट, नोट्स और सारांश।
चैट में पेमेंट लिंक भेजें और पता चलें कि भुगतान हो गया।