Démarrer avec l'API en 5 minutes
Chaque exemple de cette page fonctionne tel quel, avec les valeurs dont il a besoin dans des variables
d’environnement C2R_* : C2R_TOKEN pour le jeton, C2R_CHAT_ID pour un chat, et C2R_API uniquement
pour viser une autre adresse que https://api.click2reply.com ; les exemples OAuth et webhook
en lisent quelques autres, indiquées là où ils les utilisent. Ce sont les mêmes fichiers que nos propres
tests exécutent sur une organisation de test.
1. Obtenir un jeton
Section intitulée « 1. Obtenir un jeton »Chaque appel comporte Authorization: Bearer <token>. Le jeton à utiliser dépend de celui au nom duquel
le code agit.
Vos propres scripts : un jeton d’accès personnel
Section intitulée « Vos propres scripts : un jeton d’accès personnel »-
Dans l’application agent, ouvrez Paramètres > API et webhooks.
-
Dans Jetons d’accès personnels, créez-en un, nommez-le d’après le script et cochez uniquement les autorisations dont il a besoin. Ce démarrage rapide nécessite chats.access.
-
Copiez le jeton, qui commence par
c2r_pat_. Il n’est affiché qu’une fois ; conservez-le comme un secret.
Un jeton agit en votre nom, avec les autorisations que vous lui avez données et que votre rôle permet encore : si votre rôle perd une permission, le jeton la perd aussi. Pour un script qui ne doit pas agir au nom d’une personne, créez un agent bot et un jeton pour lui dans Jetons de bot.
Une application que d’autres organisations installent : OAuth 2.0
Section intitulée « Une application que d’autres organisations installent : OAuth 2.0 »Enregistrez l’application dans Paramètres > API et webhooks > Vos applications, avec ses URI de
redirection et le maximum d’autorisations qu’elle peut demander. Vous obtenez un client_id et, pour
une application serveur, un client_secret, affiché une seule fois.
Envoyez l’utilisateur vers l’écran d’autorisation, avec une paire PKCE, pour qu’un code volé ne serve à rien :
// Start the OAuth flow: a PKCE pair, a state, and the URL to send the user to. Node 18 or later.import { createHash, randomBytes } from "node:crypto";
const app = process.env.C2R_APP || "https://app.click2reply.com";const verifier = randomBytes(32).toString("base64url");const challenge = createHash("sha256").update(verifier).digest("base64url");const state = randomBytes(16).toString("base64url");
const url = new URL("/oauth/authorize", app);url.search = new URLSearchParams({ response_type: "code", client_id: process.env.C2R_CLIENT_ID, redirect_uri: process.env.C2R_REDIRECT_URI, scope: "chats.access", state, code_challenge: challenge, code_challenge_method: "S256",}).toString();
// Keep the verifier and the state with the user's session, then redirect the user to the URL.console.log(JSON.stringify({ url: url.href, verifier, state }));L’utilisateur donne son accord, et son navigateur revient sur votre URI de redirection avec
?code=...&state=.... Vérifiez que state est bien celui que vous avez enregistré, puis échangez le
code dans les 5 minutes :
#!/bin/sh# Exchange the code your redirect URI received for an access and a refresh token.API="${C2R_API:-https://api.click2reply.com}"
curl -sS -X POST "$API/v1/oauth/token" \ --data-urlencode "grant_type=authorization_code" \ --data-urlencode "code=$C2R_CODE" \ --data-urlencode "redirect_uri=$C2R_REDIRECT_URI" \ --data-urlencode "client_id=$C2R_CLIENT_ID" \ --data-urlencode "code_verifier=$C2R_CODE_VERIFIER" \ ${C2R_CLIENT_SECRET:+--data-urlencode "client_secret=$C2R_CLIENT_SECRET"}// Exchange the code your redirect URI received for an access and a refresh token. Node 18 or later.const api = process.env.C2R_API || "https://api.click2reply.com";
const res = await fetch(`${api}/v1/oauth/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "authorization_code", code: process.env.C2R_CODE, redirect_uri: process.env.C2R_REDIRECT_URI, client_id: process.env.C2R_CLIENT_ID, code_verifier: process.env.C2R_CODE_VERIFIER, // A public app has no secret and sends none. ...(process.env.C2R_CLIENT_SECRET ? { client_secret: process.env.C2R_CLIENT_SECRET } : {}), }),});const tokens = await res.json();if (!res.ok) throw new Error(`${tokens.error}: ${tokens.error_description}`);console.log(JSON.stringify(tokens));# Exchange the code your redirect URI received for an access and a refresh token. Python 3.8 or later.import jsonimport osimport urllib.errorimport urllib.parseimport urllib.request
API = os.environ.get("C2R_API") or "https://api.click2reply.com"
fields = { "grant_type": "authorization_code", "code": os.environ["C2R_CODE"], "redirect_uri": os.environ["C2R_REDIRECT_URI"], "client_id": os.environ["C2R_CLIENT_ID"], "code_verifier": os.environ["C2R_CODE_VERIFIER"],}# A public app has no secret and sends none.if os.environ.get("C2R_CLIENT_SECRET"): fields["client_secret"] = os.environ["C2R_CLIENT_SECRET"]form = urllib.parse.urlencode(fields).encode()
try: with urllib.request.urlopen(urllib.request.Request(API + "/v1/oauth/token", data=form)) as res: print(json.dumps(json.load(res)))except urllib.error.HTTPError as e: err = json.load(e) raise SystemExit(f"{err['error']}: {err['error_description']}")La réponse contient un access_token (c2r_oat_, valable 60 minutes), un refresh_token
(c2r_ort_, valable 60 jours), le scope accordé, ainsi que l’organization_id et l’agent_id
au nom desquels le jeton agit. Une application publique, qui ne peut pas garder de secret, omet
client_secret et doit envoyer le vérificateur PKCE.
Avant l’expiration du jeton d’accès, échangez le jeton d’actualisation contre une nouvelle paire :
#!/bin/sh# Trade a refresh token for a new access token. The answer carries a new refresh token too: keep it.API="${C2R_API:-https://api.click2reply.com}"
curl -sS -X POST "$API/v1/oauth/token" \ --data-urlencode "grant_type=refresh_token" \ --data-urlencode "refresh_token=$C2R_REFRESH_TOKEN" \ --data-urlencode "client_id=$C2R_CLIENT_ID" \ ${C2R_CLIENT_SECRET:+--data-urlencode "client_secret=$C2R_CLIENT_SECRET"}Les métadonnées du serveur d’autorisation se trouvent à l’adresse https://api.click2reply.com/v1/oauth/metadata :
une bibliothèque OAuth peut ainsi se configurer toute seule. La page authentification
détaille les autorisations, la révocation des jetons et les limites de débit.
2. Envoyer un message
Section intitulée « 2. Envoyer un message »Listez les chats les plus récents pour en trouver un, puis envoyez-y un message en tant qu’agent du jeton :
#!/bin/sh# List your newest chats, then send a message to the one C2R_CHAT_ID names, as the token's agent.API="${C2R_API:-https://api.click2reply.com}"
curl -sS "$API/v1/chats?limit=5" \ -H "Authorization: Bearer $C2R_TOKEN"
curl -sS -X POST "$API/v1/chats/$C2R_CHAT_ID:send_event" \ -H "Authorization: Bearer $C2R_TOKEN" \ -H "Content-Type: application/json" \ -d '{"event": {"type": "message", "text": "Hello from the API"}}'// List your newest chats, then send a message to one as the token's agent. Node 18 or later.const api = process.env.C2R_API || "https://api.click2reply.com";const headers = { authorization: `Bearer ${process.env.C2R_TOKEN}`, "content-type": "application/json" };
async function call(path, init = {}) { const res = await fetch(`${api}${path}`, { ...init, headers }); const body = await res.json(); if (!res.ok) throw new Error(`${res.status} ${body.error.code}: ${body.error.message}`); return body;}
const chats = await call("/v1/chats?limit=5");const chatId = process.env.C2R_CHAT_ID || chats.items[0].id;
const sent = await call(`/v1/chats/${chatId}:send_event`, { method: "POST", body: JSON.stringify({ event: { type: "message", text: "Hello from the API" } }),});console.log(JSON.stringify(sent));# List your newest chats, then send a message to one as the token's agent. Python 3.8 or later.import jsonimport osimport urllib.errorimport urllib.request
API = os.environ.get("C2R_API") or "https://api.click2reply.com"HEADERS = {"Authorization": "Bearer " + os.environ["C2R_TOKEN"], "Content-Type": "application/json"}
def call(path, body=None): data = None if body is None else json.dumps(body).encode() req = urllib.request.Request(API + path, data=data, headers=HEADERS, method="GET" if body is None else "POST") try: with urllib.request.urlopen(req) as res: return json.load(res) except urllib.error.HTTPError as e: err = json.load(e)["error"] raise SystemExit(f"{e.code} {err['code']}: {err['message']}")
chats = call("/v1/chats?limit=5")chat_id = os.environ.get("C2R_CHAT_ID") or chats["items"][0]["id"]
sent = call(f"/v1/chats/{chat_id}:send_event", {"event": {"type": "message", "text": "Hello from the API"}})print(json.dumps(sent))La réponse est { "event_id", "thread_id", "seq", "replay" }. Deux champs facultatifs peuvent accompagner text :
custom_id: votre propre identifiant pour l’événement, jusqu’à 64 caractères. Renvoyez le même, par exemple après un délai d’attente dépassé, et l’API répond avec le premier résultat et"replay": trueau lieu de publier le message deux fois. Sans lui, chaque envoi crée un nouveau message.visibility:"all"par défaut ;"agents"fait du message une note interne que le client ne voit jamais.
L’agent doit participer au chat pour y écrire. La référence de l’API liste les routes, avec les champs exacts que chacune accepte et renvoie.
3. Recevoir un webhook
Section intitulée « 3. Recevoir un webhook »-
Dans Paramètres > API et webhooks > Webhooks, ajoutez un webhook pour l’URL
httpspublique sur laquelle votre récepteur répondra, avec les événements souhaités, commeevent.created. -
Copiez le secret de signature, affiché une seule fois, dans
C2R_WEBHOOK_SECRET. -
Lancez un récepteur sur cette URL. Les deux exemples répondent
200à un envoi dont la signature est valide et401à tout le reste, et affichent l’événement :verify-webhook.mjs // Receive Click2Reply webhooks and refuse any delivery whose signature does not check out. Node 18 or later.import { createHmac, timingSafeEqual } from "node:crypto";import { createServer } from "node:http";const SECRET = process.env.C2R_WEBHOOK_SECRET;const TOLERANCE_S = 300;function verify(signature, timestamp, rawBody) {const ts = Number(timestamp);if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > TOLERANCE_S) return false;const want = createHmac("sha256", SECRET).update(`${ts}.`).update(rawBody).digest();// Right after a secret rotation the header carries two signatures, comma-separated.return String(signature ?? "").split(",").some((part) => {const [version, hex] = part.trim().split("=");return version === "v1" && /^[0-9a-f]{64}$/i.test(hex ?? "") && timingSafeEqual(Buffer.from(hex, "hex"), want);});}createServer((req, res) => {const chunks = [];req.on("data", (c) => chunks.push(c));req.on("end", () => {const raw = Buffer.concat(chunks);if (!verify(req.headers["x-c2r-signature"], req.headers["x-c2r-timestamp"], raw)) {res.writeHead(401).end();return;}const delivery = JSON.parse(raw.toString("utf8"));console.log(delivery.event, delivery.id);res.writeHead(200).end();});}).listen(Number(process.env.PORT ?? 3000), function () {console.log(`listening on ${this.address().port}`);});verify_webhook.py # Receive Click2Reply webhooks and refuse any delivery whose signature does not check out. Python 3.8 or later.import hashlibimport hmacimport jsonimport osimport timefrom http.server import BaseHTTPRequestHandler, HTTPServerSECRET = os.environ["C2R_WEBHOOK_SECRET"].encode()TOLERANCE_S = 300def verify(signature, timestamp, raw_body):try:ts = int(timestamp or "")except ValueError:return Falseif abs(time.time() - ts) > TOLERANCE_S:return Falsewant = hmac.new(SECRET, f"{ts}.".encode() + raw_body, hashlib.sha256).hexdigest()# Right after a secret rotation the header carries two signatures, comma-separated.for part in (signature or "").split(","):version, _, sig = part.strip().partition("=")if version == "v1" and len(sig) == 64 and all(c in "0123456789abcdefABCDEF" for c in sig) and hmac.compare_digest(sig.lower(), want):return Truereturn Falseclass Webhook(BaseHTTPRequestHandler):def do_POST(self):raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))if not verify(self.headers.get("X-C2R-Signature"), self.headers.get("X-C2R-Timestamp"), raw):self.send_response(401)self.end_headers()returndelivery = json.loads(raw)print(delivery["event"], delivery["id"], flush=True)self.send_response(200)self.end_headers()server = HTTPServer(("", int(os.environ.get("PORT", "3000"))), Webhook)print(f"listening on {server.server_port}", flush=True)server.serve_forever() -
Choisissez Envoyer un test : le récepteur affiche
webhook.test.
Vérifiez la signature sur le corps brut, avant toute analyse JSON : un parseur qui réordonne les clés ou les espaces modifie les octets. La page Webhooks détaille les en-têtes, les nouvelles tentatives, l’ordre et tous les événements.