Click2Reply API quickstart in 5 minutes
Every sample on this page runs as it stands, with the values it needs in C2R_* environment
variables: C2R_TOKEN for the token, C2R_CHAT_ID for a chat, C2R_API only to point it somewhere
other than https://api.click2reply.com; the OAuth and webhook samples read a few more,
named where they use them. They are the same files our own tests run against a test organization.
1. Get a token
Section titled “1. Get a token”Every call carries Authorization: Bearer <token>. Which token depends on who the code acts for.
Your own scripts: a personal access token
Section titled “Your own scripts: a personal access token”-
In the agent app, open Settings > API and webhooks.
-
Under Personal access tokens, create one, name it after the script, and tick only the scopes it needs. This quickstart needs chats.access.
-
Copy the token, which starts with
c2r_pat_. It is shown once; store it as a secret.
A token acts as you, with the scopes you gave it that your role still allows: if your role loses a permission, the token loses it too. For a script that should not act as a person, create a bot agent and a token for it under Bot tokens.
An app other organizations install: OAuth 2.0
Section titled “An app other organizations install: OAuth 2.0”Register the app under Settings > API and webhooks > Your apps with its redirect URIs and the
most it may ask for. You get a client_id, and for a server app a client_secret, shown once.
Send the user to the consent screen, with a PKCE pair so a stolen code is worthless:
// 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 }));The user approves, and their browser comes back to your redirect URI with ?code=...&state=....
Check that state is the one you stored, then exchange the code within 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']}")The answer holds an access_token (c2r_oat_, valid for 60 minutes), a refresh_token
(c2r_ort_, valid for 60 days), the scope granted, and the organization_id and agent_id
the token acts in. A public app, one that cannot keep a secret, leaves out client_secret and
must send the PKCE verifier.
Before the access token expires, trade the refresh token for a new pair:
#!/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"}The authorization server metadata is at https://api.click2reply.com/v1/oauth/metadata, so an
OAuth library can configure itself. Authentication covers scopes, token
revocation and rate limits.
2. Send a message
Section titled “2. Send a message”List the newest chats to find one, then send a message into it as the token’s agent:
#!/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))The answer is { "event_id", "thread_id", "seq", "replay" }. Two optional fields go next to text:
custom_id: your own id for the event, up to 64 characters. Send the same one again, after a timeout for instance, and the API answers with the first result and"replay": trueinstead of posting the message twice. Without one, every send is a new message.visibility:"all"by default;"agents"makes the message an internal note that the customer never sees.
The agent must be in the chat to write in it. The API reference lists the routes, with the exact fields each takes and returns.
3. Receive a webhook
Section titled “3. Receive a webhook”-
In Settings > API and webhooks > Webhooks, add a webhook for the public
httpsURL your receiver will answer on, and the events you want, such asevent.created. -
Copy the signing secret, shown once, into
C2R_WEBHOOK_SECRET. -
Run a receiver on that URL. Both samples answer
200to a delivery whose signature checks out and401to anything else, and print the event: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() -
Choose Send a test: the receiver prints
webhook.test.
Check the signature over the raw body, before any JSON parsing: a parser that reorders keys or spaces changes the bytes. Webhooks covers the headers, retries, ordering and every event.