
Online payment, part 3: integration on the website — order, payment page, callback, and signature verification
🌐 Machine-translated from Russian. Show original
i️ Terms are changing. Prices, rates, and features are as of November 2026. Before purchasing or implementing, please check the official websites.
In this part:
General scheme#
Almost all banks and payment services have the same integration:
- The server creates an order on its own site and a payment request from the bank (amount, currency, order number, return addresses, and notifications) — signed with a secret key or with token authorization.
- The bank returns a link to the payment page (or widget data).
- The buyer pays on the bank's side.
- The bank sends a callback to your server with the result.
- Your server verifies the notification signature , reconciles the amount and order number , and changes the status.
- The buyer returns to the "thank you" page, which shows the status from your database.
Creating a payment#
// псевдокод: createPayment — вызов API вашего банка по его документации
app.post("/api/orders/:id/pay", async (req, res) => {
const order = await db.order.findUniqueOrThrow({ where: { id: req.params.id, userId: req.user.id } });
if (order.status !== "NEW") return res.status(409).json({ error: "Заказ уже оплачен или отменен" });
const payment = await db.payment.create({
data: { orderId: order.id, amount: order.total, currency: "KZT", status: "CREATED" },
});
const { paymentUrl, providerId } = await createPayment({
amount: order.total, // сумма — с сервера, никогда не из браузера
currency: "KZT",
orderId: payment.id, // уникальный номер попытки оплаты
description: `Заказ №${order.number}`,
returnUrl: `https://shop.example.kz/orders/${order.id}/done`,
callbackUrl: "https://shop.example.kz/api/payments/callback",
});
await db.payment.update({ where: { id: payment.id }, data: { providerId } });
res.json({ url: paymentUrl });
});
Callback processing#
app.post("/api/payments/callback", async (req, res) => {
// 1. Подлинность: подпись или токен по документации банка (HMAC, подпись сертификатом и т. п.)
if (!verifySignature(req)) return res.status(403).end();
const { orderId, status, amount, providerId } = parseCallback(req.body);
const payment = await db.payment.findUnique({ where: { id: orderId } });
if (!payment) return res.status(404).end();
// 2. Сверка суммы и валюты с тем, что создавали
if (amount !== payment.amount) {
await alertTeam(`Сумма не совпадает: платеж ${payment.id}`);
return res.status(400).end();
}
// 3. Идемпотентность: повторное уведомление не меняет уже оплаченный заказ
if (payment.status === "PAID") return res.status(200).end();
if (status === "PAID") {
await db.$transaction([
db.payment.update({ where: { id: payment.id }, data: { status: "PAID", providerId } }),
db.order.update({ where: { id: payment.orderId }, data: { status: "PAID" } }),
]);
} else {
await db.payment.update({ where: { id: payment.id }, data: { status: "FAILED" } });
}
res.status(200).end(); // формат ответа — как требует банк
});
Rules that must not be broken#
- The amount is only from the server. Never take the amount from the browser: it's easy to swap.
- Status — only from callback or request to the bank's API, not from return address parameters: the buyer can manually open the "success" page.
- Check the signature of each notification, not just the sender's IP address.
- Idempotence: the bank can send a notification multiple times — the order does not have to be "paid" twice, and the product must not be issued twice.
- Secret keys are in server environment variables, not in frontend code, and not in the repository.
- Logs of all requests and notifications — without map data — are needed to resolve disputed cases.
If the callback did not come#
Networks are unreliable. Add a background task: for payments in the "in progress" status for longer than N minutes — request status from the bank via API. This way, orders won't freeze.
Testing#
- Test cards and scenarios from the bank's documentation: successful payment, refusal, 3-D Secure, cancellation.
- Check for recallback, callback with incorrect signature, and page closure before returning to the site.
- Only after that — battle keys.
Payment via QR and banking apps — in part 4.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.