Skip to content

PHP (cURL): checkout, verification and webhook

Collect Orange Money and Moov Money on a framework-free PHP site with cURL, PDO and four files you can copy as they are: senfenico.php, pay.php, return.php and webhook.php.

You need PHP 8.1+ with the curl, pdo_sqlite (or pdo_mysql) and json extensions, and a public URL for the webhook.

You need an orders table and a table of webhooks already received. The example uses SQLite (for MySQL, replace INSERT OR IGNORE with INSERT IGNORE below).

CREATE TABLE orders (
id INTEGER PRIMARY KEY,
amount INTEGER NOT NULL, -- XOF, integer
status TEXT NOT NULL DEFAULT 'pending',
senfenico_reference VARCHAR(200) UNIQUE,
checkout_url VARCHAR(500),
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE webhook_deliveries (
id VARCHAR(100) PRIMARY KEY, -- X-Senfenico-Delivery
received_at TEXT DEFAULT CURRENT_TIMESTAMP
);

senfenico.php holds the cURL client, the database connection and payment confirmation. It reads three environment variables: SENFENICO_SECRET_KEY (sk_test_… or sk_live_…), SENFENICO_WEBHOOK_SECRET (the Signing secret shown on the Developer › Webhooks page), APP_URL (e.g. https://shop.example).

senfenico.php
<?php
declare(strict_types=1);
const SENFENICO_BASE = 'https://api.senfenico.com/v1/payment';
final class SenfenicoError extends RuntimeException
{
public function __construct(
string $message,
public readonly int $http = 0, // 0 = network error
public readonly ?string $errorCode = null,
public readonly array $errors = [],
) {
parent::__construct($message);
}
}
function db(): PDO
{
static $pdo = null;
if ($pdo === null) {
$pdo = new PDO('sqlite:' . __DIR__ . '/shop.sqlite');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(
PDO::ATTR_DEFAULT_FETCH_MODE,
PDO::FETCH_ASSOC
);
}
return $pdo;
}
/** Calls the API. Returns the JSON envelope or throws SenfenicoError. */
function senfenico(string $method, string $path, ?array $body = null): array
{
$headers = [
'X-API-KEY: ' . getenv('SENFENICO_SECRET_KEY'),
'Accept: application/json',
];
$ch = curl_init(SENFENICO_BASE . $path);
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 10,
// a create call may wait for the operator's answer
CURLOPT_TIMEOUT => $method === 'GET' ? 20 : 90,
]);
$raw = curl_exec($ch);
if ($raw === false) {
throw new SenfenicoError('Network: ' . curl_error($ch));
}
$http = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$json = json_decode($raw, true);
$json = is_array($json) ? $json : []; // e.g. HTML 500 page
// Success = HTTP 2xx AND status strictly true
if ($http >= 200 && $http < 300 && ($json['status'] ?? null) === true) {
return $json;
}
throw new SenfenicoError(
$json['message'] ?? "HTTP $http",
$http,
$json['error_code'] ?? null,
$json['errors'] ?? [],
);
}
/** Verifies the payment with the API and marks the order paid. */
function confirm_order(array $order): bool
{
if ($order['status'] === 'paid') {
return true;
}
$ref = rawurlencode($order['senfenico_reference']);
$checkout = senfenico('GET', "/checkouts/$ref/")['data'];
// The checkout can stay "pending" while its charge
// succeeded: check the charge too.
$paid = $checkout['status'] === 'success';
if (!$paid && !empty($checkout['charge_reference'])) {
$chRef = rawurlencode($checkout['charge_reference']);
$charge = senfenico('GET', "/charges/$chRef/")['data'];
$paid = $charge['status'] === 'success';
}
if (!$paid) {
return false;
}
if ((int) $checkout['amount'] !== (int) $order['amount']) {
error_log("Senfenico: amount mismatch, order {$order['id']}");
return false;
}
// Conditional update: the order can only be fulfilled once
$stmt = db()->prepare(
"UPDATE orders SET status = 'paid'
WHERE id = ? AND status IN ('pending', 'expired')"
);
$stmt->execute([$order['id']]);
if ($stmt->rowCount() === 1) {
fulfill_order($order);
}
return true;
}
function fulfill_order(array $order): void
{
// send the email, unlock the product, etc.
}
function find_order_by_reference(string $reference): ?array
{
$stmt = db()->prepare(
'SELECT * FROM orders WHERE senfenico_reference = ?'
);
$stmt->execute([$reference]);
return $stmt->fetch() ?: null;
}

senfenico() requires an HTTP 2xx code and status === true, because an invalid key returns "status": "False" as a string (see Missing or invalid key).

<?php
// pay.php — called by the "Pay" form (POST order_id)
declare(strict_types=1);
require __DIR__ . '/senfenico.php';
$stmt = db()->prepare(
"SELECT * FROM orders WHERE id = ? AND status = 'pending'"
);
$stmt->execute([(int) ($_POST['order_id'] ?? 0)]);
$order = $stmt->fetch();
if (!$order) {
http_response_code(404);
exit('Order not found or already paid.');
}
// A checkout already exists: reuse it
if ($order['checkout_url']) {
header('Location: ' . $order['checkout_url'], true, 303);
exit;
}
try {
$res = senfenico('POST', '/checkouts/initialize/', [
'amount' => (int) $order['amount'], // min. 100 XOF
// No "?": Senfenico appends ?reference=...
'success_url' => getenv('APP_URL') . '/return.php',
'cancel_url' => getenv('APP_URL') . '/cancel.php',
]);
} catch (SenfenicoError $e) {
error_log("Checkout: {$e->getMessage()} ({$e->errorCode})");
http_response_code(502);
exit('Payment unavailable, please try again shortly.');
}
$stmt = db()->prepare(
'UPDATE orders SET senfenico_reference = ?, checkout_url = ?
WHERE id = ?'
);
$stmt->execute([
$res['data']['reference'],
$res['data']['authorization_url'],
$order['id'],
]);
header('Location: ' . $res['data']['authorization_url'], true, 303);

