Build
Recipes
Every use case we know of, with the calls it takes.
Every use case we know of, with the calls it takes. Tags say when something depends on a later phase or on a
legal sign-off; everything untagged works today. Every sample is in all nine languages: pick yours once and the
page follows. Ids such as prg_… are yours to fill in; each call is in the
reference. The samples use the client you make once:
Python
import logging
import os
import jusa
logger = logging.getLogger(__name__)
jusa.api_key = os.environ["JUSA_SECRET_KEY"] # jusa_sk_test_… while you build
Node
import Jusa from '@jusa/node';
const jusa = new Jusa(process.env.JUSA_SECRET_KEY); // jusa_sk_test_… while you build
PHP
<?php
require __DIR__ . '/vendor/autoload.php';
$jusa = new \Jusa\JusaClient(getenv('JUSA_SECRET_KEY')); // jusa_sk_test_… while you build
Go
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 build
curl
export JUSA_SECRET_KEY=jusa_sk_test_… # a test key: nothing real moves
- Sell airtime, data and ZESA at a till or in your app
- Reward a respondent for finishing a survey
- Claim cards and QR codes for offline surveys
- A micro-task earnings pot
- Reimburse SMS or USSD poll costs
- Reward in-app actions: sign-up, KYC, first transaction
- Streak rewards
- A two-sided referral chain
- Loyalty points to airtime, data or ZESA
- Reward links where the person chooses
- Radio or brand giveaways with an audit trail
- Conditional adherence incentives
- Community health worker allowances
- In-kind ZESA assistance
- Clinic or antenatal check-in
- Learn to earn data
- Exam-season data stipends
- A bursary split across data and ZESA
- Gig and rider allowances
- Employer ZESA as a benefit
- Pay per verified sale
- Outage apology credit
- Diaspora: send ZESA or airtime home
- Landlord and tenant split-meter settlement
- Checkout cashback as airtime
- Solar or IoT ZESA auto-buy
- Availability-aware buying
- Band-aware ZESA quotes
- AI agent tool calls over MCP
- WhatsApp chatbot commerce
- Escrowed conditional rewards
- Geofenced event check-in
- Farmer extension incentives
- Programmatic family allowance
- Bill-shock rescue
- Emergency power for medical devices
- Crowdsourced price or outage reports
- Data perk on ticket scan
- Fundraising thank-you airtime
- Payday ZESA nudge
Sell airtime, data and ZESA at a till or in your app
For POS software, shops and agent networks, mobile money and fintech apps.
Your customer pays you face value; Jusa debits your prepaid Jusa Credit, below face on the Dealer tier, and the airtime, bundle or token goes out in seconds. One key per till, the till's own sale number as the key so a dropped connection never sells twice, and a statement that ties to the cash drawer.
- Load the catalogue once a day; check the number or confirm the meter before the customer pays.
- POST /sends with client_reference and Idempotency-Key = the till's sale number.
- Show the status at the counter: delivered prints the receipt (and the ZESA token); failed_credited means refund the customer, the credit is already back with you.
- Close the day with GET /sends?api_key=… and the month with GET /statements.
Python
def sell_airtime(phone: str, sale_id: str, till_id: str) -> None:
try:
# The till's sale number keys it: sent twice, it is one sale.
send = jusa.Send.create(
product="airtime-usd",
target=phone,
amount="2.00",
client_reference=f"sale-{sale_id}",
metadata={"till": till_id},
idempotency_key=f"sale-{sale_id}",
)
print(send.id, send.status, send.cost)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def settle_the_sale(send_id: str) -> None:
try:
# delivered: print the receipt. failed_credited: refund the customer; the credit is back.
sale = jusa.Send.retrieve(send_id)
print(sale.status, sale.failure_code)
jusa.Send.receipt(send_id)
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function sellAirtime(phone, saleId, tillId) {
try {
// The till's sale number keys it: sent twice, it is one sale.
const send = await jusa.sends.create({
product: 'airtime-usd',
target: phone,
amount: '2.00',
client_reference: `sale-${saleId}`,
metadata: { till: tillId },
}, { idempotencyKey: `sale-${saleId}` });
console.log(send.id, send.status, send.cost);
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function settleTheSale(sendId) {
try {
// delivered: print the receipt. failed_credited: refund the customer; the credit is back.
const sale = await jusa.sends.retrieve(sendId);
console.log(sale.status, sale.failure_code);
await jusa.sends.receipt(sendId);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function sellAirtime(\Jusa\JusaClient $jusa, string $phone, string $saleId, string $tillId): void
{
try {
// The till's sale number keys it: sent twice, it is one sale.
$send = $jusa->sends->create([
'product' => 'airtime-usd',
'target' => $phone,
'amount' => '2.00',
'client_reference' => "sale-{$saleId}",
'metadata' => ['till' => $tillId],
], ['idempotency_key' => "sale-{$saleId}"]);
echo $send->id, ' ', $send->status, ' ', $send->cost, "\n";
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function settleTheSale(\Jusa\JusaClient $jusa, string $sendId): void
{
try {
// delivered: print the receipt. failed_credited: refund the customer; the credit is back.
$sale = $jusa->sends->retrieve($sendId);
echo $sale->status, ' ', $sale->failure_code, "\n";
$jusa->sends->receipt($sendId);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func sellAirtime(ctx context.Context, phone, saleID, tillID string) error {
// The till's sale number keys it: sent twice, it is one sale.
sendResult, err := jusaClient.Sends.Create(ctx, jusa.Params{
"product": "airtime-usd",
"target": phone,
"amount": "2.00",
"client_reference": "sale-" + saleID,
"metadata": jusa.Params{"till": tillID},
}, jusa.WithIdempotencyKey("sale-"+saleID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("sends.create: %w", err)
}
send := sendResult.Send
fmt.Println(send.ID, send.Status, send.Cost)
return nil
}
func settleTheSale(ctx context.Context, sendID string) error {
// delivered: print the receipt. failed_credited: refund the customer; the credit is back.
sale, err := jusaClient.Sends.Retrieve(ctx, sendID, nil)
if err != nil {
return fmt.Errorf("sends.retrieve: %w", err)
}
fmt.Println(sale.Status, sale.FailureCode)
_, err = jusaClient.Sends.Receipt(ctx, sendID, nil)
if err != nil {
return fmt.Errorf("sends.receipt: %w", err)
}
return nil
}
Java
void sellAirtime(String phone, String saleId, String tillId) throws JusaException {
try {
// The till's sale number keys it: sent twice, it is one sale.
var send = jusa.sends().create(Params.of(
"product", "airtime-usd",
"target", phone,
"amount", "2.00",
"client_reference", "sale-" + saleId,
"metadata", Map.of("till", tillId)
), RequestOptions.idempotencyKey("sale-" + saleId));
System.out.println(send.getId() + " " + send.getStatus() + " " + send.getCost());
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void settleTheSale(String sendId) throws JusaException {
try {
// delivered: print the receipt. failed_credited: refund the customer; the credit is back.
var sale = jusa.sends().retrieve(sendId);
System.out.println(sale.getStatus() + " " + sale.getFailureCode());
jusa.sends().receipt(sendId);
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SellAirtimeAsync(string phone, string saleId, string tillId)
{
try
{
// The till's sale number keys it: sent twice, it is one sale.
var sendResult = await jusa.Sends.CreateAsync(new
{
product = "airtime-usd",
target = phone,
amount = "2.00",
client_reference = $"sale-{saleId}",
metadata = new { till = tillId },
}, new RequestOptions { IdempotencyKey = $"sale-{saleId}" });
var send = sendResult.As<Send>();
Console.WriteLine($"{send.Id} {send.Status} {send.Cost}");
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task SettleTheSaleAsync(string sendId)
{
try
{
// delivered: print the receipt. failed_credited: refund the customer; the credit is back.
var sale = await jusa.Sends.RetrieveAsync(sendId);
Console.WriteLine($"{sale.Status} {sale.FailureCode}");
await jusa.Sends.ReceiptAsync(sendId);
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> sellAirtime(String phone, String saleId, String tillId) async {
try {
// The till's sale number keys it: sent twice, it is one sale.
final send = await jusa.sends.create({
'product': 'airtime-usd',
'target': phone,
'amount': '2.00',
'client_reference': 'sale-$saleId',
'metadata': {'till': tillId},
}, RequestOptions(idempotencyKey: 'sale-$saleId')) as Send;
print('${send.id} ${send.status} ${send.cost}');
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> settleTheSale(String sendId) async {
try {
// delivered: print the receipt. failed_credited: refund the customer; the credit is back.
final sale = await jusa.sends.retrieve(sendId);
print('${sale.status} ${sale.failureCode}');
await jusa.sends.receipt(sendId);
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def sell_airtime(phone, sale_id, till_id)
# The till's sale number keys it: sent twice, it is one sale.
send = Jusa::Send.create({
product: "airtime-usd",
target: phone,
amount: "2.00",
client_reference: "sale-#{sale_id}",
metadata: { till: till_id },
}, idempotency_key: "sale-#{sale_id}")
puts "#{send.id} #{send.status} #{send.cost}"
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def settle_the_sale(send_id)
# delivered: print the receipt. failed_credited: refund the customer; the credit is back.
sale = Jusa::Send.retrieve(send_id)
puts "#{sale.status} #{sale.failure_code}"
Jusa::Send.receipt(send_id)
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# The till's sale number keys it: sent twice, it is one sale.
curl https://jusa.localhost.co.zw/dev/v1/sends \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: sale-T4-000187" \
-H "Content-Type: application/json" \
-d '{
"product": "airtime-usd",
"target": "0771230000",
"amount": "2.00",
"client_reference": "sale-T4-000187",
"metadata": {"till": "4"}
}'
# delivered: print the receipt. failed_credited: refund the customer; the credit is back.
curl https://jusa.localhost.co.zw/dev/v1/sends/snd_… \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY"
curl https://jusa.localhost.co.zw/dev/v1/sends/snd_…/receipt \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY"
Calls: products.list · lookups.phone · quotes.create · sends.create · sends.retrieve · sends.receipt · statements.retrieve
Reward a respondent for finishing a survey
For KoboToolbox or ODK back-ends, SurveyCTO, research agencies. seed
The seed use case. One program holds the budget and the rules; each completed survey is one reward, keyed on the submission so it is paid once, forever.
- Create a program with a budget, a default amount and per_recipient caps (or in the dashboard).
- When your survey tool reports a completion, POST /rewards with the respondent and completion_id = the submission id.
- Listen for reward.delivered and reward.failed; a failure has already returned the budget.
Python
def reward_submission(respondent_id: str, phone: str, submission_id: str) -> None:
try:
# For each completed submission (the program is made once, in the dashboard or with programs.create):
reward = jusa.Reward.create(
program="prg_7Hq2…",
recipient={"external_id": respondent_id, "phone": phone},
delivery="direct",
completion_id=submission_id,
metadata={"survey": "form-hh-q4"},
idempotency_key=f"survey-{submission_id}",
)
print(reward.id, reward.status)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function rewardSubmission(respondentId, phone, submissionId) {
try {
// For each completed submission (the program is made once, in the dashboard or with programs.create):
const reward = await jusa.rewards.create({
program: 'prg_7Hq2…',
recipient: { external_id: respondentId, phone },
delivery: 'direct',
completion_id: submissionId,
metadata: { survey: 'form-hh-q4' },
}, { idempotencyKey: `survey-${submissionId}` });
console.log(reward.id, reward.status);
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function rewardSubmission(\Jusa\JusaClient $jusa, string $respondentId, string $phone, string $submissionId): void
{
try {
// For each completed submission (the program is made once, in the dashboard or with programs.create):
$reward = $jusa->rewards->create([
'program' => 'prg_7Hq2…',
'recipient' => ['external_id' => $respondentId, 'phone' => $phone],
'delivery' => 'direct',
'completion_id' => $submissionId,
'metadata' => ['survey' => 'form-hh-q4'],
], ['idempotency_key' => "survey-{$submissionId}"]);
echo $reward->id, ' ', $reward->status, "\n";
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func rewardSubmission(ctx context.Context, respondentID, phone, submissionID string) error {
// For each completed submission (the program is made once, in the dashboard or with programs.create):
rewardResult, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_7Hq2…",
"recipient": jusa.Params{"external_id": respondentID, "phone": phone},
"delivery": "direct",
"completion_id": submissionID,
"metadata": jusa.Params{"survey": "form-hh-q4"},
}, jusa.WithIdempotencyKey("survey-"+submissionID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
reward := rewardResult.Reward
fmt.Println(reward.ID, reward.Status)
return nil
}
Java
void rewardSubmission(String respondentId, String phone, String submissionId) throws JusaException {
try {
// For each completed submission (the program is made once, in the dashboard or with programs.create):
var reward = jusa.rewards().create(Params.of(
"program", "prg_7Hq2…",
"recipient", Map.of("external_id", respondentId, "phone", phone),
"delivery", "direct",
"completion_id", submissionId,
"metadata", Map.of("survey", "form-hh-q4")
), RequestOptions.idempotencyKey("survey-" + submissionId));
System.out.println(reward.getId() + " " + reward.getStatus());
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task RewardSubmissionAsync(string respondentId, string phone, string submissionId)
{
try
{
// For each completed submission (the program is made once, in the dashboard or with programs.create):
var rewardResult = await jusa.Rewards.CreateAsync(new
{
program = "prg_7Hq2…",
recipient = new { external_id = respondentId, phone = phone },
delivery = "direct",
completion_id = submissionId,
metadata = new { survey = "form-hh-q4" },
}, new RequestOptions { IdempotencyKey = $"survey-{submissionId}" });
var reward = rewardResult.As<Reward>();
Console.WriteLine($"{reward.Id} {reward.Status}");
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> rewardSubmission(String respondentId, String phone, String submissionId) async {
try {
// For each completed submission (the program is made once, in the dashboard or with programs.create):
final reward = await jusa.rewards.create({
'program': 'prg_7Hq2…',
'recipient': {'external_id': respondentId, 'phone': phone},
'delivery': 'direct',
'completion_id': submissionId,
'metadata': {'survey': 'form-hh-q4'},
}, RequestOptions(idempotencyKey: 'survey-$submissionId')) as Reward;
print('${reward.id} ${reward.status}');
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def reward_submission(respondent_id, phone, submission_id)
# For each completed submission (the program is made once, in the dashboard or with programs.create):
reward = Jusa::Reward.create({
program: "prg_7Hq2…",
recipient: { external_id: respondent_id, phone: phone },
delivery: "direct",
completion_id: submission_id,
metadata: { survey: "form-hh-q4" },
}, idempotency_key: "survey-#{submission_id}")
puts "#{reward.id} #{reward.status}"
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# For each completed submission (the program is made once, in the dashboard or with programs.create):
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"}
}'
Calls: programs.create · rewards.create · programs.create_completion
Claim cards and QR codes for offline surveys
For NGOs with enumerators.
Print a link or QR per respondent. They claim it on their own phone later; an OTP binding stops a forwarded link being claimed by someone else.
- Mint a batch of links with a label per enumerator and an expiry.
- Hand out the url or the qr_png_url; the hosted page at /r/{token} does the rest.
- Watch reward_link.claimed and pull a spend report grouped by program.
Python
def mint_claim_cards(enumerator_label: str) -> None:
try:
# 200 links; each has a url and a qr_png_url to print.
jusa.RewardLink.create(
program="prg_…",
count=200,
label=enumerator_label,
bind="otp",
expires_at="2026-12-31T23:59:59Z",
idempotency_key=f"claim-cards-{enumerator_label}",
)
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 mintClaimCards(enumeratorLabel) {
try {
// 200 links; each has a url and a qr_png_url to print.
await jusa.rewardLinks.create({
program: 'prg_…',
count: 200,
label: enumeratorLabel,
bind: 'otp',
expires_at: '2026-12-31T23:59:59Z',
}, { idempotencyKey: `claim-cards-${enumeratorLabel}` });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function mintClaimCards(\Jusa\JusaClient $jusa, string $enumeratorLabel): void
{
try {
// 200 links; each has a url and a qr_png_url to print.
$jusa->rewardLinks->create([
'program' => 'prg_…',
'count' => 200,
'label' => $enumeratorLabel,
'bind' => 'otp',
'expires_at' => '2026-12-31T23:59:59Z',
], ['idempotency_key' => "claim-cards-{$enumeratorLabel}"]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func mintClaimCards(ctx context.Context, enumeratorLabel string) error {
// 200 links; each has a url and a qr_png_url to print.
_, err := jusaClient.RewardLinks.Create(ctx, jusa.Params{
"program": "prg_…",
"count": 200,
"label": enumeratorLabel,
"bind": "otp",
"expires_at": "2026-12-31T23:59:59Z",
}, jusa.WithIdempotencyKey("claim-cards-"+enumeratorLabel))
if err != nil {
return fmt.Errorf("reward_links.create: %w", err)
}
return nil
}
Java
void mintClaimCards(String enumeratorLabel) throws JusaException {
try {
// 200 links; each has a url and a qr_png_url to print.
jusa.rewardLinks().create(Params.of(
"program", "prg_…",
"count", 200,
"label", enumeratorLabel,
"bind", "otp",
"expires_at", "2026-12-31T23:59:59Z"
), RequestOptions.idempotencyKey("claim-cards-" + enumeratorLabel));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task MintClaimCardsAsync(string enumeratorLabel)
{
try
{
// 200 links; each has a url and a qr_png_url to print.
await jusa.RewardLinks.CreateAsync(new
{
program = "prg_…",
count = 200,
label = enumeratorLabel,
bind = "otp",
expires_at = "2026-12-31T23:59:59Z",
}, new RequestOptions { IdempotencyKey = $"claim-cards-{enumeratorLabel}" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> mintClaimCards(String enumeratorLabel) async {
try {
// 200 links; each has a url and a qr_png_url to print.
await jusa.rewardLinks.create({
'program': 'prg_…',
'count': 200,
'label': enumeratorLabel,
'bind': 'otp',
'expires_at': '2026-12-31T23:59:59Z',
}, RequestOptions(idempotencyKey: 'claim-cards-$enumeratorLabel'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def mint_claim_cards(enumerator_label)
# 200 links; each has a url and a qr_png_url to print.
Jusa::RewardLink.create({
program: "prg_…",
count: 200,
label: enumerator_label,
bind: "otp",
expires_at: "2026-12-31T23:59:59Z",
}, idempotency_key: "claim-cards-#{enumerator_label}")
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# 200 links; each has a url and a qr_png_url to print.
curl https://jusa.localhost.co.zw/dev/v1/reward-links \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: claim-cards-enumerator-7" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_…",
"count": 200,
"label": "enumerator-7",
"bind": "otp",
"expires_at": "2026-12-31T23:59:59Z"
}'
Calls: reward_links.create · reward_links.list · reports.spend · exports.create
A micro-task earnings pot
For Premise-style task apps. P3
Each task earns into a pot; the pot pays out as airtime once it reaches a threshold.
- Set a threshold rule on the program: earn per activity, pay_at the threshold.
- POST an activity for each finished task; activity_id dedupes it for good.
- Show the person their pot with /recipients/{id}/balance.
Python
def set_up_earnings_rule() -> None:
try:
# Once: each task earns US$0.25, paid out as airtime at US$1.00.
jusa.Program.set_rules(
"prg_…",
rules=[
{
"kind": "threshold",
"activity": "task.done",
"earn": "0.25",
"pay_at": "1.00",
},
],
)
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def record_finished_task(user_id: str, task_id: str) -> None:
try:
jusa.Activity.create(
recipient=f"ext:{user_id}",
name="task.done",
activity_id=task_id,
idempotency_key=f"task-{task_id}",
)
pot = jusa.Recipient.balance(f"ext:{user_id}")
print(pot.pots)
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 setUpEarningsRule() {
try {
// Once: each task earns US$0.25, paid out as airtime at US$1.00.
await jusa.programs.setRules('prg_…', {
rules: [
{ kind: 'threshold', activity: 'task.done', earn: '0.25', pay_at: '1.00' },
],
});
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function recordFinishedTask(userId, taskId) {
try {
await jusa.activities.create({
recipient: `ext:${userId}`,
name: 'task.done',
activity_id: taskId,
}, { idempotencyKey: `task-${taskId}` });
const pot = await jusa.recipients.balance(`ext:${userId}`);
console.log(pot.pots);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function setUpEarningsRule(\Jusa\JusaClient $jusa): void
{
try {
// Once: each task earns US$0.25, paid out as airtime at US$1.00.
$jusa->programs->setRules('prg_…', [
'rules' => [
[
'kind' => 'threshold',
'activity' => 'task.done',
'earn' => '0.25',
'pay_at' => '1.00',
],
],
]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function recordFinishedTask(\Jusa\JusaClient $jusa, string $userId, string $taskId): void
{
try {
$jusa->activities->create([
'recipient' => "ext:{$userId}",
'name' => 'task.done',
'activity_id' => $taskId,
], ['idempotency_key' => "task-{$taskId}"]);
$pot = $jusa->recipients->balance("ext:{$userId}");
echo $pot->pots, "\n";
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func setUpEarningsRule(ctx context.Context) error {
// Once: each task earns US$0.25, paid out as airtime at US$1.00.
_, err := jusaClient.Programs.SetRules(ctx, "prg_…", jusa.Params{
"rules": []jusa.Params{
jusa.Params{
"kind": "threshold",
"activity": "task.done",
"earn": "0.25",
"pay_at": "1.00",
},
},
})
if err != nil {
return fmt.Errorf("programs.set_rules: %w", err)
}
return nil
}
func recordFinishedTask(ctx context.Context, userID, taskID string) error {
_, err := jusaClient.Activities.Create(ctx, jusa.Params{
"recipient": "ext:" + userID,
"name": "task.done",
"activity_id": taskID,
}, jusa.WithIdempotencyKey("task-"+taskID))
if err != nil {
return fmt.Errorf("activities.create: %w", err)
}
pot, err := jusaClient.Recipients.Balance(ctx, "ext:"+userID, nil)
if err != nil {
return fmt.Errorf("recipients.balance: %w", err)
}
fmt.Println(pot.Pots)
return nil
}
Java
void setUpEarningsRule() throws JusaException {
try {
// Once: each task earns US$0.25, paid out as airtime at US$1.00.
jusa.programs().setRules("prg_…", Params.of(
"rules", List.of(
Map.of(
"kind", "threshold",
"activity", "task.done",
"earn", "0.25",
"pay_at", "1.00"
)
)
));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void recordFinishedTask(String userId, String taskId) throws JusaException {
try {
jusa.activities().create(Params.of(
"recipient", "ext:" + userId,
"name", "task.done",
"activity_id", taskId
), RequestOptions.idempotencyKey("task-" + taskId));
var pot = jusa.recipients().balance("ext:" + userId);
System.out.println(pot.getPots());
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SetUpEarningsRuleAsync()
{
try
{
// Once: each task earns US$0.25, paid out as airtime at US$1.00.
await jusa.Programs.SetRulesAsync("prg_…", new
{
rules = new object[]
{
new
{
kind = "threshold",
activity = "task.done",
earn = "0.25",
pay_at = "1.00",
},
},
});
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task RecordFinishedTaskAsync(string userId, string taskId)
{
try
{
await jusa.Activities.CreateAsync(new
{
recipient = $"ext:{userId}",
name = "task.done",
activity_id = taskId,
}, new RequestOptions { IdempotencyKey = $"task-{taskId}" });
var pot = await jusa.Recipients.BalanceAsync($"ext:{userId}");
Console.WriteLine($"{pot.Pots}");
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> setUpEarningsRule() async {
try {
// Once: each task earns US$0.25, paid out as airtime at US$1.00.
await jusa.programs.setRules('prg_…', {
'rules': [
{
'kind': 'threshold',
'activity': 'task.done',
'earn': '0.25',
'pay_at': '1.00',
},
],
});
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> recordFinishedTask(String userId, String taskId) async {
try {
await jusa.activities.create({
'recipient': 'ext:$userId',
'name': 'task.done',
'activity_id': taskId,
}, RequestOptions(idempotencyKey: 'task-$taskId'));
final pot = await jusa.recipients.balance('ext:$userId');
print('${pot.pots}');
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def set_up_earnings_rule
# Once: each task earns US$0.25, paid out as airtime at US$1.00.
Jusa::Program.set_rules(
"prg_…",
rules: [{ kind: "threshold", activity: "task.done", earn: "0.25", pay_at: "1.00" }],
)
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def record_finished_task(user_id, task_id)
Jusa::Activity.create({
recipient: "ext:#{user_id}",
name: "task.done",
activity_id: task_id,
}, idempotency_key: "task-#{task_id}")
pot = Jusa::Recipient.balance("ext:#{user_id}")
puts "#{pot.pots}"
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# Once: each task earns US$0.25, paid out as airtime at US$1.00.
curl -X PUT https://jusa.localhost.co.zw/dev/v1/programs/prg_…/rules \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"rules": [
{"kind": "threshold", "activity": "task.done", "earn": "0.25", "pay_at": "1.00"}
]
}'
curl https://jusa.localhost.co.zw/dev/v1/activities \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: task-task-5521" \
-H "Content-Type: application/json" \
-d '{"recipient": "ext:user_123", "name": "task.done", "activity_id": "task-5521"}'
curl https://jusa.localhost.co.zw/dev/v1/recipients/ext:user_123/balance \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY"
Calls: programs.set_rules · activities.create · recipients.balance
Reimburse SMS or USSD poll costs
For Pollsters.
Pay back what answering a poll cost each participant, in one batch at the end of the day.
- Collect the numbers that answered.
- Preview, then create one batch with a line each.
Python
def reimburse_poll(poll_id: str) -> None:
try:
preview = jusa.Batch.preview(
items=[
{
"target": "0772123456",
"amount": "0.10",
"client_reference": f"poll-{poll_id}-0772123456",
},
{
"target": "0712654321",
"amount": "0.10",
"client_reference": f"poll-{poll_id}-0712654321",
},
],
)
print(preview.valid_count, preview.sufficient_credit)
jusa.Batch.create(
title=f"Poll {poll_id} reimbursement",
items=[
{
"target": "0772123456",
"amount": "0.10",
"client_reference": f"poll-{poll_id}-0772123456",
},
{
"target": "0712654321",
"amount": "0.10",
"client_reference": f"poll-{poll_id}-0712654321",
},
],
idempotency_key=f"poll-{poll_id}-reimburse",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function reimbursePoll(pollId) {
try {
const preview = await jusa.batches.preview({
items: [
{
target: '0772123456',
amount: '0.10',
client_reference: `poll-${pollId}-0772123456`,
},
{
target: '0712654321',
amount: '0.10',
client_reference: `poll-${pollId}-0712654321`,
},
],
});
console.log(preview.valid_count, preview.sufficient_credit);
await jusa.batches.create({
title: `Poll ${pollId} reimbursement`,
items: [
{
target: '0772123456',
amount: '0.10',
client_reference: `poll-${pollId}-0772123456`,
},
{
target: '0712654321',
amount: '0.10',
client_reference: `poll-${pollId}-0712654321`,
},
],
}, { idempotencyKey: `poll-${pollId}-reimburse` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function reimbursePoll(\Jusa\JusaClient $jusa, string $pollId): void
{
try {
$preview = $jusa->batches->preview([
'items' => [
[
'target' => '0772123456',
'amount' => '0.10',
'client_reference' => "poll-{$pollId}-0772123456",
],
[
'target' => '0712654321',
'amount' => '0.10',
'client_reference' => "poll-{$pollId}-0712654321",
],
],
]);
echo $preview->valid_count, ' ', $preview->sufficient_credit, "\n";
$jusa->batches->create([
'title' => "Poll {$pollId} reimbursement",
'items' => [
[
'target' => '0772123456',
'amount' => '0.10',
'client_reference' => "poll-{$pollId}-0772123456",
],
[
'target' => '0712654321',
'amount' => '0.10',
'client_reference' => "poll-{$pollId}-0712654321",
],
],
], ['idempotency_key' => "poll-{$pollId}-reimburse"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func reimbursePoll(ctx context.Context, pollID string) error {
preview, err := jusaClient.Batches.Preview(ctx, jusa.Params{
"items": []jusa.Params{
jusa.Params{
"target": "0772123456",
"amount": "0.10",
"client_reference": "poll-" + pollID + "-0772123456",
},
jusa.Params{
"target": "0712654321",
"amount": "0.10",
"client_reference": "poll-" + pollID + "-0712654321",
},
},
})
if err != nil {
return fmt.Errorf("batches.preview: %w", err)
}
fmt.Println(preview.ValidCount, preview.SufficientCredit)
_, err = jusaClient.Batches.Create(ctx, jusa.Params{
"title": "Poll " + pollID + " reimbursement",
"items": []jusa.Params{
jusa.Params{
"target": "0772123456",
"amount": "0.10",
"client_reference": "poll-" + pollID + "-0772123456",
},
jusa.Params{
"target": "0712654321",
"amount": "0.10",
"client_reference": "poll-" + pollID + "-0712654321",
},
},
}, jusa.WithIdempotencyKey("poll-"+pollID+"-reimburse"))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("batches.create: %w", err)
}
return nil
}
Java
void reimbursePoll(String pollId) throws JusaException {
try {
var preview = jusa.batches().preview(Params.of(
"items", List.of(
Map.of(
"target", "0772123456",
"amount", "0.10",
"client_reference", "poll-" + pollId + "-0772123456"
),
Map.of(
"target", "0712654321",
"amount", "0.10",
"client_reference", "poll-" + pollId + "-0712654321"
)
)
));
System.out.println(preview.getValidCount() + " " + preview.getSufficientCredit());
jusa.batches().create(Params.of(
"title", "Poll " + pollId + " reimbursement",
"items", List.of(
Map.of(
"target", "0772123456",
"amount", "0.10",
"client_reference", "poll-" + pollId + "-0772123456"
),
Map.of(
"target", "0712654321",
"amount", "0.10",
"client_reference", "poll-" + pollId + "-0712654321"
)
)
), RequestOptions.idempotencyKey("poll-" + pollId + "-reimburse"));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task ReimbursePollAsync(string pollId)
{
try
{
var preview = await jusa.Batches.PreviewAsync(new
{
items = new object[]
{
new
{
target = "0772123456",
amount = "0.10",
client_reference = $"poll-{pollId}-0772123456",
},
new
{
target = "0712654321",
amount = "0.10",
client_reference = $"poll-{pollId}-0712654321",
},
},
});
Console.WriteLine($"{preview.ValidCount} {preview.SufficientCredit}");
await jusa.Batches.CreateAsync(new
{
title = $"Poll {pollId} reimbursement",
items = new object[]
{
new
{
target = "0772123456",
amount = "0.10",
client_reference = $"poll-{pollId}-0772123456",
},
new
{
target = "0712654321",
amount = "0.10",
client_reference = $"poll-{pollId}-0712654321",
},
},
}, new RequestOptions { IdempotencyKey = $"poll-{pollId}-reimburse" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> reimbursePoll(String pollId) async {
try {
final preview = await jusa.batches.preview({
'items': [
{
'target': '0772123456',
'amount': '0.10',
'client_reference': 'poll-$pollId-0772123456',
},
{
'target': '0712654321',
'amount': '0.10',
'client_reference': 'poll-$pollId-0712654321',
},
],
});
print('${preview.validCount} ${preview.sufficientCredit}');
await jusa.batches.create({
'title': 'Poll $pollId reimbursement',
'items': [
{
'target': '0772123456',
'amount': '0.10',
'client_reference': 'poll-$pollId-0772123456',
},
{
'target': '0712654321',
'amount': '0.10',
'client_reference': 'poll-$pollId-0712654321',
},
],
}, RequestOptions(idempotencyKey: 'poll-$pollId-reimburse'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def reimburse_poll(poll_id)
preview = Jusa::Batch.preview(
items: [
{
target: "0772123456",
amount: "0.10",
client_reference: "poll-#{poll_id}-0772123456",
},
{
target: "0712654321",
amount: "0.10",
client_reference: "poll-#{poll_id}-0712654321",
},
],
)
puts "#{preview.valid_count} #{preview.sufficient_credit}"
Jusa::Batch.create({
title: "Poll #{poll_id} reimbursement",
items: [
{
target: "0772123456",
amount: "0.10",
client_reference: "poll-#{poll_id}-0772123456",
},
{
target: "0712654321",
amount: "0.10",
client_reference: "poll-#{poll_id}-0712654321",
},
],
}, idempotency_key: "poll-#{poll_id}-reimburse")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/batches/preview \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"items": [
{
"target": "0772123456",
"amount": "0.10",
"client_reference": "poll-7-0772123456"
},
{
"target": "0712654321",
"amount": "0.10",
"client_reference": "poll-7-0712654321"
}
]
}'
curl https://jusa.localhost.co.zw/dev/v1/batches \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: poll-7-reimburse" \
-H "Content-Type: application/json" \
-d '{
"title": "Poll 7 reimbursement",
"items": [
{
"target": "0772123456",
"amount": "0.10",
"client_reference": "poll-7-0772123456"
},
{
"target": "0712654321",
"amount": "0.10",
"client_reference": "poll-7-0712654321"
}
]
}'
Calls: batches.preview · batches.create · batches.retrieve
Reward in-app actions: sign-up, KYC, first transaction
For Fintech and e-commerce apps.
Reward what a user does, once per user, with sign-up rewards held in escrow until they stick.
- A program per action, with one_per_phone and per_recipient caps.
- Reward with your own external_id so caps follow the person across numbers.
- Hold sign-up rewards (hold=true) and release them after your own checks.
Python
def reward_sign_up(user_id: str, phone: str) -> None:
try:
reward = jusa.Reward.create(
program="prg_signup",
completion_id=f"signup-{user_id}",
recipient={"external_id": user_id, "phone": phone},
hold=True,
idempotency_key=f"signup-{user_id}",
)
print(reward.id, reward.status)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def release_sign_up_reward(reward_id: str, user_id: str) -> None:
try:
# … after 7 days of real use:
jusa.Reward.release(reward_id, idempotency_key=f"release-signup-{user_id}")
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function rewardSignUp(userId, phone) {
try {
const reward = await jusa.rewards.create({
program: 'prg_signup',
completion_id: `signup-${userId}`,
recipient: { external_id: userId, phone },
hold: true,
}, { idempotencyKey: `signup-${userId}` });
console.log(reward.id, reward.status);
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function releaseSignUpReward(rewardId, userId) {
try {
// … after 7 days of real use:
await jusa.rewards.release(rewardId, {}, { idempotencyKey: `release-signup-${userId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function rewardSignUp(\Jusa\JusaClient $jusa, string $userId, string $phone): void
{
try {
$reward = $jusa->rewards->create([
'program' => 'prg_signup',
'completion_id' => "signup-{$userId}",
'recipient' => ['external_id' => $userId, 'phone' => $phone],
'hold' => true,
], ['idempotency_key' => "signup-{$userId}"]);
echo $reward->id, ' ', $reward->status, "\n";
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function releaseSignUpReward(\Jusa\JusaClient $jusa, string $rewardId, string $userId): void
{
try {
// … after 7 days of real use:
$jusa->rewards->release($rewardId, [], ['idempotency_key' => "release-signup-{$userId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func rewardSignUp(ctx context.Context, userID, phone string) error {
rewardResult, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_signup",
"completion_id": "signup-" + userID,
"recipient": jusa.Params{"external_id": userID, "phone": phone},
"hold": true,
}, jusa.WithIdempotencyKey("signup-"+userID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
reward := rewardResult.Reward
fmt.Println(reward.ID, reward.Status)
return nil
}
func releaseSignUpReward(ctx context.Context, rewardID, userID string) error {
// … after 7 days of real use:
_, err := jusaClient.Rewards.Release(ctx, rewardID, nil, jusa.WithIdempotencyKey("release-signup-"+userID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.release: %w", err)
}
return nil
}
Java
void rewardSignUp(String userId, String phone) throws JusaException {
try {
var reward = jusa.rewards().create(Params.of(
"program", "prg_signup",
"completion_id", "signup-" + userId,
"recipient", Map.of("external_id", userId, "phone", phone),
"hold", true
), RequestOptions.idempotencyKey("signup-" + userId));
System.out.println(reward.getId() + " " + reward.getStatus());
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void releaseSignUpReward(String rewardId, String userId) throws JusaException {
try {
// … after 7 days of real use:
jusa.rewards().release(rewardId, RequestOptions.idempotencyKey("release-signup-" + userId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task RewardSignUpAsync(string userId, string phone)
{
try
{
var rewardResult = await jusa.Rewards.CreateAsync(new
{
program = "prg_signup",
completion_id = $"signup-{userId}",
recipient = new { external_id = userId, phone = phone },
hold = true,
}, new RequestOptions { IdempotencyKey = $"signup-{userId}" });
var reward = rewardResult.As<Reward>();
Console.WriteLine($"{reward.Id} {reward.Status}");
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task ReleaseSignUpRewardAsync(string rewardId, string userId)
{
try
{
// … after 7 days of real use:
await jusa.Rewards.ReleaseAsync(rewardId, options: new RequestOptions { IdempotencyKey = $"release-signup-{userId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> rewardSignUp(String userId, String phone) async {
try {
final reward = await jusa.rewards.create({
'program': 'prg_signup',
'completion_id': 'signup-$userId',
'recipient': {'external_id': userId, 'phone': phone},
'hold': true,
}, RequestOptions(idempotencyKey: 'signup-$userId')) as Reward;
print('${reward.id} ${reward.status}');
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> releaseSignUpReward(String rewardId, String userId) async {
try {
// … after 7 days of real use:
await jusa.rewards.release(rewardId, {}, RequestOptions(idempotencyKey: 'release-signup-$userId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def reward_sign_up(user_id, phone)
reward = Jusa::Reward.create({
program: "prg_signup",
completion_id: "signup-#{user_id}",
recipient: { external_id: user_id, phone: phone },
hold: true,
}, idempotency_key: "signup-#{user_id}")
puts "#{reward.id} #{reward.status}"
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def release_sign_up_reward(reward_id, user_id)
# … after 7 days of real use:
Jusa::Reward.release(reward_id, {}, idempotency_key: "release-signup-#{user_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: signup-u-42" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_signup",
"completion_id": "signup-u-42",
"recipient": {"external_id": "u-42", "phone": "0771230000"},
"hold": true
}'
# … after 7 days of real use:
curl -X POST https://jusa.localhost.co.zw/dev/v1/rewards/rwd_…/release \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: release-signup-u-42"
Calls: rewards.create · rewards.release · rewards.void
Streak rewards
For Edtech, health and fitness apps. P3
Pay when someone does the thing N times in D days.
- Set a streak rule: activity, count, days, amount.
- POST an activity each time; the reward is made when the streak completes.
Python
def set_up_streak_rule() -> None:
try:
# Once: five lessons within seven days earn US$1.00.
jusa.Program.set_rules(
"prg_…",
rules=[
{
"kind": "streak",
"activity": "lesson.completed",
"count": 5,
"days": 7,
"amount": "1.00",
},
],
)
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def record_lesson(learner_id: str, lesson_log_id: str) -> None:
try:
jusa.Activity.create(
recipient=f"ext:{learner_id}",
name="lesson.completed",
activity_id=lesson_log_id,
idempotency_key=f"lesson-{lesson_log_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 setUpStreakRule() {
try {
// Once: five lessons within seven days earn US$1.00.
await jusa.programs.setRules('prg_…', {
rules: [
{
kind: 'streak',
activity: 'lesson.completed',
count: 5,
days: 7,
amount: '1.00',
},
],
});
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function recordLesson(learnerId, lessonLogId) {
try {
await jusa.activities.create({
recipient: `ext:${learnerId}`,
name: 'lesson.completed',
activity_id: lessonLogId,
}, { idempotencyKey: `lesson-${lessonLogId}` });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function setUpStreakRule(\Jusa\JusaClient $jusa): void
{
try {
// Once: five lessons within seven days earn US$1.00.
$jusa->programs->setRules('prg_…', [
'rules' => [
[
'kind' => 'streak',
'activity' => 'lesson.completed',
'count' => 5,
'days' => 7,
'amount' => '1.00',
],
],
]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function recordLesson(\Jusa\JusaClient $jusa, string $learnerId, string $lessonLogId): void
{
try {
$jusa->activities->create([
'recipient' => "ext:{$learnerId}",
'name' => 'lesson.completed',
'activity_id' => $lessonLogId,
], ['idempotency_key' => "lesson-{$lessonLogId}"]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func setUpStreakRule(ctx context.Context) error {
// Once: five lessons within seven days earn US$1.00.
_, err := jusaClient.Programs.SetRules(ctx, "prg_…", jusa.Params{
"rules": []jusa.Params{
jusa.Params{
"kind": "streak",
"activity": "lesson.completed",
"count": 5,
"days": 7,
"amount": "1.00",
},
},
})
if err != nil {
return fmt.Errorf("programs.set_rules: %w", err)
}
return nil
}
func recordLesson(ctx context.Context, learnerID, lessonLogID string) error {
_, err := jusaClient.Activities.Create(ctx, jusa.Params{
"recipient": "ext:" + learnerID,
"name": "lesson.completed",
"activity_id": lessonLogID,
}, jusa.WithIdempotencyKey("lesson-"+lessonLogID))
if err != nil {
return fmt.Errorf("activities.create: %w", err)
}
return nil
}
Java
void setUpStreakRule() throws JusaException {
try {
// Once: five lessons within seven days earn US$1.00.
jusa.programs().setRules("prg_…", Params.of(
"rules", List.of(
Map.of(
"kind", "streak",
"activity", "lesson.completed",
"count", 5,
"days", 7,
"amount", "1.00"
)
)
));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void recordLesson(String learnerId, String lessonLogId) throws JusaException {
try {
jusa.activities().create(Params.of(
"recipient", "ext:" + learnerId,
"name", "lesson.completed",
"activity_id", lessonLogId
), RequestOptions.idempotencyKey("lesson-" + lessonLogId));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SetUpStreakRuleAsync()
{
try
{
// Once: five lessons within seven days earn US$1.00.
await jusa.Programs.SetRulesAsync("prg_…", new
{
rules = new object[]
{
new
{
kind = "streak",
activity = "lesson.completed",
count = 5,
days = 7,
amount = "1.00",
},
},
});
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task RecordLessonAsync(string learnerId, string lessonLogId)
{
try
{
await jusa.Activities.CreateAsync(new
{
recipient = $"ext:{learnerId}",
name = "lesson.completed",
activity_id = lessonLogId,
}, new RequestOptions { IdempotencyKey = $"lesson-{lessonLogId}" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> setUpStreakRule() async {
try {
// Once: five lessons within seven days earn US$1.00.
await jusa.programs.setRules('prg_…', {
'rules': [
{
'kind': 'streak',
'activity': 'lesson.completed',
'count': 5,
'days': 7,
'amount': '1.00',
},
],
});
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> recordLesson(String learnerId, String lessonLogId) async {
try {
await jusa.activities.create({
'recipient': 'ext:$learnerId',
'name': 'lesson.completed',
'activity_id': lessonLogId,
}, RequestOptions(idempotencyKey: 'lesson-$lessonLogId'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def set_up_streak_rule
# Once: five lessons within seven days earn US$1.00.
Jusa::Program.set_rules(
"prg_…",
rules: [
{
kind: "streak",
activity: "lesson.completed",
count: 5,
days: 7,
amount: "1.00",
},
],
)
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def record_lesson(learner_id, lesson_log_id)
Jusa::Activity.create({
recipient: "ext:#{learner_id}",
name: "lesson.completed",
activity_id: lesson_log_id,
}, idempotency_key: "lesson-#{lesson_log_id}")
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# Once: five lessons within seven days earn US$1.00.
curl -X PUT https://jusa.localhost.co.zw/dev/v1/programs/prg_…/rules \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{
"rules": [
{
"kind": "streak",
"activity": "lesson.completed",
"count": 5,
"days": 7,
"amount": "1.00"
}
]
}'
curl https://jusa.localhost.co.zw/dev/v1/activities \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: lesson-lesson-log-311" \
-H "Content-Type: application/json" \
-d '{
"recipient": "ext:learner-9",
"name": "lesson.completed",
"activity_id": "lesson-log-311"
}'
Calls: programs.set_rules · activities.create
A two-sided referral chain
For Any app. P3
Pay the referrer (and optionally the referee) once the referee does something that counts. Depth 1, held in escrow by default.
- Set a referral rule with a qualifying_activity.
- Record the referral when they sign up.
- The referee's qualifying activity (or POST …/qualify) pays out.
Python
def record_referral(referrer_id: str, referrer_phone: str, referee_id: str, referee_phone: str) -> None:
try:
jusa.Referral.create(
program="prg_…",
referrer={"external_id": referrer_id, "phone": referrer_phone},
referee={"external_id": referee_id, "phone": referee_phone},
idempotency_key=f"referral-{referrer_id}-{referee_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 recordReferral(referrerId, referrerPhone, refereeId, refereePhone) {
try {
await jusa.referrals.create({
program: 'prg_…',
referrer: { external_id: referrerId, phone: referrerPhone },
referee: { external_id: refereeId, phone: refereePhone },
}, { idempotencyKey: `referral-${referrerId}-${refereeId}` });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function recordReferral(\Jusa\JusaClient $jusa, string $referrerId, string $referrerPhone, string $refereeId, string $refereePhone): void
{
try {
$jusa->referrals->create([
'program' => 'prg_…',
'referrer' => ['external_id' => $referrerId, 'phone' => $referrerPhone],
'referee' => ['external_id' => $refereeId, 'phone' => $refereePhone],
], ['idempotency_key' => "referral-{$referrerId}-{$refereeId}"]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func recordReferral(ctx context.Context, referrerID, referrerPhone, refereeID, refereePhone string) error {
_, err := jusaClient.Referrals.Create(ctx, jusa.Params{
"program": "prg_…",
"referrer": jusa.Params{"external_id": referrerID, "phone": referrerPhone},
"referee": jusa.Params{"external_id": refereeID, "phone": refereePhone},
}, jusa.WithIdempotencyKey("referral-"+referrerID+"-"+refereeID))
if err != nil {
return fmt.Errorf("referrals.create: %w", err)
}
return nil
}
Java
void recordReferral(String referrerId, String referrerPhone, String refereeId, String refereePhone) throws JusaException {
try {
jusa.referrals().create(Params.of(
"program", "prg_…",
"referrer", Map.of("external_id", referrerId, "phone", referrerPhone),
"referee", Map.of("external_id", refereeId, "phone", refereePhone)
), RequestOptions.idempotencyKey("referral-" + referrerId + "-" + refereeId));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task RecordReferralAsync(string referrerId, string referrerPhone, string refereeId, string refereePhone)
{
try
{
await jusa.Referrals.CreateAsync(new
{
program = "prg_…",
referrer = new { external_id = referrerId, phone = referrerPhone },
referee = new { external_id = refereeId, phone = refereePhone },
}, new RequestOptions { IdempotencyKey = $"referral-{referrerId}-{refereeId}" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> recordReferral(String referrerId, String referrerPhone, String refereeId, String refereePhone) async {
try {
await jusa.referrals.create({
'program': 'prg_…',
'referrer': {'external_id': referrerId, 'phone': referrerPhone},
'referee': {'external_id': refereeId, 'phone': refereePhone},
}, RequestOptions(idempotencyKey: 'referral-$referrerId-$refereeId'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def record_referral(referrer_id, referrer_phone, referee_id, referee_phone)
Jusa::Referral.create({
program: "prg_…",
referrer: { external_id: referrer_id, phone: referrer_phone },
referee: { external_id: referee_id, phone: referee_phone },
}, idempotency_key: "referral-#{referrer_id}-#{referee_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/referrals \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: referral-u-1-u-2" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_…",
"referrer": {"external_id": "u-1", "phone": "0772123456"},
"referee": {"external_id": "u-2", "phone": "0772654321"}
}'
Calls: programs.set_rules · referrals.create · referrals.qualify
Loyalty points to airtime, data or ZESA
For Retailers, fuel stations, supermarkets. data: P2
Let members spend points on airtime or a ZESA token at face value.
- Show the catalog; for ZESA, quote first so the member sees the units.
- Send with the quote: it carries a confirmed meter.
Python
def redeem_points_for_zesa(meter_number: str, token_phone: str, redemption_id: str) -> None:
try:
quote = jusa.Quote.create(
product="zesa-usd",
amount="10.00",
target=meter_number,
)
print(quote.zesa.units_now, quote.meter.customer_name)
jusa.Send.create(
quote=quote.id,
token_phone=token_phone,
client_reference=f"redeem-{redemption_id}",
idempotency_key=f"redeem-{redemption_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function redeemPointsForZesa(meterNumber, tokenPhone, redemptionId) {
try {
const quote = await jusa.quotes.create({
product: 'zesa-usd',
amount: '10.00',
target: meterNumber,
});
console.log(quote.zesa.units_now, quote.meter.customer_name);
await jusa.sends.create({
quote: quote.id,
token_phone: tokenPhone,
client_reference: `redeem-${redemptionId}`,
}, { idempotencyKey: `redeem-${redemptionId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function redeemPointsForZesa(\Jusa\JusaClient $jusa, string $meterNumber, string $tokenPhone, string $redemptionId): void
{
try {
$quote = $jusa->quotes->create([
'product' => 'zesa-usd',
'amount' => '10.00',
'target' => $meterNumber,
]);
echo $quote->zesa->units_now, ' ', $quote->meter->customer_name, "\n";
$jusa->sends->create([
'quote' => $quote->id,
'token_phone' => $tokenPhone,
'client_reference' => "redeem-{$redemptionId}",
], ['idempotency_key' => "redeem-{$redemptionId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func redeemPointsForZesa(ctx context.Context, meterNumber, tokenPhone, redemptionID string) error {
quote, err := jusaClient.Quotes.Create(ctx, jusa.Params{
"product": "zesa-usd",
"amount": "10.00",
"target": meterNumber,
})
if err != nil {
return fmt.Errorf("quotes.create: %w", err)
}
fmt.Println(quote.Zesa.UnitsNow, quote.Meter.CustomerName)
_, err = jusaClient.Sends.Create(ctx, jusa.Params{
"quote": quote.ID,
"token_phone": tokenPhone,
"client_reference": "redeem-" + redemptionID,
}, jusa.WithIdempotencyKey("redeem-"+redemptionID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("sends.create: %w", err)
}
return nil
}
Java
void redeemPointsForZesa(String meterNumber, String tokenPhone, String redemptionId) throws JusaException {
try {
var quote = jusa.quotes().create(Params.of(
"product", "zesa-usd",
"amount", "10.00",
"target", meterNumber
));
System.out.println(quote.getZesa().getUnitsNow() + " " + quote.getMeter().getCustomerName());
jusa.sends().create(Params.of(
"quote", quote.getId(),
"token_phone", tokenPhone,
"client_reference", "redeem-" + redemptionId
), RequestOptions.idempotencyKey("redeem-" + redemptionId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task RedeemPointsForZesaAsync(string meterNumber, string tokenPhone, string redemptionId)
{
try
{
var quote = await jusa.Quotes.CreateAsync(new
{
product = "zesa-usd",
amount = "10.00",
target = meterNumber,
});
Console.WriteLine($"{quote.Zesa?.UnitsNow} {quote.Meter?.CustomerName}");
await jusa.Sends.CreateAsync(new
{
quote = quote.Id,
token_phone = tokenPhone,
client_reference = $"redeem-{redemptionId}",
}, new RequestOptions { IdempotencyKey = $"redeem-{redemptionId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> redeemPointsForZesa(String meterNumber, String tokenPhone, String redemptionId) async {
try {
final quote = await jusa.quotes.create({
'product': 'zesa-usd',
'amount': '10.00',
'target': meterNumber,
});
print('${quote.zesa?.unitsNow} ${quote.meter?.customerName}');
await jusa.sends.create({
'quote': quote.id,
'token_phone': tokenPhone,
'client_reference': 'redeem-$redemptionId',
}, RequestOptions(idempotencyKey: 'redeem-$redemptionId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def redeem_points_for_zesa(meter_number, token_phone, redemption_id)
quote = Jusa::Quote.create(product: "zesa-usd", amount: "10.00", target: meter_number)
puts "#{quote.zesa.units_now} #{quote.meter.customer_name}"
Jusa::Send.create({
quote: quote.id,
token_phone: token_phone,
client_reference: "redeem-#{redemption_id}",
}, idempotency_key: "redeem-#{redemption_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/quotes \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"product": "zesa-usd", "amount": "10.00", "target": "37261502217"}'
curl https://jusa.localhost.co.zw/dev/v1/sends \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: redeem-9031" \
-H "Content-Type: application/json" \
-d '{
"quote": "quo_…",
"token_phone": "0772123456",
"client_reference": "redeem-9031"
}'
Calls: products.list · quotes.create · sends.create · meters.retrieve
Reward links where the person chooses
For Brands. data: P2
Send a link over WhatsApp; the person picks airtime or ZESA and confirms their meter.
- Mint links with choices and bind=otp.
- Share them; the hosted page confirms the meter.
Python
def send_choice_link(customer_id: str, phone: str) -> None:
try:
jusa.RewardLink.create(
program="prg_…",
recipient=f"ext:{customer_id}",
choices=["airtime", "zesa"],
bind="otp",
phone_hint=phone,
idempotency_key=f"choice-link-{customer_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 sendChoiceLink(customerId, phone) {
try {
await jusa.rewardLinks.create({
program: 'prg_…',
recipient: `ext:${customerId}`,
choices: ['airtime', 'zesa'],
bind: 'otp',
phone_hint: phone,
}, { idempotencyKey: `choice-link-${customerId}` });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function sendChoiceLink(\Jusa\JusaClient $jusa, string $customerId, string $phone): void
{
try {
$jusa->rewardLinks->create([
'program' => 'prg_…',
'recipient' => "ext:{$customerId}",
'choices' => ['airtime', 'zesa'],
'bind' => 'otp',
'phone_hint' => $phone,
], ['idempotency_key' => "choice-link-{$customerId}"]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func sendChoiceLink(ctx context.Context, customerID, phone string) error {
_, err := jusaClient.RewardLinks.Create(ctx, jusa.Params{
"program": "prg_…",
"recipient": "ext:" + customerID,
"choices": []string{"airtime", "zesa"},
"bind": "otp",
"phone_hint": phone,
}, jusa.WithIdempotencyKey("choice-link-"+customerID))
if err != nil {
return fmt.Errorf("reward_links.create: %w", err)
}
return nil
}
Java
void sendChoiceLink(String customerId, String phone) throws JusaException {
try {
jusa.rewardLinks().create(Params.of(
"program", "prg_…",
"recipient", "ext:" + customerId,
"choices", List.of("airtime", "zesa"),
"bind", "otp",
"phone_hint", phone
), RequestOptions.idempotencyKey("choice-link-" + customerId));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SendChoiceLinkAsync(string customerId, string phone)
{
try
{
await jusa.RewardLinks.CreateAsync(new
{
program = "prg_…",
recipient = $"ext:{customerId}",
choices = new[] { "airtime", "zesa" },
bind = "otp",
phone_hint = phone,
}, new RequestOptions { IdempotencyKey = $"choice-link-{customerId}" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> sendChoiceLink(String customerId, String phone) async {
try {
await jusa.rewardLinks.create({
'program': 'prg_…',
'recipient': 'ext:$customerId',
'choices': ['airtime', 'zesa'],
'bind': 'otp',
'phone_hint': phone,
}, RequestOptions(idempotencyKey: 'choice-link-$customerId'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def send_choice_link(customer_id, phone)
Jusa::RewardLink.create({
program: "prg_…",
recipient: "ext:#{customer_id}",
choices: ["airtime", "zesa"],
bind: "otp",
phone_hint: phone,
}, idempotency_key: "choice-link-#{customer_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/reward-links \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: choice-link-cust-88" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_…",
"recipient": "ext:cust-88",
"choices": ["airtime", "zesa"],
"bind": "otp",
"phone_hint": "0771230000"
}'
Calls: reward_links.create · meters.retrieve
Radio or brand giveaways with an audit trail
For Media. prize draws: P3, needs a licence
First-come links for listeners, with an export the auditor can check. Prize draws stay off until counsel signs them off.
- Mint the links; read them out or post them.
- Export the rewards for the audit.
Python
def mint_giveaway_links() -> None:
try:
jusa.RewardLink.create(
program="prg_…",
count=50,
label="breakfast-show",
idempotency_key="giveaway-breakfast-show",
)
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def export_rewards_for_auditor() -> None:
try:
rewards_export = jusa.Export.create(
type="rewards",
from_="2026-10-01",
idempotency_key="audit-export-2026-10",
)
print(rewards_export.id, rewards_export.status)
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 mintGiveawayLinks() {
try {
await jusa.rewardLinks.create({
program: 'prg_…',
count: 50,
label: 'breakfast-show',
}, { idempotencyKey: 'giveaway-breakfast-show' });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function exportRewardsForAuditor() {
try {
const rewardsExport = await jusa.exports.create({
type: 'rewards',
from: '2026-10-01',
}, { idempotencyKey: 'audit-export-2026-10' });
console.log(rewardsExport.id, rewardsExport.status);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function mintGiveawayLinks(\Jusa\JusaClient $jusa): void
{
try {
$jusa->rewardLinks->create([
'program' => 'prg_…',
'count' => 50,
'label' => 'breakfast-show',
], ['idempotency_key' => 'giveaway-breakfast-show']);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function exportRewardsForAuditor(\Jusa\JusaClient $jusa): void
{
try {
$rewardsExport = $jusa->exports->create([
'type' => 'rewards',
'from' => '2026-10-01',
], ['idempotency_key' => 'audit-export-2026-10']);
echo $rewardsExport->id, ' ', $rewardsExport->status, "\n";
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func mintGiveawayLinks(ctx context.Context) error {
_, err := jusaClient.RewardLinks.Create(ctx, jusa.Params{
"program": "prg_…",
"count": 50,
"label": "breakfast-show",
}, jusa.WithIdempotencyKey("giveaway-breakfast-show"))
if err != nil {
return fmt.Errorf("reward_links.create: %w", err)
}
return nil
}
func exportRewardsForAuditor(ctx context.Context) error {
rewardsExport, err := jusaClient.Exports.Create(ctx, jusa.Params{
"type": "rewards",
"from": "2026-10-01",
}, jusa.WithIdempotencyKey("audit-export-2026-10"))
if err != nil {
return fmt.Errorf("exports.create: %w", err)
}
fmt.Println(rewardsExport.ID, rewardsExport.Status)
return nil
}
Java
void mintGiveawayLinks() throws JusaException {
try {
jusa.rewardLinks().create(Params.of(
"program", "prg_…",
"count", 50,
"label", "breakfast-show"
), RequestOptions.idempotencyKey("giveaway-breakfast-show"));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void exportRewardsForAuditor() throws JusaException {
try {
var rewardsExport = jusa.exports().create(Params.of(
"type", "rewards",
"from", "2026-10-01"
), RequestOptions.idempotencyKey("audit-export-2026-10"));
System.out.println(rewardsExport.getId() + " " + rewardsExport.getStatus());
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task MintGiveawayLinksAsync()
{
try
{
await jusa.RewardLinks.CreateAsync(new
{
program = "prg_…",
count = 50,
label = "breakfast-show",
}, new RequestOptions { IdempotencyKey = "giveaway-breakfast-show" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task ExportRewardsForAuditorAsync()
{
try
{
var rewardsExport = await jusa.Exports.CreateAsync(new
{
type = "rewards",
from = "2026-10-01",
}, new RequestOptions { IdempotencyKey = "audit-export-2026-10" });
Console.WriteLine($"{rewardsExport.Id} {rewardsExport.Status}");
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> mintGiveawayLinks() async {
try {
await jusa.rewardLinks.create({
'program': 'prg_…',
'count': 50,
'label': 'breakfast-show',
}, RequestOptions(idempotencyKey: 'giveaway-breakfast-show'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> exportRewardsForAuditor() async {
try {
final rewardsExport = await jusa.exports.create({
'type': 'rewards',
'from': '2026-10-01',
}, RequestOptions(idempotencyKey: 'audit-export-2026-10'));
print('${rewardsExport.id} ${rewardsExport.status}');
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def mint_giveaway_links
Jusa::RewardLink.create({
program: "prg_…",
count: 50,
label: "breakfast-show",
}, idempotency_key: "giveaway-breakfast-show")
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def export_rewards_for_auditor
rewards_export = Jusa::Export.create({
type: "rewards",
from: "2026-10-01",
}, idempotency_key: "audit-export-2026-10")
puts "#{rewards_export.id} #{rewards_export.status}"
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/reward-links \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: giveaway-breakfast-show" \
-H "Content-Type: application/json" \
-d '{"program": "prg_…", "count": 50, "label": "breakfast-show"}'
curl https://jusa.localhost.co.zw/dev/v1/exports \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: audit-export-2026-10" \
-H "Content-Type: application/json" \
-d '{"type": "rewards", "from": "2026-10-01"}'
Calls: reward_links.create · exports.create · exports.retrieve
Conditional adherence incentives
For Clinics, research trials. needs counsel: health data
Hold a reward and release it when a visit is confirmed. Sensitive-data programs stay off until Jusa approves them.
- A sensitive_data program with a lawful_basis, pseudonymous external_ids.
- Hold rewards; release or void them from your clinical system.
Python
def reward_clinic_visit(visit_id: str, patient_id: str, phone: str) -> None:
try:
reward = jusa.Reward.create(
program="prg_trial",
completion_id=f"visit-{visit_id}",
recipient={"external_id": patient_id, "phone": phone},
hold=True,
idempotency_key=f"visit-{visit_id}",
)
print(reward.id, reward.status)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def void_missed_visit(reward_id: str) -> None:
try:
# The visit did not happen:
jusa.Reward.void(reward_id, idempotency_key=f"void-{reward_id}")
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function rewardClinicVisit(visitId, patientId, phone) {
try {
const reward = await jusa.rewards.create({
program: 'prg_trial',
completion_id: `visit-${visitId}`,
recipient: { external_id: patientId, phone },
hold: true,
}, { idempotencyKey: `visit-${visitId}` });
console.log(reward.id, reward.status);
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function voidMissedVisit(rewardId) {
try {
// The visit did not happen:
await jusa.rewards.void(rewardId, {}, { idempotencyKey: `void-${rewardId}` });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function rewardClinicVisit(\Jusa\JusaClient $jusa, string $visitId, string $patientId, string $phone): void
{
try {
$reward = $jusa->rewards->create([
'program' => 'prg_trial',
'completion_id' => "visit-{$visitId}",
'recipient' => ['external_id' => $patientId, 'phone' => $phone],
'hold' => true,
], ['idempotency_key' => "visit-{$visitId}"]);
echo $reward->id, ' ', $reward->status, "\n";
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function voidMissedVisit(\Jusa\JusaClient $jusa, string $rewardId): void
{
try {
// The visit did not happen:
$jusa->rewards->void($rewardId, [], ['idempotency_key' => "void-{$rewardId}"]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func rewardClinicVisit(ctx context.Context, visitID, patientID, phone string) error {
rewardResult, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_trial",
"completion_id": "visit-" + visitID,
"recipient": jusa.Params{"external_id": patientID, "phone": phone},
"hold": true,
}, jusa.WithIdempotencyKey("visit-"+visitID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
reward := rewardResult.Reward
fmt.Println(reward.ID, reward.Status)
return nil
}
func voidMissedVisit(ctx context.Context, rewardID string) error {
// The visit did not happen:
_, err := jusaClient.Rewards.Void(ctx, rewardID, nil, jusa.WithIdempotencyKey("void-"+rewardID))
if err != nil {
return fmt.Errorf("rewards.void: %w", err)
}
return nil
}
Java
void rewardClinicVisit(String visitId, String patientId, String phone) throws JusaException {
try {
var reward = jusa.rewards().create(Params.of(
"program", "prg_trial",
"completion_id", "visit-" + visitId,
"recipient", Map.of("external_id", patientId, "phone", phone),
"hold", true
), RequestOptions.idempotencyKey("visit-" + visitId));
System.out.println(reward.getId() + " " + reward.getStatus());
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void voidMissedVisit(String rewardId) throws JusaException {
try {
// The visit did not happen:
jusa.rewards().voidReward(rewardId, RequestOptions.idempotencyKey("void-" + rewardId));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task RewardClinicVisitAsync(string visitId, string patientId, string phone)
{
try
{
var rewardResult = await jusa.Rewards.CreateAsync(new
{
program = "prg_trial",
completion_id = $"visit-{visitId}",
recipient = new { external_id = patientId, phone = phone },
hold = true,
}, new RequestOptions { IdempotencyKey = $"visit-{visitId}" });
var reward = rewardResult.As<Reward>();
Console.WriteLine($"{reward.Id} {reward.Status}");
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task VoidMissedVisitAsync(string rewardId)
{
try
{
// The visit did not happen:
await jusa.Rewards.VoidAsync(rewardId, options: new RequestOptions { IdempotencyKey = $"void-{rewardId}" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> rewardClinicVisit(String visitId, String patientId, String phone) async {
try {
final reward = await jusa.rewards.create({
'program': 'prg_trial',
'completion_id': 'visit-$visitId',
'recipient': {'external_id': patientId, 'phone': phone},
'hold': true,
}, RequestOptions(idempotencyKey: 'visit-$visitId')) as Reward;
print('${reward.id} ${reward.status}');
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> voidMissedVisit(String rewardId) async {
try {
// The visit did not happen:
await jusa.rewards.voidReward(rewardId, {}, RequestOptions(idempotencyKey: 'void-$rewardId'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def reward_clinic_visit(visit_id, patient_id, phone)
reward = Jusa::Reward.create({
program: "prg_trial",
completion_id: "visit-#{visit_id}",
recipient: { external_id: patient_id, phone: phone },
hold: true,
}, idempotency_key: "visit-#{visit_id}")
puts "#{reward.id} #{reward.status}"
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def void_missed_visit(reward_id)
# The visit did not happen:
Jusa::Reward.void(reward_id, {}, idempotency_key: "void-#{reward_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/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: visit-2207" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_trial",
"completion_id": "visit-2207",
"recipient": {"external_id": "P-0193", "phone": "0771230000"},
"hold": true
}'
# The visit did not happen:
curl -X POST https://jusa.localhost.co.zw/dev/v1/rewards/rwd_…/void \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: void-rwd_…"
Calls: rewards.create · rewards.release · rewards.void
Community health worker allowances
For Health NGOs. data: P2
A monthly allowance to every CHW, billed to the right cost centre.
- Recipients in a group, a cost centre with a GL code.
- A monthly schedule to the group.
Python
def set_up_chw_allowance() -> None:
try:
cost_center = jusa.CostCenter.create(
name="CHW programme",
gl_code="6100",
idempotency_key="cost-center-chw",
)
group = jusa.Group.create(
name="CHWs",
cost_center=cost_center.id,
idempotency_key="group-chws",
)
jusa.Schedule.create(
name="CHW airtime",
cadence="monthly",
day_of_month=1,
hour=8,
minute=0,
group=group.id,
product="airtime-usd",
amount="5.00",
idempotency_key="schedule-chw-airtime",
)
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 setUpChwAllowance() {
try {
const costCenter = await jusa.costCenters.create({
name: 'CHW programme',
gl_code: '6100',
}, { idempotencyKey: 'cost-center-chw' });
const group = await jusa.groups.create({
name: 'CHWs',
cost_center: costCenter.id,
}, { idempotencyKey: 'group-chws' });
await jusa.schedules.create({
name: 'CHW airtime',
cadence: 'monthly',
day_of_month: 1,
hour: 8,
minute: 0,
group: group.id,
product: 'airtime-usd',
amount: '5.00',
}, { idempotencyKey: 'schedule-chw-airtime' });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function setUpChwAllowance(\Jusa\JusaClient $jusa): void
{
try {
$costCenter = $jusa->costCenters->create([
'name' => 'CHW programme',
'gl_code' => '6100',
], ['idempotency_key' => 'cost-center-chw']);
$group = $jusa->groups->create([
'name' => 'CHWs',
'cost_center' => $costCenter->id,
], ['idempotency_key' => 'group-chws']);
$jusa->schedules->create([
'name' => 'CHW airtime',
'cadence' => 'monthly',
'day_of_month' => 1,
'hour' => 8,
'minute' => 0,
'group' => $group->id,
'product' => 'airtime-usd',
'amount' => '5.00',
], ['idempotency_key' => 'schedule-chw-airtime']);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func setUpChwAllowance(ctx context.Context) error {
costCenter, err := jusaClient.CostCenters.Create(ctx, jusa.Params{
"name": "CHW programme",
"gl_code": "6100",
}, jusa.WithIdempotencyKey("cost-center-chw"))
if err != nil {
return fmt.Errorf("cost_centers.create: %w", err)
}
group, err := jusaClient.Groups.Create(ctx, jusa.Params{
"name": "CHWs",
"cost_center": costCenter.ID,
}, jusa.WithIdempotencyKey("group-chws"))
if err != nil {
return fmt.Errorf("groups.create: %w", err)
}
_, err = jusaClient.Schedules.Create(ctx, jusa.Params{
"name": "CHW airtime",
"cadence": "monthly",
"day_of_month": 1,
"hour": 8,
"minute": 0,
"group": group.ID,
"product": "airtime-usd",
"amount": "5.00",
}, jusa.WithIdempotencyKey("schedule-chw-airtime"))
if err != nil {
return fmt.Errorf("schedules.create: %w", err)
}
return nil
}
Java
void setUpChwAllowance() throws JusaException {
try {
var costCenter = jusa.costCenters().create(Params.of(
"name", "CHW programme",
"gl_code", "6100"
), RequestOptions.idempotencyKey("cost-center-chw"));
var group = jusa.groups().create(Params.of(
"name", "CHWs",
"cost_center", costCenter.getId()
), RequestOptions.idempotencyKey("group-chws"));
jusa.schedules().create(Params.of(
"name", "CHW airtime",
"cadence", "monthly",
"day_of_month", 1,
"hour", 8,
"minute", 0,
"group", group.getId(),
"product", "airtime-usd",
"amount", "5.00"
), RequestOptions.idempotencyKey("schedule-chw-airtime"));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SetUpChwAllowanceAsync()
{
try
{
var costCenter = await jusa.CostCenters.CreateAsync(new
{
name = "CHW programme",
gl_code = "6100",
}, new RequestOptions { IdempotencyKey = "cost-center-chw" });
var group = await jusa.Groups.CreateAsync(new
{
name = "CHWs",
cost_center = costCenter.Id,
}, new RequestOptions { IdempotencyKey = "group-chws" });
await jusa.Schedules.CreateAsync(new
{
name = "CHW airtime",
cadence = "monthly",
day_of_month = 1,
hour = 8,
minute = 0,
group = group.Id,
product = "airtime-usd",
amount = "5.00",
}, new RequestOptions { IdempotencyKey = "schedule-chw-airtime" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> setUpChwAllowance() async {
try {
final costCenter = await jusa.costCenters.create({
'name': 'CHW programme',
'gl_code': '6100',
}, RequestOptions(idempotencyKey: 'cost-center-chw'));
final group = await jusa.groups.create({
'name': 'CHWs',
'cost_center': costCenter.id,
}, RequestOptions(idempotencyKey: 'group-chws'));
await jusa.schedules.create({
'name': 'CHW airtime',
'cadence': 'monthly',
'day_of_month': 1,
'hour': 8,
'minute': 0,
'group': group.id,
'product': 'airtime-usd',
'amount': '5.00',
}, RequestOptions(idempotencyKey: 'schedule-chw-airtime'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def set_up_chw_allowance
cost_center = Jusa::CostCenter.create({
name: "CHW programme",
gl_code: "6100",
}, idempotency_key: "cost-center-chw")
group = Jusa::Group.create({
name: "CHWs",
cost_center: cost_center.id,
}, idempotency_key: "group-chws")
Jusa::Schedule.create({
name: "CHW airtime",
cadence: "monthly",
day_of_month: 1,
hour: 8,
minute: 0,
group: group.id,
product: "airtime-usd",
amount: "5.00",
}, idempotency_key: "schedule-chw-airtime")
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/cost-centers \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: cost-center-chw" \
-H "Content-Type: application/json" \
-d '{"name": "CHW programme", "gl_code": "6100"}'
curl https://jusa.localhost.co.zw/dev/v1/groups \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: group-chws" \
-H "Content-Type: application/json" \
-d '{"name": "CHWs", "cost_center": "cc_…"}'
curl https://jusa.localhost.co.zw/dev/v1/schedules \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: schedule-chw-airtime" \
-H "Content-Type: application/json" \
-d '{
"name": "CHW airtime",
"cadence": "monthly",
"day_of_month": 1,
"hour": 8,
"minute": 0,
"group": "grp_…",
"product": "airtime-usd",
"amount": "5.00"
}'
Calls: recipients.bulk · groups.create · cost_centers.create · schedules.create · reports.spend
In-kind ZESA assistance
For WFP-style programmes.
ZESA tokens to households in a batch, credit reserved up front, dry-run in test mode first.
- Each line carries the meter and a token_phone.
- Run it in test mode, then live.
Python
def send_household_assistance(meter_number: str, token_phone: str, household_id: str) -> None:
try:
jusa.Batch.create(
title="October assistance",
items=[
{
"type": "zesa",
"meter": meter_number,
"token_phone": token_phone,
"amount": "10.00",
"client_reference": f"assistance-2026-10-{household_id}",
},
],
idempotency_key=f"assistance-2026-10-{household_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function sendHouseholdAssistance(meterNumber, tokenPhone, householdId) {
try {
await jusa.batches.create({
title: 'October assistance',
items: [
{
type: 'zesa',
meter: meterNumber,
token_phone: tokenPhone,
amount: '10.00',
client_reference: `assistance-2026-10-${householdId}`,
},
],
}, { idempotencyKey: `assistance-2026-10-${householdId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function sendHouseholdAssistance(\Jusa\JusaClient $jusa, string $meterNumber, string $tokenPhone, string $householdId): void
{
try {
$jusa->batches->create([
'title' => 'October assistance',
'items' => [
[
'type' => 'zesa',
'meter' => $meterNumber,
'token_phone' => $tokenPhone,
'amount' => '10.00',
'client_reference' => "assistance-2026-10-{$householdId}",
],
],
], ['idempotency_key' => "assistance-2026-10-{$householdId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func sendHouseholdAssistance(ctx context.Context, meterNumber, tokenPhone, householdID string) error {
_, err := jusaClient.Batches.Create(ctx, jusa.Params{
"title": "October assistance",
"items": []jusa.Params{
jusa.Params{
"type": "zesa",
"meter": meterNumber,
"token_phone": tokenPhone,
"amount": "10.00",
"client_reference": "assistance-2026-10-" + householdID,
},
},
}, jusa.WithIdempotencyKey("assistance-2026-10-"+householdID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("batches.create: %w", err)
}
return nil
}
Java
void sendHouseholdAssistance(String meterNumber, String tokenPhone, String householdId) throws JusaException {
try {
jusa.batches().create(Params.of(
"title", "October assistance",
"items", List.of(
Map.of(
"type", "zesa",
"meter", meterNumber,
"token_phone", tokenPhone,
"amount", "10.00",
"client_reference", "assistance-2026-10-" + householdId
)
)
), RequestOptions.idempotencyKey("assistance-2026-10-" + householdId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SendHouseholdAssistanceAsync(string meterNumber, string tokenPhone, string householdId)
{
try
{
await jusa.Batches.CreateAsync(new
{
title = "October assistance",
items = new object[]
{
new
{
type = "zesa",
meter = meterNumber,
token_phone = tokenPhone,
amount = "10.00",
client_reference = $"assistance-2026-10-{householdId}",
},
},
}, new RequestOptions { IdempotencyKey = $"assistance-2026-10-{householdId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> sendHouseholdAssistance(String meterNumber, String tokenPhone, String householdId) async {
try {
await jusa.batches.create({
'title': 'October assistance',
'items': [
{
'type': 'zesa',
'meter': meterNumber,
'token_phone': tokenPhone,
'amount': '10.00',
'client_reference': 'assistance-2026-10-$householdId',
},
],
}, RequestOptions(idempotencyKey: 'assistance-2026-10-$householdId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def send_household_assistance(meter_number, token_phone, household_id)
Jusa::Batch.create({
title: "October assistance",
items: [
{
type: "zesa",
meter: meter_number,
token_phone: token_phone,
amount: "10.00",
client_reference: "assistance-2026-10-#{household_id}",
},
],
}, idempotency_key: "assistance-2026-10-#{household_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/batches \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: assistance-2026-10-hh-0001" \
-H "Content-Type: application/json" \
-d '{
"title": "October assistance",
"items": [
{
"type": "zesa",
"meter": "37261502217",
"token_phone": "0772123456",
"amount": "10.00",
"client_reference": "assistance-2026-10-hh-0001"
}
]
}'
Calls: batches.preview · batches.create · statements.retrieve
Clinic or antenatal check-in
For Health. P3 needs counsel: health data
A reward link paid only by checking in at the clinic, inside its geofence and hours.
- A program with a geofence.
- The person checks in from the widget or your app.
Python
def check_in_at_clinic(link_id: str, phone: str) -> None:
try:
checkin = jusa.Checkin.create(
link=link_id,
lat=-17.8252,
lng=31.0522,
accuracy_m=25,
phone=phone,
choice="airtime",
idempotency_key=f"checkin-{link_id}",
)
print(checkin.status, checkin.distance_m)
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 checkInAtClinic(linkId, phone) {
try {
const checkin = await jusa.checkins.create({
link: linkId,
lat: -17.8252,
lng: 31.0522,
accuracy_m: 25,
phone,
choice: 'airtime',
}, { idempotencyKey: `checkin-${linkId}` });
console.log(checkin.status, checkin.distance_m);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function checkInAtClinic(\Jusa\JusaClient $jusa, string $linkId, string $phone): void
{
try {
$checkin = $jusa->checkins->create([
'link' => $linkId,
'lat' => -17.8252,
'lng' => 31.0522,
'accuracy_m' => 25,
'phone' => $phone,
'choice' => 'airtime',
], ['idempotency_key' => "checkin-{$linkId}"]);
echo $checkin->status, ' ', $checkin->distance_m, "\n";
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func checkInAtClinic(ctx context.Context, linkID, phone string) error {
checkin, err := jusaClient.Checkins.Create(ctx, jusa.Params{
"link": linkID,
"lat": -17.8252,
"lng": 31.0522,
"accuracy_m": 25,
"phone": phone,
"choice": "airtime",
}, jusa.WithIdempotencyKey("checkin-"+linkID))
if err != nil {
return fmt.Errorf("checkins.create: %w", err)
}
fmt.Println(checkin.Status, checkin.DistanceM)
return nil
}
Java
void checkInAtClinic(String linkId, String phone) throws JusaException {
try {
var checkin = jusa.checkins().create(Params.of(
"link", linkId,
"lat", -17.8252,
"lng", 31.0522,
"accuracy_m", 25,
"phone", phone,
"choice", "airtime"
), RequestOptions.idempotencyKey("checkin-" + linkId));
System.out.println(checkin.getStatus() + " " + checkin.getDistanceM());
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task CheckInAtClinicAsync(string linkId, string phone)
{
try
{
var checkin = await jusa.Checkins.CreateAsync(new
{
link = linkId,
lat = -17.8252,
lng = 31.0522,
accuracy_m = 25,
phone = phone,
choice = "airtime",
}, new RequestOptions { IdempotencyKey = $"checkin-{linkId}" });
Console.WriteLine($"{checkin.Status} {checkin.DistanceM}");
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> checkInAtClinic(String linkId, String phone) async {
try {
final checkin = await jusa.checkins.create({
'link': linkId,
'lat': -17.8252,
'lng': 31.0522,
'accuracy_m': 25,
'phone': phone,
'choice': 'airtime',
}, RequestOptions(idempotencyKey: 'checkin-$linkId'));
print('${checkin.status} ${checkin.distanceM}');
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def check_in_at_clinic(link_id, phone)
checkin = Jusa::Checkin.create({
link: link_id,
lat: -17.8252,
lng: 31.0522,
accuracy_m: 25,
phone: phone,
choice: "airtime",
}, idempotency_key: "checkin-#{link_id}")
puts "#{checkin.status} #{checkin.distance_m}"
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/checkins \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: checkin-lnk_…" \
-H "Content-Type: application/json" \
-d '{
"link": "lnk_…",
"lat": -17.8252,
"lng": 31.0522,
"accuracy_m": 25,
"phone": "0771230000",
"choice": "airtime"
}'
Calls: checkins.create · reward_links.create
Learn to earn data
For Edtech. data: P2 rules: P3
Finish lessons, earn data bundles. Live data bundles ship in P2; test mode has a simulated list.
- List a data product's bundles.
- Reward with type=data and a bundle_id.
Python
def reward_course_completion(course_completion_id: str, phone: str) -> None:
try:
# The bundles to choose from:
jusa.Product.list_bundles("econet-data-usd")
jusa.Reward.create(
program="prg_…",
completion_id=f"course-{course_completion_id}",
recipient={"phone": phone},
type="data",
bundle_id="econet-1gb-30d",
idempotency_key=f"course-{course_completion_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function rewardCourseCompletion(courseCompletionId, phone) {
try {
// The bundles to choose from:
await jusa.products.listBundles('econet-data-usd');
await jusa.rewards.create({
program: 'prg_…',
completion_id: `course-${courseCompletionId}`,
recipient: { phone },
type: 'data',
bundle_id: 'econet-1gb-30d',
}, { idempotencyKey: `course-${courseCompletionId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function rewardCourseCompletion(\Jusa\JusaClient $jusa, string $courseCompletionId, string $phone): void
{
try {
// The bundles to choose from:
$jusa->products->listBundles('econet-data-usd');
$jusa->rewards->create([
'program' => 'prg_…',
'completion_id' => "course-{$courseCompletionId}",
'recipient' => ['phone' => $phone],
'type' => 'data',
'bundle_id' => 'econet-1gb-30d',
], ['idempotency_key' => "course-{$courseCompletionId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func rewardCourseCompletion(ctx context.Context, courseCompletionID, phone string) error {
// The bundles to choose from:
_, err := jusaClient.Products.ListBundles(ctx, "econet-data-usd", nil)
if err != nil {
return fmt.Errorf("products.list_bundles: %w", err)
}
_, err = jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_…",
"completion_id": "course-" + courseCompletionID,
"recipient": jusa.Params{"phone": phone},
"type": "data",
"bundle_id": "econet-1gb-30d",
}, jusa.WithIdempotencyKey("course-"+courseCompletionID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
return nil
}
Java
void rewardCourseCompletion(String courseCompletionId, String phone) throws JusaException {
try {
// The bundles to choose from:
jusa.products().listBundles("econet-data-usd");
jusa.rewards().create(Params.of(
"program", "prg_…",
"completion_id", "course-" + courseCompletionId,
"recipient", Map.of("phone", phone),
"type", "data",
"bundle_id", "econet-1gb-30d"
), RequestOptions.idempotencyKey("course-" + courseCompletionId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task RewardCourseCompletionAsync(string courseCompletionId, string phone)
{
try
{
// The bundles to choose from:
await jusa.Products.ListBundlesAsync("econet-data-usd");
await jusa.Rewards.CreateAsync(new
{
program = "prg_…",
completion_id = $"course-{courseCompletionId}",
recipient = new { phone = phone },
type = "data",
bundle_id = "econet-1gb-30d",
}, new RequestOptions { IdempotencyKey = $"course-{courseCompletionId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> rewardCourseCompletion(String courseCompletionId, String phone) async {
try {
// The bundles to choose from:
await jusa.products.listBundles('econet-data-usd');
await jusa.rewards.create({
'program': 'prg_…',
'completion_id': 'course-$courseCompletionId',
'recipient': {'phone': phone},
'type': 'data',
'bundle_id': 'econet-1gb-30d',
}, RequestOptions(idempotencyKey: 'course-$courseCompletionId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def reward_course_completion(course_completion_id, phone)
# The bundles to choose from:
Jusa::Product.list_bundles("econet-data-usd")
Jusa::Reward.create({
program: "prg_…",
completion_id: "course-#{course_completion_id}",
recipient: { phone: phone },
type: "data",
bundle_id: "econet-1gb-30d",
}, idempotency_key: "course-#{course_completion_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# The bundles to choose from:
curl https://jusa.localhost.co.zw/dev/v1/products/econet-data-usd/bundles \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY"
curl https://jusa.localhost.co.zw/dev/v1/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: course-17" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_…",
"completion_id": "course-17",
"recipient": {"phone": "0771230000"},
"type": "data",
"bundle_id": "econet-1gb-30d"
}'
Calls: products.list_bundles · rewards.create
Exam-season data stipends
For Schools and tutors. data: P2
A weekly stipend through exam season, stopped by deleting the schedule.
- A weekly schedule to the class group.
Python
def schedule_exam_data() -> None:
try:
jusa.Schedule.create(
name="Exam data",
cadence="weekly",
day_of_week=0,
hour=7,
minute=0,
group="grp_…",
product="airtime-usd",
amount="2.00",
idempotency_key="schedule-exam-data",
)
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 scheduleExamData() {
try {
await jusa.schedules.create({
name: 'Exam data',
cadence: 'weekly',
day_of_week: 0,
hour: 7,
minute: 0,
group: 'grp_…',
product: 'airtime-usd',
amount: '2.00',
}, { idempotencyKey: 'schedule-exam-data' });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function scheduleExamData(\Jusa\JusaClient $jusa): void
{
try {
$jusa->schedules->create([
'name' => 'Exam data',
'cadence' => 'weekly',
'day_of_week' => 0,
'hour' => 7,
'minute' => 0,
'group' => 'grp_…',
'product' => 'airtime-usd',
'amount' => '2.00',
], ['idempotency_key' => 'schedule-exam-data']);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func scheduleExamData(ctx context.Context) error {
_, err := jusaClient.Schedules.Create(ctx, jusa.Params{
"name": "Exam data",
"cadence": "weekly",
"day_of_week": 0,
"hour": 7,
"minute": 0,
"group": "grp_…",
"product": "airtime-usd",
"amount": "2.00",
}, jusa.WithIdempotencyKey("schedule-exam-data"))
if err != nil {
return fmt.Errorf("schedules.create: %w", err)
}
return nil
}
Java
void scheduleExamData() throws JusaException {
try {
jusa.schedules().create(Params.of(
"name", "Exam data",
"cadence", "weekly",
"day_of_week", 0,
"hour", 7,
"minute", 0,
"group", "grp_…",
"product", "airtime-usd",
"amount", "2.00"
), RequestOptions.idempotencyKey("schedule-exam-data"));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task ScheduleExamDataAsync()
{
try
{
await jusa.Schedules.CreateAsync(new
{
name = "Exam data",
cadence = "weekly",
day_of_week = 0,
hour = 7,
minute = 0,
group = "grp_…",
product = "airtime-usd",
amount = "2.00",
}, new RequestOptions { IdempotencyKey = "schedule-exam-data" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> scheduleExamData() async {
try {
await jusa.schedules.create({
'name': 'Exam data',
'cadence': 'weekly',
'day_of_week': 0,
'hour': 7,
'minute': 0,
'group': 'grp_…',
'product': 'airtime-usd',
'amount': '2.00',
}, RequestOptions(idempotencyKey: 'schedule-exam-data'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def schedule_exam_data
Jusa::Schedule.create({
name: "Exam data",
cadence: "weekly",
day_of_week: 0,
hour: 7,
minute: 0,
group: "grp_…",
product: "airtime-usd",
amount: "2.00",
}, idempotency_key: "schedule-exam-data")
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/schedules \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: schedule-exam-data" \
-H "Content-Type: application/json" \
-d '{
"name": "Exam data",
"cadence": "weekly",
"day_of_week": 0,
"hour": 7,
"minute": 0,
"group": "grp_…",
"product": "airtime-usd",
"amount": "2.00"
}'
Calls: schedules.create · schedules.delete
A bursary split across data and ZESA
For Bursary funds. data: P2
Two schedules to the same people: airtime for data, ZESA to their meter.
- Recipients carry a meter and a token_phone.
- One airtime and one ZESA schedule.
Python
def schedule_bursary_zesa() -> None:
try:
jusa.Schedule.create(
name="Bursary ZESA",
cadence="monthly",
day_of_month=1,
hour=8,
minute=0,
recipients=["rcp_…"],
product="zesa-usd",
amount="10.00",
idempotency_key="schedule-bursary-zesa",
)
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 scheduleBursaryZesa() {
try {
await jusa.schedules.create({
name: 'Bursary ZESA',
cadence: 'monthly',
day_of_month: 1,
hour: 8,
minute: 0,
recipients: ['rcp_…'],
product: 'zesa-usd',
amount: '10.00',
}, { idempotencyKey: 'schedule-bursary-zesa' });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function scheduleBursaryZesa(\Jusa\JusaClient $jusa): void
{
try {
$jusa->schedules->create([
'name' => 'Bursary ZESA',
'cadence' => 'monthly',
'day_of_month' => 1,
'hour' => 8,
'minute' => 0,
'recipients' => ['rcp_…'],
'product' => 'zesa-usd',
'amount' => '10.00',
], ['idempotency_key' => 'schedule-bursary-zesa']);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func scheduleBursaryZesa(ctx context.Context) error {
_, err := jusaClient.Schedules.Create(ctx, jusa.Params{
"name": "Bursary ZESA",
"cadence": "monthly",
"day_of_month": 1,
"hour": 8,
"minute": 0,
"recipients": []string{"rcp_…"},
"product": "zesa-usd",
"amount": "10.00",
}, jusa.WithIdempotencyKey("schedule-bursary-zesa"))
if err != nil {
return fmt.Errorf("schedules.create: %w", err)
}
return nil
}
Java
void scheduleBursaryZesa() throws JusaException {
try {
jusa.schedules().create(Params.of(
"name", "Bursary ZESA",
"cadence", "monthly",
"day_of_month", 1,
"hour", 8,
"minute", 0,
"recipients", List.of("rcp_…"),
"product", "zesa-usd",
"amount", "10.00"
), RequestOptions.idempotencyKey("schedule-bursary-zesa"));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task ScheduleBursaryZesaAsync()
{
try
{
await jusa.Schedules.CreateAsync(new
{
name = "Bursary ZESA",
cadence = "monthly",
day_of_month = 1,
hour = 8,
minute = 0,
recipients = new[] { "rcp_…" },
product = "zesa-usd",
amount = "10.00",
}, new RequestOptions { IdempotencyKey = "schedule-bursary-zesa" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> scheduleBursaryZesa() async {
try {
await jusa.schedules.create({
'name': 'Bursary ZESA',
'cadence': 'monthly',
'day_of_month': 1,
'hour': 8,
'minute': 0,
'recipients': ['rcp_…'],
'product': 'zesa-usd',
'amount': '10.00',
}, RequestOptions(idempotencyKey: 'schedule-bursary-zesa'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def schedule_bursary_zesa
Jusa::Schedule.create({
name: "Bursary ZESA",
cadence: "monthly",
day_of_month: 1,
hour: 8,
minute: 0,
recipients: ["rcp_…"],
product: "zesa-usd",
amount: "10.00",
}, idempotency_key: "schedule-bursary-zesa")
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/schedules \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: schedule-bursary-zesa" \
-H "Content-Type: application/json" \
-d '{
"name": "Bursary ZESA",
"cadence": "monthly",
"day_of_month": 1,
"hour": 8,
"minute": 0,
"recipients": ["rcp_…"],
"product": "zesa-usd",
"amount": "10.00"
}'
Calls: recipients.create · schedules.create
Gig and rider allowances
For Delivery and ride apps.
Airtime per completed trip, capped per rider per day.
- A per-recipient daily cap on the rider.
- Reward each trip, keyed on the trip id.
Python
def cap_rider_allowance(rider_id: str) -> None:
try:
# Once per rider: at most US$3.00 a day.
jusa.Recipient.update(f"ext:{rider_id}", daily_cap="3.00")
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def pay_trip_allowance(trip_id: str, rider_id: str) -> None:
try:
jusa.Reward.create(
program="prg_trips",
completion_id=f"trip-{trip_id}",
recipient=f"ext:{rider_id}",
amount="0.50",
idempotency_key=f"trip-{trip_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function capRiderAllowance(riderId) {
try {
// Once per rider: at most US$3.00 a day.
await jusa.recipients.update(`ext:${riderId}`, { daily_cap: '3.00' });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function payTripAllowance(tripId, riderId) {
try {
await jusa.rewards.create({
program: 'prg_trips',
completion_id: `trip-${tripId}`,
recipient: `ext:${riderId}`,
amount: '0.50',
}, { idempotencyKey: `trip-${tripId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function capRiderAllowance(\Jusa\JusaClient $jusa, string $riderId): void
{
try {
// Once per rider: at most US$3.00 a day.
$jusa->recipients->update("ext:{$riderId}", ['daily_cap' => '3.00']);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function payTripAllowance(\Jusa\JusaClient $jusa, string $tripId, string $riderId): void
{
try {
$jusa->rewards->create([
'program' => 'prg_trips',
'completion_id' => "trip-{$tripId}",
'recipient' => "ext:{$riderId}",
'amount' => '0.50',
], ['idempotency_key' => "trip-{$tripId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func capRiderAllowance(ctx context.Context, riderID string) error {
// Once per rider: at most US$3.00 a day.
_, err := jusaClient.Recipients.Update(ctx, "ext:"+riderID, jusa.Params{
"daily_cap": "3.00",
})
if err != nil {
return fmt.Errorf("recipients.update: %w", err)
}
return nil
}
func payTripAllowance(ctx context.Context, tripID, riderID string) error {
_, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_trips",
"completion_id": "trip-" + tripID,
"recipient": "ext:" + riderID,
"amount": "0.50",
}, jusa.WithIdempotencyKey("trip-"+tripID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
return nil
}
Java
void capRiderAllowance(String riderId) throws JusaException {
try {
// Once per rider: at most US$3.00 a day.
jusa.recipients().update("ext:" + riderId, Params.of("daily_cap", "3.00"));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void payTripAllowance(String tripId, String riderId) throws JusaException {
try {
jusa.rewards().create(Params.of(
"program", "prg_trips",
"completion_id", "trip-" + tripId,
"recipient", "ext:" + riderId,
"amount", "0.50"
), RequestOptions.idempotencyKey("trip-" + tripId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task CapRiderAllowanceAsync(string riderId)
{
try
{
// Once per rider: at most US$3.00 a day.
await jusa.Recipients.UpdateAsync($"ext:{riderId}", new { daily_cap = "3.00" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task PayTripAllowanceAsync(string tripId, string riderId)
{
try
{
await jusa.Rewards.CreateAsync(new
{
program = "prg_trips",
completion_id = $"trip-{tripId}",
recipient = $"ext:{riderId}",
amount = "0.50",
}, new RequestOptions { IdempotencyKey = $"trip-{tripId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> capRiderAllowance(String riderId) async {
try {
// Once per rider: at most US$3.00 a day.
await jusa.recipients.update('ext:$riderId', {'daily_cap': '3.00'});
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> payTripAllowance(String tripId, String riderId) async {
try {
await jusa.rewards.create({
'program': 'prg_trips',
'completion_id': 'trip-$tripId',
'recipient': 'ext:$riderId',
'amount': '0.50',
}, RequestOptions(idempotencyKey: 'trip-$tripId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def cap_rider_allowance(rider_id)
# Once per rider: at most US$3.00 a day.
Jusa::Recipient.update("ext:#{rider_id}", daily_cap: "3.00")
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def pay_trip_allowance(trip_id, rider_id)
Jusa::Reward.create({
program: "prg_trips",
completion_id: "trip-#{trip_id}",
recipient: "ext:#{rider_id}",
amount: "0.50",
}, idempotency_key: "trip-#{trip_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# Once per rider: at most US$3.00 a day.
curl -X PATCH https://jusa.localhost.co.zw/dev/v1/recipients/ext:rider-4 \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"daily_cap": "3.00"}'
curl https://jusa.localhost.co.zw/dev/v1/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: trip-77120" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_trips",
"completion_id": "trip-77120",
"recipient": "ext:rider-4",
"amount": "0.50"
}'
Calls: recipients.update · rewards.create
Employer ZESA as a benefit
For Employers.
Workforce as it is in the Jusa app: departments, plans, allocation and the GL journal.
- Allocate to people by department.
- Pull the journal for your GL.
Python
def download_gl_journal() -> None:
try:
# The month's GL journal, as CSV for your accounting system:
jusa.Workforce.journal(from_="2026-09-01", to="2026-09-30", format="csv")
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 downloadGlJournal() {
try {
// The month's GL journal, as CSV for your accounting system:
await jusa.workforce.journal({
from: '2026-09-01',
to: '2026-09-30',
format: 'csv',
});
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function downloadGlJournal(\Jusa\JusaClient $jusa): void
{
try {
// The month's GL journal, as CSV for your accounting system:
$jusa->workforce->journal([
'from' => '2026-09-01',
'to' => '2026-09-30',
'format' => 'csv',
]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func downloadGlJournal(ctx context.Context) error {
// The month's GL journal, as CSV for your accounting system:
_, err := jusaClient.Workforce.Journal(ctx, jusa.Params{
"from": "2026-09-01",
"to": "2026-09-30",
"format": "csv",
})
if err != nil {
return fmt.Errorf("workforce.journal: %w", err)
}
return nil
}
Java
void downloadGlJournal() throws JusaException {
try {
// The month's GL journal, as CSV for your accounting system:
jusa.workforce().journal(Params.of(
"from", "2026-09-01",
"to", "2026-09-30",
"format", "csv"
));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task DownloadGlJournalAsync()
{
try
{
// The month's GL journal, as CSV for your accounting system:
await jusa.Workforce.JournalAsync(new
{
from = "2026-09-01",
to = "2026-09-30",
format = "csv",
});
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> downloadGlJournal() async {
try {
// The month's GL journal, as CSV for your accounting system:
await jusa.workforce.journal({
'from': '2026-09-01',
'to': '2026-09-30',
'format': 'csv',
});
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def download_gl_journal
# The month's GL journal, as CSV for your accounting system:
Jusa::Workforce.journal(from: "2026-09-01", to: "2026-09-30", format: "csv")
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# The month's GL journal, as CSV for your accounting system:
curl -G https://jusa.localhost.co.zw/dev/v1/workforce/journal \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-d from=2026-09-01 \
-d to=2026-09-30 \
-d format=csv
Calls: workforce.allocate · workforce.journal · meters.retrieve
Pay per verified sale
For Field sales teams.
Escrow the commission until the return window closes; void it if the sale comes back.
- A program with hold.mode=escrow and auto_release_after.
- Void on a return.
Python
def create_commission_program() -> None:
try:
jusa.Program.create(
name="Sales commission",
default_amount="1.00",
budget="200.00",
hold={"mode": "escrow", "auto_release_after": "14d"},
idempotency_key="program-sales-commission",
)
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 createCommissionProgram() {
try {
await jusa.programs.create({
name: 'Sales commission',
default_amount: '1.00',
budget: '200.00',
hold: { mode: 'escrow', auto_release_after: '14d' },
}, { idempotencyKey: 'program-sales-commission' });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function createCommissionProgram(\Jusa\JusaClient $jusa): void
{
try {
$jusa->programs->create([
'name' => 'Sales commission',
'default_amount' => '1.00',
'budget' => '200.00',
'hold' => ['mode' => 'escrow', 'auto_release_after' => '14d'],
], ['idempotency_key' => 'program-sales-commission']);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func createCommissionProgram(ctx context.Context) error {
_, err := jusaClient.Programs.Create(ctx, jusa.Params{
"name": "Sales commission",
"default_amount": "1.00",
"budget": "200.00",
"hold": jusa.Params{"mode": "escrow", "auto_release_after": "14d"},
}, jusa.WithIdempotencyKey("program-sales-commission"))
if err != nil {
return fmt.Errorf("programs.create: %w", err)
}
return nil
}
Java
void createCommissionProgram() throws JusaException {
try {
jusa.programs().create(Params.of(
"name", "Sales commission",
"default_amount", "1.00",
"budget", "200.00",
"hold", Map.of("mode", "escrow", "auto_release_after", "14d")
), RequestOptions.idempotencyKey("program-sales-commission"));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task CreateCommissionProgramAsync()
{
try
{
await jusa.Programs.CreateAsync(new
{
name = "Sales commission",
default_amount = "1.00",
budget = "200.00",
hold = new { mode = "escrow", auto_release_after = "14d" },
}, new RequestOptions { IdempotencyKey = "program-sales-commission" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> createCommissionProgram() async {
try {
await jusa.programs.create({
'name': 'Sales commission',
'default_amount': '1.00',
'budget': '200.00',
'hold': {'mode': 'escrow', 'auto_release_after': '14d'},
}, RequestOptions(idempotencyKey: 'program-sales-commission'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def create_commission_program
Jusa::Program.create({
name: "Sales commission",
default_amount: "1.00",
budget: "200.00",
hold: { mode: "escrow", auto_release_after: "14d" },
}, idempotency_key: "program-sales-commission")
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/programs \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: program-sales-commission" \
-H "Content-Type: application/json" \
-d '{
"name": "Sales commission",
"default_amount": "1.00",
"budget": "200.00",
"hold": {"mode": "escrow", "auto_release_after": "14d"}
}'
Calls: programs.create · rewards.create · rewards.void
Outage apology credit
For Banks and ISPs.
One batch to every affected customer, safe to retry with one Idempotency-Key.
- Build the items from your incident list.
- Create the batch with an idempotency key.
Python
def send_outage_apology(incident_id: str) -> None:
try:
jusa.Batch.create(
title="Sorry for Tuesday",
items=[
{
"target": "0772123456",
"amount": "1.00",
"client_reference": f"incident-{incident_id}-0772123456",
},
{
"target": "0712654321",
"amount": "1.00",
"client_reference": f"incident-{incident_id}-0712654321",
},
],
idempotency_key=f"incident-{incident_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function sendOutageApology(incidentId) {
try {
await jusa.batches.create({
title: 'Sorry for Tuesday',
items: [
{
target: '0772123456',
amount: '1.00',
client_reference: `incident-${incidentId}-0772123456`,
},
{
target: '0712654321',
amount: '1.00',
client_reference: `incident-${incidentId}-0712654321`,
},
],
}, { idempotencyKey: `incident-${incidentId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function sendOutageApology(\Jusa\JusaClient $jusa, string $incidentId): void
{
try {
$jusa->batches->create([
'title' => 'Sorry for Tuesday',
'items' => [
[
'target' => '0772123456',
'amount' => '1.00',
'client_reference' => "incident-{$incidentId}-0772123456",
],
[
'target' => '0712654321',
'amount' => '1.00',
'client_reference' => "incident-{$incidentId}-0712654321",
],
],
], ['idempotency_key' => "incident-{$incidentId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func sendOutageApology(ctx context.Context, incidentID string) error {
_, err := jusaClient.Batches.Create(ctx, jusa.Params{
"title": "Sorry for Tuesday",
"items": []jusa.Params{
jusa.Params{
"target": "0772123456",
"amount": "1.00",
"client_reference": "incident-" + incidentID + "-0772123456",
},
jusa.Params{
"target": "0712654321",
"amount": "1.00",
"client_reference": "incident-" + incidentID + "-0712654321",
},
},
}, jusa.WithIdempotencyKey("incident-"+incidentID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("batches.create: %w", err)
}
return nil
}
Java
void sendOutageApology(String incidentId) throws JusaException {
try {
jusa.batches().create(Params.of(
"title", "Sorry for Tuesday",
"items", List.of(
Map.of(
"target", "0772123456",
"amount", "1.00",
"client_reference", "incident-" + incidentId + "-0772123456"
),
Map.of(
"target", "0712654321",
"amount", "1.00",
"client_reference", "incident-" + incidentId + "-0712654321"
)
)
), RequestOptions.idempotencyKey("incident-" + incidentId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SendOutageApologyAsync(string incidentId)
{
try
{
await jusa.Batches.CreateAsync(new
{
title = "Sorry for Tuesday",
items = new object[]
{
new
{
target = "0772123456",
amount = "1.00",
client_reference = $"incident-{incidentId}-0772123456",
},
new
{
target = "0712654321",
amount = "1.00",
client_reference = $"incident-{incidentId}-0712654321",
},
},
}, new RequestOptions { IdempotencyKey = $"incident-{incidentId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> sendOutageApology(String incidentId) async {
try {
await jusa.batches.create({
'title': 'Sorry for Tuesday',
'items': [
{
'target': '0772123456',
'amount': '1.00',
'client_reference': 'incident-$incidentId-0772123456',
},
{
'target': '0712654321',
'amount': '1.00',
'client_reference': 'incident-$incidentId-0712654321',
},
],
}, RequestOptions(idempotencyKey: 'incident-$incidentId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def send_outage_apology(incident_id)
Jusa::Batch.create({
title: "Sorry for Tuesday",
items: [
{
target: "0772123456",
amount: "1.00",
client_reference: "incident-#{incident_id}-0772123456",
},
{
target: "0712654321",
amount: "1.00",
client_reference: "incident-#{incident_id}-0712654321",
},
],
}, idempotency_key: "incident-#{incident_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/batches \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: incident-2026-10-07" \
-H "Content-Type: application/json" \
-d '{
"title": "Sorry for Tuesday",
"items": [
{
"target": "0772123456",
"amount": "1.00",
"client_reference": "incident-2026-10-07-0772123456"
},
{
"target": "0712654321",
"amount": "1.00",
"client_reference": "incident-2026-10-07-0712654321"
}
]
}'
Calls: batches.create
Diaspora: send ZESA or airtime home
For Remittance apps.
The sender pays by card on a checkout session; you get the attribution and the token. Recurring by card is not possible (there is no stored card): use your own Jusa Credit and a schedule.
- Create a checkout session; send the payer to its url.
- Hear checkout.session.fulfilled.
Python
def start_zesa_checkout(meter_number: str, token_phone: str, order_id: str) -> None:
try:
checkout_session = jusa.CheckoutSession.create(
type="zesa",
target=meter_number,
amount="20.00",
currency="USD",
token_phone=token_phone,
success_url="https://app.example/thanks",
cancel_url="https://app.example/basket",
client_reference=f"order-{order_id}",
idempotency_key=f"order-{order_id}",
)
# Send the payer to the session's url.
print(checkout_session.url)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function startZesaCheckout(meterNumber, tokenPhone, orderId) {
try {
const checkoutSession = await jusa.checkoutSessions.create({
type: 'zesa',
target: meterNumber,
amount: '20.00',
currency: 'USD',
token_phone: tokenPhone,
success_url: 'https://app.example/thanks',
cancel_url: 'https://app.example/basket',
client_reference: `order-${orderId}`,
}, { idempotencyKey: `order-${orderId}` });
// Send the payer to the session's url.
console.log(checkoutSession.url);
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function startZesaCheckout(\Jusa\JusaClient $jusa, string $meterNumber, string $tokenPhone, string $orderId): void
{
try {
$checkoutSession = $jusa->checkoutSessions->create([
'type' => 'zesa',
'target' => $meterNumber,
'amount' => '20.00',
'currency' => 'USD',
'token_phone' => $tokenPhone,
'success_url' => 'https://app.example/thanks',
'cancel_url' => 'https://app.example/basket',
'client_reference' => "order-{$orderId}",
], ['idempotency_key' => "order-{$orderId}"]);
// Send the payer to the session's url.
echo $checkoutSession->url, "\n";
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func startZesaCheckout(ctx context.Context, meterNumber, tokenPhone, orderID string) error {
checkoutSession, err := jusaClient.CheckoutSessions.Create(ctx, jusa.Params{
"type": "zesa",
"target": meterNumber,
"amount": "20.00",
"currency": "USD",
"token_phone": tokenPhone,
"success_url": "https://app.example/thanks",
"cancel_url": "https://app.example/basket",
"client_reference": "order-" + orderID,
}, jusa.WithIdempotencyKey("order-"+orderID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("checkout_sessions.create: %w", err)
}
// Send the payer to the session's url.
fmt.Println(checkoutSession.URL)
return nil
}
Java
void startZesaCheckout(String meterNumber, String tokenPhone, String orderId) throws JusaException {
try {
var checkoutSession = jusa.checkoutSessions().create(Params.of(
"type", "zesa",
"target", meterNumber,
"amount", "20.00",
"currency", "USD",
"token_phone", tokenPhone,
"success_url", "https://app.example/thanks",
"cancel_url", "https://app.example/basket",
"client_reference", "order-" + orderId
), RequestOptions.idempotencyKey("order-" + orderId));
// Send the payer to the session's url.
System.out.println(checkoutSession.getUrl());
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task StartZesaCheckoutAsync(string meterNumber, string tokenPhone, string orderId)
{
try
{
var checkoutSession = await jusa.CheckoutSessions.CreateAsync(new
{
type = "zesa",
target = meterNumber,
amount = "20.00",
currency = "USD",
token_phone = tokenPhone,
success_url = "https://app.example/thanks",
cancel_url = "https://app.example/basket",
client_reference = $"order-{orderId}",
}, new RequestOptions { IdempotencyKey = $"order-{orderId}" });
// Send the payer to the session's url.
Console.WriteLine($"{checkoutSession.Url}");
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> startZesaCheckout(String meterNumber, String tokenPhone, String orderId) async {
try {
final checkoutSession = await jusa.checkoutSessions.create({
'type': 'zesa',
'target': meterNumber,
'amount': '20.00',
'currency': 'USD',
'token_phone': tokenPhone,
'success_url': 'https://app.example/thanks',
'cancel_url': 'https://app.example/basket',
'client_reference': 'order-$orderId',
}, RequestOptions(idempotencyKey: 'order-$orderId'));
// Send the payer to the session's url.
print('${checkoutSession.url}');
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def start_zesa_checkout(meter_number, token_phone, order_id)
checkout_session = Jusa::CheckoutSession.create({
type: "zesa",
target: meter_number,
amount: "20.00",
currency: "USD",
token_phone: token_phone,
success_url: "https://app.example/thanks",
cancel_url: "https://app.example/basket",
client_reference: "order-#{order_id}",
}, idempotency_key: "order-#{order_id}")
# Send the payer to the session's url.
puts "#{checkout_session.url}"
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/checkout-sessions \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: order-8812" \
-H "Content-Type: application/json" \
-d '{
"type": "zesa",
"target": "37261502217",
"amount": "20.00",
"currency": "USD",
"token_phone": "0772123456",
"success_url": "https://app.example/thanks",
"cancel_url": "https://app.example/basket",
"client_reference": "order-8812"
}'
# Send the payer to the session's url.
Calls: checkout_sessions.create · checkout_sessions.retrieve · meters.retrieve
Landlord and tenant split-meter settlement
For Property apps.
Each tenant pays their share by card; the receipt proves what went to the meter.
- A checkout session per tenant.
- Share the receipt of the delivered send.
Python
def show_meter_receipt(send_id: str) -> None:
try:
# The meter, its owner and the units that went to it:
jusa.Send.receipt(send_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 showMeterReceipt(sendId) {
try {
// The meter, its owner and the units that went to it:
await jusa.sends.receipt(sendId);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function showMeterReceipt(\Jusa\JusaClient $jusa, string $sendId): void
{
try {
// The meter, its owner and the units that went to it:
$jusa->sends->receipt($sendId);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func showMeterReceipt(ctx context.Context, sendID string) error {
// The meter, its owner and the units that went to it:
_, err := jusaClient.Sends.Receipt(ctx, sendID, nil)
if err != nil {
return fmt.Errorf("sends.receipt: %w", err)
}
return nil
}
Java
void showMeterReceipt(String sendId) throws JusaException {
try {
// The meter, its owner and the units that went to it:
jusa.sends().receipt(sendId);
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task ShowMeterReceiptAsync(string sendId)
{
try
{
// The meter, its owner and the units that went to it:
await jusa.Sends.ReceiptAsync(sendId);
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> showMeterReceipt(String sendId) async {
try {
// The meter, its owner and the units that went to it:
await jusa.sends.receipt(sendId);
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def show_meter_receipt(send_id)
# The meter, its owner and the units that went to it:
Jusa::Send.receipt(send_id)
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
curl
# The meter, its owner and the units that went to it:
curl https://jusa.localhost.co.zw/dev/v1/sends/snd_…/receipt \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY"
Calls: checkout_sessions.create · sends.receipt
Checkout cashback as airtime
For E-commerce. data: P2
A percentage back as airtime after each order, from a program budget.
- Reward on order completion, keyed on the order id.
Python
def pay_cashback(order_id: str, phone: str, cashback_amount: str) -> None:
try:
jusa.Reward.create(
program="prg_cashback",
completion_id=f"order-{order_id}",
recipient={"phone": phone},
amount=cashback_amount,
idempotency_key=f"cashback-order-{order_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function payCashback(orderId, phone, cashbackAmount) {
try {
await jusa.rewards.create({
program: 'prg_cashback',
completion_id: `order-${orderId}`,
recipient: { phone },
amount: cashbackAmount,
}, { idempotencyKey: `cashback-order-${orderId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function payCashback(\Jusa\JusaClient $jusa, string $orderId, string $phone, string $cashbackAmount): void
{
try {
$jusa->rewards->create([
'program' => 'prg_cashback',
'completion_id' => "order-{$orderId}",
'recipient' => ['phone' => $phone],
'amount' => $cashbackAmount,
], ['idempotency_key' => "cashback-order-{$orderId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func payCashback(ctx context.Context, orderID, phone, cashbackAmount string) error {
_, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_cashback",
"completion_id": "order-" + orderID,
"recipient": jusa.Params{"phone": phone},
"amount": cashbackAmount,
}, jusa.WithIdempotencyKey("cashback-order-"+orderID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
return nil
}
Java
void payCashback(String orderId, String phone, String cashbackAmount) throws JusaException {
try {
jusa.rewards().create(Params.of(
"program", "prg_cashback",
"completion_id", "order-" + orderId,
"recipient", Map.of("phone", phone),
"amount", cashbackAmount
), RequestOptions.idempotencyKey("cashback-order-" + orderId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task PayCashbackAsync(string orderId, string phone, string cashbackAmount)
{
try
{
await jusa.Rewards.CreateAsync(new
{
program = "prg_cashback",
completion_id = $"order-{orderId}",
recipient = new { phone = phone },
amount = cashbackAmount,
}, new RequestOptions { IdempotencyKey = $"cashback-order-{orderId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> payCashback(String orderId, String phone, String cashbackAmount) async {
try {
await jusa.rewards.create({
'program': 'prg_cashback',
'completion_id': 'order-$orderId',
'recipient': {'phone': phone},
'amount': cashbackAmount,
}, RequestOptions(idempotencyKey: 'cashback-order-$orderId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def pay_cashback(order_id, phone, cashback_amount)
Jusa::Reward.create({
program: "prg_cashback",
completion_id: "order-#{order_id}",
recipient: { phone: phone },
amount: cashback_amount,
}, idempotency_key: "cashback-order-#{order_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: cashback-order-8812" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_cashback",
"completion_id": "order-8812",
"recipient": {"phone": "0771230000"},
"amount": "0.84"
}'
Calls: rewards.create
Solar or IoT ZESA auto-buy
For Smart-plug and monitor vendors.
The device reads the token from the send.delivered webhook. token_phone is required: ZETDC needs a number to notify. Cap the device's key.
- A restricted key with tokens:read and a daily spend cap.
- Send ZESA when the monitor says so; read the token from the webhook.
Python
def buy_zesa_for_reading(meter_number: str, token_phone: str, reading_id: str) -> None:
try:
jusa.Send.create(
type="zesa",
target=meter_number,
amount="5.00",
token_phone=token_phone,
client_reference=f"auto-reading-{reading_id}",
idempotency_key=f"auto-reading-{reading_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function buyZesaForReading(meterNumber, tokenPhone, readingId) {
try {
await jusa.sends.create({
type: 'zesa',
target: meterNumber,
amount: '5.00',
token_phone: tokenPhone,
client_reference: `auto-reading-${readingId}`,
}, { idempotencyKey: `auto-reading-${readingId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function buyZesaForReading(\Jusa\JusaClient $jusa, string $meterNumber, string $tokenPhone, string $readingId): void
{
try {
$jusa->sends->create([
'type' => 'zesa',
'target' => $meterNumber,
'amount' => '5.00',
'token_phone' => $tokenPhone,
'client_reference' => "auto-reading-{$readingId}",
], ['idempotency_key' => "auto-reading-{$readingId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func buyZesaForReading(ctx context.Context, meterNumber, tokenPhone, readingID string) error {
_, err := jusaClient.Sends.Create(ctx, jusa.Params{
"type": "zesa",
"target": meterNumber,
"amount": "5.00",
"token_phone": tokenPhone,
"client_reference": "auto-reading-" + readingID,
}, jusa.WithIdempotencyKey("auto-reading-"+readingID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("sends.create: %w", err)
}
return nil
}
Java
void buyZesaForReading(String meterNumber, String tokenPhone, String readingId) throws JusaException {
try {
jusa.sends().create(Params.of(
"type", "zesa",
"target", meterNumber,
"amount", "5.00",
"token_phone", tokenPhone,
"client_reference", "auto-reading-" + readingId
), RequestOptions.idempotencyKey("auto-reading-" + readingId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task BuyZesaForReadingAsync(string meterNumber, string tokenPhone, string readingId)
{
try
{
await jusa.Sends.CreateAsync(new
{
type = "zesa",
target = meterNumber,
amount = "5.00",
token_phone = tokenPhone,
client_reference = $"auto-reading-{readingId}",
}, new RequestOptions { IdempotencyKey = $"auto-reading-{readingId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> buyZesaForReading(String meterNumber, String tokenPhone, String readingId) async {
try {
await jusa.sends.create({
'type': 'zesa',
'target': meterNumber,
'amount': '5.00',
'token_phone': tokenPhone,
'client_reference': 'auto-reading-$readingId',
}, RequestOptions(idempotencyKey: 'auto-reading-$readingId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def buy_zesa_for_reading(meter_number, token_phone, reading_id)
Jusa::Send.create({
type: "zesa",
target: meter_number,
amount: "5.00",
token_phone: token_phone,
client_reference: "auto-reading-#{reading_id}",
}, idempotency_key: "auto-reading-#{reading_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/sends \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: auto-reading-9921" \
-H "Content-Type: application/json" \
-d '{
"type": "zesa",
"target": "37261502217",
"amount": "5.00",
"token_phone": "0772123456",
"client_reference": "auto-reading-9921"
}'
Calls: keys.create · sends.create · webhook_endpoints.create
Availability-aware buying
For Any ZESA seller.
Check ZESA before promising a token now; queue with max_hold, or fail fast with on_zesa_down=fail.
- Read /status or hear zesa.availability.*.
- Choose on_zesa_down and max_hold per send.
Python
def buy_zesa_when_available(meter_number: str, token_phone: str, order_id: str) -> None:
try:
status = jusa.Status.retrieve()
print(status.zesa.state)
# Queue it while ZESA is down, for up to 6 hours:
jusa.Send.create(
type="zesa",
target=meter_number,
amount="10.00",
token_phone=token_phone,
on_zesa_down="queue",
max_hold="6h",
client_reference=f"order-{order_id}",
idempotency_key=f"order-{order_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function buyZesaWhenAvailable(meterNumber, tokenPhone, orderId) {
try {
const status = await jusa.status.retrieve();
console.log(status.zesa.state);
// Queue it while ZESA is down, for up to 6 hours:
await jusa.sends.create({
type: 'zesa',
target: meterNumber,
amount: '10.00',
token_phone: tokenPhone,
on_zesa_down: 'queue',
max_hold: '6h',
client_reference: `order-${orderId}`,
}, { idempotencyKey: `order-${orderId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function buyZesaWhenAvailable(\Jusa\JusaClient $jusa, string $meterNumber, string $tokenPhone, string $orderId): void
{
try {
$status = $jusa->status->retrieve();
echo $status->zesa->state, "\n";
// Queue it while ZESA is down, for up to 6 hours:
$jusa->sends->create([
'type' => 'zesa',
'target' => $meterNumber,
'amount' => '10.00',
'token_phone' => $tokenPhone,
'on_zesa_down' => 'queue',
'max_hold' => '6h',
'client_reference' => "order-{$orderId}",
], ['idempotency_key' => "order-{$orderId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func buyZesaWhenAvailable(ctx context.Context, meterNumber, tokenPhone, orderID string) error {
status, err := jusaClient.Status.Retrieve(ctx, nil)
if err != nil {
return fmt.Errorf("status.retrieve: %w", err)
}
fmt.Println(status.Zesa.State)
// Queue it while ZESA is down, for up to 6 hours:
_, err = jusaClient.Sends.Create(ctx, jusa.Params{
"type": "zesa",
"target": meterNumber,
"amount": "10.00",
"token_phone": tokenPhone,
"on_zesa_down": "queue",
"max_hold": "6h",
"client_reference": "order-" + orderID,
}, jusa.WithIdempotencyKey("order-"+orderID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("sends.create: %w", err)
}
return nil
}
Java
void buyZesaWhenAvailable(String meterNumber, String tokenPhone, String orderId) throws JusaException {
try {
var status = jusa.status().retrieve();
System.out.println(status.getZesa().getState());
// Queue it while ZESA is down, for up to 6 hours:
jusa.sends().create(Params.of(
"type", "zesa",
"target", meterNumber,
"amount", "10.00",
"token_phone", tokenPhone,
"on_zesa_down", "queue",
"max_hold", "6h",
"client_reference", "order-" + orderId
), RequestOptions.idempotencyKey("order-" + orderId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task BuyZesaWhenAvailableAsync(string meterNumber, string tokenPhone, string orderId)
{
try
{
var status = await jusa.Status.RetrieveAsync();
Console.WriteLine($"{status.Zesa?.State}");
// Queue it while ZESA is down, for up to 6 hours:
await jusa.Sends.CreateAsync(new
{
type = "zesa",
target = meterNumber,
amount = "10.00",
token_phone = tokenPhone,
on_zesa_down = "queue",
max_hold = "6h",
client_reference = $"order-{orderId}",
}, new RequestOptions { IdempotencyKey = $"order-{orderId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> buyZesaWhenAvailable(String meterNumber, String tokenPhone, String orderId) async {
try {
final status = await jusa.status.retrieve();
print('${status.zesa.state}');
// Queue it while ZESA is down, for up to 6 hours:
await jusa.sends.create({
'type': 'zesa',
'target': meterNumber,
'amount': '10.00',
'token_phone': tokenPhone,
'on_zesa_down': 'queue',
'max_hold': '6h',
'client_reference': 'order-$orderId',
}, RequestOptions(idempotencyKey: 'order-$orderId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def buy_zesa_when_available(meter_number, token_phone, order_id)
status = Jusa::Status.retrieve
puts "#{status.zesa.state}"
# Queue it while ZESA is down, for up to 6 hours:
Jusa::Send.create({
type: "zesa",
target: meter_number,
amount: "10.00",
token_phone: token_phone,
on_zesa_down: "queue",
max_hold: "6h",
client_reference: "order-#{order_id}",
}, idempotency_key: "order-#{order_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/status \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY"
# Queue it while ZESA is down, for up to 6 hours:
curl https://jusa.localhost.co.zw/dev/v1/sends \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: order-8812" \
-H "Content-Type: application/json" \
-d '{
"type": "zesa",
"target": "37261502217",
"amount": "10.00",
"token_phone": "0772123456",
"on_zesa_down": "queue",
"max_hold": "6h",
"client_reference": "order-8812"
}'
Calls: status.retrieve · status.history · sends.create
Band-aware ZESA quotes
For Budgeting apps.
Show how many units the money buys now and after the monthly reset.
- Quote with the meter.
Python
def quote_zesa_units(meter_number: str) -> None:
try:
quote = jusa.Quote.create(
product="zesa-usd",
amount="20.00",
target=meter_number,
)
print(quote.zesa.units_now, quote.zesa.units_after_reset, quote.zesa.resets_on)
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 quoteZesaUnits(meterNumber) {
try {
const quote = await jusa.quotes.create({
product: 'zesa-usd',
amount: '20.00',
target: meterNumber,
});
console.log(quote.zesa.units_now, quote.zesa.units_after_reset, quote.zesa.resets_on);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function quoteZesaUnits(\Jusa\JusaClient $jusa, string $meterNumber): void
{
try {
$quote = $jusa->quotes->create([
'product' => 'zesa-usd',
'amount' => '20.00',
'target' => $meterNumber,
]);
echo $quote->zesa->units_now, ' ', $quote->zesa->units_after_reset, ' ', $quote->zesa->resets_on, "\n";
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func quoteZesaUnits(ctx context.Context, meterNumber string) error {
quote, err := jusaClient.Quotes.Create(ctx, jusa.Params{
"product": "zesa-usd",
"amount": "20.00",
"target": meterNumber,
})
if err != nil {
return fmt.Errorf("quotes.create: %w", err)
}
fmt.Println(quote.Zesa.UnitsNow, quote.Zesa.UnitsAfterReset, quote.Zesa.ResetsOn)
return nil
}
Java
void quoteZesaUnits(String meterNumber) throws JusaException {
try {
var quote = jusa.quotes().create(Params.of(
"product", "zesa-usd",
"amount", "20.00",
"target", meterNumber
));
System.out.println(quote.getZesa().getUnitsNow() + " " + quote.getZesa().getUnitsAfterReset() + " " + quote.getZesa().getResetsOn());
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task QuoteZesaUnitsAsync(string meterNumber)
{
try
{
var quote = await jusa.Quotes.CreateAsync(new
{
product = "zesa-usd",
amount = "20.00",
target = meterNumber,
});
Console.WriteLine($"{quote.Zesa?.UnitsNow} {quote.Zesa?.UnitsAfterReset} {quote.Zesa?.ResetsOn}");
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> quoteZesaUnits(String meterNumber) async {
try {
final quote = await jusa.quotes.create({
'product': 'zesa-usd',
'amount': '20.00',
'target': meterNumber,
});
print('${quote.zesa?.unitsNow} ${quote.zesa?.unitsAfterReset} ${quote.zesa?.resetsOn}');
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def quote_zesa_units(meter_number)
quote = Jusa::Quote.create(product: "zesa-usd", amount: "20.00", target: meter_number)
puts "#{quote.zesa.units_now} #{quote.zesa.units_after_reset} #{quote.zesa.resets_on}"
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/quotes \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"product": "zesa-usd", "amount": "20.00", "target": "37261502217"}'
Calls: quotes.create
AI agent tool calls over MCP
For Assistants and chat bots.
Give an agent an ak key: it sends within a threshold and to known numbers; anything more asks a person, who approves with their payment PIN. Live agents are off until an owner turns them on.
- Create an agent key with a threshold.
- Point your MCP client at /dev/v1/mcp.
Python
def create_agent_key() -> None:
try:
agent_key = jusa.ApiKey.create(
kind="ak",
label="assistant",
approval_threshold={"USD": "10.00"},
)
# The key is shown once: put it straight into the agent's secret store.
# MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
print(agent_key.id, agent_key.redacted)
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 createAgentKey() {
try {
const agentKey = await jusa.keys.create({
kind: 'ak',
label: 'assistant',
approval_threshold: { USD: '10.00' },
});
// The key is shown once: put it straight into the agent's secret store.
// MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
console.log(agentKey.id, agentKey.redacted);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function createAgentKey(\Jusa\JusaClient $jusa): void
{
try {
$agentKey = $jusa->keys->create([
'kind' => 'ak',
'label' => 'assistant',
'approval_threshold' => ['USD' => '10.00'],
]);
// The key is shown once: put it straight into the agent's secret store.
// MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
echo $agentKey->id, ' ', $agentKey->redacted, "\n";
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func createAgentKey(ctx context.Context) error {
agentKey, err := jusaClient.Keys.Create(ctx, jusa.Params{
"kind": "ak",
"label": "assistant",
"approval_threshold": jusa.Params{"USD": "10.00"},
})
if err != nil {
return fmt.Errorf("keys.create: %w", err)
}
// The key is shown once: put it straight into the agent's secret store.
// MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
fmt.Println(agentKey.ID, agentKey.Redacted)
return nil
}
Java
void createAgentKey() throws JusaException {
try {
var agentKey = jusa.keys().create(Params.of(
"kind", "ak",
"label", "assistant",
"approval_threshold", Map.of("USD", "10.00")
));
// The key is shown once: put it straight into the agent's secret store.
// MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
System.out.println(agentKey.getId() + " " + agentKey.getRedacted());
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task CreateAgentKeyAsync()
{
try
{
var agentKey = await jusa.Keys.CreateAsync(new
{
kind = "ak",
label = "assistant",
approval_threshold = new { USD = "10.00" },
});
// The key is shown once: put it straight into the agent's secret store.
// MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
Console.WriteLine($"{agentKey.Id} {agentKey.Redacted}");
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> createAgentKey() async {
try {
final agentKey = await jusa.keys.create({
'kind': 'ak',
'label': 'assistant',
'approval_threshold': {'USD': '10.00'},
});
// The key is shown once: put it straight into the agent's secret store.
// MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
print('${agentKey.id} ${agentKey.redacted}');
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def create_agent_key
agent_key = Jusa::ApiKey.create(
kind: "ak",
label: "assistant",
approval_threshold: { USD: "10.00" },
)
# The key is shown once: put it straight into the agent's secret store.
# MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
puts "#{agent_key.id} #{agent_key.redacted}"
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/keys \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"kind": "ak", "label": "assistant", "approval_threshold": {"USD": "10.00"}}'
# The key is shown once: put it straight into the agent's secret store.
# MCP server: https://jusa.localhost.co.zw/dev/v1/mcp (Authorization: Bearer <the ak key>)
Calls: keys.create · mcp.call · approvals.list
WhatsApp chatbot commerce
For Bot builders.
Confirm the meter in the chat, send a checkout link, confirm delivery from the webhook.
- meters.retrieve for the name to confirm.
- A checkout session; reply with its url.
Python
def confirm_meter_owner(meter_number: str) -> None:
try:
meter = jusa.Meter.retrieve(meter_number)
print(meter.customer_name, meter.address)
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 confirmMeterOwner(meterNumber) {
try {
const meter = await jusa.meters.retrieve(meterNumber);
console.log(meter.customer_name, meter.address);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function confirmMeterOwner(\Jusa\JusaClient $jusa, string $meterNumber): void
{
try {
$meter = $jusa->meters->retrieve($meterNumber);
echo $meter->customer_name, ' ', $meter->address, "\n";
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func confirmMeterOwner(ctx context.Context, meterNumber string) error {
meter, err := jusaClient.Meters.Retrieve(ctx, meterNumber, nil)
if err != nil {
return fmt.Errorf("meters.retrieve: %w", err)
}
fmt.Println(meter.CustomerName, meter.Address)
return nil
}
Java
void confirmMeterOwner(String meterNumber) throws JusaException {
try {
var meter = jusa.meters().retrieve(meterNumber);
System.out.println(meter.getCustomerName() + " " + meter.getAddress());
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task ConfirmMeterOwnerAsync(string meterNumber)
{
try
{
var meter = await jusa.Meters.RetrieveAsync(meterNumber);
Console.WriteLine($"{meter.CustomerName} {meter.Address}");
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> confirmMeterOwner(String meterNumber) async {
try {
final meter = await jusa.meters.retrieve(meterNumber);
print('${meter.customerName} ${meter.address}');
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def confirm_meter_owner(meter_number)
meter = Jusa::Meter.retrieve(meter_number)
puts "#{meter.customer_name} #{meter.address}"
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/meters/37261502217 \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY"
Calls: meters.retrieve · checkout_sessions.create
Escrowed conditional rewards
For Anyone.
The general primitive: reserve now, decide later. Held credit shows as credit.reserved.
- hold=true on the reward.
- release (optionally for less) or void.
Python
def hold_task_payment(task_id: str, user_id: str) -> None:
try:
reward = jusa.Reward.create(
program="prg_…",
completion_id=f"task-{task_id}",
recipient=f"ext:{user_id}",
hold=True,
idempotency_key=f"task-{task_id}",
)
print(reward.id, reward.status)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def release_task_payment(reward_id: str, task_id: str) -> None:
try:
# Release it for less, or void it:
jusa.Reward.release(
reward_id,
amount="0.40",
idempotency_key=f"release-task-{task_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function holdTaskPayment(taskId, userId) {
try {
const reward = await jusa.rewards.create({
program: 'prg_…',
completion_id: `task-${taskId}`,
recipient: `ext:${userId}`,
hold: true,
}, { idempotencyKey: `task-${taskId}` });
console.log(reward.id, reward.status);
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function releaseTaskPayment(rewardId, taskId) {
try {
// Release it for less, or void it:
await jusa.rewards.release(rewardId, {
amount: '0.40',
}, { idempotencyKey: `release-task-${taskId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function holdTaskPayment(\Jusa\JusaClient $jusa, string $taskId, string $userId): void
{
try {
$reward = $jusa->rewards->create([
'program' => 'prg_…',
'completion_id' => "task-{$taskId}",
'recipient' => "ext:{$userId}",
'hold' => true,
], ['idempotency_key' => "task-{$taskId}"]);
echo $reward->id, ' ', $reward->status, "\n";
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function releaseTaskPayment(\Jusa\JusaClient $jusa, string $rewardId, string $taskId): void
{
try {
// Release it for less, or void it:
$jusa->rewards->release($rewardId, [
'amount' => '0.40',
], ['idempotency_key' => "release-task-{$taskId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func holdTaskPayment(ctx context.Context, taskID, userID string) error {
rewardResult, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_…",
"completion_id": "task-" + taskID,
"recipient": "ext:" + userID,
"hold": true,
}, jusa.WithIdempotencyKey("task-"+taskID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
reward := rewardResult.Reward
fmt.Println(reward.ID, reward.Status)
return nil
}
func releaseTaskPayment(ctx context.Context, rewardID, taskID string) error {
// Release it for less, or void it:
_, err := jusaClient.Rewards.Release(ctx, rewardID, jusa.Params{
"amount": "0.40",
}, jusa.WithIdempotencyKey("release-task-"+taskID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.release: %w", err)
}
return nil
}
Java
void holdTaskPayment(String taskId, String userId) throws JusaException {
try {
var reward = jusa.rewards().create(Params.of(
"program", "prg_…",
"completion_id", "task-" + taskId,
"recipient", "ext:" + userId,
"hold", true
), RequestOptions.idempotencyKey("task-" + taskId));
System.out.println(reward.getId() + " " + reward.getStatus());
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void releaseTaskPayment(String rewardId, String taskId) throws JusaException {
try {
// Release it for less, or void it:
jusa.rewards().release(rewardId, Params.of(
"amount", "0.40"
), RequestOptions.idempotencyKey("release-task-" + taskId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task HoldTaskPaymentAsync(string taskId, string userId)
{
try
{
var rewardResult = await jusa.Rewards.CreateAsync(new
{
program = "prg_…",
completion_id = $"task-{taskId}",
recipient = $"ext:{userId}",
hold = true,
}, new RequestOptions { IdempotencyKey = $"task-{taskId}" });
var reward = rewardResult.As<Reward>();
Console.WriteLine($"{reward.Id} {reward.Status}");
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task ReleaseTaskPaymentAsync(string rewardId, string taskId)
{
try
{
// Release it for less, or void it:
await jusa.Rewards.ReleaseAsync(rewardId, new
{
amount = "0.40",
}, new RequestOptions { IdempotencyKey = $"release-task-{taskId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> holdTaskPayment(String taskId, String userId) async {
try {
final reward = await jusa.rewards.create({
'program': 'prg_…',
'completion_id': 'task-$taskId',
'recipient': 'ext:$userId',
'hold': true,
}, RequestOptions(idempotencyKey: 'task-$taskId')) as Reward;
print('${reward.id} ${reward.status}');
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> releaseTaskPayment(String rewardId, String taskId) async {
try {
// Release it for less, or void it:
await jusa.rewards.release(rewardId, {
'amount': '0.40',
}, RequestOptions(idempotencyKey: 'release-task-$taskId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def hold_task_payment(task_id, user_id)
reward = Jusa::Reward.create({
program: "prg_…",
completion_id: "task-#{task_id}",
recipient: "ext:#{user_id}",
hold: true,
}, idempotency_key: "task-#{task_id}")
puts "#{reward.id} #{reward.status}"
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def release_task_payment(reward_id, task_id)
# Release it for less, or void it:
Jusa::Reward.release(reward_id, {
amount: "0.40",
}, idempotency_key: "release-task-#{task_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: task-9" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_…",
"completion_id": "task-9",
"recipient": "ext:u-9",
"hold": true
}'
# Release it for less, or void it:
curl https://jusa.localhost.co.zw/dev/v1/rewards/rwd_…/release \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: release-task-9" \
-H "Content-Type: application/json" \
-d '{"amount": "0.40"}'
Calls: rewards.create · rewards.release · rewards.void · credit.list_reservations
Geofenced event check-in
For Ag shows, churches, retail. P3
Links that pay only at the venue, during the event.
- A program with a geofence and a window.
- Check-ins from the widget.
Python
def create_ag_show_program() -> None:
try:
jusa.Program.create(
name="Ag show",
default_amount="0.50",
budget="100.00",
sources=["links"],
geofence={"lat": -17.8252, "lng": 31.0522, "radius_m": 300},
idempotency_key="program-ag-show",
)
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 createAgShowProgram() {
try {
await jusa.programs.create({
name: 'Ag show',
default_amount: '0.50',
budget: '100.00',
sources: ['links'],
geofence: { lat: -17.8252, lng: 31.0522, radius_m: 300 },
}, { idempotencyKey: 'program-ag-show' });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function createAgShowProgram(\Jusa\JusaClient $jusa): void
{
try {
$jusa->programs->create([
'name' => 'Ag show',
'default_amount' => '0.50',
'budget' => '100.00',
'sources' => ['links'],
'geofence' => ['lat' => -17.8252, 'lng' => 31.0522, 'radius_m' => 300],
], ['idempotency_key' => 'program-ag-show']);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func createAgShowProgram(ctx context.Context) error {
_, err := jusaClient.Programs.Create(ctx, jusa.Params{
"name": "Ag show",
"default_amount": "0.50",
"budget": "100.00",
"sources": []string{"links"},
"geofence": jusa.Params{"lat": -17.8252, "lng": 31.0522, "radius_m": 300},
}, jusa.WithIdempotencyKey("program-ag-show"))
if err != nil {
return fmt.Errorf("programs.create: %w", err)
}
return nil
}
Java
void createAgShowProgram() throws JusaException {
try {
jusa.programs().create(Params.of(
"name", "Ag show",
"default_amount", "0.50",
"budget", "100.00",
"sources", List.of("links"),
"geofence", Map.of("lat", -17.8252, "lng", 31.0522, "radius_m", 300)
), RequestOptions.idempotencyKey("program-ag-show"));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task CreateAgShowProgramAsync()
{
try
{
await jusa.Programs.CreateAsync(new
{
name = "Ag show",
default_amount = "0.50",
budget = "100.00",
sources = new[] { "links" },
geofence = new { lat = -17.8252, lng = 31.0522, radius_m = 300 },
}, new RequestOptions { IdempotencyKey = "program-ag-show" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> createAgShowProgram() async {
try {
await jusa.programs.create({
'name': 'Ag show',
'default_amount': '0.50',
'budget': '100.00',
'sources': ['links'],
'geofence': {'lat': -17.8252, 'lng': 31.0522, 'radius_m': 300},
}, RequestOptions(idempotencyKey: 'program-ag-show'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def create_ag_show_program
Jusa::Program.create({
name: "Ag show",
default_amount: "0.50",
budget: "100.00",
sources: ["links"],
geofence: { lat: -17.8252, lng: 31.0522, radius_m: 300 },
}, idempotency_key: "program-ag-show")
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/programs \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: program-ag-show" \
-H "Content-Type: application/json" \
-d '{
"name": "Ag show",
"default_amount": "0.50",
"budget": "100.00",
"sources": ["links"],
"geofence": {"lat": -17.8252, "lng": 31.0522, "radius_m": 300}
}'
Calls: programs.create · checkins.create
Farmer extension incentives
For EcoFarmer-scale programmes.
Reward attendance and adoption, keyed on your farmer ids; batches for the season-end bonus.
- Reward per attendance.
- A batch at season end.
Python
def reward_session_attendance(session_id: str, farmer_id: str, phone: str) -> None:
try:
jusa.Reward.create(
program="prg_extension",
completion_id=f"attend-{session_id}-{farmer_id}",
recipient={"external_id": farmer_id, "phone": phone},
idempotency_key=f"attend-{session_id}-{farmer_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function rewardSessionAttendance(sessionId, farmerId, phone) {
try {
await jusa.rewards.create({
program: 'prg_extension',
completion_id: `attend-${sessionId}-${farmerId}`,
recipient: { external_id: farmerId, phone },
}, { idempotencyKey: `attend-${sessionId}-${farmerId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function rewardSessionAttendance(\Jusa\JusaClient $jusa, string $sessionId, string $farmerId, string $phone): void
{
try {
$jusa->rewards->create([
'program' => 'prg_extension',
'completion_id' => "attend-{$sessionId}-{$farmerId}",
'recipient' => ['external_id' => $farmerId, 'phone' => $phone],
], ['idempotency_key' => "attend-{$sessionId}-{$farmerId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func rewardSessionAttendance(ctx context.Context, sessionID, farmerID, phone string) error {
_, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_extension",
"completion_id": "attend-" + sessionID + "-" + farmerID,
"recipient": jusa.Params{"external_id": farmerID, "phone": phone},
}, jusa.WithIdempotencyKey("attend-"+sessionID+"-"+farmerID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
return nil
}
Java
void rewardSessionAttendance(String sessionId, String farmerId, String phone) throws JusaException {
try {
jusa.rewards().create(Params.of(
"program", "prg_extension",
"completion_id", "attend-" + sessionId + "-" + farmerId,
"recipient", Map.of("external_id", farmerId, "phone", phone)
), RequestOptions.idempotencyKey("attend-" + sessionId + "-" + farmerId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task RewardSessionAttendanceAsync(string sessionId, string farmerId, string phone)
{
try
{
await jusa.Rewards.CreateAsync(new
{
program = "prg_extension",
completion_id = $"attend-{sessionId}-{farmerId}",
recipient = new { external_id = farmerId, phone = phone },
}, new RequestOptions { IdempotencyKey = $"attend-{sessionId}-{farmerId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> rewardSessionAttendance(String sessionId, String farmerId, String phone) async {
try {
await jusa.rewards.create({
'program': 'prg_extension',
'completion_id': 'attend-$sessionId-$farmerId',
'recipient': {'external_id': farmerId, 'phone': phone},
}, RequestOptions(idempotencyKey: 'attend-$sessionId-$farmerId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def reward_session_attendance(session_id, farmer_id, phone)
Jusa::Reward.create({
program: "prg_extension",
completion_id: "attend-#{session_id}-#{farmer_id}",
recipient: { external_id: farmer_id, phone: phone },
}, idempotency_key: "attend-#{session_id}-#{farmer_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: attend-s14-F-2231" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_extension",
"completion_id": "attend-s14-F-2231",
"recipient": {"external_id": "F-2231", "phone": "0771230000"}
}'
Calls: rewards.create · batches.create
Programmatic family allowance
For Bank standing orders. OAuth family: P3
For your own customers' families: recipients plus a payday schedule. /family needs OAuth user tokens and answers 501 until then.
- The family members as recipients.
- A payday schedule.
Python
def schedule_gogos_airtime(recipient_id: str) -> None:
try:
jusa.Schedule.create(
name="Gogo's airtime",
cadence="payday",
hour=9,
minute=0,
recipients=[recipient_id],
product="airtime-usd",
amount="5.00",
idempotency_key=f"schedule-gogo-{recipient_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 scheduleGogosAirtime(recipientId) {
try {
await jusa.schedules.create({
name: 'Gogo\'s airtime',
cadence: 'payday',
hour: 9,
minute: 0,
recipients: [recipientId],
product: 'airtime-usd',
amount: '5.00',
}, { idempotencyKey: `schedule-gogo-${recipientId}` });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function scheduleGogosAirtime(\Jusa\JusaClient $jusa, string $recipientId): void
{
try {
$jusa->schedules->create([
'name' => 'Gogo\'s airtime',
'cadence' => 'payday',
'hour' => 9,
'minute' => 0,
'recipients' => [$recipientId],
'product' => 'airtime-usd',
'amount' => '5.00',
], ['idempotency_key' => "schedule-gogo-{$recipientId}"]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func scheduleGogosAirtime(ctx context.Context, recipientID string) error {
_, err := jusaClient.Schedules.Create(ctx, jusa.Params{
"name": "Gogo's airtime",
"cadence": "payday",
"hour": 9,
"minute": 0,
"recipients": []string{recipientID},
"product": "airtime-usd",
"amount": "5.00",
}, jusa.WithIdempotencyKey("schedule-gogo-"+recipientID))
if err != nil {
return fmt.Errorf("schedules.create: %w", err)
}
return nil
}
Java
void scheduleGogosAirtime(String recipientId) throws JusaException {
try {
jusa.schedules().create(Params.of(
"name", "Gogo's airtime",
"cadence", "payday",
"hour", 9,
"minute", 0,
"recipients", List.of(recipientId),
"product", "airtime-usd",
"amount", "5.00"
), RequestOptions.idempotencyKey("schedule-gogo-" + recipientId));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task ScheduleGogosAirtimeAsync(string recipientId)
{
try
{
await jusa.Schedules.CreateAsync(new
{
name = "Gogo's airtime",
cadence = "payday",
hour = 9,
minute = 0,
recipients = new object[] { recipientId },
product = "airtime-usd",
amount = "5.00",
}, new RequestOptions { IdempotencyKey = $"schedule-gogo-{recipientId}" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> scheduleGogosAirtime(String recipientId) async {
try {
await jusa.schedules.create({
'name': 'Gogo\'s airtime',
'cadence': 'payday',
'hour': 9,
'minute': 0,
'recipients': [recipientId],
'product': 'airtime-usd',
'amount': '5.00',
}, RequestOptions(idempotencyKey: 'schedule-gogo-$recipientId'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def schedule_gogos_airtime(recipient_id)
Jusa::Schedule.create({
name: "Gogo's airtime",
cadence: "payday",
hour: 9,
minute: 0,
recipients: [recipient_id],
product: "airtime-usd",
amount: "5.00",
}, idempotency_key: "schedule-gogo-#{recipient_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/schedules \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: schedule-gogo-rcp_…" \
-H "Content-Type: application/json" \
-d '{
"name": "Gogo'\''s airtime",
"cadence": "payday",
"hour": 9,
"minute": 0,
"recipients": ["rcp_…"],
"product": "airtime-usd",
"amount": "5.00"
}'
Calls: recipients.create · schedules.create
Bill-shock rescue
For Telco-adjacent fintech.
You spot a zero balance in your own systems (Jusa cannot see it) and send US$0.50, capped per person per day.
- A per-recipient daily cap.
- One send per rescue, keyed on your alert.
Python
def send_rescue_airtime(phone: str, customer_id: str, alert_id: str) -> None:
try:
jusa.Send.create(
target=phone,
amount="0.50",
product="airtime-usd",
recipient=f"ext:{customer_id}",
client_reference=f"rescue-alert-{alert_id}",
idempotency_key=f"rescue-alert-{alert_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function sendRescueAirtime(phone, customerId, alertId) {
try {
await jusa.sends.create({
target: phone,
amount: '0.50',
product: 'airtime-usd',
recipient: `ext:${customerId}`,
client_reference: `rescue-alert-${alertId}`,
}, { idempotencyKey: `rescue-alert-${alertId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function sendRescueAirtime(\Jusa\JusaClient $jusa, string $phone, string $customerId, string $alertId): void
{
try {
$jusa->sends->create([
'target' => $phone,
'amount' => '0.50',
'product' => 'airtime-usd',
'recipient' => "ext:{$customerId}",
'client_reference' => "rescue-alert-{$alertId}",
], ['idempotency_key' => "rescue-alert-{$alertId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func sendRescueAirtime(ctx context.Context, phone, customerID, alertID string) error {
_, err := jusaClient.Sends.Create(ctx, jusa.Params{
"target": phone,
"amount": "0.50",
"product": "airtime-usd",
"recipient": "ext:" + customerID,
"client_reference": "rescue-alert-" + alertID,
}, jusa.WithIdempotencyKey("rescue-alert-"+alertID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("sends.create: %w", err)
}
return nil
}
Java
void sendRescueAirtime(String phone, String customerId, String alertId) throws JusaException {
try {
jusa.sends().create(Params.of(
"target", phone,
"amount", "0.50",
"product", "airtime-usd",
"recipient", "ext:" + customerId,
"client_reference", "rescue-alert-" + alertId
), RequestOptions.idempotencyKey("rescue-alert-" + alertId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SendRescueAirtimeAsync(string phone, string customerId, string alertId)
{
try
{
await jusa.Sends.CreateAsync(new
{
target = phone,
amount = "0.50",
product = "airtime-usd",
recipient = $"ext:{customerId}",
client_reference = $"rescue-alert-{alertId}",
}, new RequestOptions { IdempotencyKey = $"rescue-alert-{alertId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> sendRescueAirtime(String phone, String customerId, String alertId) async {
try {
await jusa.sends.create({
'target': phone,
'amount': '0.50',
'product': 'airtime-usd',
'recipient': 'ext:$customerId',
'client_reference': 'rescue-alert-$alertId',
}, RequestOptions(idempotencyKey: 'rescue-alert-$alertId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def send_rescue_airtime(phone, customer_id, alert_id)
Jusa::Send.create({
target: phone,
amount: "0.50",
product: "airtime-usd",
recipient: "ext:#{customer_id}",
client_reference: "rescue-alert-#{alert_id}",
}, idempotency_key: "rescue-alert-#{alert_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/sends \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: rescue-alert-5120" \
-H "Content-Type: application/json" \
-d '{
"target": "0771230000",
"amount": "0.50",
"product": "airtime-usd",
"recipient": "ext:cust-301",
"client_reference": "rescue-alert-5120"
}'
Calls: sends.create · recipients.update
Emergency power for medical devices
For Health IoT. needs counsel: health data
A monitor triggers a ZESA reward from the patient's own program: the program's budget is the cap, and on_zesa_down=fail on the program so a caregiver hears at once. (A send's program is attribution only: it draws on no budget.)
- A program per patient: choices ["zesa"], a budget, on_zesa_down="fail".
- A direct reward per alarm, keyed on it; listen to zesa.availability.* and reward.failed.
Python
def set_up_patient_program() -> None:
try:
jusa.Program.create(
name="Patient 12",
currency="USD",
default_amount="5.00",
budget="60.00",
choices=["zesa"],
on_zesa_down="fail",
idempotency_key="program-patient-12",
)
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
def power_for_alarm(alarm_id: str, patient_id: str, meter_number: str, token_phone: str) -> None:
try:
# One reward per alarm:
jusa.Reward.create(
program="prg_patient_12",
completion_id=f"alarm-{alarm_id}",
type="zesa",
recipient={
"external_id": patient_id,
"meter": meter_number,
"token_phone": token_phone,
},
idempotency_key=f"alarm-{alarm_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function setUpPatientProgram() {
try {
await jusa.programs.create({
name: 'Patient 12',
currency: 'USD',
default_amount: '5.00',
budget: '60.00',
choices: ['zesa'],
on_zesa_down: 'fail',
}, { idempotencyKey: 'program-patient-12' });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
async function powerForAlarm(alarmId, patientId, meterNumber, tokenPhone) {
try {
// One reward per alarm:
await jusa.rewards.create({
program: 'prg_patient_12',
completion_id: `alarm-${alarmId}`,
type: 'zesa',
recipient: {
external_id: patientId,
meter: meterNumber,
token_phone: tokenPhone,
},
}, { idempotencyKey: `alarm-${alarmId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function setUpPatientProgram(\Jusa\JusaClient $jusa): void
{
try {
$jusa->programs->create([
'name' => 'Patient 12',
'currency' => 'USD',
'default_amount' => '5.00',
'budget' => '60.00',
'choices' => ['zesa'],
'on_zesa_down' => 'fail',
], ['idempotency_key' => 'program-patient-12']);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
function powerForAlarm(\Jusa\JusaClient $jusa, string $alarmId, string $patientId, string $meterNumber, string $tokenPhone): void
{
try {
// One reward per alarm:
$jusa->rewards->create([
'program' => 'prg_patient_12',
'completion_id' => "alarm-{$alarmId}",
'type' => 'zesa',
'recipient' => [
'external_id' => $patientId,
'meter' => $meterNumber,
'token_phone' => $tokenPhone,
],
], ['idempotency_key' => "alarm-{$alarmId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func setUpPatientProgram(ctx context.Context) error {
_, err := jusaClient.Programs.Create(ctx, jusa.Params{
"name": "Patient 12",
"currency": "USD",
"default_amount": "5.00",
"budget": "60.00",
"choices": []string{"zesa"},
"on_zesa_down": "fail",
}, jusa.WithIdempotencyKey("program-patient-12"))
if err != nil {
return fmt.Errorf("programs.create: %w", err)
}
return nil
}
func powerForAlarm(ctx context.Context, alarmID, patientID, meterNumber, tokenPhone string) error {
// One reward per alarm:
_, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_patient_12",
"completion_id": "alarm-" + alarmID,
"type": "zesa",
"recipient": jusa.Params{
"external_id": patientID,
"meter": meterNumber,
"token_phone": tokenPhone,
},
}, jusa.WithIdempotencyKey("alarm-"+alarmID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
return nil
}
Java
void setUpPatientProgram() throws JusaException {
try {
jusa.programs().create(Params.of(
"name", "Patient 12",
"currency", "USD",
"default_amount", "5.00",
"budget", "60.00",
"choices", List.of("zesa"),
"on_zesa_down", "fail"
), RequestOptions.idempotencyKey("program-patient-12"));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
void powerForAlarm(String alarmId, String patientId, String meterNumber, String tokenPhone) throws JusaException {
try {
// One reward per alarm:
jusa.rewards().create(Params.of(
"program", "prg_patient_12",
"completion_id", "alarm-" + alarmId,
"type", "zesa",
"recipient", Map.of(
"external_id", patientId,
"meter", meterNumber,
"token_phone", tokenPhone
)
), RequestOptions.idempotencyKey("alarm-" + alarmId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SetUpPatientProgramAsync()
{
try
{
await jusa.Programs.CreateAsync(new
{
name = "Patient 12",
currency = "USD",
default_amount = "5.00",
budget = "60.00",
choices = new[] { "zesa" },
on_zesa_down = "fail",
}, new RequestOptions { IdempotencyKey = "program-patient-12" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
async Task PowerForAlarmAsync(string alarmId, string patientId, string meterNumber, string tokenPhone)
{
try
{
// One reward per alarm:
await jusa.Rewards.CreateAsync(new
{
program = "prg_patient_12",
completion_id = $"alarm-{alarmId}",
type = "zesa",
recipient = new
{
external_id = patientId,
meter = meterNumber,
token_phone = tokenPhone,
},
}, new RequestOptions { IdempotencyKey = $"alarm-{alarmId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> setUpPatientProgram() async {
try {
await jusa.programs.create({
'name': 'Patient 12',
'currency': 'USD',
'default_amount': '5.00',
'budget': '60.00',
'choices': ['zesa'],
'on_zesa_down': 'fail',
}, RequestOptions(idempotencyKey: 'program-patient-12'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Future<void> powerForAlarm(String alarmId, String patientId, String meterNumber, String tokenPhone) async {
try {
// One reward per alarm:
await jusa.rewards.create({
'program': 'prg_patient_12',
'completion_id': 'alarm-$alarmId',
'type': 'zesa',
'recipient': {
'external_id': patientId,
'meter': meterNumber,
'token_phone': tokenPhone,
},
}, RequestOptions(idempotencyKey: 'alarm-$alarmId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def set_up_patient_program
Jusa::Program.create({
name: "Patient 12",
currency: "USD",
default_amount: "5.00",
budget: "60.00",
choices: ["zesa"],
on_zesa_down: "fail",
}, idempotency_key: "program-patient-12")
rescue Jusa::JusaError => jusa_error
LOGGER.error("Jusa refused: #{jusa_error.code} [#{jusa_error.request_id}]")
raise
end
def power_for_alarm(alarm_id, patient_id, meter_number, token_phone)
# One reward per alarm:
Jusa::Reward.create({
program: "prg_patient_12",
completion_id: "alarm-#{alarm_id}",
type: "zesa",
recipient: {
external_id: patient_id,
meter: meter_number,
token_phone: token_phone,
},
}, idempotency_key: "alarm-#{alarm_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/programs \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: program-patient-12" \
-H "Content-Type: application/json" \
-d '{
"name": "Patient 12",
"currency": "USD",
"default_amount": "5.00",
"budget": "60.00",
"choices": ["zesa"],
"on_zesa_down": "fail"
}'
# One reward per alarm:
curl https://jusa.localhost.co.zw/dev/v1/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: alarm-880" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_patient_12",
"completion_id": "alarm-880",
"type": "zesa",
"recipient": {
"external_id": "patient-12",
"meter": "37261502217",
"token_phone": "0772123456"
}
}'
Calls: programs.create · rewards.create · status.retrieve
Crowdsourced price or outage reports
For Civic tech. P3
Each verified report is an activity; a threshold rule pays out.
- A threshold rule.
- An activity per verified report.
Python
def record_verified_report(reporter_id: str, report_id: str) -> None:
try:
jusa.Activity.create(
recipient=f"ext:{reporter_id}",
name="report.verified",
activity_id=f"report-{report_id}",
idempotency_key=f"report-{report_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 recordVerifiedReport(reporterId, reportId) {
try {
await jusa.activities.create({
recipient: `ext:${reporterId}`,
name: 'report.verified',
activity_id: `report-${reportId}`,
}, { idempotencyKey: `report-${reportId}` });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function recordVerifiedReport(\Jusa\JusaClient $jusa, string $reporterId, string $reportId): void
{
try {
$jusa->activities->create([
'recipient' => "ext:{$reporterId}",
'name' => 'report.verified',
'activity_id' => "report-{$reportId}",
], ['idempotency_key' => "report-{$reportId}"]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func recordVerifiedReport(ctx context.Context, reporterID, reportID string) error {
_, err := jusaClient.Activities.Create(ctx, jusa.Params{
"recipient": "ext:" + reporterID,
"name": "report.verified",
"activity_id": "report-" + reportID,
}, jusa.WithIdempotencyKey("report-"+reportID))
if err != nil {
return fmt.Errorf("activities.create: %w", err)
}
return nil
}
Java
void recordVerifiedReport(String reporterId, String reportId) throws JusaException {
try {
jusa.activities().create(Params.of(
"recipient", "ext:" + reporterId,
"name", "report.verified",
"activity_id", "report-" + reportId
), RequestOptions.idempotencyKey("report-" + reportId));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task RecordVerifiedReportAsync(string reporterId, string reportId)
{
try
{
await jusa.Activities.CreateAsync(new
{
recipient = $"ext:{reporterId}",
name = "report.verified",
activity_id = $"report-{reportId}",
}, new RequestOptions { IdempotencyKey = $"report-{reportId}" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> recordVerifiedReport(String reporterId, String reportId) async {
try {
await jusa.activities.create({
'recipient': 'ext:$reporterId',
'name': 'report.verified',
'activity_id': 'report-$reportId',
}, RequestOptions(idempotencyKey: 'report-$reportId'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def record_verified_report(reporter_id, report_id)
Jusa::Activity.create({
recipient: "ext:#{reporter_id}",
name: "report.verified",
activity_id: "report-#{report_id}",
}, idempotency_key: "report-#{report_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/activities \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: report-4410" \
-H "Content-Type: application/json" \
-d '{
"recipient": "ext:reporter-3",
"name": "report.verified",
"activity_id": "report-4410"
}'
Calls: activities.create · rewards.create
Data perk on ticket scan
For Promoters. data: P2
A link printed on the ticket, bound to the buyer's phone.
- A link per ticket, bind=otp with the buyer's phone_hint.
Python
def send_ticket_perk(phone: str, ticket_id: str) -> None:
try:
jusa.RewardLink.create(
program="prg_gig",
recipient={"phone": phone},
bind="otp",
phone_hint=phone,
label=ticket_id,
idempotency_key=f"perk-{ticket_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 sendTicketPerk(phone, ticketId) {
try {
await jusa.rewardLinks.create({
program: 'prg_gig',
recipient: { phone },
bind: 'otp',
phone_hint: phone,
label: ticketId,
}, { idempotencyKey: `perk-${ticketId}` });
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function sendTicketPerk(\Jusa\JusaClient $jusa, string $phone, string $ticketId): void
{
try {
$jusa->rewardLinks->create([
'program' => 'prg_gig',
'recipient' => ['phone' => $phone],
'bind' => 'otp',
'phone_hint' => $phone,
'label' => $ticketId,
], ['idempotency_key' => "perk-{$ticketId}"]);
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func sendTicketPerk(ctx context.Context, phone, ticketID string) error {
_, err := jusaClient.RewardLinks.Create(ctx, jusa.Params{
"program": "prg_gig",
"recipient": jusa.Params{"phone": phone},
"bind": "otp",
"phone_hint": phone,
"label": ticketID,
}, jusa.WithIdempotencyKey("perk-"+ticketID))
if err != nil {
return fmt.Errorf("reward_links.create: %w", err)
}
return nil
}
Java
void sendTicketPerk(String phone, String ticketId) throws JusaException {
try {
jusa.rewardLinks().create(Params.of(
"program", "prg_gig",
"recipient", Map.of("phone", phone),
"bind", "otp",
"phone_hint", phone,
"label", ticketId
), RequestOptions.idempotencyKey("perk-" + ticketId));
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task SendTicketPerkAsync(string phone, string ticketId)
{
try
{
await jusa.RewardLinks.CreateAsync(new
{
program = "prg_gig",
recipient = new { phone = phone },
bind = "otp",
phone_hint = phone,
label = ticketId,
}, new RequestOptions { IdempotencyKey = $"perk-{ticketId}" });
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> sendTicketPerk(String phone, String ticketId) async {
try {
await jusa.rewardLinks.create({
'program': 'prg_gig',
'recipient': {'phone': phone},
'bind': 'otp',
'phone_hint': phone,
'label': ticketId,
}, RequestOptions(idempotencyKey: 'perk-$ticketId'));
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def send_ticket_perk(phone, ticket_id)
Jusa::RewardLink.create({
program: "prg_gig",
recipient: { phone: phone },
bind: "otp",
phone_hint: phone,
label: ticket_id,
}, idempotency_key: "perk-#{ticket_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/reward-links \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: perk-TKT-00931" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_gig",
"recipient": {"phone": "0771230000"},
"bind": "otp",
"phone_hint": "0771230000",
"label": "TKT-00931"
}'
Calls: reward_links.create
Fundraising thank-you airtime
For Churches and schools.
Thank each donor with a little airtime after their gift.
- Reward per donation, keyed on the gift.
Python
def thank_donor(gift_id: str, phone: str) -> None:
try:
jusa.Reward.create(
program="prg_thanks",
completion_id=f"gift-{gift_id}",
recipient={"phone": phone},
amount="0.50",
idempotency_key=f"gift-{gift_id}",
)
except jusa.InsufficientCreditError:
top_up_and_try_later() # nothing was charged: retry with the same idempotency key
except jusa.JusaError as jusa_error:
logger.error("Jusa refused: %s [%s]", jusa_error.code, jusa_error.request_id)
raise
Node
import { InsufficientCreditError, JusaError } from '@jusa/node';
async function thankDonor(giftId, phone) {
try {
await jusa.rewards.create({
program: 'prg_thanks',
completion_id: `gift-${giftId}`,
recipient: { phone },
amount: '0.50',
}, { idempotencyKey: `gift-${giftId}` });
} catch (error) {
if (error instanceof InsufficientCreditError) {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
return;
}
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function thankDonor(\Jusa\JusaClient $jusa, string $giftId, string $phone): void
{
try {
$jusa->rewards->create([
'program' => 'prg_thanks',
'completion_id' => "gift-{$giftId}",
'recipient' => ['phone' => $phone],
'amount' => '0.50',
], ['idempotency_key' => "gift-{$giftId}"]);
} catch (\Jusa\Exception\InsufficientCreditException) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func thankDonor(ctx context.Context, giftID, phone string) error {
_, err := jusaClient.Rewards.Create(ctx, jusa.Params{
"program": "prg_thanks",
"completion_id": "gift-" + giftID,
"recipient": jusa.Params{"phone": phone},
"amount": "0.50",
}, jusa.WithIdempotencyKey("gift-"+giftID))
if err != nil {
var insufficientCredit *jusa.InsufficientCreditError
if errors.As(err, &insufficientCredit) {
topUpAndTryLater() // nothing was charged: retry with the same idempotency key
return nil
}
return fmt.Errorf("rewards.create: %w", err)
}
return nil
}
Java
void thankDonor(String giftId, String phone) throws JusaException {
try {
jusa.rewards().create(Params.of(
"program", "prg_thanks",
"completion_id", "gift-" + giftId,
"recipient", Map.of("phone", phone),
"amount", "0.50"
), RequestOptions.idempotencyKey("gift-" + giftId));
} catch (InsufficientCreditException insufficientCredit) {
topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task ThankDonorAsync(string giftId, string phone)
{
try
{
await jusa.Rewards.CreateAsync(new
{
program = "prg_thanks",
completion_id = $"gift-{giftId}",
recipient = new { phone = phone },
amount = "0.50",
}, new RequestOptions { IdempotencyKey = $"gift-{giftId}" });
}
catch (InsufficientCreditException)
{
await TopUpAndTryLater(); // nothing was charged: retry with the same idempotency key
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> thankDonor(String giftId, String phone) async {
try {
await jusa.rewards.create({
'program': 'prg_thanks',
'completion_id': 'gift-$giftId',
'recipient': {'phone': phone},
'amount': '0.50',
}, RequestOptions(idempotencyKey: 'gift-$giftId'));
} on InsufficientCreditException {
await topUpAndTryLater(); // nothing was charged: retry with the same idempotency key
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def thank_donor(gift_id, phone)
Jusa::Reward.create({
program: "prg_thanks",
completion_id: "gift-#{gift_id}",
recipient: { phone: phone },
amount: "0.50",
}, idempotency_key: "gift-#{gift_id}")
rescue Jusa::InsufficientCreditError
top_up_and_try_later # nothing was charged: retry with the same idempotency key
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/rewards \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Idempotency-Key: gift-1207" \
-H "Content-Type: application/json" \
-d '{
"program": "prg_thanks",
"completion_id": "gift-1207",
"recipient": {"phone": "0771230000"},
"amount": "0.50"
}'
Calls: rewards.create
Payday ZESA nudge
For HR platforms.
ZESA units are banded and reset monthly: a quote shows what the money buys before and after the reset, so staff choose when to buy.
- Quote on payday.
- A payday schedule for those who opt in.
Python
def quote_payday_zesa(meter_number: str) -> None:
try:
quote = jusa.Quote.create(
product="zesa-usd",
amount="30.00",
target=meter_number,
)
print(quote.zesa.units_now, quote.zesa.units_after_reset)
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 quotePaydayZesa(meterNumber) {
try {
const quote = await jusa.quotes.create({
product: 'zesa-usd',
amount: '30.00',
target: meterNumber,
});
console.log(quote.zesa.units_now, quote.zesa.units_after_reset);
} catch (error) {
if (error instanceof JusaError) {
console.error(`Jusa refused: ${error.code} [${error.requestId}]`);
}
throw error;
}
}
PHP
function quotePaydayZesa(\Jusa\JusaClient $jusa, string $meterNumber): void
{
try {
$quote = $jusa->quotes->create([
'product' => 'zesa-usd',
'amount' => '30.00',
'target' => $meterNumber,
]);
echo $quote->zesa->units_now, ' ', $quote->zesa->units_after_reset, "\n";
} catch (\Jusa\Exception\JusaException $jusaError) {
error_log("Jusa refused: {$jusaError->getErrorCode()} [{$jusaError->getRequestId()}]");
throw $jusaError;
}
}
Go
func quotePaydayZesa(ctx context.Context, meterNumber string) error {
quote, err := jusaClient.Quotes.Create(ctx, jusa.Params{
"product": "zesa-usd",
"amount": "30.00",
"target": meterNumber,
})
if err != nil {
return fmt.Errorf("quotes.create: %w", err)
}
fmt.Println(quote.Zesa.UnitsNow, quote.Zesa.UnitsAfterReset)
return nil
}
Java
void quotePaydayZesa(String meterNumber) throws JusaException {
try {
var quote = jusa.quotes().create(Params.of(
"product", "zesa-usd",
"amount", "30.00",
"target", meterNumber
));
System.out.println(quote.getZesa().getUnitsNow() + " " + quote.getZesa().getUnitsAfterReset());
} catch (JusaException jusaError) {
LOGGER.severe("Jusa refused: " + jusaError.getCode() + " [" + jusaError.getRequestId() + "]");
throw jusaError;
}
}
C#
async Task QuotePaydayZesaAsync(string meterNumber)
{
try
{
var quote = await jusa.Quotes.CreateAsync(new
{
product = "zesa-usd",
amount = "30.00",
target = meterNumber,
});
Console.WriteLine($"{quote.Zesa?.UnitsNow} {quote.Zesa?.UnitsAfterReset}");
}
catch (JusaException jusaError)
{
logger.LogError(jusaError, "Jusa refused: {Code} [{RequestId}]", jusaError.Code, jusaError.RequestId);
throw;
}
}
Dart
Future<void> quotePaydayZesa(String meterNumber) async {
try {
final quote = await jusa.quotes.create({
'product': 'zesa-usd',
'amount': '30.00',
'target': meterNumber,
});
print('${quote.zesa?.unitsNow} ${quote.zesa?.unitsAfterReset}');
} on JusaException catch (jusaError) {
stderr.writeln('Jusa refused: ${jusaError.code} [${jusaError.requestId}]');
rethrow;
}
}
Ruby
def quote_payday_zesa(meter_number)
quote = Jusa::Quote.create(product: "zesa-usd", amount: "30.00", target: meter_number)
puts "#{quote.zesa.units_now} #{quote.zesa.units_after_reset}"
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/quotes \
--fail-with-body \
-H "Authorization: Bearer $JUSA_SECRET_KEY" \
-H "Content-Type: application/json" \
-d '{"product": "zesa-usd", "amount": "30.00", "target": "37261502217"}'
Calls: quotes.create · schedules.create