> For the complete documentation index, see [llms.txt](https://docs.saleschat.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.saleschat.pro/getting-started/basic-crm-integration-tutorial.md).

# Basic CRM integration tutorial

Connect your CRM to Saleschat with the Lead APIs: create leads, assign them to human agents, and send Saleschat each lead's events and attributes.

This tutorial connects your CRM to Saleschat with the Lead APIs. Your CRM creates each lead in Saleschat, decides which human agent the lead is assigned to, and tells Saleschat what happens to the lead through events and attributes. The AI agent and your journeys work from that data.

## Before you start

* Get your org ID from the Saleschat team, and ask a user with the Owner or Admin role to generate an API key. See [Onboarding](https://docs.saleschat.pro/getting-started/onboarding.md).
* Allow the Saleschat domains on the networks that your CRM and your human agents use, as listed in [Whitelist URLs](https://docs.saleschat.pro/getting-started/whitelist-urls.md). If your firewall restricts which servers can call your APIs, also allow the [Outbound IP addresses](https://docs.saleschat.pro/getting-started/outbound-ip-addresses.md).

Your CRM's backend makes every call in this tutorial and sends the API key in the `x-api-key` header. The org ID in the path must be the org the key belongs to. Calls made with the API key are limited to 20 requests per second per endpoint for your org, as described in [Rate limit](https://docs.saleschat.pro/api-documentation/rate-limit.md).

If your org still uses the deprecated Contact APIs, read [Contacts vs Leads](https://docs.saleschat.pro/principles/contacts-vs-leads.md) before you add the Lead APIs.

## Create leads

Create each lead in Saleschat as soon as it exists in your CRM, so that journeys and the AI agent can work with it before a human agent picks it up.

```bash
curl --request POST \
  --url 'https://apis.saleschat.pro/v4/orgs/YOUR_ORG_ID/leads' \
  --header 'x-api-key: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "crm_id": "VYOM-8841203",
    "first_name": "Nitin",
    "last_name": "Kumar",
    "phone_number": "+919876543210",
    "attributes": { "city": "Pune", "product": "term insurance" }
  }'
```

| Field          | Required | Description                                                                                                               |
| -------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
| `crm_id`       | Yes      | The ID your CRM uses for the lead.                                                                                        |
| `first_name`   | Yes      | The lead's first name. Can't be blank.                                                                                    |
| `last_name`    | No       | The lead's last name. Can be blank or left out.                                                                           |
| `phone_number` | Yes      | The lead's WhatsApp number in E.164 format, such as `+919876543210`.                                                      |
| `attributes`   | Yes      | The lead's attributes, as described in [Update lead attributes](#update-lead-attributes). Send `{}` if you have none yet. |
| `opt_in_date`  | No       | When the lead agreed to receive WhatsApp messages, in Unix epoch seconds. Defaults to the time the lead is created.       |

The response includes the lead's `lead_id`. Every Lead API that takes a lead in its path accepts either the `lead_id` or your `crm_id`, so you don't need to store the `lead_id`.

If you don't have the lead's name yet, send the `crm_id` as `first_name`. Human agents see the lead's chat named `<crm_id> <first_name> <last_name>`, and they know the lead by its `crm_id` in both your CRM and Saleschat.

### Choose CRM IDs

Saleschat uses your `crm_id` to find the lead, so each one has to point to one lead:

* **Keep it unique in your org.** Creating a lead with a `crm_id` that another lead already has returns `409 Conflict`. You can reuse the `crm_id` of a lead that has expired.
* **Don't change it.** Once a lead exists, keep its `crm_id` the same in your CRM.
* **Don't use the lead's phone number.** Human agents see the `crm_id` in the chat name in place of the lead's phone number, so a `crm_id` that doesn't contain the number keeps it hidden from them. Leads that Saleschat creates from new inbound messages use the phone number as their `crm_id`.

Saleschat matches a `crm_id` regardless of case, so `VYOM-1` and `vyom-1` are the same ID. Trim leading and trailing spaces before you send one.

## Assign leads

Assigning a lead and showing chats are two separate steps. Assigning records which human agent the lead belongs to. Saleschat **shows chats** when it adds that human agent as a participant to the lead's chat, and only then can the human agent and their managers see the conversation and reply.

Your CRM can assign a lead in two ways.

### Assign immediately with the Assign API

Use the Assign API when the human agent needs the conversation now, for example when they select **Chat** during a call. Saleschat records the assignment within the request and shows chats straight away, a moment after it responds. Any other human agent in the chat is removed.

```bash
curl --request PUT \
  --url 'https://apis.saleschat.pro/v4/orgs/YOUR_ORG_ID/leads/VYOM-8841203/assign' \
  --header 'x-api-key: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{ "user_email": "priya@example.com" }'
```

The body takes the human agent's `user_email` or `user_id`. If you send both, Saleschat uses `user_id`. Assigning a lead to the human agent who already has it changes nothing, so you can retry the request safely. Show these errors to the human agent, so they know why the chat didn't appear:

| Status | Cause                                                                                | What to do                                                                                                                                                             |
| ------ | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `404`  | No lead has this `crm_id` or `lead_id`, or no active user has this email or user ID. | Create the lead first, or check that the human agent's user is active.                                                                                                 |
| `409`  | Another lead with the same phone number holds the conversation.                      | Activate this lead, or add a lifecycle rule that activates leads when they're assigned. See [Lead Lifecycle](https://docs.saleschat.pro/principles/lead-lifecycle.md). |
| `422`  | The lead has expired, or the body has neither `user_email` nor `user_id`.            | Create a new lead for an expired one, or add the missing field.                                                                                                        |

### Defer assignment with a lead event

Use deferred assignment for a lead who should belong to a human agent but isn't talking to you yet, mainly after a call that didn't connect. Add `sc_assigned_user_id` or `sc_assigned_email_id` to the attributes of the disposition event you record. Saleschat records the assignment straight away and shows chats when the lead replies or an AI agent hands the lead over, so the human agent's chat list holds only leads who have responded. [Record lead events](#record-lead-events) has an example.

If your dialler runs in progressive or predictive mode and hasn't given the lead to a human agent yet, record the disposition event without an assignment key. Saleschat assigns the lead when they reply. The Assign API can't create a deferred assignment.

Once a lead's chats have been shown, every later assignment of that lead shows chats immediately, whichever way it's made. [Lead assignment](https://docs.saleschat.pro/principles/lead-assignment.md) covers every way a lead can be assigned and what happens when assignments overlap.

## Record lead events

An event is something that happened to the lead at a point in time: a call that ended with a disposition, a callback that was scheduled, a pricing page the lead viewed, or an application form they started. Events start automations and appear in analytics.

This request records a phone call that didn't connect, and assigns the lead to the human agent who should follow it up:

```bash
curl --request PUT \
  --url 'https://apis.saleschat.pro/v4/orgs/YOUR_ORG_ID/leads/VYOM-8841203/events' \
  --header 'x-api-key: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "distinct_id": "call-77f21a04",
    "event": "call_completed",
    "attributes": {
      "disposition": "Not Connected",
      "sub_disposition": "Ringing No Answer",
      "sc_assigned_email_id": "priya@example.com"
    }
  }'
```

| Field         | Required | Description                                                                                                       |
| ------------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| `event`       | Yes      | The event name, up to 128 characters.                                                                             |
| `attributes`  | No       | Details of the event, as key-value pairs.                                                                         |
| `distinct_id` | No       | Your own ID for the event, up to 36 characters. Saleschat records an event with the same `distinct_id` only once. |

A `202 Accepted` response means Saleschat has recorded the event. Anything the event triggers, such as the assignment, an automation, or a [lifecycle rule](https://docs.saleschat.pro/principles/lead-lifecycle.md), runs after Saleschat responds, so the response can't report a failure in it. To confirm that a lead was assigned, subscribe to the [Contact Assigned webhook](https://docs.saleschat.pro/getting-started/webhooks.md#contact-assigned), which Saleschat sends whenever a lead is assigned. "Contact" is the older name for a lead.

Two habits keep your events useful:

* **Send your own ID as `distinct_id`**, such as the call ID, so a retry from your CRM doesn't record the same call twice.
* **Keep event names to a small, fixed set.** Every new event name appears in the automation event picker for good. Put the part that varies in `attributes`: send `call_completed` with a `disposition` attribute, not `call_completed_RNA`.

## Update lead attributes

Attributes hold what you know about the lead that changes rarely, such as their city, preferred language, product of interest, plan, or branch. Update them whenever they change in your CRM, regardless of how a call is disposed. Something that happens at a point in time, such as a call or a page visit, is an event.

```bash
curl --request PATCH \
  --url 'https://apis.saleschat.pro/v4/orgs/YOUR_ORG_ID/dynamic-attributes/lead/VYOM-8841203' \
  --header 'x-api-key: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{ "attributes": { "preferred_language": "hindi", "plan": "gold" } }'
```

Each update merges into the lead's existing attributes: new keys are added, existing keys take the new value, and keys you leave out keep their value. Keys and values are matched regardless of case, so `City` and `city` are the same key.

Keys that start with `sc_` are reserved for Saleschat. Campaign reporting reads `sc_campaign`, so set it to the name of the campaign the lead came from. Don't create any other `sc_` keys. [Events & Attributes](https://docs.saleschat.pro/principles/events-and-attributes.md) explains how automations use attributes and events together.

## Add Login and Chat buttons to your CRM

Two buttons let human agents move between your CRM and Saleschat.

### Login

**Login** opens Saleschat in a new tab with the human agent signed in. When a human agent selects it, your CRM:

1. Finds the human agent's `user_id`. Look it up by email with the [Get Users API](https://docs.saleschat.pro/api-documentation/user.md), or read it from your own mapping of emails to user IDs. The Get Users API returns a page of users, so confirm that the returned user's email matches before you use its `user_id`.
2. Generates a magic link for that `user_id` with the [Magic Link API](https://docs.saleschat.pro/api-documentation/user.md).
3. Opens the `url` from the response in a new tab.

```bash
curl --request GET \
  --url 'https://apis.saleschat.pro/v1/org/YOUR_ORG_ID/user/USER_ID/magiclink' \
  --header 'x-api-key: YOUR_API_KEY'
```

```json
{ "url": "https://..." }
```

A magic link is valid for 24 hours. Like WhatsApp Web, the Saleschat tab usually stays open all day, so most human agents sign in once or a few times a day. Your CRM decides how often to generate a link. Only one Saleschat tab can be active at a time: opening a new one makes the earlier tabs inactive.

You can create users in advance with the [Create User API](https://docs.saleschat.pro/api-documentation/user.md), for example in a one-off script. When a human agent leaves your org, delete their user and reassign their leads. Most integrations do this automatically: when your dialler reassigns the leads, your CRM calls the Assign API for each one.

### Chat

**Chat** puts the lead's chat at the top of the human agent's chat list, in the Saleschat tab they already have open. It doesn't open a new tab. Human agents use it to message a lead during a call, without waiting for the call to be disposed, or later, when a lead assigned to them in your CRM isn't in their chat list. When a human agent selects it, your CRM:

1. Looks the lead up by its `crm_id`. Percent-encode the value, so a leading `+` is sent as `%2B`.

   ```bash
   curl --request GET \
     --url 'https://apis.saleschat.pro/v4/orgs/YOUR_ORG_ID/leads/lookup?crm_id=VYOM-8841203' \
     --header 'x-api-key: YOUR_API_KEY'
   ```
2. If the lookup returns `404`, creates the lead as described in [Create leads](#create-leads).
3. Assigns the lead to the human agent with the Assign API, as described in [Assign leads](#assign-leads).

Show any error from these calls to the human agent, so they know why the chat didn't appear.

## Receive updates from Saleschat

The calls above send data from your CRM to Saleschat. To learn what happens in Saleschat, subscribe to [Webhooks](https://docs.saleschat.pro/getting-started/webhooks.md). Start with these two:

* **Opt-outs.** When a lead opts out, stop offering **Chat** for them and stop queuing them for outbound messages.
* **Chatroom Status Update.** Saleschat sends it when a lead's chat is deactivated or expires, so your CRM can show that before a human agent selects **Chat**. [Lead Lifecycle](https://docs.saleschat.pro/principles/lead-lifecycle.md) explains these states.

## Check your integration

1. Create a test lead with your own phone number.
2. As a human agent, select **Login**, then **Chat** for the test lead. The chat appears at the top of the chat list in the Saleschat tab.
3. Create a second test lead with another phone number you can message from, and record an event for it with `sc_assigned_email_id` set to your human agent's email. Saleschat sends the Contact Assigned webhook, but the chat isn't in the chat list yet.
4. Send a WhatsApp message to your business number from the second lead's phone. The chat appears in the human agent's chat list.
