Início rápido da API
Todos os exemplos desta página rodam do jeito que estão, com os valores de que precisam em variáveis de ambiente
C2R_*: C2R_TOKEN para o token, C2R_CHAT_ID para um chat, C2R_API só para apontar para algum lugar
diferente de https://api.click2reply.com; os exemplos de OAuth e de webhook leem mais algumas,
indicadas onde são usadas. São os mesmos arquivos que os nossos próprios testes executam em uma organização de teste.
1. Obtenha um token
Seção intitulada “1. Obtenha um token”Toda chamada leva Authorization: Bearer <token>. O token certo depende de em nome de quem o código age.
Seus próprios scripts: um token de acesso pessoal
Seção intitulada “Seus próprios scripts: um token de acesso pessoal”-
No app de agentes, abra Configurações > API e webhooks.
-
Em Tokens de acesso pessoal, crie um, dê a ele o nome do script e marque só os escopos de que ele precisa. Este início rápido precisa de chats.access.
-
Copie o token, que começa com
c2r_pat_. Ele é mostrado uma única vez; guarde-o como um segredo.
Um token age como você, com os escopos que você deu a ele e que a sua função ainda permite: se a sua função perder uma permissão, o token também a perde. Para um script que não deve agir como uma pessoa, crie um agente bot e um token para ele em Tokens de bot.
Um aplicativo que outras organizações instalam: OAuth 2.0
Seção intitulada “Um aplicativo que outras organizações instalam: OAuth 2.0”Registre o aplicativo em Configurações > API e webhooks > Seus apps com as URIs de redirecionamento e o
máximo que ele pode pedir. Você recebe um client_id e, para um aplicativo de servidor, um client_secret, mostrado uma única vez.
Envie o usuário para a tela de consentimento, com um par PKCE para que um código roubado não sirva para nada:
// 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 }));O usuário aprova, e o navegador dele volta para a sua URI de redirecionamento com ?code=...&state=....
Confira se state é o que você guardou e troque o código em até 5 minutos:
#!/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']}")A resposta traz um access_token (c2r_oat_, válido por 60 minutos), um refresh_token
(c2r_ort_, válido por 60 dias), o scope concedido e o organization_id e o agent_id
em nome dos quais o token age. Um aplicativo público, que não consegue guardar um segredo, omite o client_secret e
precisa enviar o verificador PKCE.
Antes de o token de acesso expirar, troque o refresh token por um novo par:
#!/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"}Os metadados do servidor de autorização ficam em https://api.click2reply.com/v1/oauth/metadata, para que uma
biblioteca OAuth possa se configurar sozinha. A página de autenticação trata de escopos, revogação
de tokens e limites de requisições.
2. Envie uma mensagem
Seção intitulada “2. Envie uma mensagem”Liste os chats mais recentes para encontrar um e envie uma mensagem nele como o agente do token:
#!/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))A resposta é { "event_id", "thread_id", "seq", "replay" }. Dois campos opcionais vão ao lado de text:
custom_id: o seu próprio id para o evento, com até 64 caracteres. Envie o mesmo de novo, depois de um timeout, por exemplo, e a API responde com o primeiro resultado e"replay": trueem vez de publicar a mensagem duas vezes. Sem ele, cada envio é uma nova mensagem.visibility:"all"por padrão;"agents"transforma a mensagem em uma nota interna que o cliente nunca vê.
O agente precisa estar no chat para escrever nele. A referência da API lista as rotas, com os campos exatos que cada uma recebe e retorna.
3. Receba um webhook
Seção intitulada “3. Receba um webhook”-
Em Configurações > API e webhooks > Webhooks, adicione um webhook para a URL
httpspública em que o seu receptor vai responder e os eventos que você quer, comoevent.created. -
Copie o segredo de assinatura, mostrado uma única vez, para
C2R_WEBHOOK_SECRET. -
Rode um receptor nessa URL. Os dois exemplos respondem
200a uma entrega cuja assinatura confere e401a qualquer outra coisa, e imprimem o evento: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() -
Escolha Enviar um teste: o receptor imprime
webhook.test.
Verifique a assinatura sobre o corpo bruto, antes de qualquer parsing de JSON: um parser que reordena chaves ou espaços muda os bytes. A página de webhooks trata dos cabeçalhos, das novas tentativas, da ordem e de todos os eventos.