# Import contacts and keep them in sync with your CRM

> Import your customer list once, push every change from your CRM with an upsert, record consent with its evidence, and get opt-outs, number changes and contact changes back from app2email as signed webhook events.

In this guide you load your customer list into app2email and keep it in step with the CRM or database you already use. Changes in your CRM go to app2email as they happen. Opt-outs, new numbers and other changes on the WhatsApp side come back to your CRM as webhook events.

**What the customer sees:** nothing new, and that is the point. The messages they get use the right first name and order number, people who agreed to offers get them, and people who said STOP, in WhatsApp or in your CRM, get no more marketing from you.

**What you see:** every contact in app2email with the same name, tags, custom fields and marketing consent as in your CRM. Your CRM marks people as unsubscribed a second after they tap "Stop promotions", and updates their phone number when they change it in WhatsApp.

app2email has no built-in connector for a particular CRM. You connect yours with the calls below: from your own code, or from an automation tool (see [Send WhatsApp messages from n8n, Zapier or Make](/guides/how-to-no-code-n8n-zapier-make)).

## How it works

1. **Once:** you import your existing list with `POST /contacts/import` (CSV or JSON, up to 5000 rows per call).
2. **From your CRM to app2email:** each time a contact is made or changed in your CRM, your code sends it to `POST /contacts`. This is an **upsert**: app2email makes the contact when it is new and updates it when it exists, matched by phone number (or business-scoped user id).
3. **From app2email to your CRM:** app2email sends signed webhook events to your URL: `contact.opted_out` when someone stops promotions, `contact.updated` when a contact is changed through the API or turns marketing back on in WhatsApp, `contact.changed_number` when someone moves to a new number, and `message.received` when someone writes to you.
4. **Now and then:** you compare both sides with `GET /contacts` (page by page) or `GET /contacts/export.csv`, to catch anything an event did not cover.

**The key you match on** is the contact's `identity`: their WhatsApp number with the country code first, digits only (`61412345678` for +61 412 345 678). Store the same value in your CRM. A contact who uses a WhatsApp username can come with a business-scoped user id instead of a number (like `AU.1234567890123456`, `identity_type` is then `bsuid`); it works wherever a number does.

## What a contact holds

| Field | What it is | Limits |
| --- | --- | --- |
| `phone` or `identity` | Which contact. `identity` takes a number or a business-scoped user id | Country code first, digits only |
| `name` | The contact's name | Up to 200 characters |
| `tags` | Labels such as `vip` or `newsletter`. A comma separated string works too | Up to 50 tags, 40 characters each |
| `custom_fields` | Your own text values, such as `first_name`, `order_id`, `crm_id`. Used as named template values in segment sends | Up to 50; names are letters, digits and underscores |
| `source` | Where the contact came from, such as `crm` | Up to 50 characters |
| `consent` | Marketing consent with its evidence: `marketing` (true or false), `at`, `source`, `text` (the wording they agreed to), `evidence` (a link, file name, IP address or message id) | `source` 100, `text` 1000, `evidence` 500 characters |

In an answer, a contact also has `identity_type` (`phone` or `bsuid`), `consent.recorded` (true when any consent record exists), `last_inbound_at`, `last_outbound_at`, `created` and `updated`. A field with no value is left out of the answer.

**How an update works:** the fields you give replace the stored ones, and the fields you leave out stay. `tags` is replaced as a whole list, so always send every tag the contact should have. `custom_fields` **merge**: the names you send are set, the others stay.

## What you need

