Concepts
Idempotency
Retry anything that moves money without paying twice.
POST /sends
Python
def send_airtime_for_order(phone: str, order_id: str) -> None:
try:
# Sent twice, it is one send: the second answer is the first.
jusa.Send.create(
product="airtime-usd",
target=phone,
amount="1.00",
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 sendAirtimeForOrder(phone, orderId) {
try {
// Sent twice, it is one send: the second answer is the first.
await jusa.sends.create({
product: 'airtime-usd',
target: phone,
amount: '1.00',
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 sendAirtimeForOrder(\Jusa\JusaClient $jusa, string $phone, string $orderId): void
{
try {
// Sent twice, it is one send: the second answer is the first.
$jusa->sends->create([
'product' => 'airtime-usd',
'target' => $phone,
'amount' => '1.00',
'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 sendAirtimeForOrder(ctx context.Context, phone, orderID string) error {
// Sent twice, it is one send: the second answer is the first.
_, err := jusaClient.Sends.Create(ctx, jusa.Params{
"product": "airtime-usd",
"target": phone,
"amount": "1.00",
"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 sendAirtimeForOrder(String phone, String orderId) throws JusaException {
try {
// Sent twice, it is one send: the second answer is the first.
jusa.sends().create(Params.of(
"product", "airtime-usd",
"target", phone,
"amount", "1.00",
"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 SendAirtimeForOrderAsync(string phone, string orderId)
{
try
{
// Sent twice, it is one send: the second answer is the first.
await jusa.Sends.CreateAsync(new
{
product = "airtime-usd",
target = phone,
amount = "1.00",
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> sendAirtimeForOrder(String phone, String orderId) async {
try {
// Sent twice, it is one send: the second answer is the first.
await jusa.sends.create({
'product': 'airtime-usd',
'target': phone,
'amount': '1.00',
'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 send_airtime_for_order(phone, order_id)
# Sent twice, it is one send: the second answer is the first.
Jusa::Send.create({
product: "airtime-usd",
target: phone,
amount: "1.00",
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
# Sent twice, it is one send: the second answer is the first.
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 '{
"product": "airtime-usd",
"target": "0771230000",
"amount": "1.00",
"client_reference": "order-8812"
}'
A network can drop the answer to a request that worked. Send the same request again with the same
Idempotency-Key and you get the first answer back; nothing runs twice.
The rules
- Required on every POST that moves money (below), up to 255 characters. Without it:
400 idempotency_key_required. - A replay returns the same object, as it is now, with the first status code. It never runs again, however long after.
- The same key with a different body is
422 idempotency_mismatch. - The same key while the first request is still running is
409 idempotency_in_progress: wait and retry. - A request refused before it did anything (most 4xx) is not remembered: fix it and send it again with the same key.
- Keys are kept 30 days. They are written in the same database transaction as the money they protect.
Two keys that last for good
client_referenceon sends, batch lines and checkout sessions: your own id, unique in your account for ever. A second send with it returns the first (200).completion_idon rewards: unique in the program for ever. The same survey submission is one reward however many times it is reported.
Use them as well as the header: they protect you across restarts, deploys and months.
In the SDKs
The SDKs add a random key to every operation that takes one and reuse it across that call's own retries. That only protects retries inside one process: pass your own (an order id, a submission id) to be safe across restarts.
Operations that take a key
| Call | Idempotency-Key | |
|---|---|---|
| POST /batches | Create a batch | required |
| POST /batches/{batch_id}/approve | Approve a batch | required |
| POST /batches/{batch_id}/retry-failed | Retry a batch's failed items | required |
| POST /checkout-sessions | Create a checkout session | required |
| POST /credit/topups | Top up Jusa Credit | required |
| POST /programs/{program_id}/defund | Take budget back | required |
| POST /programs/{program_id}/fund | Add budget (and reserved credit) | required |
| POST /referrals/{referral_id}/qualify | Qualify a referral | required |
| POST /reviews/{review_id}/approve | Approve a held reward | required |
| POST /rewards | Reward someone | required |
| POST /rewards/{reward_id}/release | Release an escrowed reward | required |
| POST /schedules/{schedule_id}/run-now | Run a schedule now | required |
| POST /sends | Create a send | required |
| POST /sends/{send_id}/retry | Retry a failed send | required |
| POST /test/approvals/{approval_id}/approve | Approve (test mode) | required |
| POST /activities | Record an activity | optional |
| POST /batches/{batch_id}/cancel | Cancel a batch | optional |
| POST /checkins | Check in to claim a geofenced link | optional |
| POST /checkout-sessions/{session_id}/meter | Fix the meter while it waits | optional |
| POST /claims/{token} | Claim a reward link | optional |
| POST /cost-centers | Create a cost centre | optional |
| POST /disputes | Open a dispute | optional |
| POST /exports | Export to CSV | optional |
| POST /groups | Create a group | optional |
| POST /members | Invite a member | optional |
| POST /programs | Create a program | optional |
| POST /quotes | Quote a send | optional |
| POST /recipients | Create or update a recipient | optional |
| POST /recipients/bulk | Import recipients | optional |
| POST /referrals | Record a referral | optional |
| POST /reviews/{review_id}/reject | Reject a held reward | optional |
| POST /reward-links | Create reward links | optional |
| POST /rewards/{reward_id}/void | Void a reward | optional |
| POST /schedules | Create a schedule | optional |
| POST /sends/{send_id}/cancel | Cancel a send not yet sent | optional |
| POST /sends/{send_id}/meter | Change a ZESA send's meter | optional |
| POST /test/approvals/{approval_id}/reject | Reject (test mode) | optional |
| POST /test/credit | Add test Jusa Credit | optional |
| POST /webhook-deliveries/{delivery_id}/redeliver | Redeliver | optional |
| POST /webhook-endpoints | Add a webhook endpoint | optional |
| POST /webhook-endpoints/{endpoint_id}/replay | Replay events | optional |
| POST /webhook-endpoints/{endpoint_id}/roll-secret | Roll the signing secret | optional |
| POST /webhook-endpoints/{endpoint_id}/test | Send a test event | optional |
| POST /workforce/allocate | Allocate airtime or ZESA | optional |
| POST /workforce/batches/{reference}/resend | Resend the failed lines | optional |
| POST /workforce/schedules/{schedule_id}/run-now | Run a plan now | optional |