Code examples
A complete sandbox integration: get a token, look up a number, optionally select another operator, create the order, confirm it and follow the result.
These examples use sandbox credentials. Run them on your server — never in a browser or mobile app, where the client_secret would be exposed.
/mobile-recharge/lookup— automatic identification of the operator./mobile-recharge/operator-switch— only if the customer chooses another operator./mobile-recharge/orders— creates the order with yourexternal_ref_id(one per transaction) and a newIdempotency-Key. Does not execute the recharge.- Store the
transaction_idreturned by Ecovoy next to yourexternal_ref_id. /mobile-recharge/confirm— executes the recharge. (Or/cancel-transactionto give up, only before confirming.)GET /transactions/{transaction_id}— until the status is final.
#!/usr/bin/env bash
# Complete sandbox flow: token -> lookup -> (operator-switch) -> order -> confirm -> status.
# Requires jq and uuidgen. A number ending in 1111 creates a PENDING order in the sandbox.
set -euo pipefail
BASE=https://api.ecovoy.com/api/v2
MOBILE="+50944101111"
TOKEN=$(curl -s -X POST "$BASE/oauth/token" \
-d grant_type=client_credentials \
-d client_id="$ECOVOY_CLIENT_ID" \
-d client_secret="$ECOVOY_CLIENT_SECRET" | jq -r .access_token)
# 1. Automatic identification
curl -s -X POST "$BASE/mobile-recharge/lookup" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d "{\"mobile_number\": \"$MOBILE\"}" | jq '.data.operators, .data.products'
# 2. (Optional) the customer chose another operator: use the products of THAT operator
PRODUCT=$(curl -s -X POST "$BASE/mobile-recharge/operator-switch" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d "{\"mobile_number\": \"$MOBILE\", \"operator_id\": \"sbx-ht-002\", \"country_iso_code\": \"HTI\"}" \
| jq -r '.data.products[0].id')
# 3. Create the order with the reference of this sale in YOUR system (one per transaction).
# Keep the key: on a network error, retry with the SAME key and body.
REF="ORDER-2026-000123"
KEY=$(uuidgen)
ORDER=$(curl -s -X POST "$BASE/mobile-recharge/orders" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-H "Idempotency-Key: $KEY" \
-d "{\"mobile_number\": \"$MOBILE\", \"product_id\": \"$PRODUCT\", \"external_ref_id\": \"$REF\", \"external_customer_id\": \"CUSTOMER-001\"}")
# 4. Store the transaction_id generated by Ecovoy next to your external_ref_id
TX=$(echo "$ORDER" | jq -r .data.transaction_id)
echo "$ORDER" | jq '.data | {transaction_id, external_ref_id, status}' # status: PENDING
# 5. Execute the recharge
curl -s -X POST "$BASE/mobile-recharge/confirm" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d "{\"transaction_id\": \"$TX\"}" | jq '.data.status'
# 6. Follow the result
curl -s "$BASE/transactions/$TX" -H "Authorization: Bearer $TOKEN" | jq .data.status
<?php
// Plain PHP 8 + ext-curl. Keep credentials in environment variables.
final class EcovoyClient
{
private ?string $token = null;
private int $expiresAt = 0;
public function __construct(
private string $clientId,
private string $clientSecret,
private string $baseUrl = 'https://api.ecovoy.com/api/v2',
) {}
public function request(string $method, string $path, ?array $body = null, array $headers = []): array
{
$ch = curl_init($this->baseUrl . $path);
$headers[] = 'Authorization: Bearer ' . $this->token();
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
]);
$json = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status >= 400) {
throw new RuntimeException(($json['error']['code'] ?? 'http_' . $status) . ': ' . ($json['error']['message'] ?? ''));
}
return $json['data'] ?? $json;
}
private function token(): string
{
if ($this->token && $this->expiresAt > time() + 60) {
return $this->token;
}
$ch = curl_init($this->baseUrl . '/oauth/token');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'client_credentials',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
]),
]);
$t = json_decode(curl_exec($ch), true);
curl_close($ch);
if (empty($t['access_token'])) {
throw new RuntimeException($t['error'] ?? 'token_error');
}
$this->token = $t['access_token'];
$this->expiresAt = time() + $t['expires_in'];
return $this->token;
}
}
$ecovoy = new EcovoyClient(getenv('ECOVOY_CLIENT_ID'), getenv('ECOVOY_CLIENT_SECRET'));
$mobile = '+50944101111'; // sandbox: ending in 1111 creates a PENDING order
// 1. Automatic identification
$lookup = $ecovoy->request('POST', '/mobile-recharge/lookup', ['mobile_number' => $mobile]);
$products = $lookup['products'];
// 2. (Optional) the customer chose another operator
$chosen = $lookup['operators'][1];
$switch = $ecovoy->request('POST', '/mobile-recharge/operator-switch', [
'mobile_number' => $mobile,
'operator_id' => $chosen['id'],
'country_iso_code' => $chosen['country_iso'],
]);
$products = $switch['products']; // use the products of the selected operator
if (!$products) {
throw new RuntimeException('No products for this operator.');
}
// 3. Create the order. external_ref_id = the id of this sale in YOUR system,
// one per transaction. Persist the key BEFORE sending, so a retry reuses it.
$externalRefId = 'ORDER-2026-000123'; // e.g. $myOrder->number
$idempotencyKey = bin2hex(random_bytes(16));
$order = $ecovoy->request('POST', '/mobile-recharge/orders', [
'mobile_number' => $mobile,
'product_id' => $products[0]['id'],
'external_ref_id' => $externalRefId,
'external_customer_id' => 'CUSTOMER-001',
], ['Idempotency-Key: ' . $idempotencyKey]);
// 4. Store the transaction_id generated by Ecovoy next to your external_ref_id
$transactionId = $order['transaction_id'];
// e.g. UPDATE my_orders SET ecovoy_transaction_id = $transactionId WHERE number = $externalRefId
// 5. Execute the recharge (Production also needs amount + currency)
$confirm = ['transaction_id' => $transactionId];
if ($order['environment'] === 'production') {
$confirm += [
'amount' => $order['retail_amount'],
'converted_retail_amount' => $order['retail_amount'],
'converted_currency' => $order['retail_unit'],
];
}
$ecovoy->request('POST', '/mobile-recharge/confirm', $confirm);
// 6. Follow the result until it is final
do {
sleep(2);
$status = $ecovoy->request('GET', '/transactions/' . $transactionId)['status'];
} while ($status === 'PENDING');
echo $status; // CONFIRMED / COMPLETED = success
// Node.js 18+ (server side). Keep credentials in environment variables.
import { randomUUID } from 'node:crypto';
const BASE = 'https://api.ecovoy.com/api/v2';
let cached = null;
async function token() {
if (cached && cached.expiresAt > Date.now() + 60_000) return cached.value;
const res = await fetch(`${BASE}/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: process.env.ECOVOY_CLIENT_ID,
client_secret: process.env.ECOVOY_CLIENT_SECRET,
}),
});
const t = await res.json();
if (!res.ok) throw new Error(t.error);
cached = { value: t.access_token, expiresAt: Date.now() + t.expires_in * 1000 };
return cached.value;
}
async function ecovoy(method, path, body, headers = {}) {
const res = await fetch(`${BASE}${path}`, {
method,
headers: {
Authorization: `Bearer ${await token()}`,
...(body ? { 'Content-Type': 'application/json' } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
const json = await res.json();
if (!res.ok) throw new Error(`${json.error?.code ?? res.status}: ${json.error?.message ?? ''}`);
return json.data ?? json;
}
const mobile = '+50944101111'; // sandbox: ending in 1111 creates a PENDING order
// 1. Automatic identification
const lookup = await ecovoy('POST', '/mobile-recharge/lookup', { mobile_number: mobile });
let products = lookup.products;
// 2. (Optional) the customer chose another operator
const chosen = lookup.operators[1];
const switched = await ecovoy('POST', '/mobile-recharge/operator-switch', {
mobile_number: mobile,
operator_id: chosen.id,
country_iso_code: chosen.country_iso,
});
products = switched.products; // use the products of the selected operator
if (products.length === 0) throw new Error('No products for this operator.');
// 3. Create the order. external_ref_id = the id of this sale in YOUR system,
// one per transaction. Persist the key BEFORE sending, so a retry reuses it.
const externalRefId = 'ORDER-2026-000123'; // e.g. myOrder.number
const idempotencyKey = randomUUID();
const order = await ecovoy(
'POST',
'/mobile-recharge/orders',
{
mobile_number: mobile,
product_id: products[0].id,
external_ref_id: externalRefId,
external_customer_id: 'CUSTOMER-001',
},
{ 'Idempotency-Key': idempotencyKey },
);
// 4. Store the transaction_id generated by Ecovoy next to your external_ref_id
const transactionId = order.transaction_id;
// 5. Execute the recharge (Production also needs amount + currency)
const confirm = { transaction_id: transactionId };
if (order.environment === 'production') {
Object.assign(confirm, {
amount: order.retail_amount,
converted_retail_amount: order.retail_amount,
converted_currency: order.retail_unit,
});
}
await ecovoy('POST', '/mobile-recharge/confirm', confirm);
// 6. Follow the result until it is final
let status;
do {
await new Promise(r => setTimeout(r, 2000));
({ status } = await ecovoy('GET', `/transactions/${transactionId}`));
} while (status === 'PENDING');
console.log(status); // CONFIRMED / COMPLETED = success
Testing different results
In the sandbox, the end of the mobile number decides the order result:
…1111: the order staysPENDING. Use it to test confirm and cancel, as in Production.…0000: the order isFAILED, withfailure_reason.- Anything else: the order is
COMPLETEDimmediately;/confirmthen returns409 TRANSACTION_NOT_PENDING.
In Production every order starts as PENDING and must be confirmed within 15 minutes. See POST /mobile-recharge/orders.
Retries
- Order creation: on a network error or
5xx, retry with the sameIdempotency-Keyand the same body (sameexternal_ref_id). If the answer is409 DUPLICATE_EXTERNAL_REF_ID, the first request did create the order: continue witherror.details.transaction_id. See Idempotency. - Confirmation: never create a new order because a confirmation timed out. Check
GET /transactions/{transaction_id}first.
Next steps
- Handle errors by
error.code— see Error codes. - Check your calls in Dashboard → API usage.
- Ready? Request Production access from your application page.