---
url: https://simplepay.webmania.cc/en/guide/ipn.md
description: >-
  SimplePay IPN endpoint in Node.js with handleIpnRequest: raw body, Signature
  header, receiveDate, signing the response, common mistakes (5100 invalid
  signature), multiple currencies, idempotency.
---

# IPN and signature verification

The **IPN** (Instant Payment Notification) is SimplePay's server-to-server notification of a payment's final result. It is the only reliable signal that an order is paid. This is the part people get wrong most often, so this page goes through it in detail.

## How it works

1. When a payment completes, SimplePay sends a `POST` to your IPN URL (set in the SimplePay merchant admin).
2. The body is compact JSON. The `Signature` header holds an HMAC-SHA384 of the body, Base64-encoded, made with the account's secret key.
3. You must verify the signature, add a `receiveDate` field to the JSON, sign the new JSON, and send it back with HTTP 200 and the new signature in the `Signature` header.
4. If your answer is wrong, SimplePay sends the IPN again and the transaction does not close properly in the merchant admin.

`handleIpnRequest` does step 3.

## An incoming IPN

```http
POST /api/simplepay/ipn HTTP/1.1
Content-Type: application/json
Signature: 0mI0u6CmGhPsQ0dU3vQh2iX5...

{"salt":"223G0O8HqBUlXjZ0Ix9u4V4hnkJwPgDx","orderRef":"order-12","method":"CARD","merchant":"P123456","finishDate":"2026-12-02T10:12:43+01:00","paymentDate":"2026-12-02T10:12:16+01:00","transactionId":504233881,"status":"FINISHED"}
```

For a recurring card registration the JSON also contains `cardMask` and `expiry`.

## The complete endpoint

Framework-agnostic example with web-standard `Request` / `Response` (Next.js route handlers, Nitro, Bun, Deno, Hono, Cloudflare Workers):

```ts
import { handleIpnRequest } from 'simplepay-js-sdk'

export async function POST(request: Request) {
  // 1. RAW text – not request.json()!
  const ipnBody = await request.text()

  // 2. the signature comes in a header
  const incomingSignature = request.headers.get('Signature') ?? ''

  let result
  try {
    // 3. verify + receiveDate + new signature
    result = handleIpnRequest(ipnBody, incomingSignature, process.env.SIMPLEPAY_MERCHANT_KEY_HUF!)
  } catch (error) {
    // bad signature or not a JSON object: don't touch the order
    console.error('Invalid SimplePay IPN', error)
    return new Response('Invalid signature', { status: 400 })
  }

  // 4. close the order – only after a valid signature
  const ipn = JSON.parse(ipnBody) as { orderRef: string, transactionId: number, status: string }
  if (ipn.status === 'FINISHED') {
    await markOrderPaid(ipn.orderRef, ipn.transactionId) // your function, make it idempotent
  }

  // 5. send the response back UNCHANGED
  return new Response(result.responseBody, {
    status: 200,
    headers: {
      'Content-Type': 'application/json',
      'Signature': result.signature,
    },
  })
}
```

