# Signature Verification

Verifying the cryptographic signature is an **absolute requirement** and the most important element of IPN notification integration. This is the only mechanism that gives you a 100% guarantee that the data sent in the notification (e.g., the amount and payment status of an order) has not been manipulated in transit (so-called Man-in-the-Middle attack) and actually comes from the SimPay system.

Not verifying the signature means that anyone who knows your endpoint address can send a fake notification and force your store to deliver goods for free.

## How Is the Signature Calculated?

Each IPN notification includes a `signature` field. It contains a unique string (hash in lowercase hex format) generated using the **SHA-256** algorithm.

The signature is generated by concatenating key values from the notification, separating them with the `|` separator, and appending your private IPN key (available in the SimPay Client Panel) at the very end.

The base string (before hashing) looks as follows:

```text
type|notification_id|date|data_value1|data_value2|...|data_valueN|YOUR_IPN_KEY
```

### Calculation Rules

1. **Order matters:** Values from the `data` field must be appended to the string in exactly the same order as they appear in the original JSON payload.
2. **Ignoring missing fields:** If the documentation indicates that a field in the `data` object may be optional and it actually does not appear in the received notification – simply skip it entirely. Do not insert empty separators `||`.
3. **Inserting empty string instead of null values** Some programming languages (e.g., Python) may interpret null as `None`, in such cases you should insert an empty string instead of the value e.g., `None`, to maintain string consistency.
4. **`signature` field:** Naturally, the value received in the `signature` field does not participate in generating your own hash (it only serves for final comparison).


## Structure Flexibility (Very Important!)

When designing the validation algorithm in your system, you must consider how we develop our API:

* **The main notification root** (fields: `type`, `notification_id`, `date`, `data`, `signature`) is fixed and **will never change**.
* **The `data` object is flexible.** We reserve the right to add new parameters inside the `data` object in the future (we will never remove an existing one, but we may add a new one).


Therefore, **you should not "hardcode"** specific field names from the `data` object in your validation function. Instead, you should use a function that dynamically flattens the entire received JSON object and extracts all values from it. We have prepared ready-made solutions to this problem in the examples below.

## Example String

Let's assume you receive the following data:

* `type`: `example:type`
* `notification_id`: `0196bf93-aca4-7253-8a2d-0941a037f25b`
* `date`: `2025-05-20T16:36:07Z`
* `data` object contains:
  * `status`: `transaction_paid`
  * `amount.currency`: `PLN`
  * `amount.value`: `5.25`
  * `transaction_id`: `123123123123`
  * `meta`: `test`
* Your key is: `keyFromPanel`


The correctly concatenated string will look like this:

```text
example:type|0196bf93-aca4-7253-8a2d-0941a037f25b|2025-05-20T16:36:07Z|transaction_paid|PLN|5.25|123123123123|test|keyFromPanel
```

*(If the `meta` field did not appear at all, the string would end with `...|123123123123|keyFromPanel`).*

You pass the prepared string to the `sha256` hashing function and compare it with the `signature` field from the notification.

## Implementation Examples (Ready SDKs)

To make secure integration easier for you, we have prepared ready-made validator classes in the most popular programming languages. They automatically handle the flexibility of the `data` object.

PHP
```php
<?php

class SimPaySignatureValidator
{
    public function isValid(): bool
    {
        $payload = json_decode(@file_get_contents('php://input'), true);
        if (empty($payload)) {
            return false;
        }

        $data = $this->flattenArray($payload);
        $data[] = 'SERVICE_IPN_KEY';

        $signature = hash('sha256', implode('|', $data));

        return hash_equals($signature, $payload['signature']);
    }

    private function flattenArray(array $array): array
    {
        unset($array['signature']);

        $return = [];

        array_walk_recursive($array, function ($a) use (&$return) {
            $return[] = $a;
        });

        return $return;
    }
}

$validator = new SimPaySignatureValidator();
if(!$validator->isValid()) {
  http_response_code(403);
  echo 'INVALID_SIGNATURE';
  die();
}

// rest of ipn
```

