Skip to content

Laravel: accept payments

Collect Orange Money and Moov Money in a Laravel shop with the Http facade, a server-verified checkout, a signed webhook and scheduled reconciliation. To pay your couriers and refund orders, continue with Laravel: pay couriers and refund.

You need Laravel 11 or 12, PHP 8.2+, a queue (Redis or database), a cache store where Cache::add is atomic (Redis, Memcached, database) and your keys, available in the dashboard.

  1. Add your secrets to .env

    Fenêtre de terminal
    SENFENICO_SECRET_KEY=sk_test_...
    SENFENICO_WEBHOOK_SECRET=your_webhook_secret_key

    An sk_test_… key means test mode, sk_live_… means live mode. The webhook secret is the Signing secret shown on the dashboard’s Developer › Webhooks page.

  2. Declare them in config/services.php

    'senfenico' => [
    'base_url' => 'https://api.senfenico.com/v1/payment/',
    'secret_key' => env('SENFENICO_SECRET_KEY'),
    'webhook_secret' => env('SENFENICO_WEBHOOK_SECRET'),
    ],
  3. Add the payment columns

    Fenêtre de terminal
    php artisan make:migration add_senfenico_to_orders

    Your orders table already exists, with amount and status. The migration only adds the missing Senfenico columns and leaves your data alone.

    database/migrations/xxxx_add_senfenico_to_orders.php
    public function up(): void
    {
    $has = fn (string $c) => Schema::hasColumn('orders', $c);
    Schema::table('orders', function (Blueprint $table) use ($has) {
    if (! $has('senfenico_reference')) {
    $table->string('senfenico_reference', 200)
    ->nullable()->unique();
    }
    if (! $has('senfenico_checkout_url')) {
    $table->string('senfenico_checkout_url', 500)
    ->nullable();
    }
    if (! $has('paid_at')) {
    $table->timestamp('paid_at')->nullable();
    }
    });
    }

    In down(), only drop the columns this migration actually added.

    • amount must hold the amount in whole XOF (no cents). A decimal column works, because the code casts it with (int).
    • The code writes pending, paid and expired to status. If your shop uses other values, adapt them in PaymentConfirmer (section 3) and senfenico:reconcile (section 5), or add a senfenico_status column and use it instead.

    Treat Senfenico references as opaque strings (up to 200 characters), without testing their prefix.

A single class calls the API. It adds the X-API-KEY header, sets timeouts, and treats a response as a success only when the HTTP code is 2xx and status is true.

app/Exceptions/SenfenicoException.php
<?php
namespace App\Exceptions;
use RuntimeException;
class SenfenicoException extends RuntimeException
{
public function __construct(
string $message,
public readonly ?string $errorCode = null,
public readonly int $httpStatus = 0,
public readonly array $errors = [],
) {
parent::__construct($message);
}
}
app/Services/SenfenicoClient.php
<?php
namespace App\Services;
use App\Exceptions\SenfenicoException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
class SenfenicoClient
{
public function initializeCheckout(
int $amount,
string $successUrl,
string $cancelUrl,
): array {
return $this->post('checkouts/initialize/', [
'amount' => $amount,
'success_url' => $successUrl,
'cancel_url' => $cancelUrl,
]);
}
public function checkout(string $reference): array
{
return $this->get('checkouts/'.rawurlencode($reference).'/');
}
public function charge(string $reference): array
{
return $this->get('charges/'.rawurlencode($reference).'/');
}
/** Reference of the checkout that created this charge, or null. */
public function checkoutReferenceForCharge(string $chargeRef): ?string
{
$list = $this->get('checkouts/', [
'charge_reference' => $chargeRef,
]);
return $list['data'][0]['reference'] ?? null;
}
private function http(): PendingRequest
{
return Http::baseUrl(config('services.senfenico.base_url'))
->withHeaders([
'X-API-KEY' => config('services.senfenico.secret_key'),
])
->acceptJson()
->connectTimeout(10);
}
private function get(string $path, array $query = []): array
{
return $this->parse(
$this->http()->timeout(20)->get($path, $query)
);
}
private function post(string $path, array $data): array
{
// a create call may wait for the operator's answer
return $this->parse(
$this->http()->timeout(90)->post($path, $data)
);
}
private function parse(Response $response): array
{
$body = $response->json() ?? []; // null if not JSON
if ($response->successful()
&& ($body['status'] ?? null) === true) {
return $body;
}
throw new SenfenicoException(
$body['message'] ?? 'HTTP '.$response->status(),
$body['error_code'] ?? null,
$response->status(),
$body['errors'] ?? [],
);
}
}

