Concepts
Webhooks
Signed events, how to verify them, and every type we send.
Add an endpoint
Python
def add_webhook_endpoint() -> None:
try:
webhook_endpoint = jusa.WebhookEndpoint.create(
url="https://example.com/jusa/webhooks",
enabled_events=["send.*", "reward.*"],
idempotency_key="webhook-endpoint-production",
)
# The signing secret (whsec_…) is in this answer only: store it, never log it.
print(webhook_endpoint.id)
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { JusaError } from '@jusa/node';
async function addWebhookEndpoint() {
try {
const webhookEndpoint = await jusa.webhookEndpoints.create({
url: 'https://example.com/jusa/webhooks',
enabled_events: ['send.*', 'reward.*'],
}, { idempotencyKey: 'webhook-endpoint-production' });
// The signing secret (whsec_…) is in this answer only: store it, never log it.
console.log(webhookEndpoint.id);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function addWebhookEndpoint(\Jusa\JusaClient $jusa): void
{
try {
$webhookEndpoint = $jusa->webhookEndpoints->create([
'url' => 'https://example.com/jusa/webhooks',
'enabled_events' => ['send.*', 'reward.*'],
], ['idempotency_key' => 'webhook-endpoint-production']);
// The signing secret (whsec_…) is in this answer only: store it, never log it.
echo $webhookEndpoint->id, "\n";
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func addWebhookEndpoint(ctx context.Context) error {
webhookEndpoint, err := jusaClient.WebhookEndpoints.Create(ctx, jusa.Params{
"url": "https://example.com/jusa/webhooks",
"enabled_events": []string{"send.*", "reward.*"},
}, jusa.WithIdempotencyKey("webhook-endpoint-production"))
if err != nil {
return fmt.Errorf("webhook_endpoints.create: %w", err)
}
// The signing secret (whsec_…) is in this answer only: store it, never log it.
fmt.Println(webhookEndpoint.ID)
return nil
}
Java
void addWebhookEndpoint() throws JusaException {
try {
var webhookEndpoint = jusa.webhookEndpoints().create(Params.of(
"url", "https://example.com/jusa/webhooks",
"enabled_events", List.of("send.*", "reward.*")
), RequestOptions.idempotencyKey("webhook-endpoint-production"));
// The signing secret (whsec_…) is in this answer only: store it, never log it.
System.out.println(webhookEndpoint.getId());
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task AddWebhookEndpointAsync()
{
try
{
var webhookEndpoint = await jusa.WebhookEndpoints.CreateAsync(new
{
url = "https://example.com/jusa/webhooks",
enabled_events = new[] { "send.*", "reward.*" },
}, new RequestOptions { IdempotencyKey = "webhook-endpoint-production" });
// The signing secret (whsec_…) is in this answer only: store it, never log it.
Console.WriteLine($"{webhookEndpoint.Id}");
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> addWebhookEndpoint() async {
try {
final webhookEndpoint = await jusa.webhookEndpoints.create({
'url': 'https://example.com/jusa/webhooks',
'enabled_events': ['send.*', 'reward.*'],
}, RequestOptions(idempotencyKey: 'webhook-endpoint-production'));
// The signing secret (whsec_…) is in this answer only: store it, never log it.
print('${webhookEndpoint.id}');
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def add_webhook_endpoint
webhook_endpoint = Jusa::WebhookEndpoint.create({
url: "https://example.com/jusa/webhooks",
enabled_events: ["send.*", "reward.*"],
}, idempotency_key: "webhook-endpoint-production")
# The signing secret (whsec_…) is in this answer only: store it, never log it.
puts "#{webhook_endpoint.id}"
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
curl https://jusa.localhost.co.zw/dev/v1/webhook-endpoints \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: webhook-endpoint-production" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com/jusa/webhooks",
"enabled_events": ["send.*", "reward.*"]
}'
# The signing secret (whsec_…) is in this answer only: store it, never log it.
The answer has the endpoint's signing secret (whsec_…). URLs must be https and
public. Subscribe to *, a family such as send.*, or exact types; up to 16 endpoints per mode.
Test-mode endpoints hear test-mode events only.
What arrives
POST /jusa/webhooks HTTP/1.1
Jusa-Signature: t=1759230000,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
Jusa-Event: send.delivered
Jusa-Delivery: whd_123
User-Agent: Jusa-Webhooks/1.0
Content-Type: application/json
{
"id": "evt_…",
"object": "event",
"type": "send.delivered",
"api_version": "2026-10-01",
"created": 1759230000,
"livemode": true,
"data": {
"object": {"id": "snd_…", "object": "send", "status": "delivered", "amount": "1.00", "currency": "USD"},
"previous_attributes": {"status": "submitted"}
},
"request": {"id": "req_…", "idempotency_key": "order-8812"}
}
data.object is the whole object as it is now (a send, a reward, a batch …), the same as
GET on it would answer; previous_attributes is what changed.
Verify every delivery
Jusa-Signature is t=<unix>,v1=<hex>, where the hex is the HMAC-SHA256 of
"{t}.{raw body}" under your endpoint's secret. Compute it over the raw bytes you received
(parsed and re-serialised JSON will not match), compare in constant time with any v1, and refuse a
t more than 5 minutes from now. While a secret is rolling there are two v1 values. Every
SDK does all of that in one call, and raises a signature error you answer with a 400:
Node
import express from 'express';
import Jusa, { SignatureVerificationError } from '@jusa/node';
const HTTP_OK = 200;
const HTTP_BAD_REQUEST = 400;
// This server's mode: a test event never reaches live handling, nor a live one test.
const SERVER_IS_LIVE = process.env.JUSA_SECRET_KEY.startsWith('jusa_sk_live_');
// express.raw keeps the body as it arrived: re-serialised JSON will not verify.
app.post('/jusa/webhooks', express.raw({ type: 'application/json' }), async (request, response) => {
let webhookEvent;
try {
webhookEvent = Jusa.webhooks.constructEvent(request.body, request.headers['jusa-signature'],
process.env.JUSA_WHSEC);
} catch (error) {
if (!(error instanceof SignatureVerificationError)) throw error;
return response.sendStatus(HTTP_BAD_REQUEST); // not from Jusa: do not trust it
}
// The other mode's event, or one already handled (MUST: dedupe on the event id).
if (webhookEvent.livemode !== SERVER_IS_LIVE || await alreadyProcessed(webhookEvent.id)) {
return response.sendStatus(HTTP_OK);
}
const reward = webhookEvent.data.object;
if (webhookEvent.type === 'reward.delivered') {
await markPaid(reward.completion_id, reward.id);
} else if (webhookEvent.type === 'reward.failed' || webhookEvent.type === 'reward.rejected') {
await flagForFollowUp(reward); // budget and credit already returned
}
await recordProcessed(webhookEvent.id);
return response.sendStatus(HTTP_OK);
});
PHP
<?php
// POST /jusa/webhooks
const HTTP_OK = 200;
const HTTP_BAD_REQUEST = 400;
// This server's mode: a test event never reaches live handling, nor a live one test.
$serverIsLive = str_starts_with((string) getenv('JUSA_SECRET_KEY'), 'jusa_sk_live_');
try {
$webhookEvent = \Jusa\Webhook::constructEvent(
file_get_contents('php://input'), // the raw body: re-encoded JSON will not match
$_SERVER['HTTP_JUSA_SIGNATURE'] ?? null,
getenv('JUSA_WHSEC'),
);
} catch (\Jusa\Exception\SignatureVerificationException) {
http_response_code(HTTP_BAD_REQUEST); // not from Jusa: do not trust it
exit;
}
// The other mode's event, or one already handled (MUST: dedupe on the event id).
if ($webhookEvent->livemode !== $serverIsLive || alreadyProcessed($webhookEvent->id)) {
http_response_code(HTTP_OK);
exit;
}
$reward = $webhookEvent->data->object;
if ($webhookEvent->type === 'reward.delivered') {
markPaid($reward->completion_id, $reward->id);
} elseif (in_array($webhookEvent->type, ['reward.failed', 'reward.rejected'], true)) {
flagForFollowUp($reward); // budget and credit already returned
}
recordProcessed($webhookEvent->id);
http_response_code(HTTP_OK);
Go
func jusaWebhook(responseWriter http.ResponseWriter, request *http.Request) {
payload, err := io.ReadAll(request.Body) // the raw bytes: re-encoded JSON will not verify
if err != nil {
http.Error(responseWriter, "unreadable body", http.StatusBadRequest)
return
}
webhookEvent, err := jusa.ConstructEvent(payload, request.Header.Get("Jusa-Signature"), os.Getenv("JUSA_WHSEC"))
if err != nil {
http.Error(responseWriter, "bad signature", http.StatusBadRequest) // not from Jusa: do not trust it
return
}
// This server's mode: a test event never reaches live handling, nor a live one test.
serverIsLive := jusa.KeyMode(os.Getenv("JUSA_SECRET_KEY")) == jusa.ModeLive
if webhookEvent.Livemode != serverIsLive || alreadyProcessed(webhookEvent.ID) { // MUST: dedupe on the event id
responseWriter.WriteHeader(http.StatusOK)
return
}
switch webhookEvent.Type {
case "reward.delivered", "reward.failed", "reward.rejected":
var reward jusa.Reward
if err := webhookEvent.DecodeObject(&reward); err != nil {
http.Error(responseWriter, err.Error(), http.StatusInternalServerError) // Jusa delivers it again
return
}
if webhookEvent.Type == "reward.delivered" {
markPaid(reward.CompletionID, reward.ID)
} else {
flagForFollowUp(reward) // budget and credit already returned
}
}
recordProcessed(webhookEvent.ID)
responseWriter.WriteHeader(http.StatusOK)
}
Java
import java.net.HttpURLConnection;
// This server's mode: a test event never reaches live handling, nor a live one test.
static final boolean SERVER_IS_LIVE = Jusa.isLiveKey(System.getenv("JUSA_SECRET_KEY"));
// POST /jusa/webhooks: pass the raw body exactly as it arrived.
int jusaWebhook(String rawBody, String signatureHeader) {
Event webhookEvent;
try {
webhookEvent = Webhook.constructEvent(rawBody, signatureHeader, System.getenv("JUSA_WHSEC"));
} catch (SignatureVerificationException signatureError) {
return HttpURLConnection.HTTP_BAD_REQUEST; // not from Jusa: do not trust it
}
boolean otherMode = Boolean.TRUE.equals(webhookEvent.getLivemode()) != SERVER_IS_LIVE;
if (otherMode || alreadyProcessed(webhookEvent.getId())) { // MUST: dedupe on the event id
return HttpURLConnection.HTTP_OK;
}
JusaObject reward = webhookEvent.getData().getObject();
switch (webhookEvent.getType()) {
case "reward.delivered":
markPaid(reward.getString("completion_id"), reward.getString("id"));
break;
case "reward.failed":
case "reward.rejected":
flagForFollowUp(reward); // budget and credit already returned
break;
default:
break;
}
recordProcessed(webhookEvent.getId());
return HttpURLConnection.HTTP_OK;
}
C#
// This server's mode: a test event never reaches live handling, nor a live one test.
var serverIsLive = Environment.GetEnvironmentVariable("JUSA_SECRET_KEY")!.StartsWith("jusa_sk_live_");
app.MapPost("/jusa/webhooks", async (HttpRequest request) =>
{
using var rawBody = new MemoryStream();
await request.Body.CopyToAsync(rawBody); // the raw bytes: re-serialised JSON will not verify
Event webhookEvent;
try
{
webhookEvent = Webhook.ConstructEvent(rawBody.ToArray(), request.Headers["Jusa-Signature"],
Environment.GetEnvironmentVariable("JUSA_WHSEC")!);
}
catch (SignatureVerificationException)
{
return Results.BadRequest(); // not from Jusa: do not trust it
}
if (webhookEvent.Livemode != serverIsLive || await AlreadyProcessed(webhookEvent.Id!)) // MUST: dedupe
return Results.Ok();
switch (webhookEvent.Type)
{
case "reward.delivered":
var reward = webhookEvent.DataObject<Reward>();
await MarkPaid(reward.CompletionId!, reward.Id!);
break;
case "reward.failed":
case "reward.rejected":
await FlagForFollowUp(webhookEvent.DataObject<Reward>()); // budget and credit already returned
break;
}
await RecordProcessed(webhookEvent.Id!);
return Results.Ok();
});
Dart
/// This server's mode: a test event never reaches live handling, nor a live one test.
final serverIsLive = Platform.environment['JUSA_SECRET_KEY']!.startsWith('jusa_sk_live_');
/// POST /jusa/webhooks (dart:io's HttpServer).
Future<void> jusaWebhook(HttpRequest request) async {
final rawBody = await request.fold<List<int>>([], (bytes, chunk) => bytes..addAll(chunk));
final Event webhookEvent;
try {
webhookEvent = Webhook.constructEvent(
rawBody, request.headers.value('jusa-signature'), Platform.environment['JUSA_WHSEC']!);
} on SignatureVerificationException {
request.response.statusCode = HttpStatus.badRequest; // not from Jusa: do not trust it
return request.response.close();
}
// The other mode's event, or one already handled (MUST: dedupe on the event id).
if (webhookEvent.livemode != serverIsLive || await alreadyProcessed(webhookEvent.id)) {
return request.response.close();
}
switch (webhookEvent.type) {
case 'reward.delivered':
final reward = webhookEvent.data.object.into(Reward.new);
await markPaid(reward.completionId, reward.id);
case 'reward.failed' || 'reward.rejected':
await flagForFollowUp(webhookEvent.data.object); // budget and credit already returned
}
await recordProcessed(webhookEvent.id);
await request.response.close();
}
Ruby
# This server's mode: a test event never reaches live handling, nor a live one test.
SERVER_IS_LIVE = ENV.fetch("JUSA_SECRET_KEY").start_with?("jusa_sk_live_")
post "/jusa/webhooks" do
begin
webhook_event = Jusa::Webhook.construct_event(
request.body.read, # the raw body: re-encoded JSON will not match
request.env["HTTP_JUSA_SIGNATURE"],
ENV.fetch("JUSA_WHSEC"),
)
rescue Jusa::SignatureVerificationError
halt Rack::Utils.status_code(:bad_request) # not from Jusa: do not trust it
end
# The other mode's event, or one already handled (MUST: dedupe on the event id).
halt Rack::Utils.status_code(:ok) if webhook_event.livemode != SERVER_IS_LIVE || already_processed?(webhook_event.id)
reward = webhook_event.data.object
case webhook_event.type
when "reward.delivered"
mark_paid(reward.completion_id, reward.id)
when "reward.failed", "reward.rejected"
flag_for_follow_up(reward) # budget and credit already returned
end
record_processed(webhook_event.id)
Rack::Utils.status_code(:ok)
end
Python
from http import HTTPStatus
#: This server's mode: a test event never reaches live handling, nor a live one test.
SERVER_IS_LIVE = os.environ["JUSA_SECRET_KEY"].startswith("jusa_sk_live_")
@app.post("/jusa/webhooks")
def jusa_webhook():
try:
webhook_event = jusa.Webhook.construct_event(
request.get_data(), request.headers.get("Jusa-Signature"), os.environ["JUSA_WHSEC"])
except jusa.SignatureVerificationError:
return "", HTTPStatus.BAD_REQUEST # not from Jusa: do not trust it
if webhook_event.livemode != SERVER_IS_LIVE or already_processed(webhook_event.id):
return "", HTTPStatus.OK # the other mode's event, or one already handled (MUST: dedupe)
reward = webhook_event.data.object
if webhook_event.type == "reward.delivered":
mark_paid(reward.completion_id, reward.id)
elif webhook_event.type in ("reward.failed", "reward.rejected"):
flag_for_follow_up(reward) # budget and credit already returned
record_processed(webhook_event.id)
return "", HTTPStatus.OK
By hand, to see what the SDKs do (with openssl, on a delivery saved as body.json):
# HEADER is the Jusa-Signature header; JUSA_WHSEC the endpoint's secret
timestamp=$(printf '%s' "$HEADER" | tr ',' '\n' | sed -n 's/^t=//p')
expected=$(printf '%s.' "$timestamp" | cat - body.json | openssl dgst -sha256 -hmac "$JUSA_WHSEC" -hex | sed 's/^.*= //')
printf '%s' "$HEADER" | tr ',' '\n' | grep -qx "v1=$expected" && echo verified
# then refuse it if the timestamp is more than 300 seconds (the tolerance) from $(date +%s)
Handling them well
- Dedupe on
event.id. This is a must. The id is stable across redeliveries and a delivery can arrive more than once. - Order is not guaranteed.
data.objectis the object as it is now; compare itsstatusrather than trusting arrival order. - Answer
2xxwithin 10 seconds, then do the work. Anything else, or a timeout, is a failure. - Retries back off exponentially for 3 days (about 17 tries); in test mode for 6 hours. After 3 days of failures
the endpoint is disabled,
webhook_endpoint.disabledfires, and its owners get an email and a text. - Missed some?
GET /events?created[gte]=…is the catch-up feed (30 days), andPOST /webhook-endpoints/{id}/replay {"from", "to", "types"}sends a range again.POST /webhook-deliveries/{id}/redeliversends one again;POST /webhook-endpoints/{id}/testsends a synthetic event. - Webhooks come from Jusa's servers. If you allowlist by IP, ask support for the current addresses; the signature is what proves a delivery is ours.
ZESA tokens
A send.delivered for ZESA carries the token masked, plus a token_url when the endpoint has
token_links: a link that reads the token once, within 15 minutes, with no key. Only a key or member
holding tokens:read turns token_links on (it is on by default when they make the endpoint),
and moving the endpoint's URL without tokens:read turns it off; replaying or redelivering send events to
an endpoint that gets tokens needs tokens:read too. An endpoint made with include_tokens: true
by a key holding account:manage and tokens:read gets the token itself. Stored events, the
delivery log and /events always show it masked.
Rolling the secret
POST /webhook-endpoints/{id}/roll-secret {"grace": "24h"}: the new secret signs at once, and the old one
signs alongside it (a second v1=) for the grace period, so you can deploy the new one without dropping
a delivery.
The legacy format
An endpoint moved from the old single webhook URL keeps format: "legacy_airtime": the flat body,
order.success|failed|unknown|retrying events and X-Airtime-Signature: sha256=…, with
Jusa-* headers alongside. PATCH {"format": "jusa"} moves it to the envelope above; it never
moves back. A legacy endpoint's secret rolls at once.
Every event type
86 types. send.meter_changed goes to every endpoint whatever it subscribed to.
send
send.created · send.submitted · send.delivered · send.token_delivered · send.token_delivery_failed · send.retrying · send.queued · send.unknown · send.requires_review · send.failed · send.credited_back · send.late_delivered · send.scheduled · send.cancelled · send.meter_changed (always delivered) · send.token_resent
batch
batch.created · batch.requires_approval · batch.processing · batch.completed · batch.partially_completed · batch.failed · batch.cancelled
schedule
schedule.occurrence.upcoming · schedule.occurrence.ran · schedule.occurrence.skipped_insufficient_credit · schedule.occurrence.retry_after_topup
credit
credit.topup.pending · credit.topup.succeeded · credit.topup.failed · credit.topup.expired · credit.balance.low · credit.shortfall.projected · credit.adjusted · credit.reserved · credit.released
program
program.activated · program.paused · program.budget.low · program.exhausted · program.reactivated · program.closed
reward
reward.created · reward.held · reward.released · reward.voided · reward.expired · reward.delivered · reward.failed · reward.duplicate · reward.rejected
reward_link
reward_link.created · reward_link.opened · reward_link.claimed · reward_link.expired · reward_link.revoked
review
review.opened · review.resolved
activity
activity.rule_matched
referral
referral.qualified
agent_approval
agent_approval.requested · agent_approval.approved · agent_approval.failed · agent_approval.rejected · agent_approval.expired
checkout
checkout.session.paid · checkout.session.expired · checkout.session.fulfilled · checkout.session.resent · checkout.session.credited
zesa
zesa.availability.down · zesa.availability.up
network
network.availability.degraded · network.availability.restored
recipient
recipient.created · recipient.updated · recipient.erasure_pending · recipient.erased
dispute
dispute.opened · dispute.resolved
dealer
dealer.application.decided
api_key
api_key.created · api_key.rolled · api_key.revoked · api_key.expiring
webhook_endpoint
webhook_endpoint.disabled