Start
Quickstart: reward a survey
Your first reward in ten minutes, in test mode.
The seed use case: a survey tool tells your server that someone finished, and they get airtime for it, once. Everything here runs in test mode first, so nothing real moves until you switch the key. Pick your language on any sample and every sample follows.
-
Make your developer organisation
Sign in at the dashboard (phone, identity or password) and choose Create developer organisation. You get a live organisation and a test-mode twin with US$1,000 and ZWG 25,000 of test Jusa Credit, topped back up every day.
-
Make a test key and install an SDK
In Developers → Keys, with the switch on Test, create a secret key. It is shown once: put it in your environment as
JUSA_SECRET_KEY. Test keys need no terms and no top-up. Every SDK installs from our own registries; with curl there is nothing to install.InstallNode
npm install @jusa/node --registry https://jusa.localhost.co.zw/sdk/npm/PHP
composer config repositories.jusa composer https://jusa.localhost.co.zw/sdk/composer composer require jusa/jusa-php:^1.0Go
go env -w GOPRIVATE=jusa.localhost.co.zw go get jusa.localhost.co.zw/sdk/go@v1.0.3Java
// build.gradle.kts (Kotlin works too); Maven is on the SDKs page repositories { mavenCentral() maven("https://jusa.localhost.co.zw/sdk/maven2/") } dependencies { implementation("zw.co.localhost.jusa:jusa-java:1.0.3") }C#
dotnet add package Jusa --source https://jusa.localhost.co.zw/sdk/nuget/v3/index.jsonDart
dart pub add jusa --hosted-url https://jusa.localhost.co.zw/sdk/pubRuby
gem install jusa --source https://jusa.localhost.co.zw/sdk/gems/Python
pip install --index-url https://jusa.localhost.co.zw/sdk/pypi/simple/ jusaSet up oncePython
import logging import os import jusa logger = logging.getLogger(__name__) jusa.api_key = os.environ["JUSA_SECRET_KEY"] # jusa_sk_test_… while you buildNode
import Jusa from '@jusa/node'; const jusa = new Jusa(process.env.JUSA_SECRET_KEY); // jusa_sk_test_… while you buildPHP
<?php require __DIR__ . '/vendor/autoload.php'; $jusa = new \Jusa\JusaClient(getenv('JUSA_SECRET_KEY')); // jusa_sk_test_… while you buildGo
package main import ( "context" "fmt" "log" "os" jusa "jusa.localhost.co.zw/sdk/go" ) func main() { apiKey, found := os.LookupEnv("JUSA_SECRET_KEY") // jusa_sk_test_… while you build if !found { log.Fatal("set JUSA_SECRET_KEY") } jusaClient := jusa.NewClient(apiKey) if err := run(context.Background(), jusaClient); err != nil { log.Fatal(err) } } // run is where the samples go: each call returns its error, wrapped with what it was doing. func run(ctx context.Context, jusaClient *jusa.Client) error { fmt.Println("live mode:", jusaClient.IsLiveMode()) return nil }Java
import java.util.logging.Logger; import zw.co.localhost.jusa.Jusa; import zw.co.localhost.jusa.Params; import zw.co.localhost.jusa.RequestOptions; import zw.co.localhost.jusa.exception.InsufficientCreditException; import zw.co.localhost.jusa.exception.JusaException; // The samples' methods go in a class like this one. Calls throw a checked JusaException. public class SurveyRewards { private static final Logger LOGGER = Logger.getLogger(SurveyRewards.class.getName()); private final Jusa jusa = new Jusa(System.getenv("JUSA_SECRET_KEY")); // jusa_sk_test_… while you build }C#
using Jusa; var app = WebApplication.CreateBuilder().Build(); var logger = app.Logger; // jusa_sk_test_… while you build. Make one client and share it. var jusa = new JusaClient(Environment.GetEnvironmentVariable("JUSA_SECRET_KEY"));Dart
import 'dart:io'; import 'package:jusa/jusa.dart'; // jusa_sk_test_… while you build. On your server only, never in a Flutter app. final jusa = Jusa(Platform.environment['JUSA_SECRET_KEY']);Ruby
require "jusa" require "logger" LOGGER = Logger.new($stderr) Jusa.api_key = ENV.fetch("JUSA_SECRET_KEY") # jusa_sk_test_… while you buildcurl
export JUSA_SECRET_KEY=jusa_sk_test_… # a test key: nothing real moves -
Make a program
A program holds the budget and the rules: how much each reward is, what it may be (airtime, data, ZESA), and the caps.
per_recipient={"lifetime": 1}pays each person once;funding="reserve"sets the whole budget aside now, so it cannot be spent twice. You can make it in the dashboard instead. Put its id in your environment asJUSA_PROGRAM, next to the key.OncePython
def create_survey_program() -> None: try: program = jusa.Program.create( name="Household survey Q4", currency="USD", default_amount="0.50", budget="500.00", funding="reserve", choices=["airtime"], per_recipient={"lifetime": 1}, idempotency_key="program-household-q4", ) # The completions secret is in this answer only: store it, never log it. print(program.id) except jusa.JusaError as jusa_error: logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id) raiseNode
import { JusaError } from '@jusa/node'; async function createSurveyProgram() { try { const program = await jusa.programs.create({ name: 'Household survey Q4', currency: 'USD', default_amount: '0.50', budget: '500.00', funding: 'reserve', choices: ['airtime'], per_recipient: { lifetime: 1 }, }, { idempotencyKey: 'program-household-q4' }); // The completions secret is in this answer only: store it, never log it. console.log(program.id); } catch (error) { if (error instanceof JusaError) { console.error(`Jusa refused: ${error.code} [${error.requestId}]`); } throw error; } }PHP
function createSurveyProgram(\Jusa\JusaClient $jusa): void { try { $program = $jusa->programs->create([ 'name' => 'Household survey Q4', 'currency' => 'USD', 'default_amount' => '0.50', 'budget' => '500.00', 'funding' => 'reserve', 'choices' => ['airtime'], 'per_recipient' => ['lifetime' => 1], ], ['idempotency_key' => 'program-household-q4']); // The completions secret is in this answer only: store it, never log it. echo $program->id, "\n"; } catch (\Jusa\Exception\JusaException $jusaError) { error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]"); throw $jusaError; } }Go
func createSurveyProgram(ctx context.Context) error { program, err := jusaClient.Programs.Create(ctx, jusa.Params{ "name": "Household survey Q4", "currency": "USD", "default_amount": "0.50", "budget": "500.00", "funding": "reserve", "choices": []string{"airtime"}, "per_recipient": jusa.Params{"lifetime": 1}, }, jusa.WithIdempotencyKey("program-household-q4")) if err != nil { return fmt.Errorf("programs.create: %w", err) } // The completions secret is in this answer only: store it, never log it. fmt.Println(program.ID) return nil }Java
void createSurveyProgram() throws JusaException { try { var program = jusa.programs().create(Params.of( "name", "Household survey Q4", "currency", "USD", "default_amount", "0.50", "budget", "500.00", "funding", "reserve", "choices", List.of("airtime"), "per_recipient", Map.of("lifetime", 1) ), RequestOptions.idempotencyKey("program-household-q4")); // The completions secret is in this answer only: store it, never log it. System.out.println(program.getId()); } catch (JusaException jusaError) { LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]"); throw jusaError; } }C#
async Task CreateSurveyProgramAsync() { try { var program = await jusa.Programs.CreateAsync(new { name = "Household survey Q4", currency = "USD", default_amount = "0.50", budget = "500.00", funding = "reserve", choices = new[] { "airtime" }, per_recipient = new { lifetime = 1 }, }, new RequestOptions { IdempotencyKey = "program-household-q4" }); // The completions secret is in this answer only: store it, never log it. Console.WriteLine($"{program.Id}"); } catch (JusaException jusaError) { logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId); throw; } }Dart
Future<void> createSurveyProgram() async { try { final program = await jusa.programs.create({ 'name': 'Household survey Q4', 'currency': 'USD', 'default_amount': '0.50', 'budget': '500.00', 'funding': 'reserve', 'choices': ['airtime'], 'per_recipient': {'lifetime': 1}, }, RequestOptions(idempotencyKey: 'program-household-q4')); // The completions secret is in this answer only: store it, never log it. print('${program.id}'); } on JusaException catch (jusaError) { stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]'); rethrow; } }Ruby
def create_survey_program program = Jusa::Program.create({ name: "Household survey Q4", currency: "USD", default_amount: "0.50", budget: "500.00", funding: "reserve", choices: ["airtime"], per_recipient: { lifetime: 1 }, }, idempotency_key: "program-household-q4") # The completions secret is in this answer only: store it, never log it. puts "#{program.id}" rescue Jusa::JusaError => jusa_error LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]") raise endcurl
curl https://jusa.localhost.co.zw/dev/v1/programs \ --fail-with-body \ -H "Authorization: Bearer $JUSA_SECRET_KEY" \ -H "Idempotency-Key: program-household-q4" \ -H "Content-Type: application/json" \ -d '{ "name": "Household survey Q4", "currency": "USD", "default_amount": "0.50", "budget": "500.00", "funding": "reserve", "choices": ["airtime"], "per_recipient": {"lifetime": 1} }' # The completions secret is in this answer only: store it, never log it. -
Reward each completion
Your survey tool calls your server; your server calls Jusa.
completion_idis required and unique per program, forever: the same submission posted twice is one reward. TheIdempotency-Keymakes a retry after a timeout safe too.POST /survey/completedPython
import logging import os from http import HTTPStatus from flask import Flask, request import jusa logger = logging.getLogger(__name__) jusa.api_key = os.environ["JUSA_SECRET_KEY"] SURVEY_PROGRAM_ID = os.environ["JUSA_PROGRAM"] # prg_… from the step above app = Flask(__name__) @app.post("/survey/completed") # Flask; called by your survey tool def survey_completed(): survey_submission = request.get_json() submission_id = survey_submission["submission_id"] try: reward = jusa.Reward.create( program=SURVEY_PROGRAM_ID, recipient={"external_id": survey_submission["respondent_id"], "phone": survey_submission["phone"]}, delivery="direct", # or "link" to let them choose metadata={"survey": survey_submission["form_id"]}, completion_id=submission_id, # required: one reward per submission, forever idempotency_key=f"survey-{submission_id}", ) except jusa.InsufficientCreditError: # Nothing was charged: top up, and the survey tool's retry pays it. return {"error": "top up Jusa Credit"}, HTTPStatus.SERVICE_UNAVAILABLE except jusa.JusaError as jusa_error: logger.error("Jusa refused %s: %s [%s]", submission_id, jusa_error.code, jusa_error.request_id) raise return {"reward": reward.id, "status": reward.status} # pending, delivered, failed or heldNode
import express from 'express'; import Jusa, { InsufficientCreditError, JusaError } from '@jusa/node'; const HTTP_SERVICE_UNAVAILABLE = 503; const SURVEY_PROGRAM_ID = process.env.JUSA_PROGRAM; // prg_… from the step above const jusa = new Jusa(process.env.JUSA_SECRET_KEY); const app = express(); app.post('/survey/completed', express.json(), async (request, response, next) => { // called by your survey tool const surveySubmission = request.body; const submissionId = surveySubmission.submission_id; try { const reward = await jusa.rewards.create({ program: SURVEY_PROGRAM_ID, recipient: { external_id: surveySubmission.respondent_id, phone: surveySubmission.phone }, delivery: 'direct', // or 'link' to let them choose completion_id: submissionId, // required: one reward per submission, forever metadata: { survey: surveySubmission.form_id }, }, { idempotencyKey: `survey-${submissionId}` }); response.json({ reward: reward.id, status: reward.status }); // pending, delivered, failed or held } catch (error) { if (error instanceof InsufficientCreditError) { // Nothing was charged: top up, and the survey tool's retry pays it. response.status(HTTP_SERVICE_UNAVAILABLE).json({ error: 'top up Jusa Credit' }); return; } if (error instanceof JusaError) { console.error(`Jusa refused ${submissionId}: ${error.code} [${error.requestId}]`); } next(error); } });PHP
<?php // POST /survey/completed, called by your survey tool require __DIR__ . '/vendor/autoload.php'; const HTTP_SERVICE_UNAVAILABLE = 503; $jusa = new \Jusa\JusaClient(getenv('JUSA_SECRET_KEY')); $surveyProgramId = getenv('JUSA_PROGRAM'); // prg_… from the step above $surveySubmission = json_decode(file_get_contents('php://input'), true, flags: JSON_THROW_ON_ERROR); $submissionId = $surveySubmission['submission_id']; try { $reward = $jusa->rewards->create([ 'program' => $surveyProgramId, 'recipient' => ['external_id' => $surveySubmission['respondent_id'], 'phone' => $surveySubmission['phone']], 'delivery' => 'direct', // or 'link' to let them choose 'metadata' => ['survey' => $surveySubmission['form_id']], 'completion_id' => $submissionId, // required: one reward per submission, forever ], ['idempotency_key' => "survey-{$submissionId}"]); } catch (\Jusa\Exception\InsufficientCreditException) { http_response_code(HTTP_SERVICE_UNAVAILABLE); // nothing was charged: top up, and the retry pays it exit; } catch (\Jusa\Exception\JusaException $jusaError) { error_log("Jusa refused {$submissionId}: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]"); throw $jusaError; } header('Content-Type: application/json'); echo json_encode(['reward' => $reward->id, 'status' => $reward->status]); // pending, delivered, failed or heldGo
func surveyCompleted(responseWriter http.ResponseWriter, request *http.Request) { // called by your survey tool var surveySubmission struct { RespondentID string `json:"respondent_id"` Phone string `json:"phone"` SubmissionID string `json:"submission_id"` FormID string `json:"form_id"` } if err := json.NewDecoder(request.Body).Decode(&surveySubmission); err != nil { http.Error(responseWriter, err.Error(), http.StatusBadRequest) return } rewardResult, err := jusaClient.Rewards.Create(request.Context(), jusa.Params{ "program": os.Getenv("JUSA_PROGRAM"), // prg_… from the step above "recipient": jusa.Params{"external_id": surveySubmission.RespondentID, "phone": surveySubmission.Phone}, "delivery": "direct", // or "link" to let them choose "metadata": jusa.Params{"survey": surveySubmission.FormID}, "completion_id": surveySubmission.SubmissionID, // required: one reward per submission, forever }, jusa.WithIdempotencyKey("survey-"+surveySubmission.SubmissionID)) var insufficientCredit *jusa.InsufficientCreditError var jusaError *jusa.Error switch { case errors.As(err, &insufficientCredit): // Nothing was charged: top up, and the survey tool's retry pays it. http.Error(responseWriter, "top up Jusa Credit", http.StatusServiceUnavailable) return case errors.As(err, &jusaError): log.Printf("jusa refused %s: %s [%s]", surveySubmission.SubmissionID, jusaError.Code, jusaError.RequestID) http.Error(responseWriter, "reward refused", http.StatusBadGateway) return case err != nil: http.Error(responseWriter, err.Error(), http.StatusBadGateway) return } reward := rewardResult.Reward responseWriter.Header().Set("Content-Type", "application/json") answer := map[string]string{"reward": reward.ID, "status": reward.Status} // pending, delivered, failed or held if err := json.NewEncoder(responseWriter).Encode(answer); err != nil { log.Printf("answer the survey tool: %v", err) } }Java
// Called by your survey tool with the submission's fields. Reward surveyCompleted(Map<String, String> surveySubmission) throws JusaException { String submissionId = surveySubmission.get("submission_id"); try { return jusa.rewards().create(Params.of( "program", System.getenv("JUSA_PROGRAM"), // prg_… from the step above "recipient", Map.of("external_id", surveySubmission.get("respondent_id"), "phone", surveySubmission.get("phone")), "completion_id", submissionId, // required: one reward per submission, forever "metadata", Map.of("survey", surveySubmission.get("form_id")) ), RequestOptions.idempotencyKey("survey-" + submissionId)); // pending, delivered, failed or held } catch (InsufficientCreditException insufficientCredit) { topUpAndTryLater(); // nothing was charged: the retry pays it throw insufficientCredit; } catch (JusaException jusaError) { LOGGER.severe("Jusa refused " + submissionId + ": " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]"); throw jusaError; } }C#
app.MapPost("/survey/completed", async (Dictionary<string, string> surveySubmission) => // your survey tool calls it { var submissionId = surveySubmission["submission_id"]; try { var result = await jusa.Rewards.CreateAsync(new { program = Environment.GetEnvironmentVariable("JUSA_PROGRAM"), // prg_… from the step above recipient = new { external_id = surveySubmission["respondent_id"], phone = surveySubmission["phone"] }, delivery = "direct", // or "link" to let them choose completion_id = submissionId, // required: one reward per submission, forever metadata = new { survey = surveySubmission["form_id"] }, }, new RequestOptions { IdempotencyKey = $"survey-{submissionId}" }); var reward = result.As<Reward>(); return Results.Ok(new { reward = reward.Id, status = reward.Status }); // pending, delivered, failed or held } catch (InsufficientCreditException) { // Nothing was charged: top up, and the survey tool's retry pays it. return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); } catch (JusaException jusaError) { logger.LogError(jusaError, "Jusa refused {SubmissionId}: {Code} [{RequestId}]", submissionId, jusaError.Code, jusaError.RequestId); throw; } });Dart
/// POST /survey/completed, called by your survey tool. Future<Map<String, Object?>> surveyCompleted(Map<String, Object?> surveySubmission) async { final submissionId = surveySubmission['submission_id']; try { final reward = await jusa.rewards.create({ 'program': Platform.environment['JUSA_PROGRAM'], // prg_… from the step above 'recipient': {'external_id': surveySubmission['respondent_id'], 'phone': surveySubmission['phone']}, 'delivery': 'direct', // or 'link' to let them choose 'metadata': {'survey': surveySubmission['form_id']}, 'completion_id': submissionId, // required: one reward per submission, forever }, RequestOptions(idempotencyKey: 'survey-$submissionId')) as Reward; return {'reward': reward.id, 'status': reward.status}; // pending, delivered, failed or held } on InsufficientCreditException { await topUpAndTryLater(); // nothing was charged: the survey tool's retry pays it rethrow; } on JusaException catch (jusaError) { stderr.writeln('Jusa refused $submissionId: ${jusaError.code} [${jusaError.requestId}]'); rethrow; } }Ruby
require "json" require "jusa" require "logger" require "sinatra" LOGGER = Logger.new($stderr) Jusa.api_key = ENV.fetch("JUSA_SECRET_KEY") SURVEY_PROGRAM_ID = ENV.fetch("JUSA_PROGRAM") # prg_… from the step above post "/survey/completed" do # Sinatra; called by your survey tool survey_submission = JSON.parse(request.body.read) submission_id = survey_submission.fetch("submission_id") reward = Jusa::Reward.create( program: SURVEY_PROGRAM_ID, recipient: { external_id: survey_submission["respondent_id"], phone: survey_submission["phone"] }, delivery: "direct", # or "link" to let them choose metadata: { survey: survey_submission["form_id"] }, completion_id: submission_id, # required: one reward per submission, forever idempotency_key: "survey-#{submission_id}", ) content_type :json { reward: reward.id, status: reward.status }.to_json # pending, delivered, failed or held rescue Jusa::InsufficientCreditError # Nothing was charged: top up, and the survey tool's retry pays it. halt Rack::Utils.status_code(:service_unavailable), "top up Jusa Credit" rescue Jusa::JusaError => jusa_error LOGGER.error("Jusa refused #{submission_id}: #{jusa_error.code} [#{jusa_error.request_id}]") raise endcurl
# What your server sends for each submission curl https://jusa.localhost.co.zw/dev/v1/rewards \ --fail-with-body \ -H "Authorization: Bearer $JUSA_SECRET_KEY" \ -H "Idempotency-Key: survey-8812" \ -H "Content-Type: application/json" \ -d '{ "program": "prg_7Hq2…", "recipient": {"external_id": "resp-8812", "phone": "0771230000"}, "delivery": "direct", "completion_id": "8812", "metadata": {"survey": "form-hh-q4"} }'A refused reward (not enough budget, a cap, a paused program) writes nothing, so the same
completion_idcan be sent again once the cause is fixed. A reward a fraud rule stops isheldand waits in Reviews. -
Hear how it went
Add a webhook endpoint (dashboard, or
POST /webhook-endpoints) forreward.*. Verify every delivery on its raw body and dedupe on the event id: that is a must, because a delivery can arrive twice. Webhooks says what the signature is.POST /jusa/webhooksNode
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) endPython
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.OKNo public URL while you build?
jusa listen --forward-to localhost:5000/jusa/webhookspolls your events and forwards them to your machine (it readsJUSA_SECRET_KEY). It signs them with its ownwhsec_cli_…secret, not your endpoint's, so run your handler withJUSA_WHSEC="$(jusa listen --print-secret)"while you forward. In test mode a reward often settles within the call; the webhook still follows. See the CLI. -
Try every outcome
In test mode the last four digits of a number choose what happens:
0772550002is rejected by the network,0772550005goesunknownand then lands,0772550010is held for review. The full list is on Test mode. -
Go live
Switch the dashboard to Live and create a live key. The first live key asks an owner or admin to accept the API Terms, Acceptable Use policy and DPA, once. There is no review and no starting cap: top up Jusa Credit by card (the card fee is the payer's) or bank transfer, any amount, and your first live reward goes out at once. Swap the key; nothing else changes.
No server? Two other ways in
Signed completions
If your survey tool can sign a webhook, it can post straight to the program:
POST /programs/{id}/completions, with no key, signed with the program's secret:
Jusa-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "{t}.{raw body}")>, within 5 minutes.
The body takes completion_id (or ref), and phone (or target),
meter, token_phone. Google Forms can do this from Apps Script; see the
Google Forms guide.
Reward links
When the phone number never reaches you (paper, enumerator devices offline, a thank-you page), mint links before
the survey: POST /reward-links {"program": "prg_…", "count": 200, "bind": "otp"}. Each has a
url and a qr_png_url; the respondent claims it on their own phone, and a code texted to that
phone stops a forwarded link being claimed by someone else.
For research, M&E and NGO teams
Everything a funder asks about is on by default:
- One reward per completion, for good (
completion_id), and one per phone when you want it (one_per_phone). - Caps per person per day, week and lifetime, a network match (
require_network) and a throttle per hour. - Fraud review: the same number behind many respondent ids, SIM-farm patterns, a number rewarded by many organisations. Held rewards wait for you in Reviews.
- The budget is money: with
funding="reserve"it is set aside at once; when it runs out the program isexhausted, and it comes back to life when budget returns. - A report a funder accepts:
GET /reports/spend?group_by=program, or an export of every reward as CSV. - Failures cost nothing: a reward that is not delivered returns its budget. A send that might have landed is never paid twice; see settlement.