The strict === true comparison is needed because an invalid key returns "status": "False" as a string (see Missing or invalid key). A refused charge initialization can also return HTTP 200 with status: false (see error handling).

A timeout throws Illuminate\Http\Client\ConnectionException. A read (GET) can be retried safely. For a create call, first search for the object by ext_id, because the API has no idempotency key (see Reconciliation and duplicates).

The same logic serves the return route, the webhook and reconciliation. It re-reads the checkout with your key, then its charge, compares the amount, and moves the order to paid exactly once with a conditional update.

app/Services/PaymentConfirmer.php
<?php
namespace App\Services;
use App\Models\Order;
use Illuminate\Support\Facades\Log;
class PaymentConfirmer
{
public function __construct(private SenfenicoClient $senfenico)
{
}
public function confirm(Order $order): bool
{
if ($order->status === 'paid') {
return true;
}
$checkout = $this->senfenico
->checkout($order->senfenico_reference)['data'];
// The checkout can stay "pending" while its charge
// succeeded (e.g. Moov USSD finished with the page
// closed): check the charge too.
$paid = $checkout['status'] === 'success';
if (! $paid && ! empty($checkout['charge_reference'])) {
$charge = $this->senfenico
->charge($checkout['charge_reference'])['data'];
$paid = $charge['status'] === 'success';
}
if (! $paid) {
return false;
}
if ((int) $checkout['amount'] !== (int) $order->amount) {
Log::critical('Senfenico: amount mismatch', [
'order' => $order->id,
'checkout' => $checkout['reference'],
]);
return false;
}
// Only one request wins, even if the webhook and the
// return page arrive at the same time.
$updated = Order::whereKey($order->id)
->whereIn('status', ['pending', 'expired'])
->update(['status' => 'paid', 'paid_at' => now()]);
if ($updated === 1) {
// fulfill here: event(new OrderPaid($order));
}
return true;
}
}
app/Http/Controllers/CheckoutController.php
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use App\Services\PaymentConfirmer;
use App\Services\SenfenicoClient;
use Illuminate\Http\Request;
class CheckoutController extends Controller
{
public function store(Order $order, SenfenicoClient $senfenico)
{
// also check that the order belongs to the user
abort_unless($order->status === 'pending', 409);
// Already have a checkout? Reuse it rather than creating
// a second one that could also get paid.
if ($order->senfenico_checkout_url) {
return redirect()->away($order->senfenico_checkout_url);
}
$body = $senfenico->initializeCheckout(
(int) $order->amount,
route('checkout.return'),
route('checkout.cancel'),
);
$order->update([
'senfenico_reference' => $body['data']['reference'],
'senfenico_checkout_url' => $body['data']['authorization_url'],
]);
return redirect()->away($body['data']['authorization_url']);
}
public function return(Request $request, PaymentConfirmer $confirmer)
{
// Senfenico appends ?reference=<checkout reference>.
// It finds the order; it does not prove payment.
$order = Order::where(
'senfenico_reference',
(string) $request->query('reference'),
)->firstOrFail();
$paid = $confirmer->confirm($order);
return view('orders.payment-return', [
'order' => $order->fresh(),
'paid' => $paid,
]);
}
public function cancel(Request $request)
{
$order = Order::where(
'senfenico_reference',
(string) $request->query('reference'),
)->firstOrFail();
return redirect()->route('orders.show', $order)
->with('status', 'Payment canceled. You can try again.');
}
}

Response from POST /v1/payment/checkouts/initialize/ (HTTP 201):

{
"status": true,
"message": "Checkout initialized",
"data": {
"reference": "CHK261126-101431--3f9a0c1d2e",
"authorization_url": "https://api.senfenico.com/v1/checkout_payment/payment_page/CHK261126-101431--3f9a0c1d2e/",
"live_mode": false
}
}

