Skip to content
HisarPay
  • Integrations
  • Published:
  • Reading time: 6 min read
  • Türkçe oku

Your first invoice with the API in Node.js, PHP and Python

A payment integration comes down to four jobs: create the invoice, send the customer away, verify the notification that comes back, and complete the order once. Here they are side by side in Node.js, PHP and Python, followed by a run in test mode. No money moves and you do not need an approved account.

On this page
  1. Set up
  2. Create the invoice and redirect
  3. Idempotency key and order_id
  4. Receive and verify the webhook
  5. Look it up by order id
  6. Errors you may meet on day one
  7. Simulate in test mode
  8. Frequently asked questions

Set up

In the dashboard, create a key that starts with hp_test_ under Developers → API keys. The invoices scope is enough. The key is shown once, so put it in an environment variable rather than in code, and install the library for your language:

Official libraries
# Node.js 18+
npm install https://hisarpay.com/downloads/hisarpay-node-1.0.0.tgz

# PHP 8.1+
composer config repositories.hisarpay composer https://hisarpay.com/downloads
composer require hisarpay/hisarpay-php

# Python 3.9+
pip install https://hisarpay.com/downloads/hisarpay-1.0.0-py3-none-any.whl

Create the invoice and redirect

You price in dollars, the customer picks a coin on the payment page, and the rate locks at that moment. Amounts are decimal strings everywhere, as in "49.90", never floats. The smallest invoice is $10.

Node.js

TypeScript
import { HisarPay } from '@hisarpay/node';

const hisarpay = new HisarPay(process.env.HISARPAY_API_KEY!);

const invoice = await hisarpay.invoices.create(
  {
    price_usd: '49.90',
    order_id: 'order_1001',
    description: 'Pro plan, 1 month',
    success_url: 'https://shop.example/thanks',
  },
  { idempotencyKey: 'order-1001' },
);

res.redirect(303, invoice.payment_url);

PHP

PHP
<?php
require 'vendor/autoload.php';

$hisarpay = new \HisarPay\HisarPay(getenv('HISARPAY_API_KEY'));

$invoice = $hisarpay->invoices->create([
    'price_usd' => '49.90',
    'order_id' => 'order_1001',
    'description' => 'Pro plan, 1 month',
    'success_url' => 'https://shop.example/thanks',
], ['idempotencyKey' => 'order-1001']);

header('Location: ' . $invoice['payment_url'], true, 303);

Python

Python
import os
from hisarpay import HisarPay

client = HisarPay(os.environ["HISARPAY_API_KEY"])

invoice = client.invoices.create(
    {
        "price_usd": "49.90",
        "order_id": "order_1001",
        "description": "Pro plan, 1 month",
        "success_url": "https://shop.example/thanks",
    },
    idempotency_key="order-1001",
)
payment_url = invoice["payment_url"]

Send the customer to payment_url. The page speaks English and Turkish and looks after the QR code, the countdown, short payments and late ones, so there is no interface for you to write. Put your own ids into metadata (up to 4 KB) and they come back in the webhook.

Afterwards they return to your success_url, but that return proves nothing: anyone can type the address. Complete the order only on a verified notification.

Idempotency key and order_id

When a request times out you cannot tell whether the invoice exists. The libraries generate a key for every POST and reuse it on their own retries. Passing your own keeps a retry safe even after your process has crashed. Two fields work together:

  • The idempotency key lasts 24 hours. Same key, same body: you get the first response again. Same key with a different body: 409 idempotency_conflict.
  • order_id is permanent. A second request with it returns the existing invoice, even an expired one. For a fresh attempt add a suffix such as order_1001-2.

Receive and verify the webhook

Add your server’s HTTPS address under Developers → Webhooks and keep the whsec_ value you get. Local addresses are refused, so use a tunnel while developing. The signature covers the raw body; parse and re-serialise the JSON and it no longer matches.

Node.js (Express)TypeScript
import express from 'express';
import { HisarPay, SignatureVerificationError } from '@hisarpay/node';

const app = express();
const secret = process.env.HISARPAY_WEBHOOK_SECRET!;
const LIVE = process.env.HISARPAY_API_KEY!.startsWith('hp_live_');

// raw body
app.post('/webhooks/hisarpay', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = HisarPay.webhooks.constructEvent(req.body, req.headers['x-hisarpay-signature'], secret);
  } catch (err) {
    if (err instanceof SignatureVerificationError) return res.status(400).send(err.message);
    throw err;
  }
  if (event.livemode !== LIVE) return res.sendStatus(200); // test events arrive here too, and anyone can mark a test invoice as paid
  if (event.type === 'invoice.paid' || event.type === 'invoice.overpaid') {
    await markPaidOnce(event.data.invoice.order_id); // unique on the order id: never runs twice
  }
  res.sendStatus(200);
});
PHPPHP
<?php
require 'vendor/autoload.php';