Framework versions: [Nuxt / Nitro](../recipes/nuxt#ipn), [Express](../recipes/express#ipn), [Next.js](../recipes/nextjs#ipn).

## What `handleIpnRequest` does

```ts
handleIpnRequest(ipnBody: string, incomingSignature: string, merchantKey: string)
  : { responseBody: string, signature: string }
```

1. `checkSignature(ipnBody, incomingSignature, merchantKey)` – if wrong, throws `Invalid IPN request signature`.
2. Checks that the body is a JSON object – if not, throws `Invalid IPN request body`.
3. Inserts `receiveDate` **as text** before the last `}` of the original body. It does not parse and re-stringify, so field order, number vs string types and formatting stay byte-identical.
4. Signs the resulting text (HMAC-SHA384, Base64).

The result, for example:

```json
{"salt":"223G0O8HqBUlXjZ0Ix9u4V4hnkJwPgDx","orderRef":"order-12","method":"CARD","merchant":"P123456","finishDate":"2026-12-02T10:12:43+01:00","paymentDate":"2026-12-02T10:12:16+01:00","transactionId":504233881,"status":"FINISHED","receiveDate":"2026-12-02T09:12:44+00:00"}
```

## Common mistakes

### 1. Reading the body as JSON

```ts
const body = await request.json()            // ❌
const ipnBody = JSON.stringify(body)        // ❌ no longer the same text
```

The signature covers the **exact bytes**. If the framework parses the body and you stringify it again, whitespace, `\/` escapes, number formatting or field order may differ, and the signature will not match. Always read the raw text:

| Framework | Correct |
|---|---|
| Web `Request` (Next.js, Nitro web handler, Hono, Bun) | `await request.text()` |
| Nuxt / Nitro (h3) | `await readRawBody(event, 'utf8')` |
| Express | `express.text({ type: 'application/json' })` on the IPN route, then `req.body` |
| Fastify | `addContentTypeParser('application/json', { parseAs: 'string' }, …)` for the IPN route |

### 2. Changing the response

```ts
return Response.json(JSON.parse(responseBody)) // ❌
res.json(responseBody)                          // ❌ wraps it in quotes
```

`responseBody` is finished, signed text. Send it exactly as is: don't format it, parse it or add to it. In Express: `res.type('application/json').send(responseBody)`.

### 3. Putting the signature in the body

The response signature goes in the **`Signature` HTTP header**, not in the JSON.

### 4. Wrong key

Use the secret key of the merchant account the IPN belongs to. With several currencies, pick it from the JSON's `merchant` field (see below). For SZÉP cards use `SIMPLEPAY_MERCHANT_KEY_HUF_SZEP`.

### 5. Missing header

`request.headers.get('Signature')` returns `null` when the header is missing. In TypeScript pass a string with `?? ''`: `checkSignature` returns `false` for an empty signature, and `handleIpnRequest` throws.

### 6. Processing the order twice

SimplePay may send the same IPN more than once (for example if your answer was slow). Make `markOrderPaid` **idempotent**: if the order is already paid, don't send the confirmation email again or reserve stock again.

### 7. A proxy that rewrites the body

Some reverse proxies, WAFs or body-parser middleware compress, re-encode or reshape JSON. If every signature fails in the sandbox, log the raw body and header and compare with `generateSignature(ipnBody, key)`.

## Multiple currencies

`handleIpnRequest` doesn't know which currency an IPN belongs to – you pass the key. The body's `merchant` field tells you which account sent it. Use the parsed object **only for reading**; `handleIpnRequest` gets the raw text:

```ts
const CURRENCIES = ['HUF', 'HUF_SZEP', 'EUR', 'USD'] as const

const merchantKeyFor = (merchantId: string) => {
  const currency = CURRENCIES.find((c) => process.env[`SIMPLEPAY_MERCHANT_ID_${c}`] === merchantId)
  const key = currency && process.env[`SIMPLEPAY_MERCHANT_KEY_${currency}`]
  if (!key) {
    throw new Error(`Unknown SimplePay merchant: ${merchantId}`)
  }
  return key
}

const ipnBody = await request.text()
const { merchant } = JSON.parse(ipnBody) as { merchant: string }
const { responseBody, signature } = handleIpnRequest(
  ipnBody,
  request.headers.get('Signature') ?? '',
  merchantKeyFor(merchant),
)
```

## IPN `status` values

| `status` | Meaning |
|---|---|
| `FINISHED` | Successful, completed payment. Fulfil the order now. |
| `AUTHORIZED` | Authorised but not yet captured (two-step payments) |
| `NOTAUTHORIZED` | Authorisation failed |
| `CANCELLED` | Cancelled |
| `TIMEOUT` | Timed out |
| `REVERSED` | Reversed |

## Doing it by hand

Without `handleIpnRequest`, the steps with the exported helpers:

```ts
import { checkSignature, generateSignature, toISO8601DateString } from 'simplepay-js-sdk'

if (!checkSignature(ipnBody, incomingSignature, merchantKey)) {
  throw new Error('Invalid signature')
}

// insert receiveDate as text, not with JSON.parse + JSON.stringify
const body = ipnBody.trimEnd()
const responseBody = `${body.slice(0, -1)},"receiveDate":"${toISO8601DateString(new Date())}"}`
const signature = generateSignature(responseBody, merchantKey)
```

## Testing locally

The SimplePay sandbox can only send IPNs to a public URL. For local development use a tunnel (for example `cloudflared tunnel` or `ngrok`) and set the resulting `https` address as the IPN URL in the sandbox merchant admin.

You can sign your own test request with `generateSignature(body, key)` and send it with `curl` to your local endpoint in the `Signature` header.
