Payment Integration Basics: Server-Side Prices, Webhooks and Idempotency

Node.js and Express: Build a Back End API from Scratch · Architecture, Reliability and Performance · 7 min read · Updated

The order becomes paid only by webhook

  1. The browser says what it wants. It never says what it costs.
  2. The server computes the total in cents and saves a pending order.
  3. The provider shows the payment page and takes the card. Card data never reaches your server.
  4. The provider calls your webhook. A verified, matching, first-time event marks the order paid.

Payments are where mistakes cost real money, so this is the lesson to read slowly. The good news is that the safe design is simple, and almost every provider, Razorpay, Stripe, PayPal and others, works the same way. Learn the pattern once and the provider's own documentation becomes easy to follow.

Four rules

  • Money is a whole number of the smallest unit. Use paise or cents, 1999, not 19.99. Decimals can drift.
  • The server decides the price. The browser sends *what* the user wants, such as a product code and a quantity, never *how much*. A client that sends a price can send any price.
  • The provider takes the card. Card numbers must never touch your server, which keeps you out of heavy compliance rules. You receive a payment link or token instead.
  • An order becomes paid only when a verified webhook says so. The user coming back to your site with ?success=true proves nothing, because anyone can type that URL.

Here is the flow. The browser asks to create an order. Your server calculates the total from your own catalogue, saves the order as pending, asks the provider to create a payment for that amount, and returns a payment URL. The user pays on the provider's page. The provider then calls your webhook with a signed message. Your server verifies the signature, finds the order, checks that the amount matches, and only then marks it paid.

import express from 'express';
import crypto from 'node:crypto';

// Rules for payments: money is in whole cents, the SERVER decides the price, the PROVIDER takes the card,
// and the order becomes "paid" only when a signed webhook from the provider says so.
export const sign = (raw, secret) => crypto.createHmac('sha256', secret).update(raw).digest('hex');

export function createApp({ provider, webhookSecret, catalog }) {
  const app = express();
  const orders = new Map();
  const seenEvents = new Set();      // idempotency: the provider may send the same event twice

  // IMPORTANT: the webhook needs the RAW body to check the signature, so it comes before express.json().
  app.post('/webhooks/payments', express.raw({ type: 'application/json' }), (req, res) => {
    const signature = req.get('x-signature') ?? '';
    const expected = sign(req.body, webhookSecret);
    const ok = signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
    if (!ok) return res.status(400).json({ error: 'Bad signature' });

    const event = JSON.parse(req.body.toString('utf8'));
    if (seenEvents.has(event.id)) return res.json({ received: true, duplicate: true });
    seenEvents.add(event.id);

    const order = orders.get(event.orderId);
    if (order && event.type === 'payment.succeeded' && event.amountCents === order.totalCents) order.status = 'paid';
    if (order && event.type === 'payment.failed') order.status = 'failed';
    res.json({ received: true });
  });

  app.use(express.json());

  app.post('/orders', async (req, res) => {
    const items = req.body?.items;
    if (!Array.isArray(items) || !items.length) return res.status(422).json({ error: 'items are required' });
    let totalCents = 0;
    for (const { sku, qty } of items) {
      const product = catalog[sku];
      if (!product || !Number.isInteger(qty) || qty < 1) return res.status(422).json({ error: `Bad item ${sku}` });
      totalCents += product.priceCents * qty;            // the price comes from OUR catalog, never from the client
    }
    const order = { id: orders.size + 1, totalCents, status: 'pending' };
    orders.set(order.id, order);
    const payment = await provider.createPayment({ orderId: order.id, amountCents: totalCents });
    res.status(201).json({ ...order, paymentUrl: payment.url });
  });

  app.get('/orders/:id', (req, res) => {
    const order = orders.get(Number(req.params.id));
    return order ? res.json(order) : res.status(404).json({ error: 'Not found' });
  });
  return app;
}

