5 分钟 API 快速入门
本页的每个示例都可以直接运行,所需的值从 C2R_* 环境变量中读取:C2R_TOKEN 为令牌,C2R_CHAT_ID 为聊天,C2R_API 仅在需要指向 https://api.click2reply.com 以外的地址时才设置;OAuth 和 Webhook 示例还会读取另外几个变量,会在用到的地方注明。我们自己的测试也是用这些文件针对测试组织运行的。
1. 获取令牌
Section titled “1. 获取令牌”每个调用都带有 Authorization: Bearer <token>。使用哪种令牌,取决于代码代表谁进行操作。
自用脚本:个人访问令牌
Section titled “自用脚本:个人访问令牌”-
在客服应用中,打开设置 > API 和 Webhook。
-
在个人访问令牌下创建一个令牌,以脚本名称为其命名,并只勾选脚本所需的权限范围。本快速入门需要 chats.access。
-
复制令牌,它以
c2r_pat_开头。令牌只显示一次,请将其作为机密妥善保存。
令牌以您的身份操作,拥有您授予它且您的角色仍然允许的权限范围:如果您的角色失去某项权限,令牌也会随之失去。如果脚本不应以真人身份操作,请创建一个机器人客服,并在机器人令牌下为其创建令牌。
供其他组织安装的应用:OAuth 2.0
Section titled “供其他组织安装的应用:OAuth 2.0”在设置 > API 和 Webhook > 您的应用下注册应用,填写其重定向 URI 以及它最多可申请的权限范围。您会获得一个 client_id;如果是服务器端应用,还会获得一个只显示一次的 client_secret。
将用户引导至授权同意页面,并附带一对 PKCE 参数,这样即使授权码被盗也毫无用处:
// 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 }));用户同意后,其浏览器会带着 ?code=...&state=... 返回您的重定向 URI。请确认 state 与您保存的值一致,然后在 5 分钟内用授权码换取令牌:
#!/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']}")返回结果包含 access_token(以 c2r_oat_ 开头,有效期 60 分钟)、refresh_token(以 c2r_ort_ 开头,有效期 60 天)、授予的 scope,以及令牌所作用的 organization_id 和 agent_id。公开应用(即无法保管密钥的应用)无需传入 client_secret,但必须发送 PKCE 验证码(verifier)。
在访问令牌过期之前,用刷新令牌换取一对新令牌:
#!/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"}授权服务器元数据位于 https://api.click2reply.com/v1/oauth/metadata,OAuth 库可以据此自动完成配置。身份验证一文介绍了权限范围、令牌撤销和速率限制。
2. 发送消息
Section titled “2. 发送消息”先列出最新的聊天以找到目标聊天,然后以令牌对应客服的身份向其中发送一条消息:
#!/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))返回结果为 { "event_id", "thread_id", "seq", "replay" }。除 text 外,还可以传入两个可选字段:
custom_id:您为该事件自定义的 ID,最多 64 个字符。再次发送相同的 ID 时(例如在超时之后),API 会返回第一次的结果并附带"replay": true,而不会重复发布这条消息。如果不传,每次发送都是一条新消息。visibility:默认为"all";设为"agents"时,该消息为内部备注,客户永远看不到。
客服必须在聊天中才能发送消息。API 参考列出了所有路由,以及每个路由接受和返回的确切字段。
3. 接收 Webhook
Section titled “3. 接收 Webhook”-
在设置 > API 和 Webhook > Webhook 中添加一个 Webhook,填写接收端将要响应的公网
httpsURL,并选择所需的事件,例如event.created。 -
将只显示一次的签名密钥复制到
C2R_WEBHOOK_SECRET中。 -
在该 URL 上运行接收端。两个示例都会对签名校验通过的投递返回
200,对其他任何请求返回401,并打印出事件内容: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() -
选择发送测试:接收端会打印出
webhook.test。
请基于原始请求体校验签名,并且要在任何 JSON 解析之前进行:解析器一旦调整了键的顺序或空格,字节就会改变。Webhook 一文介绍了请求头、重试、顺序以及全部事件。