- **A WhatsApp number connected to app2email**, on a paid plan and live. Without a plan every call answers 403 `plan_not_allowed`; a paused service answers 403 `service_not_live`. See [Getting started](https://www.app2email.com/docs/onboarding).
- **An API key** from [the API key page](https://www.app2email.com/dashboard/apikey) with these scopes. Contacts need a key made with `contacts:manage` or Full access: the Default key does not have it.

| Scope | What it is for |
| --- | --- |
| `contacts:manage` | Import, create, change and delete contacts, record consent, save segments (`POST /contacts/import`, `POST /contacts`, `PATCH /contacts/{identity}`, `DELETE /contacts/{identity}`, `POST /contacts/{identity}/consent`, `POST /segments`) |
| `messages:read` | Read contacts and segments, export, fetch events (`GET /contacts`, `GET /contacts/{identity}`, `GET /contacts/export.csv`, `GET /segments/{id}/contacts`, `GET /events`) |
| `webhooks:manage` | Register the webhook once (`POST /webhooks`). You can also add it on the API key page under Webhooks, without code |
| `dnc:manage` | Put people who unsubscribed in your CRM on the Do Not Call list, and export the compliance records (`POST /donotcall`, `GET /compliance/export.csv`) |
| `settings:manage` | Only if you use the opt-in rule for marketing: record opt-ins (`POST /optins`) |

- **A public https address** for the webhook, or a script that fetches events with `GET /events` instead.

<Warning>
**Test with a few contacts of your own, not with a sandbox key.** Contacts are not part of the instant sandbox (the demo number `12025550100` answers 403 `not_in_instant_sandbox`). A sandbox key on your own number reads contacts normally, but `POST /contacts`, `POST /contacts/import`, `PATCH`, consent and segments **change your real data**, while `DELETE /contacts/{identity}` with a sandbox key is only simulated and deletes nothing. Give your test contacts a tag such as `test`, and delete them afterwards with a normal key. Details: [Sandbox](/api/sandbox).
</Warning>

## Set up the sync, step by step

Every call goes to `https://api.app2email.com/v1/YOUR_NUMBER`, where `YOUR_NUMBER` is your WhatsApp number (country code first, digits only), with the header `Authorization: Bearer YOUR_API_KEY`. The examples read the key from the environment variable `A2E_KEY`.

<Steps>
  <Step title="Check your key">
    `GET /me` shows the key's scopes and limits.

    ```bash
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/me \
      -H "Authorization: Bearer $A2E_KEY"
    ```

    **What you get back** (shortened):

    ```json
    {
      "success": true,
      "request_id": "a7k3p",
      "key_valid": true,
      "number": "4976659348270",
      "service_status": "LIVE",
      "key": { "name": "CRM sync", "scopes": ["contacts:manage", "messages:read", "webhooks:manage", "dnc:manage"], "ip_allow": "" },
      "limits": { "max_numbers_per_request": 1000, "requests_per_second": 20, "burst": 50, "rate_limit_mode": "enforce", "webhooks_max": 5 }
    }
    ```

    `service_status` must be `LIVE`, and `key.scopes` must list the scopes you need (or `*` for full access). `limits` tells you how fast your sync may call.
  </Step>

  <Step title="Import your existing contacts once">
    Export your list from the CRM as CSV with a header row. The columns app2email knows are `phone` (or `identity`, `number`, `mobile`), `name` (or `first_name` + `last_name`), `tags` (separated by `|`), `consent_marketing` (yes or no), `consent_source`, `consent_text`, `consent_evidence`, `consent_at` and `source`. **Every other column becomes a custom field**, so a `crm_id` column keeps your CRM's own id on each contact. Up to 5000 rows per call.

    ```csv
    phone,name,first_name,crm_id,tags,consent_marketing,consent_source,consent_text,consent_evidence,consent_at,source
    61412345678,John Smith,John,C-1001,vip|newsletter,yes,web form,"Yes, send me offers on WhatsApp",https://example.com/forms/123,2026-10-01T09:00:00Z,crm
    61498765432,Mary Jones,Mary,C-1002,newsletter,no,,,,,crm
    ```

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/import \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: text/csv" \
      --data-binary @contacts.csv
    ```

    ```javascript Node.js
    import { readFile } from "node:fs/promises";

    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/contacts/import", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.A2E_KEY}`,
        "Content-Type": "text/csv",
      },
      body: await readFile("contacts.csv"),
    });
    const result = await res.json();
    console.log(res.status, result.saved, "saved,", result.skipped, "skipped");
    for (const e of result.errors ?? []) console.log(`row ${e.row}: ${e.problem}`);
    ```

    ```python Python
    import os, requests

    with open("contacts.csv", "rb") as f:
        res = requests.post(
            "https://api.app2email.com/v1/YOUR_NUMBER/contacts/import",
            headers={"Authorization": f"Bearer {os.environ['A2E_KEY']}", "Content-Type": "text/csv"},
            data=f,
            timeout=120,
        )
    result = res.json()
    print(res.status_code, result.get("saved"), "saved,", result.get("skipped"), "skipped")
    for e in result.get("errors", []):
        print(f"row {e['row']}: {e['problem']}")
    ```

    </CodeGroup>

    **What you get back:** the rows that had a problem are skipped and listed, the rest are saved.

    ```json
    {
      "success": true,
      "request_id": "i2gka",
      "rows": 120,
      "saved": 118,
      "created": 90,
      "updated": 28,
      "skipped": 2,
      "errors": [
        {
          "row": 7,
          "problem": "'0412' must be a WhatsApp number with country code, digits only (8 to 15 digits), or a business-scoped user id like 61.AbC123"
        }
      ],
      "note": "Rows with a problem were skipped (the first 50 are listed); the rest were saved."
    }
    ```

    How to read it:

    - `rows` is what app2email read, `saved` = `created` + `updated`, and `skipped` is the rows with a problem.
    - `errors` lists the first 50 problem rows with the row number and the reason. Fix those rows in your CRM (usually a number without its country code) and import just them again. Importing a row again is safe: an existing contact is updated, not doubled.
    - More than 5000 rows: split the file and send one call per part.

    The same call takes `application/json` with a list of contacts in the format of `POST /contacts` (next step). An import does **not** send `contact.updated` events, so a big first load does not flood your webhook.
  </Step>

  <Step title="Push each change from your CRM with an upsert">
    When a contact is made or changed in your CRM (a CRM webhook, a database trigger, or a job every few minutes), send it to `POST /contacts`: one contact as an object, or a list of up to 1000.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "phone": "61412345678",
        "name": "John Smith",
        "tags": ["vip", "newsletter"],
        "custom_fields": { "first_name": "John", "crm_id": "C-1001", "order_id": "1234" },
        "source": "crm"
      }'
    ```

    ```javascript Node.js
    const BASE = "https://api.app2email.com/v1/YOUR_NUMBER";
    const headers = { Authorization: `Bearer ${process.env.A2E_KEY}`, "Content-Type": "application/json" };
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

    // crmRows: the contacts that changed in your CRM since the last run
    export async function pushToApp2email(crmRows) {
      const contacts = crmRows.map((c) => ({
        phone: c.mobile,                       // 61412345678: country code first, digits only
        name: c.fullName,
        tags: c.tags,                          // the whole list: it replaces the stored tags
        custom_fields: { first_name: c.firstName, crm_id: String(c.id) },
        source: "crm",
      }));
      for (let i = 0; i < contacts.length; i += 1000) {
        const batch = contacts.slice(i, i + 1000);
        for (let attempt = 1; ; attempt++) {
          const res = await fetch(`${BASE}/contacts`, { method: "POST", headers, body: JSON.stringify(batch) });
          const body = await res.json();
          if (res.ok) { console.log(`saved ${body.saved}: ${body.created} new, ${body.updated} updated`); break; }
          if (res.status === 429 || (res.status >= 500 && attempt < 5)) {
            const wait = Number(res.headers.get("Retry-After") ?? body.error?.retry_after_seconds ?? 2 ** attempt);
            await sleep(wait * 1000);
            continue; // the same batch again is safe: it is an upsert
          }
          throw new Error(`${body.error?.code}: ${body.error?.how_to_fix} (request ${body.request_id})`);
        }
      }
    }
    ```

    ```python Python
    import os, time, requests

    BASE = "https://api.app2email.com/v1/YOUR_NUMBER"
    HEADERS = {"Authorization": f"Bearer {os.environ['A2E_KEY']}"}

    def push_to_app2email(crm_rows):
        """crm_rows: the contacts that changed in your CRM since the last run."""
        contacts = [{
            "phone": c["mobile"],               # 61412345678: country code first, digits only
            "name": c["full_name"],
            "tags": c["tags"],                  # the whole list: it replaces the stored tags
            "custom_fields": {"first_name": c["first_name"], "crm_id": str(c["id"])},
            "source": "crm",
        } for c in crm_rows]
        for i in range(0, len(contacts), 1000):
            batch = contacts[i:i + 1000]
            for attempt in range(1, 6):
                res = requests.post(f"{BASE}/contacts", headers=HEADERS, json=batch, timeout=60)
                body = res.json()
                if res.ok:
                    print(f"saved {body['saved']}: {body['created']} new, {body['updated']} updated")
                    break
                if res.status_code == 429 or res.status_code >= 500:
                    wait = res.headers.get("Retry-After") or body.get("error", {}).get("retry_after_seconds") or 2 ** attempt
                    time.sleep(float(wait))
                    continue  # the same batch again is safe: it is an upsert
                raise RuntimeError(f"{body['error']['code']}: {body['error']['how_to_fix']} (request {body['request_id']})")
    ```

    </CodeGroup>

    **What you get back:** how many were saved, made and updated, and the first 100 contacts as saved.

    ```json
    {
      "success": true,
      "request_id": "u8wqb",
      "saved": 1,
      "created": 0,
      "updated": 1,
      "contacts": [
        {
          "identity": "61412345678",
          "identity_type": "phone",
          "phone": "61412345678",
          "name": "John Smith",
          "tags": ["vip", "newsletter"],
          "custom_fields": { "first_name": "John", "crm_id": "C-1001", "order_id": "1234" },
          "source": "crm",
          "consent": {
            "marketing": true,
            "at": "2026-10-01T09:00:00Z",
            "source": "web form",
            "text": "Yes, send me offers on WhatsApp",
            "evidence": "https://example.com/forms/123",
            "recorded": true
          },
          "last_inbound_at": "2026-10-26T01:20:44Z",
          "created": "2026-10-01T09:00:10Z",
          "updated": "2026-11-21T09:00:00Z"
        }
      ]
    }
    ```

    A request of up to 50 contacts sends `contact.updated` for each one; a bigger list does not. To change only a few fields of one contact, `PATCH /contacts/{identity}` takes the same fields, and only the ones given change:

    ```bash
    curl -s -X PATCH https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678 \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{ "tags": ["vip", "newsletter", "repeat_buyer"] }'
    ```

    `PATCH` answers `404 contact_not_found` for a contact app2email does not have yet, so a sync is simplest with `POST /contacts` everywhere.
  </Step>

  <Step title="Record consent and withdrawals">
    When someone agrees to marketing in your CRM (a web form, a box ticked at checkout), record it on the contact with the wording and the evidence. You can send the same `consent` object inside `POST /contacts`, or use the consent call, which also makes the contact when it is new. `at` is now when you leave it out.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678/consent \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "marketing": true,
        "source": "web form",
        "text": "Yes, send me offers on WhatsApp",
        "evidence": "https://example.com/forms/123"
      }'
    ```

    ```javascript Node.js
    await fetch("https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678/consent", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.A2E_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        marketing: true,
        source: "web form",
        text: "Yes, send me offers on WhatsApp",
        evidence: "https://example.com/forms/123",
      }),
    });
    ```

    ```python Python
    requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678/consent",
        headers=HEADERS,
        json={
            "marketing": True,
            "source": "web form",
            "text": "Yes, send me offers on WhatsApp",
            "evidence": "https://example.com/forms/123",
        },
        timeout=10,
    )
    ```

    </CodeGroup>

    **What you get back:** the contact, with `consent.recorded: true`, and a `contact.updated` event with `change: "consent"` follows.

    When someone **unsubscribes in your CRM**, do two things:

    1. Record the withdrawal on the contact: the same call with `"marketing": false`. Segments with `consent_marketing: true` then leave them out.
    2. Put them on the Do Not Call list, so no marketing template reaches them at all (scope `dnc:manage`, up to 1000 numbers per call, all or nothing):

    ```bash
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/donotcall \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{ "numbers": [ { "number": "61498765432", "name": "Mary", "note": "Unsubscribed in our CRM" } ] }'
    ```

    The answer lists the numbers in `added` and those that were there before in `already_on_list`.

    Only record consent you really have. If your number uses the opt-in rule for marketing (`PUT /settings/optin`), the rule looks at **opt-in records**, which are kept apart from the consent on a contact: record those people with `POST /optins` too (scope `settings:manage`). The [marketing broadcast guide](/guides/how-to-marketing-broadcast) shows how.
  </Step>

  <Step title="Register a webhook for the changes on the app2email side">
    One call. The answer holds the **signing secret** (`whsec_...`) that signs every event: keep it as `WEBHOOK_SECRET`.

    ```bash
    curl -s -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{ "url": "https://crm-sync.example.com/app2email" }'
    ```

    **What you get back** (201 Created, shortened):

    ```json
    {
      "success": true,
      "request_id": "w8hk2",
      "webhook": {
        "id": "wh_a1b2c3d4e5f6g7h8",
        "url": "https://crm-sync.example.com/app2email",
        "secret": "whsec_...",
        "active": true,
        "format": "app2email"
      }
    }
    ```

    Every webhook of the number gets every event (at most 5 webhooks per number), so your receiver picks the types it handles by `type` and answers 2xx to all the others. Registering the same URL again answers that webhook, so the call is safe to repeat.

    No public address? `GET /events?types=contact.updated,contact.opted_out,contact.changed_number,message.received&wait=25` fetches the same events. Keep the answer's `cursor` and pass it as `after` on the next call. The first call switches the feed on, and events are kept for 72 hours from then on.
  </Step>

  <Step title="Write the changes into your CRM">
    Your receiver checks the signature, skips events it already handled, answers 200 at once, and then updates the CRM.

    <CodeGroup>

    ```javascript Node.js
    import crypto from "node:crypto";
    import express from "express";

    function verifyWebhook(rawBody, header, secret, toleranceSeconds = 300) {
      const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
      const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]);
      if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSeconds) return false;
      const expected = crypto.createHmac("sha256", secret).update(t + ".").update(rawBody).digest("hex");
      return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
    }

    const app = express();
    app.post("/app2email", express.raw({ type: "application/json" }), async (req, res) => {
      if (!verifyWebhook(req.body, req.get("X-App2email-Signature"), process.env.WEBHOOK_SECRET)) return res.sendStatus(401);
      const eventId = req.get("X-App2email-Delivery");
      if (await alreadySeen(eventId)) return res.sendStatus(200); // a retry
      const event = JSON.parse(req.body);
      res.sendStatus(200); // answer within 10 seconds, then do the work
      if (event.test) return; // test events carry made-up contacts
      const d = event.data;

      switch (event.type) {
        case "contact.opted_out": // STOP, "Stop promotions" or one of your opt-out words
          await crm.markUnsubscribed(d.number, { channel: "whatsapp", reason: d.source, at: d.timestamp });
          break;
        case "contact.updated": {
          if (d.change === "marketing_resumed") {
            await crm.noteMarketingResumed(d.contact.identity, d.timestamp);
            break;
          }
          // upsert, patch or consent: write only what differs, so your own pushes do not loop
          const c = d.contact;
          const current = await crm.findByIdentity(c.identity);
          if (current && sameValues(current, c)) break;
          await crm.save(c.identity, { name: c.name, tags: c.tags, fields: c.custom_fields, consent: c.consent });
          break;
        }
        case "contact.changed_number":
          if (d.change === "user_changed_number") await crm.changePhone(d.previous.phone, d.new.phone);
          else await crm.changeUserId(d.previous.user_id, d.new.user_id);
          break;
        case "message.received": // someone wrote: a lead, or a "last contacted" date
          await crm.touch(d.from ?? d.from_user_id, { name: d.name, lastInboundAt: d.timestamp });
          break;
      }
      await markSeen(eventId);
    });

    app.listen(3000);
    ```

    ```python Python
    import hashlib, hmac, json, os, re, time
    from flask import Flask, request

    def verify_webhook(raw_body: 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 "")
        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_body, hashlib.sha256).hexdigest()
        return any(hmac.compare_digest(v, expected) for v in v1)

    app = Flask(__name__)

    @app.post("/app2email")
    def app2email():
        raw = request.get_data()
        if not verify_webhook(raw, request.headers.get("X-App2email-Signature"), os.environ["WEBHOOK_SECRET"]):
            return "", 401
        event_id = request.headers.get("X-App2email-Delivery")
        if already_seen(event_id):
            return "", 200  # a retry
        queue.put(json.loads(raw))  # a worker calls handle(event) after the answer
        mark_seen(event_id)
        return "", 200  # within 10 seconds

    def handle(event):
        if event.get("test"):
            return  # test events carry made-up contacts
        d = event["data"]
        t = event["type"]
        if t == "contact.opted_out":
            crm.mark_unsubscribed(d["number"], channel="whatsapp", reason=d["source"], at=d.get("timestamp"))
        elif t == "contact.updated":
            if d["change"] == "marketing_resumed":
                crm.note_marketing_resumed(d["contact"]["identity"], d.get("timestamp"))
                return
            c = d["contact"]
            current = crm.find_by_identity(c["identity"])
            if current and same_values(current, c):
                return  # your own push coming back: nothing to do
            crm.save(c["identity"], name=c.get("name"), tags=c.get("tags", []),
                     fields=c.get("custom_fields", {}), consent=c.get("consent"))
        elif t == "contact.changed_number":
            if d["change"] == "user_changed_number":
                crm.change_phone(d["previous"].get("phone"), d["new"].get("phone"))
            else:
                crm.change_user_id(d["previous"].get("user_id"), d["new"].get("user_id"))
        elif t == "message.received":
            crm.touch(d.get("from") or d.get("from_user_id"), name=d.get("name"), last_inbound_at=d.get("timestamp"))
    ```

    </CodeGroup>

    `crm.*`, `alreadySeen`, `markSeen` and `sameValues` stand for your own code. Test the receiver with `POST /webhooks/{id}/test` and a body such as `{"type": "contact.opted_out"}`: you get that event's signed sample, with `"test": true`.
  </Step>

  <Step title="Optional: segments from your CRM's tags and fields">
    A segment is a saved filter over your contacts, so the lists you keep in your CRM can become audiences without copying numbers around. Every condition given must hold: `tags_any`, `tags_all`, `consent_marketing`, `last_inbound_days` (wrote to you in the last N days, 1 to 3650) and `search` (part of the name or number). Up to 100 segments per number.

    <CodeGroup>

    ```bash cURL
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/segments \
      -H "Authorization: Bearer $A2E_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "VIP, consented",
        "filter": { "tags_any": ["vip"], "consent_marketing": true, "last_inbound_days": 90 }
      }'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/segments", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.A2E_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        name: "VIP, consented",
        filter: { tags_any: ["vip"], consent_marketing: true, last_inbound_days: 90 },
      }),
    });
    const { segment } = await res.json();
    console.log(segment.id, segment.contacts);
    ```

    ```python Python
    res = requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/segments",
        headers=HEADERS,
        json={"name": "VIP, consented",
              "filter": {"tags_any": ["vip"], "consent_marketing": True, "last_inbound_days": 90}},
        timeout=10,
    )
    segment = res.json()["segment"]
    print(segment["id"], segment["contacts"])
    ```

    </CodeGroup>

    **What you get back** (HTTP 201): the segment with `id`, `name`, `filter`, `created`, `updated` and `contacts`, how many contacts match now. `GET /segments/{id}/contacts` lists them (page with `next_cursor`), and the id or the exact name works in the path.

    A segment follows your contacts: when the sync changes a tag or the consent, the segment's members change with it. Send a template to it with `"segment": "VIP, consented"` on `POST /messages`; a named template value without a value of its own is filled from each contact's `custom_fields` (`name` from the contact's name). See [Send a marketing broadcast that respects opt-ins](/guides/how-to-marketing-broadcast). A drip sequence with an `enrol_tag` enrols contacts who get that tag from then on: see [Follow up automatically with a drip sequence](/guides/how-to-drip-sequence).
  </Step>

  <Step title="Compare both sides now and then">
    Events cover the API changes, opt-outs and number changes, but `contact.updated` is not sent for imports, for upsert lists of more than 50 contacts, or for changes made outside the API. Once a night (or once a week), read every contact and compare.

    `GET /contacts` pages through the contacts, newest first, up to 200 per page. Filter with `tag`, `consent` (true or false) or `q` (part of the name or number) when you only need some of them.

    <CodeGroup>

    ```bash cURL
    curl -s "https://api.app2email.com/v1/YOUR_NUMBER/contacts?limit=200" \
      -H "Authorization: Bearer $A2E_KEY"
    # next page: add &cursor=<next_cursor of the previous answer>
    ```

    ```javascript Node.js
    export async function* allContacts() {
      let cursor;
      do {
        const url = new URL("https://api.app2email.com/v1/YOUR_NUMBER/contacts");
        url.searchParams.set("limit", "200");
        if (cursor) url.searchParams.set("cursor", cursor);
        const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.A2E_KEY}` } });
        const page = await res.json();
        yield* page.contacts;
        cursor = page.next_cursor;
      } while (cursor);
    }

    for await (const c of allContacts()) {
      if (new Date(c.updated) > lastReconcile) await compareWithCrm(c);
    }
    ```

    ```python Python
    def all_contacts():
        cursor = None
        while True:
            params = {"limit": 200}
            if cursor:
                params["cursor"] = cursor
            page = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/contacts",
                                headers=HEADERS, params=params, timeout=30).json()
            yield from page["contacts"]
            cursor = page.get("next_cursor")
            if not cursor:
                break

    for c in all_contacts():
        if c["updated"] > last_reconcile_iso:
            compare_with_crm(c)
    ```

    </CodeGroup>

    **What you get back:** `contacts` (each in the shape shown in the upsert step), `count` on this page, `total`, and `next_cursor` until the last page.

    For a spreadsheet or a backup, `GET /contacts/export.csv` gives every contact as one CSV file (up to 50,000 rows): one row per contact, tags separated by `|`, the consent, and the custom fields as JSON.

    ```bash
    curl -s https://api.app2email.com/v1/YOUR_NUMBER/contacts/export.csv \
      -H "Authorization: Bearer $A2E_KEY" -o contacts-export.csv
    ```
  </Step>
</Steps>

## The result

Your CRM and app2email now hold the same people with the same tags, fields and consent. This is what arrives at your webhook, and when.

| Event | When it comes | What your CRM does |
| --- | --- | --- |
| `contact.opted_out` | The contact replied STOP (or one of your opt-out words) or tapped "Stop promotions". They are on the Do Not Call list now. `source` is `stop_promotions`, `whatsapp_stop` or `keyword` | Mark them unsubscribed from WhatsApp marketing |
| `contact.updated` with `change` `upsert`, `patch` or `consent` | A contact was made or changed through the API: your sync, another integration, or an AI agent using the MCP tool `upsert_contact` | Save what differs |
| `contact.updated` with `change: "marketing_resumed"` | The contact turned marketing messages from you back on inside WhatsApp | Note it. It is not new consent: record consent only when you have it |
| `contact.changed_number` | The contact moved to a new WhatsApp number (`user_changed_number`), or their business-scoped user id changed (`user_changed_user_id`) | Update the phone or the id on the CRM record |
| `message.received` | The contact wrote to you or tapped a button | Make a lead, or set "last contacted" |

**A contact saved through the API** (`contact.updated`):

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "contact.updated",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": {
      "identity": "61412345678",
      "identity_type": "phone",
      "phone": "61412345678",
      "name": "Sample Contact",
      "tags": ["vip"],
      "custom_fields": { "city": "Sydney" },
      "source": "api",
      "consent": {
        "marketing": true,
        "at": "2026-11-06T01:00:00.000Z",
        "source": "website form",
        "recorded": true
      },
      "created": "2026-11-06T01:00:00.000Z",
      "updated": "2026-11-06T01:00:00.000Z"
    },
    "change": "upsert",
    "timestamp": "2026-11-06T01:00:00.000Z"
  }
}
```

**An opt-out** (`contact.opted_out`):

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "contact.opted_out",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "number": "61412345678",
    "name": "Sample Contact",
    "source": "stop_promotions",
    "detail": "Stop promotions",
    "timestamp": "2026-11-06T01:00:00.000Z"
  }
}
```

