PHP payment integration: accept payments with cURL and a verified webhook
A PHP payment gateway integration step by step: create an order with cURL, redirect to checkout, verify the webhook with hash_equals and fulfil once.
On this page
A PHP payment gateway integration does not need a framework or an SDK. Two scripts are enough: checkout.php, which creates an order and redirects the buyer to a hosted checkout, and webhook.php, which receives the signed notification that the payment succeeded. Card details are entered on the hosted page, never on your server.
This tutorial builds that PHP payment integration with KukoPay using plain PHP and cURL — creating the order, verifying the webhook signature with hash_equals, fulfilling exactly once, and testing in the sandbox — with notes for Laravel along the way.
Before you start: do you need code at all?
If you run an existing system rather than your own code, check first:
- Systems with an epay (易支付) setting — V2Board, SSPanel, Dujiaoshuka — can connect with three values and no code. See V2Board payment gateway.
- Xboard has a ready-made plugin — see the Xboard payment plugin.
- No system at all? A payment link needs no code — see what is a payment link.
Otherwise, read on. You need PHP 8 with the cURL extension, a sandbox API key (kuko_test_…) and the app's callback signing secret from Developers → API keys, and a public HTTPS URL for webhook.php.
Step 1: checkout.php — create the order
<?php
$order = create_local_order($_POST['product']); // your own order, with its price
$payload = [
'out_trade_no' => $order['id'],
'amount' => $order['amount_cents'], // integer cents: 2990 = $29.90
'currency' => 'USD',
'subject' => $order['title'],
'notify_url' => 'https://shop.example.com/webhook.php',
'return_url' => 'https://shop.example.com/orders/{OUT_TRADE_NO}/complete',
];
$ch = curl_init('https://api.kukopay.com/v1/orders');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'X-Api-Key: ' . getenv('KUKOPAY_API_KEY'),
'Idempotency-Key: create-' . $order['id'],
],
CURLOPT_POSTFIELDS => json_encode($payload),
]);
$response = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status >= 300) {
error_log('create order failed: ' . ($response['error'] ?? '?') . ' request_id=' . ($response['request_id'] ?? '?'));
http_response_code(502);
exit('Checkout is unavailable, please try again.');
}
header('Location: ' . $response['data']['checkout_url'], true, 303);The essentials:
out_trade_nois your order id, so repeating the request returns the same order — see what is an idempotency key.amountis anintin cents, computed on the server. Never pass a float such as29.9, and never a price from the form — see why payment APIs take the amount in cents.- The API key comes from the environment, not from the code or the repository — see API key in frontend code.
Step 2: webhook.php — verify the signature
<?php
function kukopay_verify(string $raw, string $header, string $secret): bool
{
$t = null; $sigs = [];
foreach (explode(',', $header) as $item) {
[$k, $v] = array_pad(explode('=', trim($item), 2), 2, null);
if ($k === 't') { $t = $v; }
if ($k === 'v1') { $sigs[] = $v; }
}
if ($t === null || !$sigs || abs(time() - (int) $t) > 300) {
return false;
}
$expected = hash_hmac('sha256', $t . '.' . $raw, $secret);
foreach ($sigs as $sig) {
if (hash_equals($expected, $sig)) { return true; }
}
return false;
}
$raw = file_get_contents('php://input'); // the raw body, exactly as sent
$header = $_SERVER['HTTP_X_KUKOPAY_SIGNATURE'] ?? '';
if (!kukopay_verify($raw, $header, getenv('KUKOPAY_WEBHOOK_SECRET'))) {
http_response_code(400);
exit;
}
$event = json_decode($raw, true);
if (empty($event['test'])) { // test webhooks: acknowledge only
handle_event($event);
}
http_response_code(200);Read php://input, not $_POST or a re-encoded array, and compare with hash_equals so the check takes constant time. Keep every v1 value: during a secret rotation there are two. See how to verify webhook signatures.
Step 3: fulfil exactly once
function handle_event(array $event): void
{
$pdo = db();
$pdo->beginTransaction();
$stmt = $pdo->prepare('INSERT IGNORE INTO kukopay_events (id) VALUES (?)'); // id is the primary key
$stmt->execute([$event['id']]);
if ($stmt->rowCount() === 0) { $pdo->commit(); return; } // already processed
if ($event['type'] === 'payment.succeeded') {
$o = $event['data']['object'];
mark_order_paid($pdo, $o['out_trade_no'], $o['trade_no'], $o['amount']);
queue_fulfilment($pdo, $o['out_trade_no']);
}
$pdo->commit();
}The event id and the order update share one transaction, so a retried webhook cannot ship twice. Answer within 10 seconds and move slow work to a queue. See payment webhook idempotency.
Doing it in Laravel
The same two pieces map directly onto Laravel:
- Creating the order:
Http::withHeaders([...])->post('https://api.kukopay.com/v1/orders', $payload), thenreturn redirect()->away($checkoutUrl);. - The webhook route: read
$request->getContent()for the raw body and$request->header('X-KukoPay-Signature'), and exclude the route from CSRF verification — the signature does that job. - Deduplication: a unique index on the event id and
DB::transaction()around the insert and the order update.
Step 4: test in the sandbox
- Run
checkout.php, pay with4242 4242 4242 4242(any future expiry, any CVC), and try a decline with4000 0000 0000 0002— see test credit card numbers. - Make
webhook.phpreturn500once and check the retry is deduplicated. - If the signature fails, use Send test webhook and the signature self-check in the dashboard — see how to test webhooks locally.
Going live means replacing the sandbox key and secret with the same app's live values. Other languages: Node.js, Python.
Summary
- A PHP payment gateway integration needs two scripts: one creating the order and redirecting to
checkout_url, one receiving the webhook; - create orders with cURL using your order id as
out_trade_no, an integer amount and anIdempotency-Key; - verify
X-KukoPay-Signatureonphp://inputwithhash_equals, accepting any matchingv1; - record the event id and fulfil in one transaction; acknowledge test webhooks without acting;
- systems with an epay setting or the Xboard plugin need no code at all.
Try it in the sandbox
Create a merchant account and request a test key. The sandbox needs no business verification.