# Verify PayGate.to callback signatures (PHP, Node.js, Python)

> How PayGate.to signs payment callbacks and how to verify them: the exact signed string, raw query handling, key IDs, and the order, txid and payout checks.

Source: https://withoutkyc.to/knowledge-base/developers/verify-callback-signatures/
Updated: 2026-11-15

When a payment confirms, PayGate.to sends a `GET` request to your callback URL with the payment data added to the query string. Anyone who knows that URL could send the same request, so **verify the signature before you credit an order**. The scheme is documented in the [Callback Event reference](https://withoutkyc.to/docs/payment-gateway-api/#callback-event); this guide adds tested code and the mistakes that cause valid callbacks to be rejected.

## What arrives

```text
GET /paygate/callback.php?order=1001&token=…&value_coin=49.92&coin=polygon_usdc&txid_in=0x…&txid_out=0x…
    &address_in=0x…&value_forwarded_coin=49.42&address_out=%7B%220xYourWallet%22%3A%221.0000%22%7D
User-Agent: paygate.to
X-PayGate-Signature: (344 characters of base64)
X-PayGate-Key-Id: v1
```

- **Signature:** RSA 2048-bit, SHA-256, PKCS#1 v1.5, base64 encoded.
- **Key ID:** which published key signed it (`v1` today).
- **User-Agent:** proves nothing; anyone can send it.

## What is signed

The exact URL PayGate.to requested: **your registered callback URL, `?`, and the query string exactly as sent**, in the same order and with the same encoding.

```text
signed = "https://shop.example8585859.com/paygate/callback.php" + "?" + RAW_QUERY_STRING
```

### Step 1: Take the base from your own constant

Use the callback URL you registered when you created the wallet, cut before `?`, written as a constant in your code. **Never read the `Host` header**: a proxy, a CDN or an attacker controls it.

### Step 2: Take the query string raw

Use the bytes after `?` exactly as received: `$_SERVER['QUERY_STRING']` in PHP, `req.originalUrl` in Node.js, `environ['QUERY_STRING']` in Python WSGI.

### Step 3: Verify with the published key

Download [paygate_callback_public.pem](https://withoutkyc.to/docs/paygate_callback_public.pem) once and ship it with your code. Choose the key by `X-PayGate-Key-Id`; answer **403** if it doesn't verify.

## Why rebuilding the query breaks signatures

Parsing the parameters and joining them again looks equivalent and passes simple tests, then fails on a real callback. We checked these against a request signed the way PayGate.to signs:

| Original bytes in the query | After a rebuild | Result |
|---|---|---|
| `%20` | `+` | rejected |
| `%7b` (lowercase escape) | `%7B` | rejected |
| `~` | `%7E` (PHP and Node.js) | rejected |
| `a=1&a=2` | `a=2` (PHP keeps the last value) | rejected |
| parameters in PayGate.to's order | sorted | rejected |

Using the raw query string accepted all of them.

## PHP (no SDK)

```php
<?php
const CALLBACK = 'https://shop.example8585859.com/paygate/callback.php';   // as registered
const KEYS = ['v1' => __DIR__ . '/paygate_callback_public.pem'];

$qs     = $_SERVER['QUERY_STRING'] ?? '';                                 // raw
$signed = $qs === '' ? CALLBACK : CALLBACK . '?' . $qs;
$keyId  = $_SERVER['HTTP_X_PAYGATE_KEY_ID'] ?? 'v1';
$sig    = base64_decode($_SERVER['HTTP_X_PAYGATE_SIGNATURE'] ?? '', true);

$ok = isset(KEYS[$keyId]) && $sig !== false
    && openssl_verify($signed, $sig, openssl_pkey_get_public(file_get_contents(KEYS[$keyId])), OPENSSL_ALGO_SHA256) === 1;

if (!$ok) { http_response_code(403); exit; }
// Only now read $_GET
```

## Node.js (no SDK)

```js
const crypto = require('node:crypto');
const fs = require('node:fs');

const CALLBACK = 'https://shop.example8585859.com/paygate/callback';      // as registered
const KEYS = { v1: fs.readFileSync('paygate_callback_public.pem', 'utf8') };

function verifyPayGate(req) {
  const url = req.originalUrl ?? req.url ?? '';
  const i = url.indexOf('?');
  const signed = CALLBACK + (i === -1 ? '' : url.slice(i));
  const pem = KEYS[req.headers['x-paygate-key-id'] || 'v1'];
  const sig = req.headers['x-paygate-signature'] || '';
  return Boolean(pem) && crypto.verify('sha256', Buffer.from(signed), pem, Buffer.from(sig, 'base64'));
}
```

## Python (no SDK)

```python
import base64
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.exceptions import InvalidSignature

CALLBACK = "https://shop.example8585859.com/paygate/callback"            # as registered
KEYS = {"v1": serialization.load_pem_public_key(open("paygate_callback_public.pem", "rb").read())}

def verify_paygate(environ):
    qs = environ.get("QUERY_STRING", "")                                  # raw
    signed = f"{CALLBACK}?{qs}" if qs else CALLBACK
    key = KEYS.get(environ.get("HTTP_X_PAYGATE_KEY_ID") or "v1")
    try:
        sig = base64.b64decode(environ.get("HTTP_X_PAYGATE_SIGNATURE", ""), validate=True)
        key.verify(sig, signed.encode(), padding.PKCS1v15(), hashes.SHA256())
        return True
    except (InvalidSignature, ValueError, AttributeError):
        return False
```

## With the official SDKs

| SDK | Call |
|---|---|
| PHP | `$paygate->callbacks()->verifyRequest(CALLBACK)` · [PHP guide](https://withoutkyc.to/knowledge-base/developers/accept-crypto-php/) |
| Node.js | `await paygate.callbacks.verifyRequest(CALLBACK_URL, req)` · [Node.js guide](https://withoutkyc.to/knowledge-base/developers/accept-crypto-nodejs/) |
| Laravel | `->middleware('paygate.callback:order')` (checks against `APP_URL`) · [Laravel guide](https://withoutkyc.to/knowledge-base/developers/accept-crypto-laravel/) |

The SDKs bundle the `v1` key, fail closed, and return a reason such as `signature_absent` or `signature_mismatch`.

## After the signature: four more checks

A valid signature proves PayGate.to sent the callback and nothing was changed. It doesn't prove the payment is the one you expected.

1. **Order token.** Anyone can create a wallet whose callback names one of your orders. Add an HMAC token of the order ID to your callback URL and check it (the SDKs' `CallbackToken` and Laravel's `paygate_callback_url()` do this).
2. **Credit each `txid_in` once.** Callbacks repeat until you answer `ok`, and two deliveries can arrive together. Use a unique index.
3. **Coin and amount.** Compare `coin` and `value_coin` with what you asked for. Any token can be sent to an address.
4. **Payout to your wallet.** `address_out` is a JSON object of payout address → share of `value_forwarded_coin`. Check that your own wallet received its share; a leaked callback URL could otherwise be reused with someone else's wallet.

```php
$shares = json_decode($_GET['address_out'], true);                // $_GET is already percent-decoded
$toMe   = isset($shares[MY_WALLET]) ? bcmul($_GET['value_forwarded_coin'], $shares[MY_WALLET], 18) : null;
```

> **Fail closed**
If anything doesn't verify, answer 403 and change nothing. Don't fall back to "accept unsigned callbacks" when verification fails.

> **All crypto endpoints and callback parameters: [crypto API reference](https://withoutkyc.to/docs/crypto-payment-api/). For AI-generated integrations, give your assistant the [AI agent reference](https://withoutkyc.to/docs/crypto-payment-api/paygate-crypto-payment-api-llm.md).**

## Frequently asked questions

### Valid callbacks are rejected with "signature mismatch". What's wrong?

Almost always the signed string: the base came from the `Host` header or differs from the registered URL (`http` vs `https`, `www`, a trailing slash), or the query was rebuilt or decoded. Log the exact string you verify and compare it with your registered URL.

### Should I fetch the public key on every callback?

No. Ship it with your code or cache it. When a new key ID appears, fetch the published key for it once, then reject IDs you can't resolve.

### Is verification required?

It's optional on PayGate.to's side, but anything that credits an account or releases goods should verify. It's the only proof the request came from PayGate.to.
