Learning path: An AI agent on WhatsApp with n8nStep 3 of 5

WhatsApp· 5 min read

Save to the CRM before you reply in WhatsApp automations


Write the contact and the inbound message to your CRM or database before you send the reply. When the reply comes first and fails, the workflow stops at that node and leaves no contact, no message and no record of the failure. The order that holds up is receive, acknowledge with 200, upsert the contact, log the inbound message, send the reply, log the reply.

What a reply-first flow loses

In n8n, a node whose On Error setting is Stop Workflow halts the entire workflow when it fails (node settings). When the reply node comes before the CRM node, every failed reply is also a contact that never existed in your system.

Replies fail for ordinary reasons. The phone behind a QR connection is offline, so the provider rejects or queues the message. On Meta’s official API, the 24-hour customer service window has closed and a free-form message returns error 131047, covered in WhatsApp error 131047. The messaging API returns a 5xx for a minute. In each case the person who wrote to you is absent from your data. When they write again tomorrow, your flow treats them as new.

Attribution goes with them. The first inbound message tells you where the contact came from: the number they wrote to, the time, and any ref or campaign parameter your entry link added. A second message rarely repeats it.

The audit trail goes too. When the reply is logged only after it succeeds, a failed reply looks identical to a message you never answered, and nobody can tell which replies to resend.

The sequence

  1. Acknowledge the webhook with 200 as soon as it arrives. Why the provider needs this and how to dedupe retries is in Duplicate WhatsApp webhooks in n8n.
  2. Upsert the contact, keyed on the identifier your provider gives for the sender. Insert if new, update last_seen_at and the name if known.
  3. Log the inbound message with its provider message id, the contact id from step 2, the direction and the raw payload.
  4. Send the reply through your messaging API and keep the id the API returns.
  5. Log the reply with that id and a status of accepted. Update the status when the delivery webhook arrives. API acceptance and delivery to the phone are two events; only the second means delivered.

The n8n build

Start with the Webhook node, Respond set to Immediately, Response Code 200 (Webhook node), then the dedupe step from the post linked above.

For your own contact table, use the Postgres node with the Execute Query operation. Pass values through the Query Parameters option, which n8n sanitizes (Postgres node). The upsert uses ON CONFLICT DO UPDATE with the EXCLUDED row and returns the contact id in one round trip (PostgreSQL INSERT):

INSERT INTO contacts (sender_id, display_name, first_seen_at, last_seen_at, source)
VALUES ($1, $2, now(), now(), $3)
ON CONFLICT (sender_id) DO UPDATE
  SET display_name = COALESCE(EXCLUDED.display_name, contacts.display_name),
      last_seen_at = now()
RETURNING id;

Query Parameters: {{ [ $json.body.sender_id, $json.body.sender_name, $json.body.to_number ] }}. The three field names come from your provider’s webhook documentation, so replace them with the paths your provider documents; for Z-API Omni, the developer docs are the reference. The source column holds the number the customer wrote to, the attribution you cannot recover later.

Use the same operation to log the inbound message:

INSERT INTO messages (provider_message_id, contact_id, direction, body, raw, received_at)
VALUES ($1, $2, 'in', $3, $4::jsonb, now())
ON CONFLICT (provider_message_id) DO NOTHING;

Query Parameters: {{ [ $('Webhook').item.json.body.message_id, $json.id, $('Webhook').item.json.body.text, JSON.stringify($('Webhook').item.json.body) ] }}. The $('Webhook') reference reads the original payload after the Postgres node has replaced $json with the contact row. The raw jsonb payload keeps the fields you did not think to extract.

If the CRM is HubSpot, its node’s Contact resource offers “Create/Update a contact” (HubSpot node), which replaces the first query. Keep the messages table in Postgres either way; a status webhook needs a row it can find by provider message id.

Send the reply with the HTTP Request node pointed at your messaging API. For Omni, the request format is in the same developer docs.

Then a third Postgres node writes the reply row with direction = 'out', the id from the send response and status = 'accepted'. A separate workflow, triggered by the provider’s status webhook, updates that row to delivered or read.

The Make build

Make answers the webhook for you. A Custom webhook that accepts a request returns 200 with the body “Accepted” (Make webhooks). Data not processed at once waits in that webhook’s queue, up to a limit set by your plan. Add a Webhook response module only when the caller needs a custom body, and put it last. Make warns that a response module placed mid-scenario keeps later errors from deactivating the scenario, so they go unnoticed.

The upsert is your CRM app’s create-or-update module, or the Data store module “Add/Replace a Record” keyed on the sender identifier (Make data stores). The message log is a second data store record keyed on the provider message id, or a row in your database through its app. The send module comes after both. The reply log comes last.

When the CRM is down

When the CRM is unreachable for ten minutes, the contact record can wait. The message log and the reply should still happen. Two settings make that true.

In n8n, open the CRM node’s Settings tab and turn on Retry On Fail, which reruns the node after a failure (node settings). Then set On Error to Continue (using error output), which passes the error to a second output instead of stopping the run. Connect that error output to a Postgres node that inserts the raw payload into a pending_crm table. Then rejoin the main path so the message log and the reply still run; the message row goes in with a null contact_id, and the replay fills it.

A second workflow with a Schedule Trigger set to Minutes, every 5 (Schedule Trigger), reads pending_crm, replays the upsert, updates the message rows and deletes what succeeded. Attach an Error Trigger workflow to both so the failures you did not foresee reach you (Error Trigger).

In Make, right-click the CRM module and add the Retry error handler. It “pulls the failing bundle out of the flow”, saves the error and the data that caused it, and lets the rest of the scenario continue. It requires Store incomplete executions set to Yes in the scenario settings. With Automatically complete execution set to Yes, Make retries on the schedule you give it (Retry error handler).

Caveat

The queue covers the contact record only. A reply the customer never receives is still a lost conversation. Give the send step its own failure path: a row in messages with status = 'failed' and the error text, so a person can answer by hand.

Z-API Omni team