Guest mode. You can read posts without signing up. Comments, ratings, job contacts and your own posts open after you sign up and accept the rules. What is Kommit →

Редакция КоммитРедакция портала
commit 571456d · 19 days ago

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:

  1. 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.
  2. The bank returns a link to the payment page (or widget data).
  3. The buyer pays on the bank's side.
  4. The bank sends a callback to your server with the result.
  5. Your server verifies the notification signature , reconciles the amount and order number , and changes the status.
  6. 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 00 участников · 0 гостей🔒 Rate and discuss after signing up

Comments · 0

No comments yet.Sign in to comment, rate and see all comments.