API response (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
}
}

Checkout has neither ext_id nor metadata, so the reference stored on the order is your only link to the payment.

Anyone can open return.php?reference=…, so the page re-reads the payment with your key before fulfilling the order (see Confirm the payment server-side).

return.php
<?php
declare(strict_types=1);
require __DIR__ . '/senfenico.php';
$order = find_order_by_reference((string) ($_GET['reference'] ?? ''));
if (!$order) {
http_response_code(404);
exit('Order not found.');
}
try {
$paid = confirm_order($order);
} catch (SenfenicoError $e) {
error_log("Verification: {$e->getMessage()}");
$paid = false; // the webhook or reconciliation will take over
}
if ($paid) {
echo 'Thank you! Your payment is confirmed.';
} else {
echo 'Payment being verified. '
. 'You will get a confirmation as soon as it clears.';
}

Response from GET /v1/payment/checkouts/{reference}/ after payment:

{
"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/return.php",
"cancel_url": "https://shop.example/cancel.php",
"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"
}
}

cancel.php also receives ?reference=…. Find the order there and offer to try again, since the same checkout_url stays usable.

Subscribe https://shop.example/webhook.php to checkout.success and charge.success (dashboard Developer › Webhooks page, in test mode then live mode). The check reuses the one from Verify webhook signatures.

webhook.php
<?php
declare(strict_types=1);
require __DIR__ . '/senfenico.php';
function verify_senfenico(
string $payload,
?string $timestamp,
?string $signature,
string $secret,
int $tolerance = 300
): bool {
if (!$timestamp || !$signature
|| strncmp($signature, 'v1=', 3) !== 0
|| !ctype_digit($timestamp)) {
return false;
}
if (abs(time() - (int) $timestamp) > $tolerance) {
return false;
}
$expected = hash_hmac('sha256', $timestamp . '.' . $payload, $secret);
return hash_equals($expected, substr($signature, 3));
}
$payload = file_get_contents('php://input'); // raw body
$timestamp = $_SERVER['HTTP_X_SENFENICO_TIMESTAMP'] ?? null;
$signature = $_SERVER['HTTP_X_SENFENICO_SIGNATURE'] ?? null;
$delivery = $_SERVER['HTTP_X_SENFENICO_DELIVERY'] ?? '';
$secret = (string) getenv('SENFENICO_WEBHOOK_SECRET');
if (!verify_senfenico($payload, $timestamp, $signature, $secret)) {
http_response_code(400);
exit;
}
// Duplicate? (same X-Senfenico-Delivery on every retry)
$stmt = db()->prepare(
'INSERT OR IGNORE INTO webhook_deliveries (id) VALUES (?)'
);
$stmt->execute([$delivery]);
if ($delivery !== '' && $stmt->rowCount() === 0) {
http_response_code(200);
exit;
}
// Answer right away (under 5 s), process afterwards
http_response_code(200);
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request(); // PHP-FPM
}
$event = json_decode($payload, true);
$data = is_string($event['data']) // data is a JSON string
? json_decode($event['data'], true)
: $event['data'];
try {
$checkoutRef = null;
if ($event['event'] === 'checkout.success') {
$checkoutRef = $data['reference'];
} elseif ($event['event'] === 'charge.success') {
// was the charge created by a checkout?
$q = http_build_query(['charge_reference' => $data['reference']]);
$list = senfenico('GET', "/checkouts/?$q");
$checkoutRef = $list['data'][0]['reference'] ?? null;
}
if ($checkoutRef && ($order = find_order_by_reference($checkoutRef))) {
confirm_order($order);
}
} catch (Throwable $e) {
// the reconciliation job will catch this order
error_log('Senfenico webhook: ' . $e->getMessage());
}

Read php://input before any decoding, otherwise the signature won’t match. The data field is a JSON string, hence the second json_decode. The script also listens to charge.success, for the reason given in Confirm the payment server-side. If fastcgi_finish_request() doesn’t exist (Apache mod_php), processing happens before the response, so keep it short.

With an sk_test_ key, create an order for the amount paired with a test number and pay on the page:

Check that return.php shows “payment confirmed” and that webhook.php receives checkout.success. To replay the signature by hand, see Test your verification.

7. Reconcile pending orders with a cron job

Section titled “7. Reconcile pending orders with a cron job”

A webhook can be lost (server down for more than an hour). Add a script run by cron every 15 minutes that calls confirm_order() for pending orders created more than 10 minutes ago:

<?php
// reconcile.php — crontab: */15 * * * * php /var/www/reconcile.php
declare(strict_types=1);
require __DIR__ . '/senfenico.php';
$orders = db()->query(
"SELECT * FROM orders
WHERE status = 'pending' AND senfenico_reference IS NOT NULL
AND created_at < datetime('now', '-10 minutes')
AND created_at > datetime('now', '-2 days')"
)->fetchAll();
foreach ($orders as $order) {
try {
confirm_order($order);
} catch (SenfenicoError $e) {
error_log("Reconcile {$order['id']}: {$e->getMessage()}");
}
}