Developer kit
Add DPDP-ready consent in minutes
Three pieces: a banner that holds trackers back until a visitor agrees, a server SDK to check and record consent before you message anyone, and signed webhooks that tell you when someone withdraws. India’s DPDP Act is enforced from 13 May 2027.
- Create your website in the dashboard and publish its notice.
- Add the banner (below). Your site slug is shown on the Website banner page.
- Create an API key under Integrations & API, and use it on your server only.
npm install @zeroclauseai/privacyThis package is for JavaScript and TypeScript (Node, Next.js, React). Using another language? The API below works from any language. Machine-readable description (OpenAPI 3.1, for Postman, Swagger UI or a code generator): /openapi.json. Readable version: API reference. Is something down? See the status page.
2. Check and record consent on your server
Never put your API key in browser code. For a child under 18, send minor: true and the parent’s details; offers are never allowed for a child.
import { ZeroClause } from "@zeroclauseai/privacy";
const zc = new ZeroClause({ apiKey: process.env.ZEROCLAUSE_API_KEY!, siteId: "your-site-slug" });
// before you send a reminder
const { canSendReminders } = await zc.consent.get({ subjectRef: patientId });
if (canSendReminders) await sendReminder(patientId);
// record a choice you collected yourself
await zc.consent.record({ subjectRef: patientId, action: "custom", choices: { reminders: true, marketing: false } });
// a personal link or QR for one patient
const { url } = await zc.consent.link({ subjectRef: patientId, days: 7 });
// who has not answered yet (any list size, sent in batches of 500)
const toAsk = await zc.consent.lookupAll({ subjectRefs: allPatientIds, onlyNeedingAction: true });
// totals
const totals = await zc.consent.summary();Not using JavaScript? It is plain HTTPS and JSON:
curl "https://zeroclauseai.com/api/v1/consent?siteId=your-site-slug&subjectRef=PATIENT-1" \
-H "Authorization: Bearer zc_live_YOUR_KEY"3. Webhooks
We call your address when consent is recorded, withdrawn or confirmed, and when a privacy request arrives. Every delivery is signed: X-ZeroClause-Signature: t=<unix>,v1=<HMAC-SHA256 of "t.body">.
import { verifyWebhook, WebhookVerificationError } from "@zeroclauseai/privacy/webhooks";
export async function POST(req: Request) {
try {
const event = await verifyWebhook({
payload: await req.text(), // the RAW body, not re-written JSON
signature: req.headers.get("x-zeroclause-signature"),
secret: process.env.ZEROCLAUSE_WEBHOOK_SECRET!,
});
if (event.event === "consent.withdrawn") await stopMessaging(event.data);
return new Response("ok");
} catch (e) {
if (e instanceof WebhookVerificationError) return new Response("bad signature", { status: 400 });
throw e;
}
}Answer with any 2xx within 5 seconds. If you do not, we try again after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 24 hours, with the same event id each time, so keep the ids you have handled and ignore repeats. After 7 failed attempts an event is dead; you can list and re-send it for 14 days. Even so, ask consent.get right before you send a message: it is the source of truth.
API reference
| Method | Path | Key scope | What it does |
|---|---|---|---|
| GET | /api/v1/consent | consent:read | Is this person's consent on file? canSendReminders, canSendMarketing |
| POST | /api/v1/consent | consent:write | Record a choice for your own patient or contact id |
| POST | /api/v1/consent-link | consent:write | A signed personal consent link (or short-lived for a screen) |
| POST | /api/v1/preferences-link | consent:write | A patient's own My privacy choices page (up to 365 days): see, change, withdraw |
| POST | /api/v1/consent/lookup | consent:read | Status of up to 500 patients; onlyNeedingAction lists who to ask |
| GET | /api/v1/consent/summary | consent:read | Totals for the whole website or clinic |
| GET | /api/v1/notice | notice:read | The published notice, grievance contact and public links |
| POST · GET | /api/v1/requests | requests:write · read | Create or list privacy requests (see, correct, erase) |
| POST | /api/v1/breach | breach:write | Start the 6-hour and 72-hour clocks and alert the owner |
| POST · GET | /api/v1/display | consent:write · read | The optional counter screen: show a patient's QR, clear, list |
| POST · GET | /api/v1/sites | sites:manage (platform key) | Create or update clinics by your own id; safe to repeat |
| POST | /api/v1/sandbox/confirm | consent:write (test key) | Sandbox only: confirm a patient's waiting choice, as if they had sent the code |
| POST · GET · DELETE | /api/v1/webhook | sites:manage (platform key) | One webhook address for all your clinics |
| GET · POST | /api/v1/webhook/deliveries | sites:manage (platform key) | The delivery log with retry state; re-send a dead event |
Auth: Authorization: Bearer zc_live_…. Site keys work for one website; a platform key works for all the clinics your software creates. The full guide for clinic software is in the Clinsnap integration guide.
Test keys (sandbox)
Create a sandbox and a test key in the dashboard (Integrations & API → Test keys). Software with many clinics can make a platform test key (Plan & billing → API access) and create up to 20 practice clinics with POST /api/v1/sites. A zc_test_… key works only on the sandbox website, with made-up data, and answers exactly like a live key. Nobody is emailed, a breach report is always a practice drill, and the sandbox never reaches your live webhook. Live and test keys can never be mixed: each is refused on the other's website.
const zc = new ZeroClause({ apiKey: process.env.ZEROCLAUSE_TEST_KEY!, siteId: "your-sandbox-id" });
await zc.consent.record({ subjectRef: "P-1", action: "custom", choices: { reminders: true }, phone: "98000 11111" });
// there is no patient phone in a sandbox: act as the patient who sends the code
await zc.sandbox.confirm({ subjectRef: "P-1" }); // fires consent.confirmedAny language, any website or app
You do not need our package. The API is plain HTTPS with JSON, so it works from any language that can send a web request, and the banner is one line for any website. Pick what fits:
- No code at all: the banner line works on WordPress, Shopify, Wix, plain HTML or any page. Consent links and QR posters need nothing installed.
- Your server, any language: call the API from your back end. The same two calls are below in curl, Python, PHP, Java, C#, Go and Ruby.
- A mobile app (Android, iOS, Flutter, React Native): call the API from your server, never from the app, so the key stays secret. The app only shows the consent link or QR.
- Another language, or a ready-made client: take /openapi.json to a generator such as OpenAPI Generator, which writes a client for 40+ languages.
curl (command line)run and tested
Check consent before you message someone, then record a choice. Set ZEROCLAUSE_API_KEY and ZEROCLAUSE_SITE.
#!/bin/sh
# Privacy by ZeroClause from the command line (or any language that can run a web request).
# Set ZEROCLAUSE_API_KEY (zc_live_… or zc_test_…) and ZEROCLAUSE_SITE (your website's slug).
BASE="${ZEROCLAUSE_BASE:-https://zeroclauseai.com}"
# 1. Before you send a reminder: is this patient's consent on file?
curl -s "$BASE/api/v1/consent?siteId=$ZEROCLAUSE_SITE&subjectRef=P-1042" \
-H "Authorization: Bearer $ZEROCLAUSE_API_KEY"
# -> {"ok":true,"status":"consented","canSendReminders":true,"canSendMarketing":false,...}
# 2. Record a choice you collected yourself
curl -s -X POST "$BASE/api/v1/consent" \
-H "Authorization: Bearer $ZEROCLAUSE_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"siteId\":\"$ZEROCLAUSE_SITE\",\"subjectRef\":\"P-1042\",\"action\":\"custom\",\"choices\":{\"reminders\":true,\"marketing\":false}}"Pythonrun and tested
Check consent before you message someone, then record a choice. Set ZEROCLAUSE_API_KEY and ZEROCLAUSE_SITE.
# Privacy by ZeroClause from Python (standard library only, no packages to install).
# Set ZEROCLAUSE_API_KEY (zc_live_… or zc_test_…) and ZEROCLAUSE_SITE (your website's slug).
import json
import os
import urllib.error
import urllib.request
BASE = os.environ.get("ZEROCLAUSE_BASE", "https://zeroclauseai.com")
KEY = os.environ["ZEROCLAUSE_API_KEY"]
SITE = os.environ["ZEROCLAUSE_SITE"]
def call(method, path, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(
BASE + path,
data=data,
method=method,
headers={"Authorization": "Bearer " + KEY, "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=15) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e: # 4xx / 5xx still carry {"error": "..."}
return e.code, json.load(e)
# 1. Before you send a reminder: is this patient's consent on file?
status, consent = call("GET", "/api/v1/consent?siteId=%s&subjectRef=%s" % (SITE, "P-1042"))
if status == 200 and consent["canSendReminders"]:
print("OK to send the reminder")
else:
print("Do not send. Status:", consent.get("status") or consent.get("error"))
# 2. Record a choice you collected yourself
status, saved = call("POST", "/api/v1/consent", {
"siteId": SITE,
"subjectRef": "P-1042",
"action": "custom",
"choices": {"reminders": True, "marketing": False},
})
print(status, saved.get("consentId"), saved.get("error"))Check that a webhook really came from us (same signature in every language).
# Check that a webhook really came from ZeroClause (Python, standard library only).
# Header: X-ZeroClause-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
import hashlib
import hmac
import time
def verify_webhook(raw_body: bytes, header: str, secret: str, tolerance_seconds: int = 300) -> bool:
"""raw_body must be the exact bytes received, not parsed and re-written JSON."""
try:
parts = dict(p.strip().split("=", 1) for p in header.split(","))
t, v1 = int(parts["t"]), parts["v1"]
except (KeyError, ValueError):
return False
if abs(time.time() - t) > tolerance_seconds: # too old: could be a replay
return False
expected = hmac.new(secret.encode(), ("%d." % t).encode() + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1)
# In your web framework's handler, for example Flask:
# if not verify_webhook(request.get_data(), request.headers.get("X-ZeroClause-Signature", ""), WEBHOOK_SECRET):
# return "bad signature", 400
# event = request.get_json() # {"id": "evt_...", "event": "consent.withdrawn", "siteId": "...", "data": {...}}
# remember event["id"] and ignore it if you have seen it (retries use the same id), then answer 200PHP (WordPress, Laravel)written, not run yet
Check consent before you message someone, then record a choice. Set ZEROCLAUSE_API_KEY and ZEROCLAUSE_SITE.
<?php
// Privacy by ZeroClause from PHP (plain curl extension; works in WordPress, Laravel, or any PHP app).
// Keep the key on the server: put it in an environment variable or a config file outside the web root.
$base = getenv('ZEROCLAUSE_BASE') ?: 'https://zeroclauseai.com';
$key = getenv('ZEROCLAUSE_API_KEY'); // zc_live_… or zc_test_…
$site = getenv('ZEROCLAUSE_SITE'); // your website's slug
function zc_call(string $method, string $path, ?array $body = null): array {
global $base, $key;
$ch = curl_init($base . $path);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key, 'Content-Type: application/json'],
]);
if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
$out = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
return [$status, json_decode($out ?: '{}', true)];
}
// 1. Before you send a reminder: is this patient's consent on file?
[$status, $consent] = zc_call('GET', '/api/v1/consent?siteId=' . urlencode($site) . '&subjectRef=' . urlencode('P-1042'));
if ($status === 200 && !empty($consent['canSendReminders'])) {
echo "OK to send the reminder\n";
} else {
echo 'Do not send. Status: ' . ($consent['status'] ?? $consent['error'] ?? 'unknown') . "\n";
}
// 2. Record a choice you collected yourself
[$status, $saved] = zc_call('POST', '/api/v1/consent', [
'siteId' => $site,
'subjectRef' => 'P-1042',
'action' => 'custom',
'choices' => ['reminders' => true, 'marketing' => false],
]);
echo $status . ' ' . ($saved['consentId'] ?? $saved['error'] ?? '') . "\n";Check that a webhook really came from us (same signature in every language).
<?php
// Check that a webhook really came from ZeroClause (PHP).
// Header: X-ZeroClause-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
function zc_verify_webhook(string $rawBody, string $header, string $secret, int $tolerance = 300): bool {
$parts = [];
foreach (explode(',', $header) as $p) {
$kv = explode('=', trim($p), 2);
if (count($kv) === 2) $parts[$kv[0]] = $kv[1];
}
if (!isset($parts['t'], $parts['v1']) || !ctype_digit($parts['t'])) return false;
if (abs(time() - (int)$parts['t']) > $tolerance) return false; // too old: could be a replay
$expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret);
return hash_equals($expected, $parts['v1']);
}
// In your webhook endpoint:
// $raw = file_get_contents('php://input'); // the exact bytes, not json_decode + json_encode
// $sig = $_SERVER['HTTP_X_ZEROCLAUSE_SIGNATURE'] ?? '';
// if (!zc_verify_webhook($raw, $sig, getenv('ZEROCLAUSE_WEBHOOK_SECRET'))) { http_response_code(400); exit; }
// $event = json_decode($raw, true); // ['id' => 'evt_…', 'event' => 'consent.withdrawn', 'siteId' => …]
// remember $event['id'] and ignore repeats (retries use the same id), then answer 200Java / Kotlinwritten, not run yet
Check consent before you message someone, then record a choice. Set ZEROCLAUSE_API_KEY and ZEROCLAUSE_SITE.
// Privacy by ZeroClause from Java 11+ (built-in HttpClient, no libraries). Works the same in Kotlin and Android back-ends.
// Keep the key on your server. Set ZEROCLAUSE_API_KEY (zc_live_… or zc_test_…) and ZEROCLAUSE_SITE (your website's slug).
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
public class Consent {
static final String BASE = System.getenv().getOrDefault("ZEROCLAUSE_BASE", "https://zeroclauseai.com");
static final String KEY = System.getenv("ZEROCLAUSE_API_KEY");
static final String SITE = System.getenv("ZEROCLAUSE_SITE");
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build();
static HttpResponse<String> call(String method, String path, String jsonBody) throws Exception {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(BASE + path))
.timeout(Duration.ofSeconds(15))
.header("Authorization", "Bearer " + KEY)
.header("Content-Type", "application/json");
b = jsonBody == null ? b.method(method, HttpRequest.BodyPublishers.noBody()) : b.method(method, HttpRequest.BodyPublishers.ofString(jsonBody));
return HTTP.send(b.build(), HttpResponse.BodyHandlers.ofString());
}
public static void main(String[] args) throws Exception {
// 1. Before you send a reminder: is this patient's consent on file?
String q = "siteId=" + URLEncoder.encode(SITE, StandardCharsets.UTF_8) + "&subjectRef=" + URLEncoder.encode("P-1042", StandardCharsets.UTF_8);
HttpResponse<String> r = call("GET", "/api/v1/consent?" + q, null);
// Parse the JSON with the library you already use (Jackson, Gson, ...). The field to read is "canSendReminders".
boolean ok = r.statusCode() == 200 && r.body().contains("\"canSendReminders\":true");
System.out.println(ok ? "OK to send the reminder" : "Do not send: " + r.body());
// 2. Record a choice you collected yourself
String body = "{\"siteId\":\"" + SITE + "\",\"subjectRef\":\"P-1042\",\"action\":\"custom\",\"choices\":{\"reminders\":true,\"marketing\":false}}";
HttpResponse<String> saved = call("POST", "/api/v1/consent", body);
System.out.println(saved.statusCode() + " " + saved.body());
}
}Check that a webhook really came from us (same signature in every language).
// Check that a webhook really came from ZeroClause (Java 17+).
// Header: X-ZeroClause-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.HexFormat;
public class Webhook {
/** rawBody must be the exact text received, not parsed and re-written JSON. */
public static boolean verify(String rawBody, String header, String secret, long toleranceSeconds) {
try {
String t = null, v1 = null;
for (String part : header.split(",")) {
String[] kv = part.trim().split("=", 2);
if (kv.length == 2 && kv[0].equals("t")) t = kv[1];
if (kv.length == 2 && kv[0].equals("v1")) v1 = kv[1];
}
if (t == null || v1 == null) return false;
if (Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(t)) > toleranceSeconds) return false; // too old: could be a replay
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
String expected = HexFormat.of().formatHex(mac.doFinal((t + "." + rawBody).getBytes(StandardCharsets.UTF_8)));
return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), v1.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
return false;
}
}
// In your endpoint: read the body as a String, call verify(body, request.getHeader("X-ZeroClause-Signature"), secret, 300),
// answer 400 if false. Then parse the JSON, remember event "id" and ignore repeats (retries use the same id), answer 200.
}C# / .NETrun and tested
Check consent before you message someone, then record a choice. Set ZEROCLAUSE_API_KEY and ZEROCLAUSE_SITE.
// Privacy by ZeroClause from C# / .NET 6+ (built-in HttpClient, no packages). Run it with: dotnet run Consent.cs (.NET 10)
// Keep the key on your server. Set ZEROCLAUSE_API_KEY (zc_live_… or zc_test_…) and ZEROCLAUSE_SITE (your website's slug).
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
var baseUrl = Environment.GetEnvironmentVariable("ZEROCLAUSE_BASE") ?? "https://zeroclauseai.com";
var key = Environment.GetEnvironmentVariable("ZEROCLAUSE_API_KEY")!;
var site = Environment.GetEnvironmentVariable("ZEROCLAUSE_SITE")!;
using var http = new HttpClient { BaseAddress = new Uri(baseUrl), Timeout = TimeSpan.FromSeconds(15) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
// 1. Before you send a reminder: is this patient's consent on file?
var res = await http.GetAsync($"/api/v1/consent?siteId={Uri.EscapeDataString(site)}&subjectRef={Uri.EscapeDataString("P-1042")}");
using var consent = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
var canSend = res.IsSuccessStatusCode && consent.RootElement.TryGetProperty("canSendReminders", out var p) && p.GetBoolean();
Console.WriteLine(canSend ? "OK to send the reminder" : "Do not send: " + consent.RootElement);
// 2. Record a choice you collected yourself
var body = new JsonObject { ["siteId"] = site, ["subjectRef"] = "P-1042", ["action"] = "custom", ["choices"] = new JsonObject { ["reminders"] = true, ["marketing"] = false } }.ToJsonString();
var saved = await http.PostAsync("/api/v1/consent", new StringContent(body, Encoding.UTF8, "application/json"));
Console.WriteLine($"{(int)saved.StatusCode} {await saved.Content.ReadAsStringAsync()}");Check that a webhook really came from us (same signature in every language).
// Check that a webhook really came from ZeroClause (C# / .NET 6+).
// Header: X-ZeroClause-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
using System;
using System.Security.Cryptography;
using System.Text;
public static class ZeroClauseWebhook
{
/// <summary>rawBody must be the exact text received, not parsed and re-written JSON.</summary>
public static bool Verify(string rawBody, string header, string secret, int toleranceSeconds = 300)
{
string? t = null, v1 = null;
foreach (var part in header.Split(','))
{
var kv = part.Trim().Split('=', 2);
if (kv.Length == 2 && kv[0] == "t") t = kv[1];
if (kv.Length == 2 && kv[0] == "v1") v1 = kv[1];
}
if (t is null || v1 is null || !long.TryParse(t, out var sent)) return false;
if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - sent) > toleranceSeconds) return false; // too old: could be a replay
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret));
var expected = Convert.ToHexString(hmac.ComputeHash(Encoding.UTF8.GetBytes($"{t}.{rawBody}"))).ToLowerInvariant();
return CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(v1));
}
}
// In an ASP.NET endpoint: read the body as a string (Request.Body with StreamReader), call
// ZeroClauseWebhook.Verify(body, Request.Headers["X-ZeroClause-Signature"], secret); answer 400 if false.
// Then parse the JSON, remember the event "id" and ignore repeats (retries use the same id), answer 200.Gowritten, not run yet
Check consent before you message someone, then record a choice. Set ZEROCLAUSE_API_KEY and ZEROCLAUSE_SITE.
// Privacy by ZeroClause from Go (standard library only).
// Set ZEROCLAUSE_API_KEY (zc_live_… or zc_test_…) and ZEROCLAUSE_SITE (your website's slug).
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"time"
)
var (
base = envOr("ZEROCLAUSE_BASE", "https://zeroclauseai.com")
key = os.Getenv("ZEROCLAUSE_API_KEY")
site = os.Getenv("ZEROCLAUSE_SITE")
client = &http.Client{Timeout: 15 * time.Second}
)
func envOr(k, d string) string {
if v := os.Getenv(k); v != "" {
return v
}
return d
}
func call(method, path string, body any) (int, map[string]any, error) {
var buf bytes.Buffer
if body != nil {
if err := json.NewEncoder(&buf).Encode(body); err != nil {
return 0, nil, err
}
}
req, err := http.NewRequest(method, base+path, &buf)
if err != nil {
return 0, nil, err
}
req.Header.Set("Authorization", "Bearer "+key)
req.Header.Set("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return 0, nil, err
}
defer res.Body.Close()
var out map[string]any
_ = json.NewDecoder(res.Body).Decode(&out)
return res.StatusCode, out, nil
}
func main() {
// 1. Before you send a reminder: is this patient's consent on file?
q := url.Values{"siteId": {site}, "subjectRef": {"P-1042"}}
status, consent, err := call("GET", "/api/v1/consent?"+q.Encode(), nil)
if err == nil && status == 200 && consent["canSendReminders"] == true {
fmt.Println("OK to send the reminder")
} else {
fmt.Println("Do not send:", status, consent, err)
}
// 2. Record a choice you collected yourself
status, saved, err := call("POST", "/api/v1/consent", map[string]any{
"siteId": site, "subjectRef": "P-1042", "action": "custom",
"choices": map[string]bool{"reminders": true, "marketing": false},
})
fmt.Println(status, saved["consentId"], saved["error"], err)
}Check that a webhook really came from us (same signature in every language).
// Check that a webhook really came from ZeroClause (Go, standard library only).
// Header: X-ZeroClause-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
package zeroclause
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"strings"
"time"
)
// VerifyWebhook reports whether the delivery is genuine. rawBody must be the exact bytes received.
func VerifyWebhook(rawBody []byte, header, secret string, tolerance time.Duration) bool {
var t, v1 string
for _, part := range strings.Split(header, ",") {
kv := strings.SplitN(strings.TrimSpace(part), "=", 2)
if len(kv) == 2 && kv[0] == "t" {
t = kv[1]
}
if len(kv) == 2 && kv[0] == "v1" {
v1 = kv[1]
}
}
sent, err := strconv.ParseInt(t, 10, 64)
if err != nil || v1 == "" {
return false
}
age := time.Since(time.Unix(sent, 0))
if age > tolerance || age < -tolerance { // too old (or clock far off): could be a replay
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(fmt.Sprintf("%d.", sent)))
mac.Write(rawBody)
expected := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(expected), []byte(v1))
}
// In your handler: body, _ := io.ReadAll(r.Body); if !VerifyWebhook(body, r.Header.Get("X-ZeroClause-Signature"), secret, 5*time.Minute) { http.Error(w, "bad signature", 400); return }
// then json.Unmarshal(body, &event), remember event.ID and ignore repeats (retries use the same id), answer 200.Ruby (Rails)written, not run yet
Check consent before you message someone, then record a choice. Set ZEROCLAUSE_API_KEY and ZEROCLAUSE_SITE.
# Privacy by ZeroClause from Ruby (standard library only; works in Rails too).
# Set ZEROCLAUSE_API_KEY (zc_live_… or zc_test_…) and ZEROCLAUSE_SITE (your website's slug).
require "json"
require "net/http"
require "uri"
BASE = ENV.fetch("ZEROCLAUSE_BASE", "https://zeroclauseai.com")
KEY = ENV.fetch("ZEROCLAUSE_API_KEY")
SITE = ENV.fetch("ZEROCLAUSE_SITE")
def call(method, path, body = nil)
uri = URI(BASE + path)
req = Net::HTTP.const_get(method.capitalize).new(uri)
req["Authorization"] = "Bearer #{KEY}"
req["Content-Type"] = "application/json"
req.body = JSON.generate(body) if body
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 15, open_timeout: 15) { |h| h.request(req) }
[res.code.to_i, JSON.parse(res.body.to_s.empty? ? "{}" : res.body)]
end
# 1. Before you send a reminder: is this patient's consent on file?
status, consent = call("get", "/api/v1/consent?siteId=#{URI.encode_www_form_component(SITE)}&subjectRef=#{URI.encode_www_form_component('P-1042')}")
if status == 200 && consent["canSendReminders"]
puts "OK to send the reminder"
else
puts "Do not send: #{consent['status'] || consent['error']}"
end
# 2. Record a choice you collected yourself
status, saved = call("post", "/api/v1/consent", { siteId: SITE, subjectRef: "P-1042", action: "custom", choices: { reminders: true, marketing: false } })
puts "#{status} #{saved['consentId'] || saved['error']}"Check that a webhook really came from us (same signature in every language).
# Check that a webhook really came from ZeroClause (Ruby, standard library only).
# Header: X-ZeroClause-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
require "openssl"
# raw_body must be the exact text received, not parsed and re-written JSON.
def zeroclause_webhook_valid?(raw_body, header, secret, tolerance_seconds = 300)
parts = header.to_s.split(",").map { |p| p.strip.split("=", 2) }.to_h
t = parts["t"]
v1 = parts["v1"]
return false unless t =~ /\A\d+\z/ && v1
return false if (Time.now.to_i - t.to_i).abs > tolerance_seconds # too old: could be a replay
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw_body}")
expected.bytesize == v1.bytesize && OpenSSL.fixed_length_secure_compare(expected, v1)
end
# In a Rails controller:
# raw = request.raw_post
# head :bad_request and return unless zeroclause_webhook_valid?(raw, request.headers["X-ZeroClause-Signature"], ENV["ZEROCLAUSE_WEBHOOK_SECRET"])
# event = JSON.parse(raw) # remember event["id"] and ignore repeats (retries use the same id), then head :ok“Run and tested” means we ran the example against our test environment. The others follow the same steps from each language’s standard library; if one does not work for you, tell us and we will fix it.
Errors and retries
Errors are JSON, { "error": "code", "message": "…" }, with the right HTTP status: 400 for a bad request, 401 or 403 for a key problem, 402 when the account’s plan has paused, 409 when the notice is not published yet, 429 when you send too fast. The SDK throws ZeroClauseError with status and code. Reads are retried twice; writes are never retried, so you cannot create duplicates.
Before you go live
- Publish your notice and have a lawyer read it. ZeroClause gives tools and templates, not legal advice.
- Check consent right before every reminder or offer. Someone who said no, or withdrew, is a no.
- Keep API keys and webhook secrets in environment variables. Rotate a key if it leaks (Integrations & API).
- Run the free website check and fix what it finds.