API + MCP: complete setup guide
Yeh guide aapki doosri website ko is WhatsApp gateway se connect karne ke liye hai. Gateway URL: https://wacrmflow.online. Examples mein YOUR_KEY, YOUR_SESSION_ID aur recipient number ko apni values se replace karein. Agar gateway apne domain par host karein, sab examples mein gateway URL badlein.
1. Gateway aur API key setup
- Gateway dashboard mein login karein.
- Dashboard ke device/session section mein WhatsApp session banayein ya existing device open karein.
- Phone par WhatsApp → Linked devices → Link a device kholein aur dashboard ka QR scan karein. Session ka status CONNECTED hona chahiye.
- Webhooks & API page par Generate dabayein.
- API key turant copy karke apne password manager ya backend secret settings mein save karein. Key sirf ek baar dikhayi jaati hai.
- Existing integration chal rahi ho to bina zaroorat Regenerate na karein: purani key invalid ho jaayegi. Regenerate karne par sab connected websites ki saved key update karein.
Aapko teen values chahiye: gateway URL, API key, aur WhatsApp sessionId. Session ID step 3 mein API se milegi. Gateway ki key aapke account aur accessible WhatsApp sessions se associated hoti hai.
2. API ya MCP: kya choose karein?
| Aapka kaam | Use karein | Connection |
|---|---|---|
| Website se order update, support reply ya user-requested message | REST API | Backend → /api/... |
| AI assistant ko sessions, chats aur message tools dena | MCP | MCP client → /mcp |
| React / HTML page mein send button | Apna backend + REST API | Browser → aapka backend → gateway |
| WordPress, PHP, Laravel, Node.js ya serverless website | REST API | Server-side HTTPS request |
Recommended flow: Visitor → aapki website ka authenticated backend → WhatsApp gateway → connected WhatsApp device.
API key ko browser JavaScript, HTML, public GitHub repository, URL query string, NEXT_PUBLIC_... ya VITE_... variables mein na daalein. Sirf frontend/static website hai to pehle serverless function ya backend add karein. CORS enabled hone ka matlab key public rakhna safe nahi hai.
3. Backend variables aur first API test
Doosri website ke hosting dashboard mein Environment / Secrets section kholein. Render par Environment, ya apne hosting provider ke equivalent settings mein yeh values save karein:
GATEWAY_URL=https://wacrmflow.online
GATEWAY_API_KEY=YOUR_KEY
GATEWAY_SESSION_ID=YOUR_SESSION_IDLocal development mein server-side .env use kar sakte hain. File ko Git mein commit na karein. Settings save karne ke baad apni doosri website ka backend restart/redeploy karein.
Pehle sessions list karein
Neeche ke terminal examples Bash/Zsh ke liye hain. GATEWAY_URL aur GATEWAY_API_KEY environment mein available hone chahiye. .env file banane se shell variables automatically load nahi hote; apne runtime ka environment loader use karein.
curl --fail-with-body --max-time 60 \
"$GATEWAY_URL/api/sessions" \
-H "X-API-Key: $GATEWAY_API_KEY"Expected: HTTP 200, status: true, aur data array. Example response simplified hai; actual response mein aur fields bhi hote hain:
{
"status": true,
"data": [
{ "id": "database-record-id", "sessionId": "my-device", "status": "CONNECTED" }
]
}data se sessionId copy karein, id nahi. Isi value ko GATEWAY_SESSION_ID mein save karein. Empty array aaye to is account ka device create/connect karein ya session access check karein. 401 aaye to key/header verify karein.
4. Website se WhatsApp message bhejein
Recipient ka number country code ke saath use karein, jaise Indian number ke liye 91 + 10 digits. Individual chat ka JID NUMBER@s.whatsapp.net hota hai. Example number ko apne authorized test recipient se replace karein.
Endpoint: POST /api/messages/{sessionId}/{jid}/send
Header: X-API-Key: YOUR_KEY and Content-Type: application/json
Body: {"message":{"text":"Hello from my website"}}
Node.js backend example
Yeh server-side helper Node.js 22+ ke liye hai. Isse apne existing authenticated API route, order handler ya backend job se call karein. Yeh standalone public send route nahi banata.
const base = process.env.GATEWAY_URL.replace(/\/$/, '');
async function gateway(path, options = {}) {
const response = await fetch(base + path, {
...options,
redirect: 'error',
headers: {
'Content-Type': 'application/json',
'X-API-Key': process.env.GATEWAY_API_KEY,
},
signal: AbortSignal.timeout(60000),
});
const result = await response.json();
if (!response.ok || result.status === false) {
throw new Error(result.message || `Gateway HTTP ${response.status}`);
}
return result;
}
export async function sendWhatsAppText(phone, text) {
const digits = phone.replace(/\D/g, '');
if (!/^\d{8,15}$/.test(digits) || !text.trim()) {
throw new Error('Country code wala valid number aur message required hain');
}
const session = encodeURIComponent(process.env.GATEWAY_SESSION_ID);
const jid = encodeURIComponent(`${digits}@s.whatsapp.net`);
return gateway(`/api/messages/${session}/${jid}/send`, {
method: 'POST',
body: JSON.stringify({ message: { text } }),
});
}
// Apne backend mein user permission check ke baad call karein:
// await sendWhatsAppText('91XXXXXXXXXX', 'Aapka order confirm ho gaya hai.');PHP / Laravel server example
Hardened server-side helper. Supported, patched PHP release aur cURL extension use karein. Yeh helper sirf approved HTTPS gateway ko key bhejta hai; redirects follow nahi karta, certificates verify karta hai aur response size limit lagata hai. Server environment mein teen variables step 3 ke mutabik set karein.
Code ko web root ke bahar apne service/helper module mein rakhein. Laravel mein authenticated controller se, WordPress mein permission-checked server handler se call karein. Yeh function khud login, CSRF ya per-user authorization implement nahi karta; neeche diye controls apne endpoint mein lagana required hai.
<?php
declare(strict_types=1);
function sendWhatsAppText(string $phone, string $text): array
{
// Country code required. Letters/formatting silently remove nahi hote.
if (!preg_match('/\A\+?[1-9][0-9]{7,14}\z/', $phone)
|| trim($text) === '' || strlen($text) > 4096
|| preg_match('//u', $text) !== 1) {
throw new InvalidArgumentException('Valid phone and UTF-8 text required (max 4096 bytes)');
}
$base = rtrim((string) getenv('GATEWAY_URL'), '/');
$key = (string) getenv('GATEWAY_API_KEY');
$session = (string) getenv('GATEWAY_SESSION_ID');
// Trusted destination is code-owned; request/form se URL kabhi na lein.
// Apna gateway domain ho to review karke yeh exact origin badlein.
if ($base !== 'https://wacrmflow.online'
|| !preg_match('/\Awag_[A-Za-z0-9_-]{32}\z/', $key)
|| $session === '' || strlen($session) > 128
|| preg_match('/[\x00-\x20\x7f]/', $session)) {
throw new RuntimeException('Invalid gateway server configuration');
}
$jid = rawurlencode(ltrim($phone, '+') . '@s.whatsapp.net');
$url = $base . '/api/messages/' . rawurlencode($session) . '/' . $jid . '/send';
$payload = json_encode(['message' => ['text' => $text]], JSON_THROW_ON_ERROR);
$curl = curl_init($url);
if ($curl === false) throw new RuntimeException('Gateway unavailable');
$raw = '';
try {
$configured = curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json',
'X-API-Key: ' . $key,
],
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_MAXREDIRS => 0,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 60,
// Bound memory even if upstream sends an unexpectedly large body.
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$raw): int {
if (strlen($raw) + strlen($chunk) > 65536) return 0;
$raw .= $chunk;
return strlen($chunk);
},
]);
if (!$configured || curl_exec($curl) === false) {
// Message may already be sent: do not automatically retry.
throw new RuntimeException('Gateway connection failed; check send status before retry');
}
$status = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
$type = (string) curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
if ($status < 200 || $status >= 300
|| stripos($type, 'application/json') !== 0) {
throw new RuntimeException('Gateway request unsuccessful');
}
try {
$result = json_decode($raw, true, 16, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw new RuntimeException('Invalid gateway response');
}
if (!is_array($result) || ($result['status'] ?? null) !== true) {
throw new RuntimeException('Gateway request unsuccessful');
}
// Caller ko sirf necessary success flag; upstream details forward nahi hote.
return ['status' => true];
} finally {
curl_close($curl);
}
}
// Apne authenticated backend mein permission + CSRF + rate-limit checks ke baad:
// sendWhatsAppText('91XXXXXXXXXX', 'Hello from my website');PHP endpoint ko protect karna
- Authentication + ownership: Laravel ka authentication middleware / WordPress capability check use karein. Server par order/contact lookup karke verify karein ki current user ko is recipient par message bhejne ka access hai. Sirf valid phone number hona permission nahi hai.
- CSRF: Cookie-based login wale endpoint par framework ki CSRF protection enable rakhein. Laravel ke CSRF-protected web route ya WordPress nonce ke saath capability check use karein. Nonce login/permission ka replacement nahi hai. Send endpoint sirf POST accept kare.
- Rate limits: Apne backend par per-account/user send limits aur abuse controls lagayein. Gateway ki quota ke saath apne endpoint ko bhi protect karein; in-memory limit multi-instance hosting mein enough nahi hoti.
- Secrets:
.env, backups, SQL dumps aur logs public web root se bahar rakhein. Server ko dotfiles/backups serve karne se block karein. Key ko browser, error response, analytics ya request logs mein include na karein. Suspected exposure par gateway dashboard se key rotate karke har integration update karein. - Production errors:
display_errors=Offaur restricted server logging use karein. User ko generic failure aur request reference dein; raw exception, upstream body, token aur message content return/log na karein. - TLS + updates: Certificate verification kabhi disable na karein. CA trust store, PHP, libcurl, framework aur plugins updated rakhein. PHP version ka support status official support table par check karein.
- Minimum access: Website ke liye dedicated gateway account aur sirf required session access use karein. Har website ko SUPERADMIN key dene se bachein. Database access, backups aur deployment credentials bhi restrict karein.
Validation scope: Example mein outbound request protections hain; aapki actual PHP website ka login, database, web-server configuration aur installed plugins is gateway project mein available nahi hain. Unka security review alag chahiye. Kisi breach ki report se yeh establish nahi hota ki PHP hi uska cause tha.
cURL options reference: PHP official cURL documentation. Certificate verification pehle example mein cURL ke defaults par thi; ab explicitly set hai aur unsafe config reject hoti hai.
Frontend button ko connect karna
- Apni website par authenticated backend route banayein, jaise
POST /api/send-whatsapp. - Route mein logged-in user ki permission, recipient aur message validate karein. Apni website ki session authentication aur CSRF protection use karein.
- Us route ke andar upar diya server helper call karein. Rate limiting bhi lagayein.
- Browser button sirf apni website ke route ko call kare; gateway key browser tak nahi jaani chahiye.
- Success/error UI dikhayein. Message send karne ke baad timeout aaye to blindly retry na karein—message pehle hi deliver ho sakta hai.
API success gateway ke send operation ko confirm karta hai; recipient ne message read kiya ya final delivery hui, yeh alag status hai.
5. Postman ya curl se verify karein
Postman/API client mein GET request banayein: https://wacrmflow.online/api/sessions. Headers tab mein X-API-Key add karein; value apni key rakhein. Send par 200 milna chahiye.
Message test ke liye method POST, step 4 ka endpoint, aur Body → raw → JSON mein message.text bhejein. Yeh actual message bhejega; apna test number use karein.
Project source available ho to supplied checker bhi use kar sakte hain:
node scripts/check-integration.mjsEnvironment mein GATEWAY_URL aur GATEWAY_API_KEY required hain. Checker REST auth, invalid-key rejection, browser preflight aur MCP handshake/tools test karta hai. Yeh WhatsApp message send nahi karta. Restricted CORS_ALLOW_ORIGIN hone par checker ka example-origin probe fail ho sakta hai; backend requests CORS par depend nahi karti.
6. MCP AI assistant connect karein
MCP ek AI tool connection hai. Normal website mein notification bhejne ke liye MCP zaroori nahi; REST API enough hai. MCP use karein jab aapki website ka AI assistant gateway ke tools discover/call karna chahta ho.
MCP client mein settings
- Apne AI app ya website backend ke MCP client mein Add remote server / equivalent option kholein.
- Name:
WhatsApp Gateway. - Server URL:
https://wacrmflow.online/mcp. - Custom header add karein: name
Authorization, valueBearer YOUR_KEY. Alternative header:X-API-Key: YOUR_KEY. - Client mein supported HTTP transport choose karein. Server direct JSON-RPC POST aur legacy HTTP+SSE deta hai; advertised protocol
2024-11-05hai. Client ko is protocol/transport ke saath compatible hona chahiye. - Connect/refresh tools karein. Pehle
whatsapp_list_sessionscall karein. Message tool tabhi call karein jab user ne actual sending authorize ki ho.
Client compatibility: API-key clients remote URL + headers use kar sakte hain. ChatGPT ke liye OAuth authorization-code + PKCE S256 flow available hai. Har AI app mein transport aur authentication support verify karein; individual client connection tabhi verified hai jab tools scan aur read-only test pass ho.
ChatGPT mein OAuth se connect karein
- ChatGPT web mein Plugins → + → Add custom MCP server kholein (account/workspace permission required).
- Name
WA CRM Flow, Server URLhttps://wacrmflow.online/mcpdaalein. - Authentication OAuth select karein. Dynamic client registration (DCR / register automatically) use karein; client ID aur secret manually bharne ki zaroorat nahi hai.
- Discovery metadata se authorization URL aur token endpoint milenge. Is server mein issuer identification enabled hai; supported exact callback
https://chatgpt.com/connector_platform_oauth_redirecthai. Agar ChatGPT koi alag callback dikhaye, allowlist ko review karna hoga; URL mein key mat lagayein. - Apne WA CRM Flow account se login karein. Consent screen par read access review karke Allow access karein. Agar
mcp:sendscope request hua ho, sending ke liye separate checkbox tick karein.offline_accessrefresh-token connection deta hai. - ChatGPT mein tool scan complete karein, plugin install/enable karein, phir bolein: Mere WhatsApp sessions list karo; koi message send mat karo.
- Access band karne ke liye dashboard → AI Connections, ya
https://wacrmflow.online/oauth/connectionspar Disconnect karein.
Access tokens maximum 1 hour ke hain, connection maximum 30 days ka hai, refresh tokens har use par rotate hote hain. Reused refresh token connection revoke karta hai. Password change existing OAuth tokens invalidate karta hai. Admin users ke OAuth connection ko bhi global administrator access nahi milta—sirf owned/shared sessions. Read-only consent mein send tool available nahi hoga.
OAuth metadata: https://wacrmflow.online/.well-known/oauth-authorization-server aur https://wacrmflow.online/.well-known/oauth-protected-resource/mcp.
Official references: ChatGPT connection, OAuth authentication.
Website ke AI backend mein MCP connection/key server-side store karein. Website users ko apni application permissions ke mutabik tools access dein; shared admin key se sab visitors ko unrestricted tools access na dein.
MCP handshake manually test karein
curl --fail-with-body --max-time 60 "$GATEWAY_URL/mcp" \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"my-website","version":"1.0.0"}}}'Expected: result.protocolVersion, result.capabilities aur result.serverInfo. Normal MCP client initialization lifecycle khud manage karta hai. Manual test mein initialized notification bhejein:
curl --max-time 60 "$GATEWAY_URL/mcp" \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"notifications/initialized"}'Notification par 202 / empty body expected hai. Ab tools discover karein:
curl --fail-with-body --max-time 60 "$GATEWAY_URL/mcp" \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'Read-only tool call:
curl --fail-with-body --max-time 60 "$GATEWAY_URL/mcp" \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"whatsapp_list_sessions","arguments":{}}}'Result content array mein aata hai. HTTP 200 ke saath bhi JSON-RPC error ya result.isError: true ho sakta hai; AI integration mein dono check karein. SSE client pehle authenticated GET /mcp with Accept: text/event-stream karta hai, phir returned endpoint par same auth header ke saath POST karta hai.
7. Available MCP tools
| Tool | Kaam | Main arguments |
|---|---|---|
whatsapp_list_sessions | Accessible devices aur connection status | none |
whatsapp_get_account_info | Account aur plan details | none |
whatsapp_get_chats | Recent conversations | sessionId optional |
whatsapp_get_messages | Contact ki message history | phone, optional sessionId, limit |
whatsapp_list_contacts | Saved contacts search | optional sessionId, search, limit |
whatsapp_list_groups | Connected account ke groups | sessionId optional |
whatsapp_check_number | WhatsApp registration check | phone, optional sessionId |
whatsapp_send_message | Actual text message send | phone, message, optional sessionId |
Multiple devices hain to explicit sessionId dein. Latest argument schema ke liye tools/list response use karein. History/contact tools private account data return kar sakte hain; access sirf authorized users ko dein.
8. Common errors aur fixes
| Problem | Kya check karein |
|---|---|
401 Unauthorized | Key missing/incorrect/revoked. REST ke liye X-API-Key; MCP ke liye Bearer ya X-API-Key. URL mein ?key= supported nahi. |
403 Forbidden | Is account ko requested device ka access hai? Correct endpoint aur header use ho raha hai? |
404 / session not found | /api/sessions ka sessionId use karein; apni website URL ko gateway URL se confuse na karein. |
| Device disconnected / socket not ready | Dashboard mein WhatsApp reconnect karein; server running hona chahiye. |
429 / quota error | Plan quota aur API rate limit check karein; repeated requests reduce karein. |
| Browser CORS error | Recommended backend flow use karein. Direct browser integration mein gateway ke allowed origin/preflight check karein, key public na karein. |
| MCP tools nahi dikh rahe | URL /mcp, custom headers, transport aur protocol compatibility check karein. Initialize/tools-list responses dekhein. |
| MCP HTTP 200 but operation failed | JSON-RPC error aur tool result ka isError check karein. |
| Slow first request / timeout | Hosting instance sleep/startup, logs aur health check karein. Sending ko blind retry na karein. |
| Regenerate ke baad old integration band | Doosri website ke secret settings mein new key save karke backend redeploy karein. |
Render par WhatsApp connection ke liye continuously running instance helpful hai. Sleeping/restarting server se connection interrupt ho sakta hai. Plan change is guide ka automatic part nahi hai.
9. Go-live checklist
- Gateway health
GET /api/healthreturns200. - WhatsApp device dashboard mein connected hai.
- Backend environment mein gateway URL, API key aur correct
sessionIdsaved hain. - Valid key se sessions list successful; invalid key reject hoti hai.
- Apne authorized test number par ek message send karke receipt verify ki hai.
- Key frontend bundle, browser requests to your own backend, logs aur public source mein expose nahi hoti.
- Website endpoint apne users authenticate karta hai, permissions check karta hai aur request rate limit karta hai.
- AI/MCP use kar rahe hain to read-only tool call successful hai; message-sending permission controlled hai.
Next: Generate/manage API key · MCP dashboard test · Full API reference.