Response from GET /v1/payment/checkouts/{reference}/ once paid:

{
"status": true,
"message": "Checkout details retrieved",
"data": {
"email": null,
"reference": "CHK261126-101431--3f9a0c1d2e",
"charge_reference": "CH261126-101502-ORANGE_BF-8b41079ee8",
"amount": 1000,
"success_url": "https://shop.example/checkout/return",
"cancel_url": "https://shop.example/checkout/cancel",
"phone": "76000000",
"provider": "orange_bf",
"live_mode": false,
"created_at": "2026-11-26T10:14:31.512345Z",
"updated_at": "2026-11-26T10:15:02.104512Z",
"status": "success"
}
}
routes/web.php
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\SenfenicoWebhookController;
Route::post('/orders/{order}/pay', [CheckoutController::class, 'store'])
->name('checkout.store');
Route::get('/checkout/return', [CheckoutController::class, 'return'])
->name('checkout.return');
Route::get('/checkout/cancel', [CheckoutController::class, 'cancel'])
->name('checkout.cancel');
Route::post('/webhooks/senfenico', SenfenicoWebhookController::class)
->name('webhooks.senfenico');

Checkout accepts neither ext_id nor metadata, so the checkout reference stored on the order is your only link. The minimum amount is 100 XOF.

  1. Exempt the route from CSRF in bootstrap/app.php (Laravel 11+):

    ->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
    'webhooks/senfenico',
    ]);
    })

    On Laravel 10, add 'webhooks/senfenico' to the $except array of App\Http\Middleware\VerifyCsrfToken.

  2. Verify the signature, drop duplicates, queue

    The check is the one from Verify webhook signatures, moved into a controller.

    app/Http/Controllers/SenfenicoWebhookController.php
    <?php
    namespace App\Http\Controllers;
    use App\Jobs\HandleSenfenicoEvent;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Cache;
    use Throwable;
    class SenfenicoWebhookController extends Controller
    {
    public function __invoke(Request $request)
    {
    $payload = $request->getContent(); // raw body
    $timestamp = (string) $request->header('X-Senfenico-Timestamp');
    $signature = (string) $request->header('X-Senfenico-Signature');
    $secret = config('services.senfenico.webhook_secret');
    $fresh = ctype_digit($timestamp)
    && abs(time() - (int) $timestamp) <= 300;
    $valid = str_starts_with($signature, 'v1=')
    && hash_equals(
    hash_hmac('sha256', $timestamp.'.'.$payload, $secret),
    substr($signature, 3)
    );
    if (! $fresh || ! $valid) {
    return response('', 400);
    }
    // Same ID on every retry of the same event
    $delivery = (string) $request->header('X-Senfenico-Delivery');
    $key = 'senfenico:delivery:'.$delivery;
    if ($delivery !== ''
    && ! Cache::add($key, true, now()->addDays(2))) {
    return response('', 200); // duplicate
    }
    $event = json_decode($payload, true);
    $data = is_string($event['data']) // data is a JSON string
    ? json_decode($event['data'], true)
    : $event['data'];
    try {
    HandleSenfenicoEvent::dispatch($event['event'], $data);
    } catch (Throwable $e) {
    Cache::forget($key); // let Senfenico retry
    throw $e;
    }
    return response('', 200);
    }
    }
  3. Process the event in a job

    For money, the job doesn’t trust the webhook body and re-reads the object from the API. It first ignores events from the other mode (data.live_mode different from your key’s mode). checkout.* and settlement.* are currently sent in test mode and live mode alike, and re-reading them with the wrong key would fail with 404.

    app/Jobs/HandleSenfenicoEvent.php
    <?php
    namespace App\Jobs;
    use App\Models\Order;
    use App\Services\PaymentConfirmer;
    use App\Services\SenfenicoClient;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Queue\Queueable;
    class HandleSenfenicoEvent implements ShouldQueue
    {
    use Queueable;
    public int $tries = 5;
    public array $backoff = [10, 60, 300];
    public function __construct(
    public string $event,
    public array $data,
    ) {
    }
    public function handle(
    SenfenicoClient $senfenico,
    PaymentConfirmer $confirmer,
    ): void {
    $reference = $this->data['reference'] ?? null;
    if (! $reference) {
    return;
    }
    // checkout.* and settlement.* arrive in both modes
    $live = str_starts_with(
    (string) config('services.senfenico.secret_key'),
    'sk_live_'
    );
    if (($this->data['live_mode'] ?? null) !== $live) {
    return; // other mode: ignore, don't fail
    }
    switch ($this->event) {
    case 'checkout.success':
    $this->confirmOrder($reference, $confirmer);
    break;
    case 'charge.success':
    // was the charge created by a checkout?
    $checkoutRef = $senfenico
    ->checkoutReferenceForCharge($reference);
    if ($checkoutRef) {
    $this->confirmOrder($checkoutRef, $confirmer);
    }
    break;
    // transfer.* and refund.*: see laravel-payouts
    // other events: ignored (answering 200 is enough)
    }
    }
    private function confirmOrder(
    string $checkoutRef,
    PaymentConfirmer $confirmer,
    ): void {
    $order = Order::where('senfenico_reference', $checkoutRef)
    ->first();
    if ($order) {
    $confirmer->confirm($order);
    }
    }
    }
  4. Subscribe the URL in the dashboard

    On the Developer › Webhooks page, create one entry per event (checkout.success and charge.success), in test mode then in live mode. The URL must be public. Locally, use a tunnel (ngrok, Cloudflare Tunnel).