**A new number** (`contact.changed_number`):

```json
{
  "id": "evt_Pa3k9m2Lw8Rt5Yp1Zs03",
  "type": "contact.changed_number",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "change": "user_changed_number",
    "previous": { "phone": "61412345678", "user_id": "AU.9876543210987654" },
    "new": { "phone": "61498765432", "user_id": "AU.1234567890123456" },
    "name": "Sample Contact",
    "body": "User Sample Contact changed from 61412345678 to 61498765432",
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
    "timestamp": "2026-11-06T01:00:00.000Z"
  }
}
```

In each event, `number` at the top is **your** WhatsApp number; the contact is inside `data`. A field with no value is left out, so read every field as optional except the ones you match on. `GET /webhooks/samples` gives a sample of every event type.

## When a contact is deleted in your CRM

`DELETE /contacts/{identity}` deletes the contact record. The Do Not Call list and the opt-in records are separate and **stay**, so a person who said STOP is still protected after the delete. Their appointments, notes and payments are kept too, unless you add `?booking_data=erase`: that also erases or anonymises their booking and ticket data, cannot be undone, and is meant for an erasure request. It is refused, with the reason in `note`, while the contact holds a valid ticket for a coming date.

```bash
curl -s -X DELETE "https://api.app2email.com/v1/YOUR_NUMBER/contacts/61412345678" \
  -H "Authorization: Bearer $A2E_KEY"
```