use HisarPay\Exception\SignatureVerificationException;
use HisarPay\Webhook;

$payload = file_get_contents('php://input'); // raw body
$header = $_SERVER['HTTP_X_HISARPAY_SIGNATURE'] ?? null;

try {
    $event = Webhook::constructEvent($payload, $header, getenv('HISARPAY_WEBHOOK_SECRET'));
} catch (SignatureVerificationException $e) {
    http_response_code(400);
    exit;
}

// test events arrive here too, and anyone can mark a test invoice as paid
$live = str_starts_with((string) getenv('HISARPAY_API_KEY'), 'hp_live_');
if ($event['livemode'] === $live && in_array($event['type'], ['invoice.paid', 'invoice.overpaid'], true)) {
    mark_paid_once($event['data']['invoice']['order_id']);
}
http_response_code(200);
Python (Flask)Python
import os
from flask import Flask, abort, request
from hisarpay import SignatureVerificationError, webhooks

app = Flask(__name__)

@app.post("/webhooks/hisarpay")
def hisarpay_webhook():
    try:
        event = webhooks.construct_event(
            request.get_data(),  # raw body
            request.headers.get(webhooks.SIGNATURE_HEADER),
            os.environ["HISARPAY_WEBHOOK_SECRET"],
        )
    except SignatureVerificationError:
        abort(400)
    live = os.environ["HISARPAY_API_KEY"].startswith("hp_live_")
    # test events arrive here too, and anyone can mark a test invoice as paid
    if event["livemode"] is live and event["type"] in ("invoice.paid", "invoice.overpaid"):
        mark_paid_once(event["data"]["invoice"]["order_id"])
    return "", 200

Why key on the order and not on the event id? One invoice can send invoice.paid and later, if the customer sends something extra, invoice.overpaid. Two events, one order. If your order table allows the step to “paid” only once, neither does harm.

Keep test events apartEndpoints receive live and test events. In production, never complete an order on an event whose livemode is false: anyone who opens the payment page of a test invoice can mark it paid.

Answer 2xx within 10 seconds and queue slow work. Otherwise the event comes back at intervals for about two days. Ordering is not guaranteed. Manual verification and common errors are in the signature guide.

Look it up by order id

For a support screen, or when you suspect a missed event, read the invoice by your own number. Next to status, the answer lists the payments received:

Lookup
// Node.js
const invoice = await hisarpay.invoices.retrieveByOrder('order_1001');

// PHP
$invoice = $hisarpay->invoices->retrieveByOrder('order_1001');

# Python
invoice = client.invoices.retrieve_by_order("order_1001")

Errors you may meet on day one

  • 400 amount_too_small: the price is under $10.
  • 401 unauthorized: the key was cut short or revoked.
  • 403 forbidden: the key lacks the invoices scope, or the request came from an IP that is not on its allowlist.
  • 404 not_found: no such invoice. Test and live invoices do not see each other.
  • 503 rate_unavailable: no fresh rate right now; try again shortly.

The libraries retry network errors, 429 and 5xx twice by default. Validation and permission errors are not repeated, since the same request earns the same result. Quote the request id when you write to support.

Simulate in test mode

A simulated payment
// Node.js
await hisarpay.invoices.simulate(invoice.id, { outcome: 'paid' });

// PHP
$hisarpay->invoices->simulate($invoice['id'], ['outcome' => 'paid']);

# Python
client.invoices.simulate(invoice["id"], {"outcome": "paid"})

A simulation runs the real state machine and delivers a signed webhook. Try these in order:

  1. paid: the order completes once.
  2. partial, then paid: it waits, then completes.
  3. expired, then paid: the late payment counts and carries late: true.
  4. Resend the same event from the dashboard: nothing changes.

When all four behave, swap in the live key; the code stays the same. Read the go-live list first. Every field is in the invoice guide.

Frequently asked questions

Do I have to use an official library?
No. A JSON body, a Bearer key and the Idempotency-Key header are enough to call the API directly. The libraries add retries and signature checks.
Can I decide which coin the customer pays with?
Yes. Fix it with token, or narrow the choice with the tokens list. With neither, the customer chooses between USDT and TRX.
Can a test key withdraw or create webhook endpoints?
No, those two scopes exist on live keys only. Add the endpoint in the dashboard and it receives test events as well.
  • #API
  • #Node.js
  • #PHP
  • #Python
  • #Webhooks

Try crypto payments in test mode

No setup or monthly fees. Experiment as much as you like in test mode and go live when you are ready.

More guides that go well with this one.