5분 API 빠른 시작 가이드
이 페이지의 모든 샘플은 그대로 실행되며, 필요한 값은 C2R_* 환경 변수에서 읽습니다. 토큰은 C2R_TOKEN, 채팅은
C2R_CHAT_ID에 넣고, C2R_API는 https://api.click2reply.com이 아닌 다른 주소를 가리킬 때만 설정합니다.
OAuth와 웹훅 샘플은 변수를 몇 가지 더 읽으며, 각 변수는 사용하는 곳에서 안내합니다. 이 샘플들은 저희 테스트가 테스트
조직을 대상으로 실행하는 파일과 동일합니다.
1. 토큰 발급받기
섹션 제목: “1. 토큰 발급받기”모든 호출에는 Authorization: Bearer <token> 헤더가 포함됩니다. 어떤 토큰을 쓸지는 코드가 누구를 대신해 동작하는지에
따라 다릅니다.
직접 만든 스크립트: 개인 액세스 토큰
섹션 제목: “직접 만든 스크립트: 개인 액세스 토큰”-
에이전트 앱에서 설정 > API 및 웹훅을 여세요.
-
개인 액세스 토큰에서 토큰을 만들고, 스크립트를 알아볼 수 있는 이름을 붙인 다음, 필요한 범위만 선택하세요. 이 빠른 시작에는 chats.access가 필요합니다.
-
c2r_pat_로 시작하는 토큰을 복사하세요. 토큰은 한 번만 표시되므로 시크릿으로 안전하게 보관하세요.
토큰은 부여한 범위 중 내 역할이 여전히 허용하는 범위 안에서 나를 대신해 동작합니다. 역할에서 권한이 빠지면 토큰에서도 그 권한이 빠집니다. 사람이 아닌 주체로 동작해야 하는 스크립트라면 봇 상담원을 만들고 봇 토큰에서 해당 봇의 토큰을 만드세요.
다른 조직이 설치하는 앱: OAuth 2.0
섹션 제목: “다른 조직이 설치하는 앱: OAuth 2.0”설정 > API 및 웹훅 > 내 앱에서 리디렉션 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. 메시지 보내기
섹션 제목: “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자입니다. 타임아웃 후처럼 같은 값으로 다시 보내면 API는 메시지를 두 번 게시하지 않고 첫 번째 결과와"replay": true로 응답합니다. 지정하지 않으면 보낼 때마다 새 메시지가 됩니다.visibility: 기본값은"all"입니다."agents"로 지정하면 고객에게 보이지 않는 내부 메모가 됩니다.
상담원은 채팅에 참여해 있어야 메시지를 쓸 수 있습니다. 각 경로가 받고 반환하는 정확한 필드는 API 레퍼런스에서 확인하세요.
3. 웹훅 수신하기
섹션 제목: “3. 웹훅 수신하기”-
설정 > API 및 웹훅 > 웹훅에서 웹훅을 추가하세요. 수신기가 응답할 공개
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을 파싱하기 전에 원본 본문(raw body)으로 확인하세요. 키 순서나 공백을 바꾸는 파서를 거치면 바이트가 달라집니다. 헤더, 재시도, 순서, 전체 이벤트는 웹훅에서 다룹니다.