# Add buyers to a group

> Sell a group course on your website and let your shop add every buyer to the right Quenza group, with the course's activities sent to them.

Source: https://quenza.com/help/api/guides/add-buyers-to-a-group/

When you sell a group course online, every buyer should end up in the course's group in Quenza, with the chat and the activities the group already received. This guide sets that up once and then handles each purchase automatically.

Bright Path Coaching sells its eight-week Mindfulness course in its web shop. When Lucas Meyer buys a place, the shop creates him in Quenza and adds him to the Mindfulness group. Lucas gets his invitation, joins the group chat and receives the first week's activities, even though the course started a week ago.

The examples come in JavaScript (Node.js 18 or later), Python (with `requests`) and PHP (with Guzzle); pick your language in the tabs.

## Create the group once

[Create a group](https://quenza.com/help/api/groups/create-a-group/) for the course, or create it in Quenza by hand. Switch on `auto_send_assignments_to_new_members`, so people who join later get what the group already received, and `enable_chat` for a group chat:

**JavaScript**

```js
const API = 'https://developers.quenza.com/v1';
const headers = {
  Authorization: `Bearer ${process.env.QUENZA_API_TOKEN}`,
  Accept: 'application/json',
  'Content-Type': 'application/json',
};

const response = await fetch(`${API}/groups`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    name: 'Mindfulness group',
    description: 'Eight weekly sessions on attention, breathing and self-compassion.',
    enable_chat: true,
    auto_send_assignments_to_new_members: true,
  }),
});
if (!response.ok) throw new Error(`Quenza API error ${response.status}`);
const groupId = (await response.json()).data.id; // "R4XN8VQT"
```

**Python**

```python
import os

import requests

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

response = requests.post(f"{API}/groups", headers=HEADERS, json={
    "name": "Mindfulness group",
    "description": "Eight weekly sessions on attention, breathing and self-compassion.",
    "enable_chat": True,
    "auto_send_assignments_to_new_members": True,
})
response.raise_for_status()
group_id = response.json()["data"]["id"]  # "R4XN8VQT"
```

**PHP**

```php
<?php

require 'vendor/autoload.php';

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

$response = $http->post('groups', ['json' => [
    'name' => 'Mindfulness group',
    'description' => 'Eight weekly sessions on attention, breathing and self-compassion.',
    'enable_chat' => true,
    'auto_send_assignments_to_new_members' => true,
]]);
$groupId = json_decode($response->getBody(), true)['data']['id']; // "R4XN8VQT"
```


Store the group's ID in your shop's settings, next to the product. A group you created in Quenza by hand has an ID too, but the API has no list of groups; create the group through the API if your shop needs its ID.

## Add each buyer

When an order is paid, create the client, then [add them to the group](https://quenza.com/help/api/groups/add-members-to-a-group/):

**JavaScript**

```js
async function enrol(order, groupId) {
  const created = await fetch(`${API}/clients`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ email: order.email, first_name: order.first_name, last_name: order.last_name }),
  });
  const body = await created.json();
  let clientId;
  if (created.status === 422 && body.errors?.email) {
    clientId = await findClientId(order.email); // already a client, see below
  } else if (!created.ok) {
    throw new Error(`Quenza API error ${created.status}: ${body.message}`);
  } else {
    clientId = body.data.id;
  }

  const added = await fetch(`${API}/groups/${groupId}/members`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ members: [clientId] }),
  });
  if (!added.ok) throw new Error(`Quenza API error ${added.status}`);
}
```

**Python**

```python
def enrol(order, group_id):
    response = requests.post(f"{API}/clients", headers=HEADERS, json={
        "email": order["email"],
        "first_name": order["first_name"],
        "last_name": order["last_name"],
    })
    if response.status_code == 422 and "email" in response.json().get("errors", {}):
        client_id = find_client_id(order["email"])  # already a client, see below
    else:
        response.raise_for_status()
        client_id = response.json()["data"]["id"]

    response = requests.post(
        f"{API}/groups/{group_id}/members",
        headers=HEADERS,
        json={"members": [client_id]},
    )
    response.raise_for_status()
```

**PHP**

```php
use GuzzleHttp\Exception\ClientException;

function enrol(GuzzleHttp\Client $http, array $order, string $groupId): void
{
    try {
        $response = $http->post('clients', ['json' => [
            'email' => $order['email'],
            'first_name' => $order['first_name'],
            'last_name' => $order['last_name'],
        ]]);
        $clientId = json_decode($response->getBody(), true)['data']['id'];
    } catch (ClientException $e) {
        $body = json_decode($e->getResponse()->getBody(), true);
        if ($e->getResponse()->getStatusCode() !== 422 || !isset($body['errors']['email'])) {
            throw $e;
        }
        $clientId = findClientId($http, $order['email']); // already a client, see below
    }

    $http->post("groups/{$groupId}/members", ['json' => ['members' => [$clientId]]]);
}
```


A buyer who is already a client cannot be created again. Find their ID in the list of clients, as [Sync clients from your CRM](https://quenza.com/help/api/guides/sync-clients/#handle-clients-who-already-exist) shows.

Adding someone who is already in the group does nothing and answers with `204`. So when a payment notification arrives twice, nothing breaks.

## What the buyer gets

- An invitation email to set up their account.
- A place in the group chat, if the group has one.
- The activities and programs the group already received, because `auto_send_assignments_to_new_members` is on. See [New group members](https://quenza.com/help/clients/new-group-members/).

> **Tip:** Your plan's client limit also applies to clients created through the API. When it is reached, creating a client fails with `422` and `Limit reached`. Let the shop email you in that case, so no buyer is left waiting. See [Errors](https://quenza.com/help/api/errors/#422-validation-error).
