Home Blog FAQ Contact API documentation

Payment Gateway API Integration: Webhooks, Retries, Code

A practical guide to payment gateway API integration: create payments, verify webhook signatures, handle retries and idempotency, with curl, PHP and Node.

Developers By the VelyoPay team 7 min read
Code brackets connected to a payment card and a shield, linked by glowing data lines

Most payment integrations do not fail on the first API call. They fail later, on a webhook that arrived twice, a signature that was never checked or an order that stayed "pending" because a server was down for five minutes. This guide walks through a clean payment gateway API integration and the webhook practices that keep it reliable in production.

Examples use the VelyoPay REST API, but the principles apply to almost any modern gateway.

How a hosted-checkout integration works

With a hosted checkout, card data never touches your server. Your backend only talks to the gateway about amounts and statuses, which keeps your security scope small. The flow looks like this:

  1. Your server creates a payment through the API with an amount, a currency and your own order reference.
  2. The API returns a payment id and a checkout_url.
  3. You redirect the customer to the checkout page, where they pay by card, Apple Pay, Google Pay or crypto.
  4. The gateway sends a signed webhook to your server when the payment is paid.
  5. Your server verifies the signature, marks the order as paid and fulfils it.

The key idea: the redirect back to your site is for the customer's comfort; the webhook is the source of truth.

Step 1: create a payment

Authenticate with your secret key as a Bearer token. Keep this key on the server only, in an environment variable, never in front-end code or a public repository.

curl https://api.velyopay.com/v1/payments \
  -H "Authorization: Bearer vp_live_xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"amount": 49.90, "currency": "USD", "reference": "order_10234"}'

The response includes a payment id (starting with pay_) and a checkout_url:

{
  "id": "pay_8f2k1x...",
  "checkout_url": "https://..."
}

The same call in Node.js (18+, built-in fetch):

const res = await fetch("https://api.velyopay.com/v1/payments", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.VELYOPAY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ amount: 49.9, currency: "USD", reference: "order_10234" }),
});
const payment = await res.json();
// Save payment.id next to your order, then redirect to payment.checkout_url

Store the returned id alongside your order. Use your own reference to link the payment to the order on your side. Always check the exact field formats in the API documentation.

Step 2: verify webhook signatures

Anyone who knows your webhook URL can send it a fake "payment.paid" request. Signature verification is what stops them. VelyoPay signs every webhook with HMAC-SHA256 and sends the result in the VelyoPay-Signature header:

VelyoPay-Signature: t=1764072000,v1=5f2b...e9

To verify it:

  1. Read the raw request body, exactly as received, before any JSON parsing.
  2. Split the header into the timestamp t and the signature v1.
  3. Build the string "<t>.<raw body>" and compute its HMAC-SHA256 with your webhook secret, in hex.
  4. Compare it with v1 using a constant-time comparison.
  5. Reject the request if the timestamp is too old (for example, more than 5 minutes) to block replayed messages.

PHP version:

$payload = file_get_contents('php://input');
$header  = $_SERVER['HTTP_VELYOPAY_SIGNATURE'] ?? '';
parse_str(str_replace(',', '&', $header), $parts);

$expected = hash_hmac('sha256', $parts['t'] . '.' . $payload, getenv('VELYOPAY_WEBHOOK_SECRET'));

if (!isset($parts['v1']) || !hash_equals($expected, $parts['v1'])
    || abs(time() - (int) $parts['t']) > 300) {
    http_response_code(400);
    exit;
}
$event = json_decode($payload, true);

Node.js version with Express:

import crypto from "node:crypto";
import express from "express";

const app = express();

app.post("/webhooks/velyopay", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("VelyoPay-Signature") || "";
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const expected = crypto
    .createHmac("sha256", process.env.VELYOPAY_WEBHOOK_SECRET)
    .update(`${parts.t}.${req.body}`)
    .digest("hex");

  const valid =
    parts.v1 &&
    parts.v1.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1)) &&
    Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;

  if (!valid) return res.sendStatus(400);

  const event = JSON.parse(req.body);
  // queue the event for processing, then answer quickly
  res.sendStatus(200);
});

The most common bug: a framework that parses JSON before your code runs. Re-serialising the object changes spacing and key order, so the HMAC no longer matches. Always sign the raw bytes.

Step 3: make your handler idempotent

Webhook delivery is "at least once". Because VelyoPay retries failed deliveries automatically, your endpoint may see the same payment.paid event more than once, for instance when your server processed it but timed out before answering.

Idempotency means processing the same event twice has the same effect as processing it once. In practice:

  • Record what you processed. Keep a table of handled event or payment ids with a unique constraint.
  • Use state transitions, not toggles. "Set order to paid if it is still pending" is safe to repeat; "add one item to the shipping queue" is not.
  • Wrap it in a transaction. Check the order status and update it in the same database transaction to avoid race conditions between two simultaneous deliveries.

The same mindset applies to your outgoing calls. If your request to create a payment times out, do not blindly fire another one: look up the order by your reference first, so a customer never ends up with two open payments for one order.

Step 4: respond fast and handle retries

Retries are your safety net, but only if you cooperate with them:

Your endpoint does... Result
Returns 2xx within a few seconds Delivery marked as successful
Returns 4xx/5xx or times out Gateway retries later
Does heavy work before answering Risk of timeouts and duplicate deliveries

Good habits:

  • Acknowledge first, work later. Verify the signature, store or queue the event, return 200, and run emails, invoices and stock updates in a background job.
  • Return an error on real failures. If your database is down, a 500 is better than a fake 200: it lets the retry deliver the event later.
  • Log every delivery with its timestamp and outcome. You will need it the day a customer says "I paid but nothing happened".
  • Reconcile periodically. A daily job that compares pending orders with payment statuses catches anything that slipped through.

Security checklist before going live

  • API key and webhook secret stored in environment variables, never in code.
  • HTTPS-only webhook endpoint with a valid certificate.
  • Signature and timestamp verified on every request.
  • Duplicate events ignored safely.
  • Order amounts checked against what you expected to charge.
  • Alerts on repeated webhook failures.

FAQ

Do I need PCI DSS certification for a hosted checkout?

With a hosted checkout, card details are entered on the gateway's page, not on yours, which greatly reduces your compliance scope. Your obligations still depend on your setup, so check them with your acquirer or advisor.

Why not just trust the customer's redirect back to my site?

Customers close tabs, lose connection or never return. The redirect can also be faked. Only a verified webhook should mark an order as paid.

How do I test webhooks locally?

Expose your local server with a tunnelling tool, point the webhook URL to it, and replay real deliveries. Check the docs for the test options available.

Which currency do I receive?

Customers pay in their currency, and VelyoPay pays merchants in USDC on Polygon directly to their own wallet. Our guide to USDC on Polygon for merchants explains wallets and cash-out.

Want to try it with your own code? Create a free VelyoPay account in about a minute, grab your API key and create your first payment today.

All articles

Ready to accept payments?

Create your account in one minute: no KYC, no setup fee, no monthly fee. 5.99% per successful transaction.

Create a free account