Developers
Connect your AI assistant, apps and website
Ask your AI assistant about your chats, deals and payments, or build your own integrations with the Hafsage CRM REST API and webhooks. Both are included in the Growth and Business plans and in the free trial.
Connect your AI assistant
Hafsage CRM works with any AI assistant that supports MCP (Model Context Protocol) connectors. Once connected, you can ask it things like:
- “Which chats are still open from this morning?”
- “Which deals in Site visit haven’t paid a deposit yet?”
- “Send Wanjiru an M-Pesa prompt for the KES 50,000 deposit.”
- “Add a task to call Amina tomorrow at 10.”
How to connect
- In your assistant’s settings, add a custom connector with this address:
https://mcp.hafsage.com/mcp - Sign in with your Hafsage CRM login when the assistant asks.
- Check the approval page. It shows the account, your role and what the assistant will be able to do. Choose Approve.
No API key is needed. The assistant acts as you, so it can do only what your role allows:
| Your role | What the assistant can do |
|---|---|
| Viewer | Read contacts, conversations, messages, payments, tasks, pipelines and deals |
| Agent | Everything a viewer can, plus send messages, add and update contacts, create and update tasks and deals, and send M-Pesa payment prompts |
| Admin and owner | Everything an agent can, plus send broadcasts |
- Assistants can never change settings, team members, billing or webhooks.
- Each person can see and disconnect their assistants in Settings → API keys → Connected assistants.
- If the account is read-only (an overdue subscription or an ended trial), assistants can still read but can’t change anything.
- What the assistant reads is sent to the company that runs it, under that company’s terms. See our privacy policy.
REST API
Base URL: https://app.hafsage.com/api/v1. Send your API key as a bearer token on every request:
Authorization: Bearer hafsage_live_xxxAPI keys
- Admins and owners create keys in Settings → API keys. The full key is shown once, so copy it then.
- A key works on one account only, and can do only what its permissions (scopes) allow. Give it only the ones it needs.
- Revoke a key at any time; it stops working on its next request.
| Scope | Allows |
|---|---|
messages:send | Send WhatsApp messages |
messages:read | Read messages and their delivery status |
contacts:read | List and read contacts |
contacts:write | Create and update contacts |
conversations:read | List and read conversations |
broadcasts:send | Send broadcasts and check their progress |
webhooks:manage | Add and manage webhook endpoints |
payments:read | List and read payments and M-Pesa prompts |
payments:request | Send M-Pesa payment prompts |
tasks:read | List and read tasks |
tasks:write | Create, update, complete and delete tasks |
deals:read | List pipelines, and list and read deals |
deals:write | Create, update and move deals |
Responses and errors
// Success
{ "data": { … }, "meta": { "next_cursor": "eyJ…" } }
// Failure: branch on error.code; error.message is for people
{ "error": { "code": "forbidden", "message": "This API key is missing the 'messages:send' scope" } }| Status | Code | Meaning |
|---|---|---|
| 400 | bad_request | The request isn’t valid |
| 401 | unauthorized | The key is missing, unknown, revoked or expired |
| 403 | forbidden | The key lacks a scope, or the plan or account status doesn’t allow it |
| 404 | not_found | No such item in this account |
| 409 | conflict | An M-Pesa prompt to that number is still waiting |
| 429 | rate_limited | Too many requests; wait for the Retry-After seconds |
| 500 | internal | Something went wrong on our side |
| 503 | unavailable | The key couldn’t be checked just now; try again |
Limits and paging
- Up to 120 requests a minute per key, and up to 10 M-Pesa prompts a minute per key.
- Lists return 50 items by default (up to 100 with
?limit=). Passmeta.next_cursorback as?cursor=for the next page;nullmeans the last page. - Phone numbers use the international format with a plus sign and country code, such as
+254712345678.
API reference
All paths are relative to https://app.hafsage.com/api/v1. Open an endpoint for its fields and examples. In the examples, … stands for an id from your account.
Account
GET/meCheck a key: its account, scopes, plan and access
Scope: Any valid key
- Use it to test a new key, and to check the plan before calling endpoints it may not include.
Example request
curl https://app.hafsage.com/api/v1/me \
-H "Authorization: Bearer hafsage_live_xxx"Example response
{
"data": {
"account": { "id": "…", "name": "Acme Homes" },
"key": { "id": "…", "scopes": ["messages:send", "contacts:read"] },
"plan": { "code": "growth", "status": "active", "features": ["mpesa_payments", "flows", "automations", "ai_replies", "api"] },
"access": "full"
}
}Messages and conversations
POST/messagesSend a WhatsApp message to a phone number
Scope: messages:send
- Finds or creates the contact and conversation, then sends.
- Outside WhatsApp's 24-hour reply window, only a Meta-approved template can be sent.
- Other errors: 400 whatsapp_not_configured (no WhatsApp number connected), 502 meta_error (Meta refused the message), 500 template_malformed.
Body (JSON)
| Field | Type | Description |
|---|---|---|
torequired | string | Phone number with + and country code, such as +254712345678. Numbers without + are refused. |
type | string | text (default), template, image, video, document or audio |
text | string | The message, or the caption for media |
media_url | string | Public URL of the file. Required for image, video, document and audio. |
filename | string | File name shown for a document |
template | object | Required for type template: name, language (such as en_US) and params (a list of body values, in order) |
reply_to_message_id | string | Reply to a message in the same conversation |
name | string | Names the contact if this call creates it. An existing contact's name isn't changed. |
Example request
curl -X POST https://app.hafsage.com/api/v1/messages \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{
"to": "+254712345678",
"type": "template",
"template": { "name": "site_visit_reminder", "language": "en", "params": ["Wanjiru", "Saturday 10am"] }
}'Example response
// 201 Created
{
"data": {
"message_id": "…",
"whatsapp_message_id": "wamid.…",
"conversation_id": "…",
"contact_id": "…",
"contact_created": false
}
}GET/conversationsList conversations, newest first
Scope: conversations:read
Query parameters
| Field | Type | Description |
|---|---|---|
status | string | open, pending or closed |
contact_id | string | Only this contact's conversations |
limit | number | Items per page: 50 by default, up to 100 |
cursor | string | The meta.next_cursor from the previous page |
Example response
{
"data": [
{
"id": "…",
"contact_id": "…",
"status": "open",
"assigned_agent_id": "…",
"last_message_text": "Can I pay the deposit in two parts?",
"last_message_at": "2026-11-16T08:14:00Z",
"unread_count": 1,
"created_at": "…",
"updated_at": "…",
"contact": { "id": "…", "phone": "+254712345678", "name": "Brian O.", "email": null, "company": null, "tags": [] }
}
],
"meta": { "next_cursor": null }
}GET/conversations/{id}Read one conversation
Scope: conversations:read
- Same shape as a list item. 404 if it isn't in your account.
GET/conversations/{id}/messagesList a conversation's messages, newest first
Scope: messages:read
Query parameters
| Field | Type | Description |
|---|---|---|
limit | number | Items per page: 50 by default, up to 100 |
cursor | string | The meta.next_cursor from the previous page |
Example response
{
"data": [
{
"id": "…",
"conversation_id": "…",
"direction": "inbound",
"sender_type": "customer",
"content_type": "text",
"content_text": "Hi, is the Kitengela plot still available?",
"media_url": null,
"template_name": null,
"whatsapp_message_id": "wamid.…",
"status": "read",
"reply_to_message_id": null,
"interactive_reply_id": null,
"created_at": "…"
}
],
"meta": { "next_cursor": "eyJ…" }
}Contacts
GET/contactsList contacts, newest first
Scope: contacts:read
Query parameters
| Field | Type | Description |
|---|---|---|
search | string | Matches name or phone |
tag | string | A tag id |
limit | number | Items per page: 50 by default, up to 100 |
cursor | string | The meta.next_cursor from the previous page |
Example response
{
"data": [
{
"id": "…",
"phone": "+254712345678",
"name": "Wanjiru K.",
"email": null,
"company": null,
"avatar_url": null,
"tags": [{ "id": "…", "name": "Hot lead", "color": "#10b981" }],
"created_at": "…",
"updated_at": "…"
}
],
"meta": { "next_cursor": null }
}POST/contactsCreate a contact, or find it by phone
Scope: contacts:write
- A new contact returns 201. If the phone number already exists, you get 200 with that contact: its name, email and company stay as they are, and the tags you send are added to its tags.
Body (JSON)
| Field | Type | Description |
|---|---|---|
phonerequired | string | With + and country code |
name | string | |
email | string | |
company | string | |
tags | string[] | Tag names. Tags that don't exist yet are created. |
Example request
curl -X POST https://app.hafsage.com/api/v1/contacts \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{ "phone": "+254712345678", "name": "Wanjiru K.", "tags": ["Website lead"] }'GET, PATCH/contacts/{id}Read or update a contact
Scope: contacts:read, contacts:write
- PATCH changes only the fields you send: name, email, company. Sending tags replaces all of the contact's tags.
Broadcasts
POST/broadcastsSend a Meta-approved template to a list of people
Scope: broadcasts:send
- Only message people who have agreed to hear from you.
- Up to 1,000 recipients per request; split larger lists.
- Invalid numbers are skipped and counted as rejected; the same contact listed twice gets one message.
- Returns at once while sending continues. Check progress with GET /broadcasts/{id}.
Body (JSON)
| Field | Type | Description |
|---|---|---|
template_namerequired | string | The approved template |
template_language | string | The template's language, such as en. Defaults to en_US. |
name | string | A label for your own reference |
recipientsrequired | object[] | Each with to (phone number) and optional params (template values) |
Example request
curl -X POST https://app.hafsage.com/api/v1/broadcasts \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{
"name": "December offer",
"template_name": "december_offer",
"template_language": "en",
"recipients": [
{ "to": "+254712345678", "params": ["Wanjiru"] },
{ "to": "+254733456789", "params": ["Brian"] }
]
}'Example response
// 202 Accepted
{
"data": {
"broadcast_id": "…",
"status": "sending",
"total_recipients": 2,
"accepted": 2,
"rejected": 0,
"duplicates": 0
}
}GET/broadcasts/{id}A broadcast's progress
Scope: broadcasts:send
- status moves from sending to sent; the delivered and read counts keep rising as WhatsApp reports them.
M-Pesa payments
Needs M-Pesa connected in the app (Settings → Payments) and a plan with M-Pesa payments (Growth and up).
POST/payment-requestsSend an M-Pesa PIN prompt (STK Push) to the customer in a conversation
Scope: payments:request
- The money goes to your own Paybill or Till. Up to 10 prompts a minute per key.
- Errors: 404 if the conversation or deal isn't found; 409 conflict if a prompt to that number is still waiting; 400 for invalid input, M-Pesa not connected, or Safaricom's own reason.
- When it's paid, the payment is recorded (against the deal, if given) and payment.received fires.
Body (JSON)
| Field | Type | Description |
|---|---|---|
conversation_idrequired | string | The customer's conversation |
amountrequired | number | Whole shillings, 1 to 250,000 |
phone | string | M-Pesa number to prompt, if not the contact's own |
deal_id | string | The contact's deal to record the payment against |
label | string | Shown to the customer, such as Deposit (up to 60 characters) |
Example request
curl -X POST https://app.hafsage.com/api/v1/payment-requests \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{ "conversation_id": "…", "deal_id": "…", "amount": 50000, "label": "Deposit" }'Example response
// 201 Created
{
"data": {
"id": "…",
"status": "pending",
"amount": 50000,
"currency": "KES",
"phone": "254712345678",
"label": "Deposit",
"contact_id": "…",
"conversation_id": "…",
"deal_id": "…",
"environment": "production",
"mpesa_receipt": null,
"failure_reason": null,
"result_desc": null,
"completed_at": null,
"created_at": "…",
"updated_at": "…",
"payment_id": null
}
}GET/payment-requests/{id}A prompt's status
Scope: payments:read
- status is pending, paid or failed. Once paid, mpesa_receipt and payment_id are filled in.
- failure_reason is one of: cancelled, timeout, insufficient_funds, wrong_pin, busy, expired, rejected or failed.
GET/paymentsList payments, newest first
Scope: payments:read
- Includes M-Pesa prompts, direct Paybill and Till payments, and cash, bank and other payments recorded in the app.
Query parameters
| Field | Type | Description |
|---|---|---|
contact_id | string | Only this contact's payments |
method | string | mpesa_stk, mpesa_c2b (direct Paybill or Till), cash, bank or other |
environment | string | production or sandbox |
limit | number | Items per page: 50 by default, up to 100 |
cursor | string | The meta.next_cursor from the previous page |
GET/payments/{id}Read one payment
Scope: payments:read
- The same shape as the payment in payment webhooks, shown under Webhooks below.
Tasks
GET/tasksList tasks, newest first
Scope: tasks:read
Query parameters
| Field | Type | Description |
|---|---|---|
status | string | open or done |
contact_id | string | |
assigned_to | string | A team member's user id |
due_before, due_after | string | Date and time, such as 2026-11-20T00:00:00+03:00 |
limit | number | Items per page: 50 by default, up to 100 |
cursor | string | The meta.next_cursor from the previous page |
POST/tasksCreate a task
Scope: tasks:write
- The assignee gets reminders in the app, as for tasks created there.
Body (JSON)
| Field | Type | Description |
|---|---|---|
titlerequired | string | Up to 200 characters |
due_atrequired | string | Date and time, such as 2026-11-20T14:30:00+03:00. Or send due_date instead. |
due_date | string | A date only, such as 2026-11-20; stored at 09:00 Nairobi time |
type | string | follow_up (default), call, meeting or other |
priority | string | normal (default) or high |
remind_before_minutes | number | 0, 15, 60, 1440 or null for no reminder |
notes | string | Up to 2,000 characters |
contact_id | string | Link the task to a contact |
assigned_to / assignee_email | string | The team member, by user id or email |
Example request
curl -X POST https://app.hafsage.com/api/v1/tasks \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{
"title": "Call Amina about the site visit",
"type": "call",
"due_at": "2026-11-20T10:00:00+03:00",
"remind_before_minutes": 15,
"contact_id": "…",
"assignee_email": "brian@example.co.ke"
}'Example response
// 201 Created
{
"data": {
"id": "…",
"title": "Call Amina about the site visit",
"type": "call",
"priority": "normal",
"due_at": "2026-11-20T07:00:00.000Z",
"due_has_time": true,
"remind_before_minutes": 15,
"done": false,
"contact": { "id": "…", "name": "Amina H.", "phone": "+254722345678" },
"assignee": { "id": "…", "name": "Brian", "email": "brian@example.co.ke" },
…
}
}GET, PATCH, DELETE/tasks/{id}Read, update, complete or delete a task
Scope: tasks:read, tasks:write
- PATCH takes any of the create fields, plus done: true to complete it or false to reopen it.
- DELETE returns { "data": { "id": "…", "deleted": true } }.
Pipelines and deals
GET/pipelinesYour pipelines, each with its stages in order
Scope: deals:read
- Use it to find the pipeline and stage ids for creating and moving deals.
GET/dealsList deals, newest first
Scope: deals:read
Query parameters
| Field | Type | Description |
|---|---|---|
pipeline_id | string | |
stage_id | string | |
contact_id | string | |
status | string | open, won or lost |
limit | number | Items per page: 50 by default, up to 100 |
cursor | string | The meta.next_cursor from the previous page |
POST/dealsCreate a deal
Scope: deals:write
Body (JSON)
| Field | Type | Description |
|---|---|---|
titlerequired | string | Up to 200 characters |
value | number | 0 or more |
currency | string | Such as KES, UGX, TZS or USD. Defaults to the account's currency. |
status | string | open, won or lost |
pipeline_id | string | Defaults to your first pipeline |
stage_id | string | Defaults to the pipeline's first stage |
contact_id | string | |
conversation_id | string | Link the deal to its WhatsApp conversation |
expected_close_date | string | Such as 2026-12-01 |
notes | string | Up to 5,000 characters |
assigned_to / assignee_email | string | The team member, by user id or email |
Example request
curl -X POST https://app.hafsage.com/api/v1/deals \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{ "title": "50x100 plot, Kitengela", "value": 850000, "contact_id": "…", "conversation_id": "…" }'GET, PATCH/deals/{id}Read, update or move a deal
Scope: deals:read, deals:write
- PATCH takes any of the create fields. To move a deal, send stage_id (a stage in its pipeline), or pipeline_id with or without a stage_id.
- A deal that has payments keeps its currency.
Example request
curl -X PATCH https://app.hafsage.com/api/v1/deals/{id} \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{ "stage_id": "…" }'Webhooks
Webhooks tell your system when something happens, so it doesn’t have to keep asking. You set them up through the API with a key that has the webhooks:manage scope.
| Event | Sent when |
|---|---|
message.received | A customer sends a message |
message.status_updated | A message you sent is sent, delivered, read or fails |
conversation.created | A new conversation starts |
payment.received | A payment is recorded: a paid M-Pesa prompt, a direct Paybill or Till payment, or a manual payment |
payment.allocated | A payment is assigned to a customer or split across deals |
payment.refunded | A refund is recorded |
payment.voided | A manual payment is voided |
Add an endpoint
Send your endpoint’s address and the events it wants. The address must start with https://, must be reachable on the public internet, and can’t include a username or password.
curl -X POST https://app.hafsage.com/api/v1/webhooks \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{ "url": "https://example.co.ke/hooks/hafsage", "events": ["message.received", "payment.received"] }'The response includes the signing secret. It’s shown only this once, so store it where your endpoint can read it. If you lose it, delete the endpoint and add it again.
// 201 Created. Store the secret now: it is never shown again.
{
"data": {
"id": "…",
"url": "https://example.co.ke/hooks/hafsage",
"events": ["message.received", "payment.received"],
"is_active": true,
"last_delivery_at": null,
"failure_count": 0,
"created_at": "…",
"secret": "whsec_…"
}
}List, update or pause an endpoint
GET /webhookslists your endpoints andGET /webhooks/{id}reads one. The secret is never shown again.PATCH /webhooks/{id}changes any ofurl,eventsandis_active. Send"is_active": falseto pause it, ortrueto turn it back on; turning it on also resets its failure count.
curl -X PATCH https://app.hafsage.com/api/v1/webhooks/{id} \
-H "Authorization: Bearer hafsage_live_xxx" \
-H "Content-Type: application/json" \
-d '{ "is_active": true }'Delete an endpoint
curl -X DELETE https://app.hafsage.com/api/v1/webhooks/{id} \
-H "Authorization: Bearer hafsage_live_xxx"
// 200 OK
{ "data": { "id": "…", "deleted": true } }What a delivery looks like
Each delivery is a POST with a JSON body and the X-Hafsage-Event, X-Hafsage-Webhook-Id and X-Hafsage-Signature headers. The body is the same for every event; only data changes:
{
"id": "8f3c…",
"event": "message.received",
"occurred_at": "2026-11-16T08:14:00.000Z",
"account_id": "…",
"data": { … }
}data for message.received
{ "conversation_id": "…", "contact_id": "…", "whatsapp_message_id": "wamid.…", "content_type": "text", "text": "Is the plot still available?" }data for message.status_updated
{ "whatsapp_message_id": "wamid.…", "conversation_id": "…", "status": "delivered" }data for conversation.created
{ "conversation_id": "…", "contact_id": "…" }data for payment.received, payment.allocated, payment.refunded, payment.voided
{
"payment": {
"id": "…",
"method": "mpesa_stk",
"amount": 50000,
"currency": "KES",
"environment": "production",
"mpesa_receipt": "TKB12XYZ9",
"payer_name": "Wanjiru K.",
"contact_id": "…",
"payment_request_id": "…",
"paid_at": "2026-11-16T09:12:00Z",
"allocations": [{ "deal_id": "…", "amount": 50000 }],
"refunds": [],
"allocated": 50000,
"refunded": 0,
"unallocated": 0
}
}Payment events carry the payment as it stands after the change, so you always have the current balance. Ignore "environment": "sandbox" payments in production. Some fields, such as payment_request_id and voided_at, appear only when they apply.
Check the signature
Recompute the signature over the raw request body (before any JSON parsing) with your endpoint’s secret, compare it in constant time, and reject old deliveries so a captured one can’t be replayed:
// Node.js. The header looks like: X-Hafsage-Signature: t=1763197920,v1=5f8a…
// t is when the delivery was signed (Unix seconds); v1 is the signature.
const [, t, v1] = header.match(/t=(\d+),v1=([0-9a-f]+)/) ?? [];
if (!t || Math.abs(Date.now() / 1000 - Number(t)) > 300) {
return reject(); // missing, or older than 5 minutes: possibly replayed
}
const expected = crypto.createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(v1);
const valid = a.length === b.length && crypto.timingSafeEqual(a, b);Delivery rules
- Reply with any
2xxstatus within 5 seconds. Do slow work after you reply. - Each delivery is tried once. There are no automatic retries, and redirects aren’t followed.
- After 15 failures in a row the endpoint is paused (
"is_active": false). Fix it, then turn it back on withPATCH. - WhatsApp can report the same message status more than once or out of order, so
message.status_updatedcan repeat. Don’t rely on the order, and treat a status you already have as a repeat. - When a missed event matters, use the read endpoints to catch up.
Plans and account status
| Account | API keys and assistants | Webhooks |
|---|---|---|
| Growth, Business or free trial | Work as their permissions allow | Sent |
| Starter | Not included: keys can’t be created and assistants can’t connect | Not sent |
| Read-only (payment overdue, or trial ended) | Read only | Sent |
| Suspended | Refused, with the reason | Sent |
Nothing is deleted in any of these states. Keys work again as soon as the account is paid or upgraded. GET /me returns the plan and access, so an integration can check first. See the plans.
See it with your own sales process
Try it free for 14 days, no card needed, or book a 15-minute demo.
- Meta Tech Provider
- No markup on Meta fees
- M-Pesa built in