Laravel: pay couriers and refund
Pay your couriers by transfer, batch the evening payouts and refund an order from Laravel, reusing the client, the webhook job and the scheduler from Laravel: accept payments.
The API has no idempotency key and ext_id is not unique. Each payout therefore gets a stable ext_id, which the code searches for before creating anything (see Reconciliation and duplicates).
1. Extend the client
Section titled “1. Extend the client”Add these methods to app/Services/SenfenicoClient.php. They reuse get(), post(), http() and parse() from the payments client.
// add to app/Services/SenfenicoClient.phppublic function createTransfer(array $payload): array{ return $this->post('transfers/', $payload);}
public function transfer(string $reference): array{ return $this->get('transfers/'.rawurlencode($reference).'/');}
public function transfersByExtId(string $extId): array{ return $this->get('transfers/', ['ext_id' => $extId]);}
public function balances(): array{ return $this->get('balances/');}
public function bulkTransfers(array $items): array{ // 100 items saved one by one: generous timeout return $this->parse( $this->http()->timeout(180) ->post('transfers/bulk/', ['transfers' => $items]) );}
public function createRefund(array $payload): array{ return $this->post('refunds/', $payload);}
public function refund(string $reference): array{ return $this->get('refunds/'.rawurlencode($reference).'/');}
public function refundsByExtId(string $extId): array{ return $this->get('refunds/', ['ext_id' => $extId]);}2. Pay a courier with a transfer
Section titled “2. Pay a courier with a transfer”POST /v1/payment/transfers/ sends money from your balance to a mobile money account. Fields are described in Transfers.
// payouts table migrationSchema::create('payouts', function (Blueprint $table) { $table->id(); $table->foreignId('courier_id')->constrained(); $table->unsignedInteger('amount'); // XOF $table->string('phone', 20); // 8 digits $table->string('ext_id')->unique(); // payout-42, then payout-42-2 $table->string('senfenico_reference', 200)->nullable(); $table->string('status')->default('new'); $table->timestamps();});<?phpnamespace App\Jobs;
use App\Models\Payout;use App\Services\SenfenicoClient;use Illuminate\Contracts\Queue\ShouldBeUnique;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Http\Client\ConnectionException;
class PayCourier implements ShouldQueue, ShouldBeUnique{ use Queueable;
public int $tries = 3; public array $backoff = [120, 600]; // give the API time
public function __construct(public Payout $payout) { }
public function uniqueId(): string { return (string) $this->payout->id; // never 2 at once }
public function handle(SenfenicoClient $senfenico): void { $payout = $this->payout->fresh(); if ($payout->senfenico_reference) { return; // already created }
// 1. A previous attempt may have worked without a response. $found = $senfenico->transfersByExtId($payout->ext_id)['data']; if ($found) { $payout->update([ 'senfenico_reference' => $found[0]['reference'], 'status' => $found[0]['status'], ]); return; }
// 2. Otherwise, create the transfer. try { $transfer = $senfenico->createTransfer([ 'amount' => (int) $payout->amount, 'recipient_phone' => $payout->phone, 'ext_id' => $payout->ext_id, ])['data']; } catch (ConnectionException $e) { // Outcome unknown: the next attempt searches by // ext_id first (step 1). $payout->update(['status' => 'unknown']); throw $e; }
$payout->update([ 'senfenico_reference' => $transfer['reference'], 'status' => $transfer['status'], // "pending" ]); }}Response from POST /v1/payment/transfers/ (HTTP 201):
{ "status": true, "message": "Transfer has been queued", "data": { "reference": "TR261126-180002-ORANGE_BF-5d6e7f8a9b", "amount": 2500, "fees": 2.99, "recipient_phone": "76000000", "currency": "XOF", "ip_address": "203.0.113.10", "status": "pending", "live_mode": false, "recipient_wallet": "orange_bf", "ext_id": "payout-42", "created_at": "2026-11-26T18:00:02.418210Z" }}- Without
recipient_wallet, the operator is inferred from the number’s second digit (0 to 3 for Moov, 4 to 7 for Orange). The amount ranges from 100 to 1,000,000 XOF. feesis your fee rate in percent, not an amount. The create response returns it as a number (2.99), retrievals and lists as a string ("2.990"). Your balance is debitedamount × (1 + fees / 100).- An insufficient balance (fees included) returns HTTP
403witherror_code: "MERCHANT_INSUFFICIENT_FUNDS". No transfer is created, and you can retry after a top-up. - The status moves from
pendingtoin_transit, then tosuccessorfailed.in_transitis not final.
Retry a failed transfer
Section titled “Retry a failed transfer”If the transfer found in step 1 is failed, the job records failed and stops. To pay again, give the payout a new ext_id, clear senfenico_reference, then dispatch the job again. While a transfer is pending, in_transit or success, never recreate it.
// only if the previous transfer is "failed"$payout->update([ 'ext_id' => $payout->ext_id.'-2', // payout-42-2 'senfenico_reference' => null, 'status' => 'new',]);PayCourier::dispatch($payout);Track the status with transfer.* webhooks
Section titled “Track the status with transfer.* webhooks”Subscribe transfer.success and transfer.failed on the Developer › Webhooks page, then add these cases to the switch in HandleSenfenicoEvent (section 4 of the payments guide), with use App\Models\Payout;:
case 'transfer.success':case 'transfer.failed': $transfer = $senfenico->transfer($reference)['data']; Payout::where('senfenico_reference', $reference) ->update(['status' => $transfer['status']]); break;The dashboard can only resend charge notifications, not transfer ones. If a transfer webhook is lost, re-read the transfer with GET /v1/payment/transfers/{reference}/.
3. Evening bulk payout
Section titled “3. Evening bulk payout”Every evening at 7 p.m., a job pays every waiting courier with POST /v1/payment/transfers/bulk/. It replaces PayCourier for these payouts, so don’t use both on the same payouts row.
The batch rules are detailed in Bulk transfers: 100 items at most, a 202 response even when everything was rejected, accepted items without a reference or status. The job follows the retry policy from that page. A pending, in_transit or success transfer is never resent. An item still missing 10 minutes after sending goes out again with the same ext_id. A failed transfer goes out again with a new suffixed ext_id (payout-42-2), 3 attempts at most.
Columns and configuration
Section titled “Columns and configuration”The ext_id is computed when sending, as payout-{id}-{attempt}.
// migration: extend the payouts table from section 2Schema::table('payouts', function (Blueprint $table) { if (! Schema::hasColumn('payouts', 'attempt')) { $table->unsignedTinyInteger('attempt')->default(1); } // computed when sending, cleared before a new attempt $table->string('ext_id')->nullable()->change();});// config/services.php, inside 'senfenico'// your highest transfer fee rate, in %// (a transfer's fees field, e.g. 2.99)'transfer_fee_rate' => env('SENFENICO_TRANSFER_FEE_RATE'),The evening job
Section titled “The evening job”It first checks the transfer balance (GET /v1/payment/balances/), then sends batches of 100. Each row moves to queued before the call, so reconciliation knows what to look for if the connection drops.
<?phpnamespace App\Jobs;
use App\Models\Payout;use App\Services\SenfenicoClient;use Illuminate\Contracts\Queue\ShouldBeUnique;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Http\Client\ConnectionException;use Illuminate\Support\Collection;use Illuminate\Support\Facades\Log;
class PayCouriersEvening implements ShouldQueue, ShouldBeUnique{ use Queueable;
public int $tries = 1; // never blindly resend the batch public int $timeout = 1800;
public function handle(SenfenicoClient $senfenico): void { $todo = Payout::where('status', 'new') ->orderBy('id')->get();
if ($todo->isEmpty() || ! $this->funded($senfenico, $todo)) { return; }
foreach ($todo->chunk(100) as $batch) { // 100 maximum $this->send($senfenico, $batch); } }
private function funded( SenfenicoClient $senfenico, Collection $todo, ): bool { $data = $senfenico->balances()['data']; $balances = $data['transfer_balances']; $rate = (float) config('services.senfenico.transfer_fee_rate');
$needed = []; foreach ($todo as $p) { // 2nd digit 0-3: Moov, 4-7: Orange $key = $p->phone[1] <= '3' ? 'moov_bf' : 'orange_money_bf'; $needed[$key] = ($needed[$key] ?? 0) + $p->amount * (1 + $rate / 100); }
foreach ($needed as $key => $sum) { if ($balances[$key]['available'] < $sum) { Log::warning('Senfenico: insufficient balance', [ 'balance' => $key, 'needed' => $sum, ]); return false; // nothing is sent } }
return true; }
private function send( SenfenicoClient $senfenico, Collection $batch, ): void { foreach ($batch as $p) { $p->update([ 'ext_id' => "payout-{$p->id}-{$p->attempt}", 'status' => 'queued', ]); }
try { $body = $senfenico->bulkTransfers( $batch->map(fn ($p) => [ 'amount' => (int) $p->amount, 'recipient_phone' => $p->phone, 'ext_id' => $p->ext_id, ])->values()->all() ); } catch (ConnectionException $e) { report($e); // outcome unknown: rows stay "queued" return; }
// 202 even if everything failed: read failed_transfers foreach ($body['failed_transfers'] ?? [] as $failed) { $p = $batch->firstWhere( 'ext_id', $failed['data']['ext_id'] ?? null, ); // errors as a string: the transfer may exist, // the row stays "queued" and gets reconciled if (! $p || is_string($failed['errors'])) { continue; }
$why = $failed['errors']['non_field_errors'][0] ?? ''; $p->update([ // rejected: nothing was created 'status' => str_starts_with($why, 'Insufficient') ? 'new' // same ext_id in the next batch : 'rejected', // phone or amount to fix ]); Log::warning('Senfenico: transfer rejected', $failed); } // The others were created; their reference comes // from reconciliation. }}In a batch, an insufficient balance doesn’t carry the MERCHANT_INSUFFICIENT_FUNDS code. It shows up in failed_transfers as "non_field_errors": ["Insufficient balance for Moov BF transfer including fees."]. The upfront check avoids a half-paid batch, and the balance is re-checked for each item anyway.
Reconciling by ext_id
Section titled “Reconciling by ext_id”<?phpnamespace App\Jobs;
use App\Models\Payout;use App\Services\SenfenicoClient;use Illuminate\Contracts\Queue\ShouldBeUnique;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;
class ReconcilePayouts implements ShouldQueue, ShouldBeUnique{ use Queueable;
public function handle(SenfenicoClient $senfenico): void { // 1. Sent without a reference: search by ext_id. // 10 min: time for the batch to be saved. $sent = Payout::whereIn('status', ['queued', 'unknown']) ->where('updated_at', '<', now()->subMinutes(10)) ->get();
foreach ($sent as $p) { $found = $senfenico ->transfersByExtId($p->ext_id)['data']; if ($found) { $this->apply($p, $found[0]); } else { // absent: nothing was created, same ext_id $p->update(['status' => 'new']); } }
// 2. Created but not final yet (or failed // received by webhook). $open = Payout::whereIn( 'status', ['pending', 'in_transit', 'failed'] )->whereNotNull('senfenico_reference')->get();
foreach ($open as $p) { $ref = $p->senfenico_reference; $this->apply($p, $senfenico->transfer($ref)['data']); } }
private function apply(Payout $p, array $transfer): void { if ($transfer['status'] !== 'failed') { // pending, in_transit, success: resend nothing $p->update([ 'senfenico_reference' => $transfer['reference'], 'status' => $transfer['status'], ]); return; }
if ($p->attempt >= 3) { $p->update(['status' => 'needs_review']); return; }
// final failure: new ext_id in the next batch $p->update([ 'attempt' => $p->attempt + 1, 'ext_id' => null, 'senfenico_reference' => null, 'status' => 'new', ]); }}If the ext_id search returns several transfers, a duplicate was already created. Flag it instead of paying again. transfer.* webhooks for a bulk item only find the row once this reconciliation has stored its reference.
Scheduling
Section titled “Scheduling”use App\Jobs\PayCouriersEvening;use App\Jobs\ReconcilePayouts;use Illuminate\Support\Facades\Schedule;
Schedule::job(new PayCouriersEvening) ->dailyAt('19:00') ->timezone('Africa/Ouagadougou'); // Benin: Africa/Porto-Novo
Schedule::job(new ReconcilePayouts)->everyFifteenMinutes();A row set back to new goes out with the next day’s batch. After a top-up, you can send a batch right away with PayCouriersEvening::dispatch(). In test mode, transfers are simulated and move to success without contacting the operator.
4. Refund an order
Section titled “4. Refund an order”A refund gives back all or part of the charge that paid the order. You create it through the API, but the Senfenico team processes it manually, with no guaranteed delay. It stays pending until then, and always in test mode. The full rules are in Refunds.
The table
Section titled “The table”// migration: one refund per row (partial refunds allowed)Schema::create('order_refunds', function (Blueprint $table) { $table->id(); $table->foreignId('order_id')->constrained(); $table->unsignedInteger('amount'); // XOF $table->string('ext_id')->unique(); // refund-5531-1 $table->string('senfenico_reference', 200) ->nullable()->unique(); // re_… $table->string('status')->default('new'); $table->timestamps();});Add the relations Order::refunds() (hasMany) and OrderRefund::order() (belongsTo).
Create the refund
Section titled “Create the refund”The order only knows the checkout reference, while the charge field of POST /v1/payment/refunds/ expects the charge reference. The service reads it from the checkout’s charge_reference.
<?phpnamespace App\Services;
use App\Models\OrderRefund;use Illuminate\Http\Client\ConnectionException;use RuntimeException;
class OrderRefunder{ public function __construct(private SenfenicoClient $senfenico) { }
public function refund(OrderRefund $refund): void { if ($refund->senfenico_reference) { return; // already created }
// 1. A previous attempt may have worked without a response. $found = $this->senfenico ->refundsByExtId($refund->ext_id)['data']; if ($found) { $refund->update([ 'senfenico_reference' => $found[0]['reference'], 'status' => $found[0]['status'], ]); return; }
// 2. The charge that paid, through the checkout. $checkout = $this->senfenico ->checkout($refund->order->senfenico_reference)['data']; if (empty($checkout['charge_reference'])) { throw new RuntimeException('Checkout has no charge'); }
// 3. Create the refund. try { $created = $this->senfenico->createRefund([ 'charge' => $checkout['charge_reference'], 'amount' => (int) $refund->amount, 'reason' => 'requested_by_customer', 'note' => 'Order '.$refund->order_id, 'ext_id' => $refund->ext_id, ])['data']; } catch (ConnectionException $e) { // outcome unknown: the next attempt searches // by ext_id first (step 1) $refund->update(['status' => 'unknown']); throw $e; }
$refund->update([ 'senfenico_reference' => $created['reference'], 'status' => $created['status'], // "pending" ]); }}// for example in an admin controller$n = $order->refunds()->count() + 1;$refund = $order->refunds()->create([ 'amount' => 1000, // XOF, partial allowed 'ext_id' => "refund-{$order->id}-{$n}",]);app(OrderRefunder::class)->refund($refund);Response from POST /v1/payment/refunds/ (HTTP 201). The request is recorded, not yet executed.
{ "status": true, "message": "Refund attempted", "data": { "reference": "re_8d2f6a1c0b9e4d7fa3c5e1b2d4f6a8c0", "charge": "CH261126-101502-ORANGE_BF-8b41079ee8", "amount": 1000, "reason": "requested_by_customer", "status": "pending", "live_mode": false, "note": "Order 5531", "ext_id": "refund-5531-1", "created_at": "2026-11-26T11:40:09.512330Z" }}amountis required and greater than 0. The sum of a charge’spendingandsuccessrefunds can’t exceed its amount, andfailedones don’t count.reasonis optional and takesrequested_by_customer,fraudulentorabandoned.- A rejection throws
SenfenicoExceptionwith HTTP400,errorCodeINVALID_DATAand the details inerrors, for exampleOnly successful charges can be refunded.orRefund amount exceeds the remaining charge balance. charge_referenceis the last payment attempt made on the checkout page. If it isn’tsuccess, the refund is rejected. Check the charge or write tocontact@senfenico.com.
Track the status with refund.* webhooks
Section titled “Track the status with refund.* webhooks”Subscribe refund.pending, refund.success and refund.failed on the Developer › Webhooks page. Here is the data of a refund webhook, once decoded:
{ "reference": "re_8d2f6a1c0b9e4d7fa3c5e1b2d4f6a8c0", "charge": 48213, "amount": 1000, "mmo": "orange_bf", "reason": "requested_by_customer", "status": "success", "live_mode": false, "note": "Order 5531", "ext_id": "refund-5531-1", "created_at": "2026-11-26T11:40:09.512Z", "updated_at": "2026-11-28T09:12:44.031Z"}refund.pending is sent as soon as the refund is created and can arrive before your code has stored that reference. The job then falls back to your ext_id. Add these cases to the switch in HandleSenfenicoEvent, with use App\Models\OrderRefund;:
case 'refund.pending':case 'refund.success':case 'refund.failed': // re-read the refund instead of trusting the webhook $r = $senfenico->refund($reference)['data']; $local = OrderRefund::where('senfenico_reference', $reference) ->first() ?? OrderRefund::where('ext_id', (string) $r['ext_id']) ->first(); $local?->update([ 'senfenico_reference' => $reference, 'status' => $r['status'], ]); break;In test mode, a refund stays pending and you can’t trigger refund.success on demand. Cover this case with an automated test. Http::fake() simulates the GET /v1/payment/refunds/{reference}/ response with "status": "success", then you run the job with a data like the one above.
Going live
Section titled “Going live”- Set
SENFENICO_TRANSFER_FEE_RATEto your live rate, then runphp artisan config:cache. - If you enabled the IP allowlist, add the outbound IP of the workers that run the transfer and refund jobs.
- Subscribe
transfer.*andrefund.*in live mode, because subscriptions are separate from test mode.
Checklist
Section titled “Checklist”- Every transfer has a stable
ext_id, andPayCouriersearches byext_idbefore creating. - A
failedtransfer is only retried with a new suffixedext_id. - The evening job checks the balance, sends batches of at most 100 and reads
failed_transfers. -
ReconcilePayoutsruns every 15 minutes and finds bulk transfers byext_id. - Refunds go through the checkout’s
charge_reference. -
refund.*webhooks are matched onreference, never oncharge.