# Sync clients from your CRM

> Create clients in Quenza when a lead in your CRM becomes a client, find clients who already exist, and keep their details up to date.

Source: https://quenza.com/help/api/guides/sync-clients/

Many practices keep leads in a CRM and move them to Quenza once they book. This guide connects the two: when a lead becomes a client in the CRM, your integration creates them in Quenza, remembers their Quenza ID and keeps their details in step.

Sarah Bennett, for example, tracks enquiries for Bright Path Coaching in her CRM. When she marks Emma Clarke as **Booked**, the CRM calls her integration, Emma gets her invitation from Quenza, and the CRM stores Emma's Quenza ID for later updates.

Every example comes in JavaScript (Node.js 18 or later), Python (with `requests`) and PHP (with Guzzle); pick your language in the tabs. They all use this small helper, which sends a request and stops with an error when Quenza answers with one:

**JavaScript**

```js
const API = 'https://developers.quenza.com/v1';

async function quenza(method, path, body) {
  const response = await fetch(`${API}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.QUENZA_API_TOKEN}`,
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: body && JSON.stringify(body),
  });
  const json = response.status === 204 ? null : await response.json();
  if (!response.ok) throw Object.assign(new Error(json.message), { status: response.status, errors: json.errors });
  return json;
}
```

**Python**

```python
import os

import requests

API = "https://developers.quenza.com/v1"
HEADERS = {
    "Authorization": f"Bearer {os.environ['QUENZA_API_TOKEN']}",
    "Accept": "application/json",
    "Content-Type": "application/json",
}


class QuenzaError(Exception):
    def __init__(self, response):
        body = response.json()
        super().__init__(body.get("message"))
        self.status = response.status_code
        self.errors = body.get("errors", {})


def quenza(method, path, body=None):
    response = requests.request(method, f"{API}{path}", headers=HEADERS, json=body)
    if not response.ok:
        raise QuenzaError(response)
    return response.json() if response.content else None
```

**PHP**

```php
<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

$http = new Client([
    'base_uri' => 'https://developers.quenza.com/v1/',
    'headers' => [
        'Authorization' => 'Bearer ' . getenv('QUENZA_API_TOKEN'),
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
    ],
]);

// Guzzle throws a ClientException when Quenza answers with an error.
$quenza = function (string $method, string $path, ?array $body = null) use ($http): ?array {
    $response = $http->request($method, $path, $body === null ? [] : ['json' => $body]);
    return json_decode($response->getBody(), true);
};
```


## Create the client

[Create a client](https://quenza.com/help/api/clients/create-a-client/) with their email and name. Quenza sends the invitation email straight away and assigns the client to the professional who owns the token.

**JavaScript**

```js
const { data: client } = await quenza('POST', '/clients', {
  email: 'emma.clarke@example.com',
  first_name: 'Emma',
  last_name: 'Clarke',
  timezone: 'Europe/Amsterdam',
  language_code: 'en',
});
// Store client.id ("8GJ4D9KQ") on the contact in your CRM.
```

**Python**

```python
client = quenza("POST", "/clients", {
    "email": "emma.clarke@example.com",
    "first_name": "Emma",
    "last_name": "Clarke",
    "timezone": "Europe/Amsterdam",
    "language_code": "en",
})["data"]
# Store client["id"] ("8GJ4D9KQ") on the contact in your CRM.
```

**PHP**

```php
$client = $quenza('POST', 'clients', [
    'email' => 'emma.clarke@example.com',
    'first_name' => 'Emma',
    'last_name' => 'Clarke',
    'timezone' => 'Europe/Amsterdam',
    'language_code' => 'en',
])['data'];
// Store $client['id'] ("8GJ4D9KQ") on the contact in your CRM.
```


Store the returned `id` in your CRM, for example in a custom field. Every later request about this client uses it.

## Handle clients who already exist

An email address can belong to only one client in a workspace. When the client is already in Quenza, for example because they signed up through a landing page, the request fails with `422` and an `errors.email` entry. The API has no search, so look the client up in the list of clients:

**JavaScript**

```js
async function findClientByEmail(email) {
  let path = '/clients?limit=100';
  while (path) {
    const { data, links } = await quenza('GET', path);
    const match = data.find((c) => c.email.toLowerCase() === email.toLowerCase());
    if (match) return match;
    path = links.next && links.next.replace(API, '');
  }
  return null;
}

async function createOrFindClient(contact) {
  try {
    return (await quenza('POST', '/clients', contact)).data;
  } catch (error) {
    if (error.status === 422 && error.errors?.email) return findClientByEmail(contact.email);
    throw error;
  }
}
```

**Python**

```python
def find_client_by_email(email):
    path = "/clients?limit=100"
    while path:
        page = quenza("GET", path)
        for client in page["data"]:
            if client["email"].lower() == email.lower():
                return client
        path = page["links"]["next"] and page["links"]["next"].replace(API, "")
    return None


def create_or_find_client(contact):
    try:
        return quenza("POST", "/clients", contact)["data"]
    except QuenzaError as error:
        if error.status == 422 and "email" in error.errors:
            return find_client_by_email(contact["email"])
        raise
```

**PHP**

```php
function findClientByEmail(callable $quenza, string $email): ?array
{
    $url = 'clients?limit=100';
    while ($url !== null) {
        $page = $quenza('GET', $url);
        foreach ($page['data'] as $client) {
            if (strcasecmp($client['email'], $email) === 0) {
                return $client;
            }
        }
        $url = $page['links']['next'];
    }
    return null;
}

function createOrFindClient(callable $quenza, array $contact): ?array
{
    try {
        return $quenza('POST', 'clients', $contact)['data'];
    } catch (ClientException $e) {
        $body = json_decode($e->getResponse()->getBody(), true);
        if ($e->getResponse()->getStatusCode() === 422 && isset($body['errors']['email'])) {
            return findClientByEmail($quenza, $contact['email']);
        }
        throw $e;
    }
}
```


A `422` without `errors.email` means something else, for example that your plan's client limit is reached; the code passes those errors on. Reading the whole list for every contact is slow in a large workspace. Do it once, store the IDs in your CRM, and only fall back to the list when a contact has no ID yet.

## Keep details up to date

When a phone number or name changes in the CRM, [update the client](https://quenza.com/help/api/clients/update-a-client/) with only the fields that changed:

**JavaScript**

```js
await quenza('PATCH', `/clients/${contact.quenzaId}`, { phone: '+31 6 9876 5432' });
```

**Python**

```python
quenza("PATCH", f"/clients/{contact['quenza_id']}", {"phone": "+31 6 9876 5432"})
```

**PHP**

```php
$quenza('PATCH', "clients/{$contact['quenza_id']}", ['phone' => '+31 6 9876 5432']);
```


Leave out the fields you do not want to change. To clear an optional field, send `null`.

## When the coaching ends

When a client leaves, [archive them](https://quenza.com/help/api/clients/archive-a-client/). Their history stays in Quenza, their assignments are cancelled and their chats become read-only. If they come back, [unarchive them](https://quenza.com/help/api/clients/unarchive-a-client/).

## The other direction

To update the CRM when something happens in Quenza, for example when a client accepts their invitation, use [webhooks](https://quenza.com/help/api/webhooks/). Together with the API, both systems stay in step without anyone copying data by hand.