charge.success covers the customer who pays and then closes the page (see Confirm the payment server-side). Events are listed in the webhooks overview.

Webhooks are retried for about an hour only. A scheduled command re-checks orders still pending.

app/Console/Commands/ReconcileSenfenicoOrders.php
<?php
namespace App\Console\Commands;
use App\Models\Order;
use App\Services\PaymentConfirmer;
use Illuminate\Console\Command;
use Throwable;
class ReconcileSenfenicoOrders extends Command
{
protected $signature = 'senfenico:reconcile';
protected $description = 'Re-check pending Senfenico orders';
public function handle(PaymentConfirmer $confirmer): int
{
Order::where('status', 'pending')
->whereNotNull('senfenico_reference')
->where('created_at', '<', now()->subMinutes(10))
->where('created_at', '>', now()->subDays(2))
->chunkById(50, function ($orders) use ($confirmer) {
foreach ($orders as $order) {
try {
$confirmer->confirm($order);
} catch (Throwable $e) {
report($e); // move on to the next one
}
}
});
// Too old: mark as expired. A late payment still moves
// it to "paid" (see PaymentConfirmer).
Order::where('status', 'pending')
->where('created_at', '<=', now()->subDays(2))
->update(['status' => 'expired']);
return self::SUCCESS;
}
}
routes/console.php
use Illuminate\Support\Facades\Schedule;
Schedule::command('senfenico:reconcile')
->everyFifteenMinutes()
->withoutOverlapping();

Laravel’s scheduler needs a cron entry on the server: * * * * * cd /var/www/app && php artisan schedule:run >> /dev/null 2>&1. The 2-day window is this example’s choice, not a Senfenico rule. For a full nightly reconciliation, see the reconciliation guide.

With an sk_test_ key, pay on the checkout page with a test number, using the amount paired with it:

A 1,000 XOF order paid with Orange 76000000 and OTP 123456 should be paid on return, and the job should receive checkout.success.

  • Replace sk_test_ with sk_live_ in .env, then php artisan config:cache.
  • If you enabled the IP allowlist, add the outbound IP of your web servers and your queue workers.
  • Recreate webhook subscriptions in live mode, because they are separate from test mode.
  • Keys live in .env, never in Git or in a mobile app.
  • success_url and cancel_url contain no ?.
  • The return route re-reads the checkout and the charge from the API before fulfilling.
  • The amount returned by the API is compared with the order amount.
  • The move to paid is a conditional update (fulfilled once).
  • The webhook route is CSRF-exempt, verifies the HMAC signature and drops X-Senfenico-Delivery values already seen.
  • checkout.success and charge.success are subscribed, in test mode and live mode.
  • senfenico:reconcile runs through schedule:run.