Notice three details in the code. The webhook route comes before express.json() and uses express.raw, because the signature is calculated over the exact raw bytes. Next, the signature is compared with timingSafeEqual, as in lesson 23. Last, seenEvents makes the handler idempotent: providers resend an event when they do not receive a quick 200, so the same event can arrive twice, and you must not process it twice. In a real system you would store event ids in the database with a unique index.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express.
  3. Save the code as payments.js. The test needs npm install -D supertest. It uses a fake payment provider, so no account is needed.
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp, sign } from './pay38-payments.js';

const provider = { createPayment: async ({ orderId }) => ({ url: `https://pay.example/checkout/${orderId}` }) };
const catalog = { pen: { priceCents: 1500 }, book: { priceCents: 49900 } };
const SECRET = 'whsec_test';

function webhook(app, event, secret = SECRET) {
  const raw = JSON.stringify(event);
  return request(app).post('/webhooks/payments').set('Content-Type', 'application/json').set('x-signature', sign(raw, secret)).send(raw);
}

test('server computes the price and only a signed webhook marks it paid', async () => {
  const app = createApp({ provider, webhookSecret: SECRET, catalog });

  // The client tries to send its own price: it is ignored.
  const created = await request(app).post('/orders').send({ items: [{ sku: 'pen', qty: 2, priceCents: 1 }, { sku: 'book', qty: 1 }] });
  assert.equal(created.status, 201);
  assert.equal(created.body.totalCents, 52900);
  assert.equal(created.body.status, 'pending');

  // Unsigned or wrongly signed: refused, order unchanged.
  assert.equal((await webhook(app, { id: 'e1', type: 'payment.succeeded', orderId: 1, amountCents: 52900 }, 'wrong')).status, 400);
  assert.equal((await request(app).get('/orders/1')).body.status, 'pending');

  // Wrong amount: ignored.
  await webhook(app, { id: 'e2', type: 'payment.succeeded', orderId: 1, amountCents: 100 });
  assert.equal((await request(app).get('/orders/1')).body.status, 'pending');

  // Correct: paid. Sending it again is harmless.
  await webhook(app, { id: 'e3', type: 'payment.succeeded', orderId: 1, amountCents: 52900 });
  assert.equal((await request(app).get('/orders/1')).body.status, 'paid');
  const again = await webhook(app, { id: 'e3', type: 'payment.succeeded', orderId: 1, amountCents: 52900 });
  assert.equal(again.body.duplicate, true);
});
ok 1 - server computes the price and only a signed webhook marks it paid

The test creates an order whose price comes from the catalogue even though the client tries to send its own, checks that the order is pending, sends a webhook with a bad signature and gets 400, sends a correct one and sees paid, and sends the same event again to confirm that it is recognised as a duplicate.

Other things a real integration needs

  • Refunds and failures: handle payment.failed and refund events, and show a clear state to the user.
  • Amounts must match. The code compares the paid amount with the order total. Without this a cheap payment could pay for an expensive order.
  • Test mode first. Every provider has a sandbox with test card numbers. Use it until the whole flow works, including failures.
  • Keep records. Store the provider's payment id on your order so that you can match it with their dashboard.
  • Legal and tax rules: invoices, taxes and refunds are governed by the law of your country. Ask an accountant or lawyer, and read the provider's own rules.

Your task

  1. Add a payment.refunded event that sets the order to refunded.
  2. Reject an order that asks for more than 10 of one item.
  3. Store the provider payment id on the order and show it in GET /orders/:id.

How to check it worked

  • A price sent by the client is ignored.
  • A webhook with a bad signature returns 400.
  • Sending the same webhook twice changes nothing the second time.

Frequently asked questions

Why not trust the success page after payment?

Anyone can open that URL by hand. Only a signed message from the provider, received by your server, proves that money moved.

Why must the server set the price?

A browser can send any value. If the server accepted the price, a user could pay one rupee for any product.

What if the webhook arrives twice?

Providers retry, so keep the event ids you have seen and ignore repeats. That is idempotency.

Practise with interview questions