## Production checklist

<AccordionGroup>
  <Accordion title="Check the webhook signature">
    Every event has the header `X-App2email-Signature: t=<unix seconds>,v1=<hex>`. The `v1` value is the HMAC-SHA256 of `"<t>.<raw body>"`, with the webhook's secret (`whsec_...`, prefix included) as the key. Check every `v1=` (there are two while an old secret is still kept after a rotation), compute it over the raw body exactly as received, and refuse an old `t`. The receiver above does this. Refuse an event that fails the check: anyone can post to a public URL, and a forged `contact.opted_out` or `contact.changed_number` would change your CRM.
  </Accordion>

  <Accordion title="Drop repeated events, and do not loop">
    Answer with a 2xx status within 10 seconds. Otherwise the event is sent again after 10 s, 1 min, 5 min, 30 min, 1, 2, 4, 8 and 16 hours. `X-App2email-Delivery` (the event `id`, `evt_...`) is the same on every retry: store it and skip an event you already handled.

    Your own upserts of up to 50 contacts come back as `contact.updated`. If your CRM sends a change to app2email every time a record is saved, writing that event back to the CRM saves the record again, and the two systems ping each other forever. Compare first, and write only the fields that differ. Match records by `identity`, not by name: names are not unique and people change them.
  </Accordion>

  <Accordion title="Safe retries">
    The contact calls take no `Idempotency-Key` header, and they do not need one: an upsert matched by `identity` can be sent again after a timeout or a `500`, and the contact ends up the same, not doubled. The same holds for an import row. Send a `consent` block only when the consent itself changed, not on every sync, so its `at` time and evidence stay those of the real agreement. `POST /donotcall` leaves numbers that are already on the list as they are.
  </Accordion>

  <Accordion title="Rate limits and batch size">
    Send lists, not one call per contact: up to 1000 contacts per `POST /contacts`, up to 5000 rows per `POST /contacts/import`, 200 contacts per page of `GET /contacts`. Every answer has `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (seconds until full again) and `X-RateLimit-Policy`; `limits` in `GET /me` shows the key's `requests_per_second` and `burst`. Over the limit you get `429 rate_limited` with a `Retry-After` header and `error.retry_after_seconds`: wait that long, then send the same request again.

    Any other `4xx`: do not retry unchanged. Decide by `error.code`, follow `how_to_fix`, and quote `request_id` to support. `error.is_retriable` tells you whether the same request can work later.
  </Accordion>

  <Accordion title="Consent, opt-outs and the Do Not Call list">
    - Keep consent in one place of truth. A contact's `consent` is the evidence the Spam Act 2003 expects you to be able to show: the time, where, the wording and the proof. Only record consent you really have.
    - A STOP in WhatsApp puts the person on the Do Not Call list by itself and sends `contact.opted_out`. Write it into your CRM, and do not take them off the list from your CRM unless they agreed again.
    - An unsubscribe in your CRM: `"marketing": false` on the contact and `POST /donotcall`.
    - `contact.updated` with `marketing_resumed` means the person turned your marketing back on inside WhatsApp. It is a signal, not consent with evidence.
    - The Do Not Call list and the opt-in rule apply to MARKETING templates only. Order updates and other utility templates still go out, and so do your replies to someone who wrote to you.
    - `GET /compliance/export.csv` (scope `dnc:manage`) gives the consent records, the Do Not Call list and the opt-ins as one file.
  </Accordion>

  <Accordion title="The 24-hour window and templates">
    Contacts and segments only decide who gets a message. Starting a conversation, or writing after the contact's last message is more than 24 hours old, still needs an approved template; inside the window you can send normal messages. `GET /conversations/{contact}` shows `window_state` and `window_closes_at`. See [Send order and appointment notifications with templates](/guides/how-to-order-notifications).
  </Accordion>

  <Accordion title="Keep the key on your server">
    The sync key can read and change every contact. Keep it in your server's environment, never in a web page or a CRM field that other users can see. A key can be limited to your server's IP addresses (a call from elsewhere answers `403 ip_not_allowed`) and can expire; give it only the scopes this guide needs.
  </Accordion>
</AccordionGroup>

## If it does not work

Every error is JSON with `error.code`, `message`, `how_to_fix` and a `request_id` to quote to support. See [Errors](/api/errors) for every code and [Limits](/api/limits) for the limits.

| Code | When | What to do |
| --- | --- | --- |
| `403 insufficient_scope` | The key lacks a scope (`details.required_scope`), often `contacts:manage` on the Default key | Make a key with the scopes in the table above, or Full access |
| `403 not_in_instant_sandbox` | A contacts call on the demo number `12025550100` | Use your own connected number |
| `403 api_key_number_mismatch` | The key and the number in the URL do not belong together, for example a real number's key used with the demo number | Use the key of the number in the URL |
| `401 missing_api_key`, `invalid_api_key`, `api_key_revoked`, `api_key_expired` | No key, a wrong key, or a key that was revoked or expired | Send `Authorization: Bearer YOUR_API_KEY` with a key listed on the API key page |
| `403 plan_not_allowed`, `403 service_not_live` | No paid plan, or the service is paused | Check the plan and the service status in the dashboard |
| `400 invalid_contacts` | A contact in the body is not valid, or there is nothing to change | Send `{"phone": "61412345678", "name": "John", "tags": ["vip"]}` or a list of them |
| `400 too_many_numbers` | More contacts in one request than allowed (1000 for `POST /contacts`) | Split the list, or use `POST /contacts/import` (up to 5000 rows) |
| `400 invalid_csv` | The CSV has no header row or no contact row | Send a header row and at least one row, as `text/csv` |
| `400 invalid_json` | The body is not valid JSON | Check quotes, commas and brackets near the position in the message |
| `413 request_too_large` | The body is too large | Send the file in smaller parts |
| A row in `errors` of the import | One row could not be read, for example a number without its country code | Fix that row and import it again; the other rows were saved |
| `400 invalid_phone` | The contact in the URL is not a number or a business-scoped user id | Use the full number, country code first, digits only (`/contacts/61412345678`) |
| `404 contact_not_found` | `GET` or `PATCH` for a contact app2email does not have | Check the identity; `POST /contacts` makes it |
| `400 invalid_numbers` | `POST /donotcall` with a number that is not valid (`details.invalid`); nothing was added | Fix the listed numbers and send the call again |
| `400 invalid_segment` | The segment name is empty, longer than 100 characters, or just a number | Send `{"name": "VIP, consented", "filter": {...}}` |
| `409 segment_exists` | A segment with that name exists | Use another name, or change it with `PUT /segments/{id}` |
| `400 too_many_segments` | The number has 100 segments | Delete one you no longer use |
| `404 segment_not_found` | No segment with that id or name | `GET /segments` lists them; use the id or the exact name |
| `400 invalid_cursor` | The `cursor` was changed or comes from another list | Pass `next_cursor` unchanged, or leave it out for the first page |
| `429 rate_limited` | Too many calls for this key | Wait `Retry-After` seconds, then send the same request again |
| Events do not arrive | The webhook was switched off after many failed deliveries, or your URL does not answer 2xx within 10 seconds | Look at `GET /webhooks/{id}/deliveries`; turn it back on with `PATCH /webhooks/{id}` and `{"active": true}` |
| No `contact.updated` after a sync | Imports, and upsert lists of more than 50 contacts, send no event | Expected; compare with `GET /contacts` instead |

## More how-to guides

<CardGroup cols={2}>
  <Card title="Send a marketing broadcast that respects opt-ins" href="/guides/how-to-marketing-broadcast">
    Send a template to a segment of contacts who agreed, and follow the result per number.
  </Card>
  <Card title="Follow up automatically with a drip sequence" href="/guides/how-to-drip-sequence">
    Enrol contacts by tag and send a series of templates on their own schedule.
  </Card>
  <Card title="Send WhatsApp messages from n8n, Zapier or Make" href="/guides/how-to-no-code-n8n-zapier-make">
    Run the sync and the sends from an automation tool, without writing a server.
  </Card>
  <Card title="Send order and appointment notifications with templates" href="/guides/how-to-order-notifications">
    Create a utility template, get it approved, and follow every message.
  </Card>
</CardGroup>

[All how-to guides](https://www.app2email.com/docs#how-to)
