Integrate payments.
The right way.
Create a FastPay24 invoice from your server, redirect your customer to the hosted checkout, and securely process the encrypted server-to-server callback.
How the integration works
- Your backend creates a unique
order_idand stores a pending order in your own database. - Your backend sends an HTTPS POST request to the invoice creation endpoint.
- FastPay24 returns a
payment_url. Redirect the customer to that URL. - After payment is successfully completed, FastPay24 sends an encrypted POST request to your
callback_url. - Your callback handler verifies the signature, decrypts the payload, validates the order and amount, and then marks the order as paid exactly once.
Create an invoice
https://payment.fastpay24.xyz/invoice/create.phpSend the request from your server over HTTPS using application/x-www-form-urlencoded. Do not expose your API key in frontend JavaScript, HTML, or mobile-app source code.
Request fields
| Field | Required | Description |
|---|---|---|
| api_key | Yes | Your FastPay24 API key issued for your brand. |
| amount | Yes | Payment amount as a decimal string, e.g. 10.00. |
| order_id | Yes | Your unique order reference. Save it in your database before creating the invoice. |
| callback_url | Yes | Public HTTPS endpoint on your server that receives the encrypted payment callback. |
| redirect_url | Yes | Customer-facing URL to open after checkout. |
| user_id | Optional | Your internal customer/user reference, if your integration uses one. |
cURL
curl --request POST \ --url 'https://payment.fastpay24.xyz/invoice/create.php' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'api_key=YOUR_FASTPAY24_API_KEY' \ --data-urlencode 'amount=10.00' \ --data-urlencode 'order_id=ORDER-10001' \ --data-urlencode 'callback_url=https://yourdomain.com/fastpay24-callback.php' \ --data-urlencode 'redirect_url=https://yourdomain.com/payment-result' \ --data-urlencode 'user_id=12345'
Invoice creation response
A successful response is expected to contain status: success and a payment_url. The gateway may also return an invoice identifier.
{
"status": "success",
"payment_url": "https://payment.fastpay24.xyz/...",
"invoice_id": "GATEWAY_INVOICE_ID"
}Use the actual response returned by the API. Treat the example URL and invoice ID above as illustrative values, not fixed values.
<?php
$apiUrl = 'https://payment.fastpay24.xyz/invoice/create.php';
$apiKey = 'YOUR_FASTPAY24_API_KEY';
$orderId = 'ORDER-' . bin2hex(random_bytes(8));
$amount = '10.00';
// Save this order as PENDING in your database before the API call.
$postData = [
'api_key' => $apiKey,
'amount' => $amount,
'order_id' => $orderId,
'callback_url' => 'https://yourdomain.com/fastpay24-callback.php',
'redirect_url' => 'https://yourdomain.com/payment-result',
'user_id' => '12345',
];
$ch = curl_init($apiUrl);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($postData),
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_TIMEOUT => 25,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$raw = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($raw === false || $curlError !== '' || $httpCode < 200 || $httpCode >= 300) {
http_response_code(502);
exit('Unable to contact FastPay24');
}
$result = json_decode($raw, true);
if (!is_array($result) || ($result['status'] ?? '') !== 'success'
|| empty($result['payment_url'])) {
http_response_code(502);
exit('Invoice creation failed');
}
$paymentUrl = filter_var($result['payment_url'], FILTER_VALIDATE_URL);
if (!$paymentUrl || parse_url($paymentUrl, PHP_URL_SCHEME) !== 'https') {
http_response_code(502);
exit('Invalid payment URL received');
}
header('Location: ' . $paymentUrl, true, 303);
exit;What happens when payment succeeds?
FastPay24 sends an HTTP POST request directly from its server to the exact callback_url supplied during invoice creation. The request body is JSON containing an encrypted envelope. It is not the plaintext payment object shown in older sample snippets.
Content-Type: application/json X-FastPay24-Version: 1 X-FastPay24-Timestamp: <unix_timestamp> X-FastPay24-Event: <32-character-hex-event-id> X-FastPay24-Signature: sha256=<hex-hmac>
Your endpoint should read the raw request body exactly as received. Verify the HMAC against that exact raw body before decrypting it. Return a 2xx HTTP response after safely accepting/processing the event. A callback may be retried, so processing must be idempotent.
Encrypted callback envelope
The callback uses the API Secret belonging to the brand that created the invoice. Put that same secret directly in your callback handler file. Do not put it in a public frontend file, commit it to a public repository, or send it to the browser. The secret is not a database setting required by this callback example.
{
"version": 1,
"algorithm": "AES-256-GCM",
"timestamp": 1790000000,
"event_id": "0123456789abcdef0123456789abcdef",
"iv": "BASE64_ENCODED_12_BYTE_IV",
"tag": "BASE64_ENCODED_GCM_TAG",
"aad": "FASTPAY24|CALLBACK|V1",
"ciphertext": "BASE64_ENCODED_CIPHERTEXT"
}The values above are placeholders illustrating the envelope shape, not a real callback.
Signature input: timestamp + "." + event_id + "." + raw_request_body
HMAC key: your brand API Secret.
HKDF: SHA-256, output length 32 bytes, info FASTPAY24_CALLBACK_V1, salt FASTPAY24.
AES-GCM AAD: FASTPAY24|CALLBACK|V1; IV is 12 bytes and tag is 16 bytes.
PHP callback handler
Save as fastpay24-callback.php. Add your brand's API Secret in the marked line. The sample verifies the signature and decrypts the payload. Connect the final validated order update to your own database schema.
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
// Paste the API Secret for the brand that created this invoice.
$API_SECRET = 'PASTE_YOUR_BRAND_API_SECRET_HERE';
function fail(int $code, string $message): never {
http_response_code($code);
echo json_encode(['received' => false, 'message' => $message]);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
fail(405, 'POST required');
}
if ($API_SECRET === 'PASTE_YOUR_BRAND_API_SECRET_HERE' || $API_SECRET === '') {
fail(500, 'Callback secret is not configured');
}
$rawBody = file_get_contents('php://input');
if (!is_string($rawBody) || $rawBody === '' || strlen($rawBody) > 65536) {
fail(400, 'Invalid request body');
}
$timestamp = (string)($_SERVER['HTTP_X_FASTPAY24_TIMESTAMP'] ?? '');
$eventId = (string)($_SERVER['HTTP_X_FASTPAY24_EVENT'] ?? '');
$signatureHeader = (string)($_SERVER['HTTP_X_FASTPAY24_SIGNATURE'] ?? '');
if (!ctype_digit($timestamp) || !preg_match('/^[a-f0-9]{32}$/i', $eventId)) {
fail(400, 'Missing or invalid callback headers');
}
if (abs(time() - (int)$timestamp) > 300) {
fail(401, 'Callback timestamp expired');
}
if (!preg_match('/^sha256=([a-f0-9]{64})$/i', $signatureHeader, $m)) {
fail(401, 'Invalid signature format');
}
$expected = hash_hmac('sha256', $timestamp . '.' . $eventId . '.' . $rawBody, $API_SECRET);
if (!hash_equals($expected, strtolower($m[1]))) {
fail(401, 'Signature verification failed');
}
$envelope = json_decode($rawBody, true);
if (!is_array($envelope)
|| ($envelope['version'] ?? null) !== 1
|| ($envelope['algorithm'] ?? '') !== 'AES-256-GCM'
|| (string)($envelope['timestamp'] ?? '') !== $timestamp
|| ($envelope['event_id'] ?? '') !== $eventId
|| ($envelope['aad'] ?? '') !== 'FASTPAY24|CALLBACK|V1') {
fail(400, 'Invalid callback envelope');
}
$iv = base64_decode((string)($envelope['iv'] ?? ''), true);
$tag = base64_decode((string)($envelope['tag'] ?? ''), true);
$ciphertext = base64_decode((string)($envelope['ciphertext'] ?? ''), true);
if ($iv === false || strlen($iv) !== 12 || $tag === false || strlen($tag) !== 16
|| $ciphertext === false) {
fail(400, 'Invalid encrypted fields');
}
$key = hash_hkdf('sha256', $API_SECRET, 32, 'FASTPAY24_CALLBACK_V1', 'FASTPAY24');
$plaintext = openssl_decrypt(
$ciphertext,
'aes-256-gcm',
$key,
OPENSSL_RAW_DATA,
$iv,
$tag,
'FASTPAY24|CALLBACK|V1'
);
if ($plaintext === false) {
fail(400, 'Callback decryption failed');
}
$payment = json_decode($plaintext, true);
if (!is_array($payment)
|| ($payment['status'] ?? '') !== 'paid'
|| empty($payment['order_id'])
|| !isset($payment['amount'])
|| !isset($payment['txn_id'])) {
fail(400, 'Invalid payment data');
}
// IMPORTANT: Before updating your order:
// 1) Reject an event_id already processed (store it with a UNIQUE constraint).
// 2) Find the pending order using order_id.
// 3) Compare the callback amount with the amount stored for that order.
// 4) Confirm currency/brand context if your integration uses them.
// 5) Atomically change PENDING to PAID; never credit twice.
// Do not trust an amount supplied only by this callback.
$orderId = (string)$payment['order_id'];
$amount = (string)$payment['amount'];
$transactionId = (string)$payment['txn_id'];
$method = (string)($payment['method'] ?? '');
// TODO: Perform the database transaction and idempotency checks described above.
// Acknowledge only after the event is safely recorded/processed.
http_response_code(200);
echo json_encode(['received' => true]);Node.js verification and decryption core
Use the raw request body, not a re-serialized JSON object. This example uses Node.js built-in crypto.
const crypto = require('node:crypto');
const API_SECRET = 'PASTE_YOUR_BRAND_API_SECRET_HERE';
function decryptFastPay24(rawBody, headers) {
const timestamp = String(headers['x-fastpay24-timestamp'] || '');
const eventId = String(headers['x-fastpay24-event'] || '');
const sig = String(headers['x-fastpay24-signature'] || '');
if (!/^\\d+$/.test(timestamp) || !/^[a-f0-9]{32}$/i.test(eventId))
throw new Error('Invalid callback headers');
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300)
throw new Error('Expired callback');
if (!/^sha256=[a-f0-9]{64}$/i.test(sig))
throw new Error('Invalid signature format');
const expected = crypto.createHmac('sha256', API_SECRET)
.update(`${timestamp}.${eventId}.${rawBody}`)
.digest('hex');
const supplied = sig.slice(7).toLowerCase();
if (!crypto.timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(supplied, 'hex')))
throw new Error('Signature mismatch');
const env = JSON.parse(rawBody);
if (env.version !== 1 || env.algorithm !== 'AES-256-GCM'
|| String(env.timestamp) !== timestamp || env.event_id !== eventId
|| env.aad !== 'FASTPAY24|CALLBACK|V1')
throw new Error('Invalid envelope');
const key = Buffer.from(crypto.hkdfSync(
'sha256', Buffer.from(API_SECRET), Buffer.from('FASTPAY24'),
Buffer.from('FASTPAY24_CALLBACK_V1'), 32
));
const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(env.iv, 'base64'));
decipher.setAAD(Buffer.from('FASTPAY24|CALLBACK|V1'));
decipher.setAuthTag(Buffer.from(env.tag, 'base64'));
const plain = Buffer.concat([
decipher.update(Buffer.from(env.ciphertext, 'base64')),
decipher.final()
]).toString('utf8');
const payment = JSON.parse(plain);
if (payment.status !== 'paid' || !payment.order_id || payment.amount == null || !payment.txn_id)
throw new Error('Invalid payment payload');
return { eventId, payment };
}
// Express route: register express.raw BEFORE express.json for this route.
// app.post('/fastpay24-callback', express.raw({ type: 'application/json' }), (req, res) => {
// try {
// const { eventId, payment } = decryptFastPay24(req.body.toString('utf8'), req.headers);
// // Add DB idempotency, pending-order lookup, amount comparison and atomic PAID update.
// res.status(200).json({ received: true });
// } catch (e) { res.status(400).json({ received: false }); }
// });Python verification and decryption core
Install the cryptography package with pip install cryptography. Keep the API Secret private on the server.
import base64, hashlib, hmac, json, time
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
API_SECRET = b"PASTE_YOUR_BRAND_API_SECRET_HERE"
def decrypt_fastpay24(raw_body: bytes, headers: dict):
timestamp = headers.get("X-FastPay24-Timestamp", "")
event_id = headers.get("X-FastPay24-Event", "")
signature = headers.get("X-FastPay24-Signature", "")
if not timestamp.isdigit() or len(event_id) != 32:
raise ValueError("Invalid callback headers")
if abs(time.time() - int(timestamp)) > 300:
raise ValueError("Expired callback")
expected = hmac.new(
API_SECRET,
timestamp.encode() + b"." + event_id.encode() + b"." + raw_body,
hashlib.sha256
).hexdigest()
supplied = signature.removeprefix("sha256=").lower()
if not hmac.compare_digest(expected, supplied):
raise ValueError("Signature mismatch")
env = json.loads(raw_body)
if (env.get("version") != 1 or env.get("algorithm") != "AES-256-GCM"
or str(env.get("timestamp")) != timestamp
or env.get("event_id") != event_id
or env.get("aad") != "FASTPAY24|CALLBACK|V1"):
raise ValueError("Invalid envelope")
key = HKDF(
algorithm=hashes.SHA256(), length=32,
salt=b"FASTPAY24", info=b"FASTPAY24_CALLBACK_V1"
).derive(API_SECRET)
iv = base64.b64decode(env["iv"], validate=True)
tag = base64.b64decode(env["tag"], validate=True)
ciphertext = base64.b64decode(env["ciphertext"], validate=True)
plaintext = AESGCM(key).decrypt(
iv, ciphertext + tag, b"FASTPAY24|CALLBACK|V1"
)
payment = json.loads(plaintext)
if (payment.get("status") != "paid" or not payment.get("order_id")
or payment.get("amount") is None or not payment.get("txn_id")):
raise ValueError("Invalid payment payload")
return event_id, payment
# After decryption, implement persistent event-id deduplication,
# pending-order lookup, exact amount comparison and atomic PAID update.Before marking an order as paid
- ✓Verify the HMAC signature using the exact raw request body and your brand API Secret.
- ✓Reject timestamps outside the 300-second acceptance window.
- ✓Decrypt AES-256-GCM successfully and validate the payload status is exactly
paid. - ✓Find the matching pending order using
order_id; do not create an order based on callback data. - ✓Compare the callback amount against the amount stored before invoice creation. Use decimal-safe comparison, not floating-point equality.
- ✓Store
event_idwith a UNIQUE constraint and make the order transition atomic so duplicate callbacks cannot credit twice. - ✓Only after all checks pass, change the order from PENDING to PAID and record
txn_idand payment method.
timestamp.event_id.rawBody, HKDF-SHA256 with the documented salt and info, and AES-256-GCM using the documented AAD. Port these exact values when implementing Laravel, WordPress, or Cloudflare Workers.