Examples

The examples use shell variables: API for your API base URL, TOKEN for an access token. Run them on your servers only; never put a client secret or token in a web page or a mobile app.

1. Get an access token

curl
TOKEN=$(curl -s https://<auth host>/auth/realms/cmp/protocol/openid-connect/token \
  -d grant_type=client_credentials -d client_id="$CMP_CLIENT_ID" \
  --data-urlencode client_secret="$CMP_CLIENT_SECRET" | jq -r .access_token)

Tokens last 5 minutes. Cache one and request a new one shortly before it expires, rather than one per call.

2. Show the active notice

Fetch the published notice in the customer's language and show its text and purposes before asking for consent.

curl (scope consents:read)
curl -s "$API/v1/notices/active?code=privacy-notice&locale=en-IN" -H "Authorization: Bearer $TOKEN"
# → { "notice": { "noticeVersionId": "…", "version": 3, "content": "…", "contentHash": "…" },
#     "purposes": [ { "id": "…", "code": "marketing.email", "title": "…", "description": "…" } ] }

3. Record the customer's choice

Send the notice version the customer saw and one choice per purpose (grant, deny or withdraw). The Idempotency-Key makes retries safe: the same key returns the first result instead of recording twice. Keep the signed receipt (jws).

curl (scope consents:write)
curl -s -X POST "$API/v1/consents" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen | tr -d -)" \
  -d '{
    "principalRef": "CUST-000123",
    "noticeVersionId": "<noticeVersionId from step 2>",
    "channel": "mobile",
    "choices": [ { "purposeId": "<purpose id>", "action": "grant" } ],
    "application": "ios-app"
  }'
Node.js 20+
import { randomUUID } from "node:crypto";

async function recordConsent(api, token, body) {
  const res = await fetch(`${api}/v1/consents`, {
    method: "POST",
    headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", "Idempotency-Key": randomUUID().replaceAll("-", "") },
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    const problem = await res.json(); // RFC 9457: { type, title, status, detail, code }
    throw new Error(`${res.status} ${problem.code}: ${problem.detail}`);
  }
  return res.json(); // { receiptId, jws, recordedAt, events }
}

channel is one of web, mobile, branch, call_centre, api or consent_manager. Omit application when your key is bound to an application: the bound one is used.

4. Check consent before processing

curl (scope decisions:read)
curl -s -X POST "$API/v1/consent-decisions" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{ "principalRef": "CUST-000123", "purposeCode": "marketing.email" }'
# → { "permit": true, "reason": "consent_granted", "purposeCode": "marketing.email", "purposeVersion": 2, "evaluatedAt": "…" }

Process the data only when permit is true. Other reasons: consent_absent (also after a refusal), consent_withdrawn, consent_expired; purposes with another legal basis answer legal_basis_non_consent. If the API cannot be reached, do not assume consent.

5. Verify webhook signatures

Events are CloudEvents signed per the Standard Webhooks scheme: v1, + base64 HMAC-SHA256 of id.timestamp.body with the secret shown once when the webhook was created (whsec_…). Reject old timestamps and compare signatures in constant time.

Node.js 20+ (raw request body required)
import { createHmac, timingSafeEqual } from "node:crypto";

function verifyWebhook(secret, headers, rawBody) {
  const id = headers["webhook-id"], timestamp = headers["webhook-timestamp"];
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; // replay protection
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = "v1," + createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest("base64");
  return headers["webhook-signature"].split(" ").some((candidate) => {
    const a = Buffer.from(candidate), b = Buffer.from(expected);
    return a.length === b.length && timingSafeEqual(a, b);
  });
}

6. Embed the consent or preference widget

Register the page's origin as a web application (Settings → Applications). On your server, issue a single-use access link for the signed-in customer and pass only its token to the page. Add our web host to the page's CSP script-src and frame-src.

Server (scope consents:write)
curl -s -X POST "$API/v1/portal/access-links" -H "Authorization: Bearer $TOKEN"   -H "Content-Type: application/json" -d '{ "principalRef": "CUST-000123", "validMinutes": 15 }'
# → { "token": "…", "link": "…", "expiresAt": "…" }   (use the token once; never log it)
Your web page
<div id="privacy"></div>
<script src="https://<your web host>/sdk/v1/widgets.js"></script>
<script>
  PrivatrailWidgets.mount(document.getElementById("privacy"), {
    organisation: "<your organisation code>",
    widget: "consents",            // or "preferences"
    token: "<token from your server>",
    locale: "hi",
    onEvent: (e) => { if (e.type === "consent.saved") { /* refresh your view */ } },
  });
</script>

Events: ready, resize, consent.saved (purpose code and action), preferences.saved, error. They carry no personal data. Your page cannot read the widget, and the token is removed from the widget's address once used.

7. React Native apps

The React Native SDK uses the same single-use token from your server. It keeps the customer session in memory, talks only to the customer endpoints and comes with hooks and ready-made lists in the customer's language. Ask us for the package.

React Native
import { PrivatrailClient, PrivatrailProvider, ConsentList, PreferenceList } from "@privatrail/consent-react-native";

const client = new PrivatrailClient({ apiBaseUrl: "https://<your api host>" });
await client.startSession(tokenFromYourServer);   // single use; never an API key in the app

<PrivatrailProvider client={client}>
  <ConsentList locale="hi" onSessionEnded={getNewToken} />
  <PreferenceList locale="hi" />
</PrivatrailProvider>

8. Confirm a withdrawal

When your webhook asks for confirmations, tell the platform once your system has stopped the processing after a consent.withdrawn event. The confirmation is signed with the same secret; the developer guide shows the full request.

Node.js 20+
const body = JSON.stringify({ eventId: event.id, status: "processed", note: "" });
const timestamp = Math.floor(Date.now() / 1000);
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
const signature = "v1," + createHmac("sha256", key).update(`${event.id}.${timestamp}.${body}`).digest("base64");
await fetch(api + acknowledgementUrl, {
  method: "POST",
  headers: { "Content-Type": "application/json", "webhook-timestamp": String(timestamp), "webhook-signature": signature },
  body,
});