Node
```js
const crypto = require('crypto');

class SimPaySignatureValidator {
    constructor(payload) {
        this.payload = payload;
    }

    isValidHex(str) {
        if (typeof str !== 'string' || str.length !== 64) {
            return false;
        }
        return /^[0-9a-fA-F]+$/.test(str);
    }

    isValid() {
        if (!this.payload || typeof this.payload !== 'object') {
            return false;
        }

        const data = this.flattenArray(this.payload);
        data.push('SERVICE_IPN_KEY');

        const signature = crypto
            .createHash('sha256')
            .update(data.join('|'))
            .digest('hex');

        const payloadSignature = this.payload.signature || '';

        if (!this.isValidHex(payloadSignature)) {
            return false;
        }

        // Secure comparison using timingSafeEqual
        return crypto.timingSafeEqual(
            Buffer.from(signature, 'hex'),
            Buffer.from(payloadSignature, 'hex')
        );
    }

    flattenArray(array) {
        const arrayClone = { ...array };
        delete arrayClone.signature;

        const result = [];

        const flatten = (obj) => {
            if (Array.isArray(obj)) {
                obj.forEach(item => flatten(item));
            } else if (typeof obj === 'object' && obj !== null) {
                Object.values(obj).forEach(value => flatten(value));
            } else {
                result.push(obj);
            }
        };

        flatten(arrayClone);
        return result;
    }
}

// Example usage with Express.js
const express = require('express');
const app = express();

app.use(express.json());

app.post('/webhook', (req, res) => {
    const validator = new SimPaySignatureValidator(req.body);

    if (!validator.isValid()) {
        return res.status(403).send('INVALID_SIGNATURE');
    }

    res.send('OK');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

// Export class for use in other modules
module.exports = SimPaySignatureValidator;
```

Python (Flask)
```python
import hashlib
import hmac
import json
from flask import Flask, request, abort

app = Flask(__name__)

class SimPaySignatureValidator:
    SECRET_KEY = 'SERVICE_IPN_KEY'

    def is_valid(self, payload: dict) -> bool:
        if not payload:
            return False

        signature_from_payload = payload.get('signature')
        if not signature_from_payload:
            return False

        data = self.flatten_array(payload)
        data.append(self.SECRET_KEY)
        signature = hashlib.sha256('|'.join(data).encode()).hexdigest()

        return hmac.compare_digest(signature, signature_from_payload)

    def flatten_array(self, obj, exclude_key='signature'):
        result = []

        def _recurse(o):
            if isinstance(o, dict):
                for k, v in o.items():
                    if k == exclude_key:
                        continue
                    _recurse(v)
            elif isinstance(o, list):
                for item in o:
                    _recurse(item)
            else:
                # Replace None with empty string
                result.append(str(o) if o is not None else '')

        _recurse(obj)
        return result

@app.route('/', methods=['POST'])
def validate_signature():
    try:
        payload = request.get_json(force=True)
    except Exception:
        abort(403, 'INVALID_SIGNATURE')

    validator = SimPaySignatureValidator()
    if not validator.is_valid(payload):
        abort(403, 'INVALID_SIGNATURE')

    return Response("OK", status=200, mimetype="text/plain")

if __name__ == '__main__':
    app.run(port=5000)
```

Laravel SDK
```php
// for more details visit https://github.com/SimPaypl/simpay-laravel
<?php

use SimPay\Laravel\Facades\SimPay;

if(!SimPay::payment()->ipnSignatureValid(request())) {
  abort(403, 'invalid signature');
}
```

TypeScript SDK
```ts
// for more details visit https://github.com/SimPaypl/simpay-typescript
import express from "express";
import {
    SimPayClient,
    SimPayIpnError,
    type PaymentIpnNotification,
} from "@simpay/typescript";

const app = express();
app.use(express.json());

const simpay = new SimPayClient({
    api: {
        password: process.env.SIMPAY_API_PASSWORD!,
    },
    service: {
        id: process.env.SIMPAY_SERVICE_ID!,
    },
    ipn: {
        signatureKey: process.env.SIMPAY_IPN_SIGNATURE_KEY!,
        validateSourceIp: true,
    },
});

app.post("/webhooks/simpay/payment", async (req, res) => {
    try {
        await simpay.notifications.payment.verify({
            payload: req.body,
            sourceIp: req.ip,
        });

        const payload = req.body as PaymentIpnNotification;

        // handle rest of your ipn logic here, e.g. update order status in database

        res.status(200).send("OK");
    } catch (error) {
        if (error instanceof SimPayIpnError) {
            res.status(400).send(error.code);
            return;
        }

        res.status(500).send("ERROR");
    }
});
```