Skip to content

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.

Every call carries Authorization: Bearer <token>. Which token depends on who the code acts for.

  1. In the agent app, open Settings > API and webhooks.

  2. Under Personal access tokens, create one, name it after the script, and tick only the scopes it needs. This quickstart needs chats.access.

  3. 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:

authorize-url.mjs
// 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:

oauth-token.sh
#!/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"}

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:

refresh-token.sh
#!/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.

List the newest chats to find one, then send a message into it as the token’s agent:

send-message.sh
#!/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"}}'

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": true instead 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.

  1. In Settings > API and webhooks > Webhooks, add a webhook for the public https URL your receiver will answer on, and the events you want, such as event.created.

  2. Copy the signing secret, shown once, into C2R_WEBHOOK_SECRET.

  3. Run a receiver on that URL. Both samples answer 200 to a delivery whose signature checks out and 401 to 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}`);
    });
  4. 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.