Connect a WhatsApp agent
Read an authorized conversation and reply only while its version is current.
Permissionsevents.read · whatsapp.read · whatsapp.send
- Line numbers include the country code as digits. Messages are listed newest first. Use direction=inbound to recognize incoming messages even when status is sent. privacy, expires_at and edited_at describe privacy, expiration and edits.
- The send ID is also the message ID. pending means accepted and awaiting processing or confirmation. Poll the same ID with increasing intervals. Confirmation can take longer than 15 seconds. Other states include sent, delivered, read, played, failed and unknown. Timing depends on the queue and provider.
- Select the company line in the ERP. Check its ID and number with GET /whatsapp/lines. Enable incoming message notifications or poll GET /events. The event identifies the message and its conversation context.
- Check the line, conversation version and most recent messages. Reply only to the expected incoming message. Stop if a human has responded. The version reflects messages that Kaserk has received.
- Compose the text and persist the intent in your system. Include expected_version. HTTP 202 returns data.id. Check GET /whatsapp/sends/{id} for the same attempt. Reading messages via API preserves the team’s unread indicators.
curl --fail-with-body \
-H "Authorization: Bearer ${KASERK_API_KEY}" \
"https://api.kaserk.com/v1/whatsapp/lines"JavaScript example
import { request } from './client.mjs';
export async function reply({ conversationId, lineId, incomingId, eventId, compose, saveIntent }) {
const path = '/whatsapp/conversations/' + encodeURIComponent(conversationId);
const { data: conversation } = await request(path);
if (conversation.line_id !== lineId) throw new Error('Wrong WhatsApp line.');
const { data: recent } = await request(path + '/messages?limit=30');
// Newest messages arrive first. A newer message or a missing target needs
// another decision; do not send an answer based on stale context.
if (recent[0]?.id !== incomingId || recent[0].direction !== 'inbound' ||
recent[0].origin !== 'contact' || !recent[0].text) return;
const text = await compose(recent);
if (!text) return;
// Persist this exact intent before dispatch. On transport timeout retry the
// same key and body. On 409 reread the conversation and reconsider the reply.
const intent = { line_id: lineId, expected_version: conversation.version, text };
const key = eventId + ':reply';
const saved = await saveIntent(key, intent); // Insert once; return the durable body.
return request(path + '/messages', { method: 'POST', key, body: saved });
}
Recovery
On 409 reread the conversation and reconsider the reply. After a timeout, recover the stored intent and reuse its body and key. If delivery is unknown, monitor the attempt and wait for reconciliation.