Add free AI to your app in just a few minutes — rewards included
The AIRewards SDK by Jutera gives your users a free AI chat inside your app or web experience. Users ask a question, compare two answers, pick the better one with a reason, and can earn in your own currency when you reward picks. This page is the complete integration reference, so you can get started in a few minutes. Giving this to your agent? Point them to /llms.txt.
High-Level Integration Steps
-
Dashboard Copy your keys
pk_…is public and ships in the client.sk_…is the server secret, shown once. -
Browser Try a session with no server
Open the standalone test widget from Integration → step 4 with your publishable key in test mode. Ask, pick, and choose a reason. A test
reward.earnedfires and is never payable. -
Your server Mint a launch token
Sign one short-lived token per user. Live sessions require it. Test mode can skip it.
-
Your app Open the widget
Load the loader and call
AIRewards.initon the web, or inside a native webview. -
Your server Credit from the webhook
Receive
reward.earned, verify the signature, credit the user, and dedupe onevent_id. This is the only place you credit. -
Your server · optional Check availability first
GET /v1/availabilitybefore you show the “Earn with AI search” entry point, so you can hide it when the user is capped or you have no fill. -
Dashboard Go live
When test events land, request live (payable) approval from Settings (or Overview) — the button is available any time while you are pending. We review your test traffic, webhook, and terms, and email the account owners with the decision; a rejection includes what to fix, and you can re-request at any time. Test mode keeps working. Questions: hello@jutera.com.
1 · Keys
| Key | Where it lives | What it does |
|---|---|---|
pk_… publishable | Client code, snippets, mobile apps | Identifies your publisher account. Safe to ship. |
sk_… secret | Your server only (env var) | Signs launch tokens; authenticates the Availability and Reporting APIs. Shown once; Owners can rotate it in Keys & API (the old key stops working immediately). |
whsec_… webhook secret | Your server only | Verifies webhook signatures. Shown masked after creation; Owners can rotate it on the Webhook page if it is lost. |
Lost your secret key? Sign in to the dashboard (your account email is all you need), rotate from Keys & API, and update the secret on your server right away — the old secret stops working the moment you rotate, so live signing breaks until your server has the new one. If you cannot sign in, email hello@jutera.com.
Never put sk_… or whsec_… in client code, repos, or logs.
2 · Launch token (your server)
A launch token is a short-lived pass your server signs for one end user. It names that user and proves your secret key minted it. The widget sends the token when it opens a session.
The publishable key only identifies your account, and it is safe to ship in the client. Live mode rejects a session that arrives without a valid token (invalid_token), so a copied pk_… cannot earn as your users. Test mode can omit the token; those events are marked test_mode and are never payable.
Sign it on your server, never in the browser. One token per end-user session. Format (JWT-shaped, HS256):
base64url({"alg":"HS256","typ":"JWT"}) + "." + base64url(payload) + "." + base64url(HMAC_SHA256(signing_input, sk_…))
Payload:
{
"pk": "pk_…",
"user_id": "your-user-123",
"metadata": {
"placement": "earn_tab"
},
"test_mode": false,
"iat": 1760000000,
"exp": 1760000600
}
iat and exp are Unix time in seconds — the same unit as Math.floor(Date.now() / 1000), not milliseconds.
pkRequired- Your publishable key. It must be the account whose secret signed the token.
user_idRequired- An opaque, stable id for this user. Caps and reporting key on it. Never an email or a name.
metadata.placementRequired- Where you offer this session, such as
earn_tab. Use 1–32 characters: letters, numbers, underscore, and hyphen. A missing value is rejected asmissing_placement. A value outside that set isinvalid_placement. The value is echoed on the webhook and in reports. metadataOther keys optional- Any key besides
placementis optional. Values are strings. The map is echoed verbatim in webhooks and reports, so keep it small — for examplecampaign. test_modeOptional- When true, the session is a test. Test events are never payable.
iatIssued at- Unix seconds when you minted the token. The samples set this to now. If you leave it out, the server measures the lifetime cap from the moment it checks the token.
expExpires at · required- Unix seconds when the token stops working. A missing or past
expis rejected astoken_expired.exp − iatmust be at most 900 seconds (15 minutes), or the server rejects the token asinvalid_token. The samples use 600 seconds (10 minutes). A visit that outlasts the token needs a fresh one — see the note under the samples.
Node.js
const crypto = require('crypto');
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
function launchToken({ userId, metadata = {}, testMode = false }) {
const now = Math.floor(Date.now() / 1000);
const header = b64({ alg: 'HS256', typ: 'JWT' });
const payload = b64({
pk: process.env.AIREWARDS_PK,
user_id: String(userId),
metadata,
test_mode: testMode,
iat: now,
exp: now + 600,
});
const input = header + '.' + payload;
const sig = crypto.createHmac('sha256', process.env.AIREWARDS_SK).update(input).digest('base64url');
return input + '.' + sig;
}
// In your page/app bootstrap handler. placement is required; other metadata keys are optional.
// res.json({ airewardsToken: launchToken({
// userId: req.user.id,
// metadata: { placement: 'earn_tab' },
// }) })
Python
import base64, hashlib, hmac, json, os, time
def _b64(obj):
raw = json.dumps(obj, separators=(',', ':')).encode()
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode()
def launch_token(user_id, metadata=None, test_mode=False):
now = int(time.time())
header = _b64({'alg': 'HS256', 'typ': 'JWT'})
payload = _b64({
'pk': os.environ['AIREWARDS_PK'],
'user_id': str(user_id),
'metadata': metadata or {},
'test_mode': test_mode,
'iat': now,
'exp': now + 600,
})
signing_input = header + '.' + payload
sig = base64.urlsafe_b64encode(
hmac.new(os.environ['AIREWARDS_SK'].encode(), signing_input.encode(), hashlib.sha256).digest()
).rstrip(b'=').decode()
return signing_input + '.' + sig
# placement is required; other metadata keys are optional.
# launch_token(user_id, {'placement': 'earn_tab'})
PHP
<?php
function airewards_token($userId, $metadata = [], $testMode = false) {
$b64 = function ($obj) {
$json = json_encode($obj);
return rtrim(strtr(base64_encode($json), '+/', '-_'), '=');
};
$now = time();
$header = $b64(['alg' => 'HS256', 'typ' => 'JWT']);
$payload = $b64([
'pk' => getenv('AIREWARDS_PK'),
'user_id' => (string) $userId,
'metadata' => (object) $metadata,
'test_mode' => $testMode,
'iat' => $now,
'exp' => $now + 600,
]);
$input = $header . '.' . $payload;
$sig = rtrim(strtr(base64_encode(hash_hmac('sha256', $input, getenv('AIREWARDS_SK'), true)), '+/', '-_'), '=');
return $input . '.' . $sig;
}
// placement is required; other metadata keys are optional.
// airewards_token($userId, ['placement' => 'earn_tab']);
When a token expires mid-visit, the widget tells your page (see §4): fetch a fresh token and call AIRewards.setLaunchToken(newToken) — no reload needed.
3 · Web embed
<script src="https://airewards.b-cdn.net/loader@1.js" async></script>
<div id="airewards"></div>
<script>
// If the async loader already ran, init immediately; otherwise wait for it.
// (Listening only can race the loader and never fire.)
if (window.AIRewards) initWidget(); else window.addEventListener('airewards:ready', initWidget);
function initWidget() {
AIRewards.init({
publishableKey: 'pk_…',
launchToken: '<from your server>', // or omit + testMode: true for browser testing
container: '#airewards',
heightMode: 'auto', // see "Container height" below
theme: { primaryColor: '#0f0f0f', accentColor: '#ffce33', fontFamily: "'Inter', sans-serif",
borderRadius: 14, elementRadius: 10, colorScheme: 'Light', showPoweredBy: true, typingIndicator: 'dots', pickAlignment: 'center' },
onPick: (e) => { /* pick confirmed — e.rewarded tells you if it earned; e.event_id is null when it did not */ },
onEarn: (e) => { /* e.event_id — refresh UI; credit ONLY from the webhook */ },
onTokenExpired: () => { /* fetch a fresh token, then AIRewards.setLaunchToken(t) */ },
onNewChat: (e) => { /* e.abandoned — optional */ },
onConversationStarted: (e) => { /* e.conversation_id — optional */ },
onRewardIneligible: (e) => { /* e.conversation_id, e.duel_id, e.reason — optional; see Trivial questions below */ },
// trivialGate: 'soft', // optional per-embed override; see Trivial questions below
});
}
</script>
Theme tokens (the complete list the loader honors): primaryColor, accentColor, background, textColor, fontFamily, borderRadius (outer container), elementRadius (answer cards, buttons, inputs), colorScheme ('Light' or 'Dark'), showPoweredBy (the small “Powered by Jutera” footer line), showNewChat / showHistory (the New chat and History buttons in the top right, both shown by default; see New chat & history), typingIndicator ('dots' default, 'bars', 'pulse', 'bloom', 'fade', 'spinner', 'caret', or 'slide' — the animated indicator in answers while AI responses stream in), pickAlignment ('left', 'center' default, or 'right' — alignment of the Pick A / Pick B buttons), headerText (top-of-widget message, default “Ask anything”; pass '' for no message), headerLogoUrl / headerLogoUrlDark / headerLogoHeight / headerLogoAlt (header logo; see Header logo), introText (start-screen headline above the composer, default “Ask a question — you'll compare two anonymous answers and pick the better one.”), starterText (line above the composer before the first question, default “Ask anything to get started.”), earnedTitle / earnedSubtitle (selection confirmation copy shown after a pick; if you offer rewards, use these for your reward message — {event_id} expands to the reward event id). Values saved in Dashboard → Appearance always apply; keys you pass in theme override just those values for that launch (everything you leave out keeps the saved setting). A flat color such as primaryColor overrides both the light and dark saved colors unless you also pass that color inside theme.light / theme.dark. Answer anonymity, the reason-chip step, and the ad slot cannot be themed away.
Header logo
The widget header can show a logo, a message, both, or neither. Upload a logo in Dashboard → Appearance (PNG, JPEG, WebP, or SVG up to 512 KB; we serve it from our CDN), or pass your own image URL per launch:
AIRewards.init({
// ...publishableKey, launchToken, container
theme: {
headerLogoUrl: 'https://cdn.example.com/logo-wide.svg', // https only
headerLogoUrlDark: 'https://cdn.example.com/logo-wide-dark.svg', // optional, used in dark mode
headerLogoHeight: 32, // px, 16–48, default 28
headerLogoAlt: 'Example', // read by screen readers when no message is shown
headerText: '' // '' = logo only; omit to keep your saved message
}
});
- Icon + message: a square logo with
headerTextset — the logo sits to the left of the message. - Full logo: a wide logo with
headerText: ''. Width follows the image's aspect ratio and is capped so the History and New chat buttons always fit. - Your own URL: must be
https://(other schemes, includinghttp:anddata:, are ignored). It is loaded as a plain image with no referrer, so no CORS setup is needed. Host it somewhere fast and cacheable; if it fails to load, the logo is hidden and any message still shows. - Dark mode:
headerLogoUrlDarkis used when the widget renders dark (colorScheme: 'Dark', or Match device on a dark OS) and falls back toheaderLogoUrl. - Blank header: with no logo, an empty message, and both header buttons hidden (
showNewChat: false,showHistory: false), the header bar is removed entirely.
Test without server code: pass testMode: true with just your publishable key (or use the links in Integration → step 4). Unsigned launch is test-mode only; test events are flagged ("test_mode": true) and never payable. In live mode a signed token is always required.
The loader is served from the CDN at https://airewards.b-cdn.net/loader@1.js (versioned — pin that exact URL). Calling init twice is guarded; call the returned handle’s destroy() to tear down.
Container height: heightMode
As answers stream, the conversation grows. heightMode decides who scrolls:
| Scenario | Mode | What to do |
|---|---|---|
| Inline web embed (article, landing page, dashboard panel in page flow) | 'auto' (default) | Give the container no fixed height. The iframe grows with the conversation and the host page scrolls — no nested scrollbar. Recommended for most web embeds. |
| Fixed-height chat panel, sidebar, or app shell | 'fixed' | Set an explicit container height (e.g. height:640px) — it may be shorter than the screen when your own content sits above it. The loader sizes the iframe to the container (and follows resizes), the conversation scrolls inside it, and the composer stays pinned to the bottom of your chosen height. |
| Native app, webview fills the screen | 'fixed' | The webview owns the viewport; internal scrolling is correct. |
| Native app, webview inline in a scrolling feed/page | 'auto' | Listen for airewards:height bridge messages ({ height } in CSS pixels) and resize the webview container to match, so the native page scrolls instead. |
Before the first question the widget shows a start screen: the headline and composer sit about a third of the way down the widget (closer to the top on phones) and snap to the bottom on the first send. That offset is measured against the iframe height, so in 'auto' mode it uses the 560px starting height and in 'fixed' mode your container height.
If you pass neither heightMode nor a container height, you get 'auto'. Do not combine 'auto' with a fixed-height, overflow:hidden container — the growing iframe will be clipped. The widget reports its height continuously (see the airewards:height event below); hosts that manage their own layout can consume those reports directly instead of using the loader’s resizing.
4 · Widget events (all stacks)
| Event | When | Payload |
|---|---|---|
airewards:ready (window) | Loader has loaded | — (then call AIRewards.init) |
onPick callback / airewards:pick-confirmed (window CustomEvent) | A pick + at least one reason was confirmed by the server — rewarded or not. Fires before onEarn when the pick also earns | { conversation_id, duel_id, rewarded, reward_eligible, reason, event_id, test_mode } — event_id is null when the pick did not earn; no winner or model is included |
onEarn callback / airewards:earned (window CustomEvent) | A pick + at least one reason was accepted and the earning event created | { event_id, test_mode } — same id as the webhook |
onTokenExpired / airewards:token-expired | The session or launch token expired | Fetch a fresh token and call AIRewards.setLaunchToken(t) |
onConversationStarted / airewards:conversation-started | A new question opened a conversation (the duel started) | { conversation_id } — the same id as in the webhook and /v1/conversations |
onNewChat / airewards:new-chat | The widget went back to a fresh chat (header button or AIRewards.newChat()) | { abandoned } — true when an unpicked duel was left behind (it will not earn) |
onRewardIneligible / airewards:reward-ineligible | A trivial question was let through without rewards (see Trivial questions) and its duel is ready to pick | { conversation_id, duel_id, reason: 'trivial_question', test_mode } — UI hint only; no reward.earned webhook fires for this pick |
airewards:height (window CustomEvent, detail { height }) | Widget content height changed (streaming, pick, ad, follow-up) | In heightMode:'auto' the loader resizes the iframe for you; consume it directly only if you manage the container yourself (e.g. a native webview) |
Inside a native webview the same moments are also posted on the same bridge: a confirmed pick as { source: 'airewards', type: 'airewards:pick-confirmed', conversation_id, duel_id, rewarded, reward_eligible, reason, event_id, test_mode }, and an earning pick as { source: 'airewards', type: 'reward.earned', event_id, test_mode }, via window.postMessage and, where the container registers them, webkit.messageHandlers.airewards (iOS), AIRewardsBridge (Android), and ReactNativeWebView (React Native). Use onPick as your completion signal (for rewarded and non-rewarded implementations alike) and onEarn only as the reward signal — do not count a pick twice from both. Both are UI hints; balances are credited only from the server webhook.
Trivial questions
Every first question is checked before a duel runs. Gibberish, keyboard mashing, and non-questions are always blocked with your rejection message (Dashboard → Settings). A trivial question — a genuine quick-fact question that every AI model answers about the same, such as a capital city or a population figure — is handled by your trivial-question setting:
- Let through without rewards (default). The user still gets the duel, picks the better answer, and can continue the chat. No reward is paid: no earning event is created and no
reward.earnedwebhook fires for that pick. The widget tells the user before they pick (“Quick fact questions like this don't earn”), and your app is notified at the same moment with theonRewardIneligiblecallback /airewards:reward-ineligibleevent so you can show the same expectation in your own UI. - Block. The question never starts a duel and your rejection message is shown instead, exactly as before this setting existed.
Set the account-wide behavior in Dashboard → Settings → Trivial questions. To vary it per embed, pass trivialGate: 'soft' or trivialGate: 'hard' to AIRewards.init(...) (test mode), or include "trivial_gate": "soft" | "hard" in the signed launch-token metadata (live mode). A per-embed value wins over the dashboard setting for that session. Neither mode ever pays a reward for a trivial question, and crediting still happens only from the reward.earned webhook — the reward-ineligible event is a UI hint, never a crediting signal.
New chat & history
The widget header has two buttons in the top right: History (the user's past chats) and New chat. If the user taps New chat before picking an answer, the widget asks first, because a duel left unpicked does not earn. Hide either button with the theme tokens showHistory: false / showNewChat: false (or in Dashboard → Appearance) and drive the same actions from your own UI:
// Start a fresh conversation (no confirmation; resolves right away).
const { abandoned } = await AIRewards.newChat(); // abandoned: an unpicked duel was left behind
// The signed-in user's past chats, most recent first (last 90 days).
const { conversations, next_cursor } = await AIRewards.getHistory({ limit: 20 });
// conversations[i]: { conversation_id, title, status: 'picked' | 'unpicked', resumable,
// turns, test_mode, created_at, last_activity_at }
// Next page: AIRewards.getHistory({ cursor: next_cursor })
// Open one of them in the widget.
const { resumable } = await AIRewards.openConversation(conversations[0].conversation_id);
The same three methods are on the handle returned by init(). Rules:
- History in the browser is always the launch-token user's. There is no
user_idparameter in the browser, because your publishable key is public. To look up any user's chats, use GET /v1/conversations from your server. - Picked chats can be continued with follow-ups on the answer the user chose. Unpicked chats are read-only: the widget shows the question and a note, and the two answers can no longer be picked or earned on.
- Test-mode launches see only test-mode chats, and live launches see only live chats.
- Calls made before the widget finishes loading are queued. A call rejects with an
Errorwhosecodeisnot_initialized(noinityet),timeout(10 seconds),widget_reloaded(you calledsetLaunchTokenwhile it was in flight),token_expired(fetch a new token, thensetLaunchToken), ornot_found(openConversationwith an id this user does not own).
Native apps run the same methods by evaluating JavaScript in your bootstrap page (the page that calls AIRewards.init). The airewards:new-chat and airewards:conversation-started events arrive on the same bridge as reward.earned.
iOS
webView.evaluateJavaScript("AIRewards.newChat()")
// callAsyncJavaScript awaits the Promise and hands back the result.
webView.callAsyncJavaScript("return await AIRewards.getHistory({ limit: 20 })",
arguments: [:], in: nil, in: .page) { result in
if case .success(let value) = result { /* value: ["conversations": [...], "next_cursor": ...] */ }
}
Android
webView.evaluateJavascript("AIRewards.newChat()", null)
// evaluateJavascript does not await Promises: post the result back over your bridge.
webView.evaluateJavascript(
"AIRewards.getHistory({ limit: 20 }).then(function (r) {" +
" AIRewardsBridge.postMessage(JSON.stringify({ source: 'airewards', type: 'history', result: r }));" +
"});", null)
React Native
webViewRef.current.injectJavaScript('AIRewards.newChat(); true;');
webViewRef.current.injectJavaScript(`
AIRewards.getHistory({ limit: 20 }).then(function (r) {
window.ReactNativeWebView.postMessage(JSON.stringify({ source: 'airewards', type: 'history', result: r }));
}); true;`);
// onMessage: m.type === 'history' -> m.result.conversations
Flutter
await controller.runJavaScript('AIRewards.newChat()');
await controller.runJavaScript(
"AIRewards.getHistory({ limit: 20 }).then(function (r) {"
" AIRewardsBridge.postMessage(JSON.stringify({ source: 'airewards', type: 'history', result: r }));"
"});");
// AIRewardsBridge channel: msg.message is the JSON above
If your webview loads the widget URL directly instead of a bootstrap page with the loader, call AIRewardsWidget.command({ type: 'newChat' }), { type: 'getHistory', limit, cursor }, or { type: 'openConversation', conversation_id } in that page. Each returns a Promise. If you add a request_id, the answer is also posted to the bridge as { source: 'airewards', type: 'airewards:response', request_id, ok, result | error }.
5 · Native webviews
New: full step-by-step Quickstarts per platform — iOS (WKWebView) · Android (WebView) · React Native · Flutter. Each covers the user id, token, bootstrap page, embedding, events, and webhook in plain language. The fragments below remain as the quick reference.
General rules for every stack: (1) your app fetches a launch token from your server first — never mint tokens in the app with sk_…; (2) enable JavaScript and DOM storage; (3) listen for the earn bridge to refresh native UI; (4) handle token expiry by fetching a fresh token and handing it to the widget; (5) credit only from the webhook; (6) pick a height behavior: full-screen webviews use heightMode:'fixed', while a webview inline in a scrolling native page should use 'auto' and resize its container from the airewards:height bridge messages ({ source:'airewards', type:'airewards:height', height }).
iOS
let config = WKWebViewConfiguration()
config.userContentController.add(self, name: "airewards") // WKScriptMessageHandler
let webView = WKWebView(frame: .zero, configuration: config)
// Load your hosted bootstrap page that calls AIRewards.init with a server-fetched token.
func userContentController(_ c: WKUserContentController, didReceive message: WKScriptMessage) {
guard let body = message.body as? [String: Any], body["source"] as? String == "airewards",
body["type"] as? String == "reward.earned" else { return }
refreshBalanceFromYourBackend() // your backend credits on the webhook; this is only the UI hint
}
Android
class Bridge { @JavascriptInterface fun postMessage(json: String) { /* parse: source/type/event_id */ } }
webView.settings.javaScriptEnabled = true
webView.settings.domStorageEnabled = true
webView.addJavascriptInterface(Bridge(), "AIRewardsBridge")
// Only ever load your own bootstrap page (with a server-fetched token) in this webview —
// addJavascriptInterface is unsafe with untrusted URLs.
React Native
<WebView
source={{ uri: yourBootstrapUrl }} // page that calls AIRewards.init with your token
onMessage={(e) => {
const m = JSON.parse(e.nativeEvent.data);
if (m.source === 'airewards' && m.type === 'reward.earned') refreshBalance();
}}
/>
Flutter
final controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..addJavaScriptChannel('AIRewardsBridge', onMessageReceived: (msg) {
// parse msg.message: {source: 'airewards', type: 'reward.earned', event_id}
})
..loadRequest(Uri.parse(yourBootstrapUrl));
6 · Webhooks
A webhook is how your server learns that a user earned. After they pick an answer and a reason, AIRewards POSTs a reward.earned event to the HTTPS URL you save in Dashboard → Webhook.
Credit the user from this request, in your own currency. Verify the signature with your whsec_… secret before you credit. The widget onEarn callback and the native bridge can refresh your UI; this webhook is the event to trust. Retries reuse the same event_id, so dedupe before you credit twice.
The request is a POST of JSON to that saved URL. Headers:
AIRewards-Signature: t=1760000123,v1=5257a869…
AIRewards-Event-Id: evt_… (same id as the body's "id")
{
"id": "evt_…", "type": "reward.earned",
"created_at": "2026-10-17T12:00:05Z", "test_mode": false,
"publisher_id": "pub_…", "user_id": "your-user-123",
"metadata": { "placement": "earn_tab" },
"duel_id": 12345, "conversation_id": "c_…",
"winner": "A", "attributes": ["More accurate", "Clearer"]
}
Rules: respond with any 2xx within 10 seconds (do slow work async); verify the signature over the raw body bytes (tolerance 5 minutes); dedupe on event_id — retries and dashboard resends reuse it; delivery is at-least-once with ~24h exponential backoff, then dead-letter (visible in your Webhook page). The payload carries no money fields: what you credit your user is your own points logic, and revenue reconciles through the Reporting API.
Verify the signature
Same three languages as the launch token. Compare the HMAC in constant time, over t + "." + rawBody, and reject timestamps more than five minutes off.
Node.js
const crypto = require('crypto');
function verifyWebhook(rawBody, header, secret) {
const parts = Object.fromEntries(String(header || '').split(',').map((s) => s.split('=')));
if (!parts.t || !parts.v1) return false;
if (Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return false;
const expected = crypto.createHmac('sha256', secret).update(parts.t + '.' + rawBody).digest('hex');
return expected.length === parts.v1.length &&
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
}
// Express: capture the raw body BEFORE any JSON parser touches it:
app.post('/airewards/webhook', express.raw({ type: 'application/json' }), (req, res) => {
if (!verifyWebhook(req.body.toString('utf8'), req.headers['airewards-signature'], process.env.AIREWARDS_WHSEC)) {
return res.status(401).end();
}
const event = JSON.parse(req.body.toString('utf8'));
// TODO(you): if event.id already credited, return 200 immediately (idempotency).
// TODO(you): credit event.user_id in your currency; never trust a browser event for this.
res.status(200).end();
});
Python
import hashlib, hmac, json, os, time
def verify_webhook(raw_body, header, secret):
parts = {}
for piece in str(header or '').split(','):
if '=' not in piece:
continue
key, value = piece.split('=', 1)
parts[key.strip()] = value.strip()
if 't' not in parts or 'v1' not in parts:
return False
try:
ts = int(parts['t'])
except ValueError:
return False
if abs(time.time() - ts) > 300:
return False
if isinstance(raw_body, str):
raw_body = raw_body.encode()
signed = parts['t'].encode() + b'.' + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, parts['v1'])
# Flask — use the raw body before JSON parsing:
# @app.post('/airewards/webhook')
# def airewards_webhook():
# raw = request.get_data()
# header = request.headers.get('AIRewards-Signature', '')
# if not verify_webhook(raw, header, os.environ['AIREWARDS_WHSEC']):
# return ('', 401)
# event = json.loads(raw)
# # If event['id'] is already credited, return 200 (retries reuse it).
# # Credit event['user_id'] in your currency. Never trust a browser event for this.
# return ('', 200)
PHP
<?php
function airewards_verify_webhook($rawBody, $header, $secret) {
$parts = [];
foreach (explode(',', (string) $header) as $piece) {
$i = strpos($piece, '=');
if ($i === false) continue;
$parts[trim(substr($piece, 0, $i))] = trim(substr($piece, $i + 1));
}
if (empty($parts['t']) || empty($parts['v1'])) return false;
if (abs(time() - (int) $parts['t']) > 300) return false;
$expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret);
return hash_equals($expected, $parts['v1']);
}
// $raw = file_get_contents('php://input');
// $header = $_SERVER['HTTP_AIREWARDS_SIGNATURE'] ?? '';
// if (!airewards_verify_webhook($raw, $header, getenv('AIREWARDS_WHSEC'))) {
// http_response_code(401);
// exit;
// }
// $event = json_decode($raw, true);
// // If $event['id'] is already credited, respond 200 (retries reuse it).
// // Credit $event['user_id'] in your currency. Never trust a browser event for this.
// http_response_code(200);
Fastest path to a known-good handler: save your URL, click Send test event on the Webhook page, and watch the delivery row go green with your real signed test payload ("test_mode": true — do not credit for it).
7 · Availability
Call it server-side before rendering your “Earn with AI search” entry point; cache per user up to cache_ttl_seconds. Reasons are deliberately coarse: available, daily_cap_reached, publisher_paused (also used for global maintenance pauses), no_fill_expected, user_ineligible. Never expose sk_… to the client to make this call — the widget itself degrades gracefully if you skip it.
GET https://jutera.com/v1/availability?user_id=your-user-123
Authorization: Bearer sk_…
200
{
"eligible": true,
"reason": "available",
"cache_ttl_seconds": 60
}
8 · Reporting API
All endpoints use Authorization: Bearer sk_… and return as_of with every response. Revenue is estimated/provisional until the settlement job moves it to payable; events are near-real-time. Test-mode events are excluded from revenue and returned only when you ask for them.
Daily funnel + revenue
GET https://jutera.com/v1/reports/daily?from=2026-10-11&to=2026-10-17
→ { "publisher_id": "pub_…", "from": "…", "to": "…", "as_of": "…", "days": [
{ "day": "2026-10-17", "chats": 12, "duels": 9, "picks": 7, "users": 5,
"earned": 4, "earned_test": 1,
"provisional_cents": 0, "payable_cents": 0, "gross_cents": 0 } ] }
One zero-filled row per day in the range (default: last 7 days): chats (conversations started), duels, picks (duels with a chosen winner), users (distinct chat users), earned / earned_test, and revenue cents split provisional_cents vs payable_cents. Add &group_by=metadata.placement (any metadata key) for a per-value earned/revenue breakdown in groups.
Event list (cursor paginated)
GET https://jutera.com/v1/reports/events?from=2026-10-11&to=2026-10-17&limit=25
[&user_id=…] [&test_mode=true] [&cursor=<last event_id from the previous page>]
→ { "events": [ { "event_id": "evt_…", "type": "reward.earned", "test_mode": false,
"user_id": "…", "duel_id": 42, "winner": "A", "attributes": ["Clearer"],
"state": "provisional", "publisher_cents": 0, "floor_applied": false,
"created_at": "…", "payable_at": null, "webhook": "delivered" } ],
"next_cursor": "evt_… or null" }
Single event
GET https://jutera.com/v1/reports/events/evt_…
→ { "event": { …same shape as the list… }, "as_of": "…" } · 404 if it is not yours
The Dashboard → Reports CSV export mirrors the event list for the selected range.
Conversation history
One user's chats for your own UI, support tools, or exports: the last 90 days, most recent activity first. user_id is required and is the same opaque id you put in the launch token. status is picked (resumable in the widget) or unpicked (the duel was left before a pick). Unpicked chats return only the question; the two duel answers are never returned. Add test_mode=true or false to filter by mode; leave it out to get both.
GET https://jutera.com/v1/conversations?user_id=your-user-123&limit=20
[&test_mode=false] [&cursor=<next_cursor from the previous page>]
→ { "publisher_id": "pub_…", "user_id": "your-user-123",
"conversations": [ { "conversation_id": "c_…", "title": "How do I…",
"status": "picked", "resumable": true, "turns": 3, "test_mode": false,
"created_at": "…", "last_activity_at": "…" } ],
"next_cursor": "opaque string or null" }
GET https://jutera.com/v1/conversations/c_…?user_id=your-user-123
→ { "publisher_id": "pub_…", "user_id": "your-user-123",
"conversation": { "conversation_id": "c_…", "title": "…", "status": "picked",
"resumable": true, "test_mode": false, "created_at": "…", "last_activity_at": "…",
"messages": [ { "role": "user", "content": "…", "created_at": "…" },
{ "role": "assistant", "content": "…", "created_at": "…" } ] } }
· 404 if it does not belong to you and that user_id
Node.js
async function conversationHistory(userId, cursor) {
const url = new URL('https://jutera.com/v1/conversations');
url.searchParams.set('user_id', String(userId));
if (cursor) url.searchParams.set('cursor', cursor);
const res = await fetch(url, { headers: { Authorization: 'Bearer ' + process.env.AIREWARDS_SK } });
if (!res.ok) throw new Error((await res.json()).error.code);
return res.json(); // { conversations, next_cursor }
}
Python
import os, requests
def conversation_history(user_id, cursor=None):
params = {"user_id": str(user_id)}
if cursor:
params["cursor"] = cursor
r = requests.get("https://jutera.com/v1/conversations", params=params,
headers={"Authorization": "Bearer " + os.environ["AIREWARDS_SK"]}, timeout=10)
r.raise_for_status()
return r.json() # {"conversations": [...], "next_cursor": ...}
PHP
function conversation_history(string $userId, ?string $cursor = null): array {
$q = ['user_id' => $userId];
if ($cursor) { $q['cursor'] = $cursor; }
$ch = curl_init('https://jutera.com/v1/conversations?' . http_build_query($q));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('AIREWARDS_SK')],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status !== 200) { throw new RuntimeException('AIRewards ' . $status . ': ' . $body); }
return json_decode($body, true); // ['conversations' => [...], 'next_cursor' => ...]
}
9 · Errors, versioning
Errors use the envelope { "error": { "code": "…" } }. Codes you may see: unauthorized (bad/missing sk_…), invalid_token and token_expired (launch token), missing_placement and invalid_placement (metadata.placement), not_found, missing_user_id and invalid_cursor (conversation history), and — from the widget session flow — the coarse availability reasons above. APIs are versioned under /v1/; breaking changes ship as /v2/ with overlap. Pin the loader as loader@1.js.