{"templateId":"markdown","sharedDataIds":{"sidebar":"sidebar-sidebars.yaml"},"props":{"metadata":{"markdoc":{"tagList":["tabs","tab"]},"type":"markdown"},"seo":{"title":"Weryfikacja sygnatury","description":"Znajdziesz tutaj wszystkie niezbędne informacje dotyczące integracji i obsługi systemu płatności SimPay.pl","siteUrl":"https://docs.simpay.pl","llmstxt":{"hide":false,"sections":[{"title":"Table of contents","includeFiles":["**/*"],"excludeFiles":[]}],"excludeFiles":[]}},"dynamicMarkdocComponents":[],"compilationErrors":[],"ast":{"$$mdtype":"Tag","name":"article","attributes":{},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":1,"id":"weryfikacja-sygnatury","__idx":0},"children":["Weryfikacja sygnatury"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Weryfikacja sygnatury kryptograficznej to ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["absolutny wymóg"]}," i najważniejszy element integracji powiadomień IPN. To"," ","jedyny mechanizm, który daje Ci 100% gwarancji, że dane przesyłane w powiadomieniu (np. kwota i status opłacenia"," ","zamówienia) nie zostały zmanipulowane w drodze (tzw. atak Man-in-the-Middle) i faktycznie pochodzą od systemu SimPay."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Brak weryfikacji sygnatury oznacza, że każdy, kto zna adres Twojego endpointu, może wysłać fałszywe powiadomienie i"," ","wymusić na Twoim sklepie darmowe wydanie towaru."]},{"$$mdtype":"Tag","name":"hr","attributes":{},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"jak-wyliczana-jest-sygnatura","__idx":1},"children":["Jak wyliczana jest sygnatura?"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Do każdego powiadomienia IPN dołączamy pole ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["signature"]},". Zawiera ono unikalny ciąg znaków (hash w formacie lowercase"," ","hex) wygenerowany za pomocą algorytmu ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["SHA-256"]},"."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Sygnaturę generuje się poprzez zestawienie ze sobą kluczowych wartości z powiadomienia, oddzielenie ich separatorem ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["|"]}," ","i dodanie na samym końcu Twojego prywatnego klucza IPN (dostępnego w Panelu Klienta SimPay)."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Bazowy ciąg znaków (przed zahashowaniem) wygląda następująco:"]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"text","header":{"controls":{"copy":{}}},"source":"type|notification_id|date|data_value1|data_value2|...|data_valueN|TWÓJ_KLUCZ_IPN\n","lang":"text"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"zasady-wyliczania","__idx":2},"children":["Zasady wyliczania"]},{"$$mdtype":"Tag","name":"ol","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Kolejność ma znaczenie:"]}," Wartości z pola ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["data"]}," muszą być dołączane do ciągu dokładnie w takiej kolejności, w"," ","jakiej występują w oryginalnym payloadzie JSON."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Ignorowanie brakujących pól:"]}," Jeśli dokumentacja wskazuje, że jakieś pole w obiekcie ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["data"]}," może być"," ","opcjonalne i faktycznie nie występuje w otrzymanym powiadomieniu – po prostu całkowicie je pomijasz. Nie wstawiasz"," ","pustych separatorów ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["||"]},"."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Wstawienie pustego stringa zamiast wartości null"]}," Niektóre języki programowania (np. Python) mogą interpretować"," ","null jako ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["None"]},", w takim przypadku należy wstawić pusty string zamiast wartości np. ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["None"]},", aby zachować spójność ciągu znaków."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Pole ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["signature"]},":"]}," Naturalnie, wartość otrzymana w polu ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["signature"]}," nie bierze udziału w generowaniu Twojego"," ","własnego hasha (służy tylko do końcowego porównania)."]}]},{"$$mdtype":"Tag","name":"hr","attributes":{},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"elastyczność-struktury-bardzo-ważne","__idx":3},"children":["Elastyczność struktury (Bardzo ważne!)"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Projektując algorytm walidacji w swoim systemie, musisz wziąć pod uwagę, w jaki sposób rozwijamy nasze API:"]},{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Główny root powiadomienia"]}," (pola: ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["type"]},", ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["notification_id"]},", ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["date"]},", ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["data"]},", ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["signature"]},") jest stały i ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["nigdy się"," ","nie zmieni"]},"."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Obiekt ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["data"]}," jest elastyczny."]}," Zastrzegamy sobie prawo do dodawania nowych parametrów wewnątrz obiektu ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["data"]}," w"," ","przyszłości (nigdy nie usuniemy istniejącego, ale możemy dodać nowy)."]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Dlatego ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["nie należy \"na sztywno\" (hardcodować)"]}," konkretnych nazw pól z obiektu ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["data"]}," w funkcji walidującej. Zamiast"," ","tego powinieneś użyć funkcji, która dynamicznie spłaszcza (tzw. ",{"$$mdtype":"Tag","name":"em","attributes":{},"children":["flatten"]},") cały otrzymany obiekt JSON i wyciąga z niego"," ","wszystkie wartości. Przygotowaliśmy dla Ciebie gotowe rozwiązania tego problemu w poniższych przykładach."]},{"$$mdtype":"Tag","name":"hr","attributes":{},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"przykładowy-ciąg-znaków","__idx":4},"children":["Przykładowy ciąg znaków"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Załóżmy, że otrzymujesz następujące dane:"]},{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["type"]},": ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["example:type"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["notification_id"]},": ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["0196bf93-aca4-7253-8a2d-0941a037f25b"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["date"]},": ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["2025-05-20T16:36:07Z"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Obiekt ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["data"]}," zawiera:",{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["status"]},": ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["transaction_paid"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["amount.currency"]},": ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["PLN"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["amount.value"]},": ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["5.25"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["transaction_id"]},": ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["123123123123"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["meta"]},": ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["test"]}]}]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Twój klucz to: ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["keyFromPanel"]}]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Prawidłowo połączony ciąg elementów będzie wyglądał tak:"]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"text","header":{"controls":{"copy":{}}},"source":"example:type|0196bf93-aca4-7253-8a2d-0941a037f25b|2025-05-20T16:36:07Z|transaction_paid|PLN|5.25|123123123123|test|keyFromPanel\n","lang":"text"},"children":[]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":[{"$$mdtype":"Tag","name":"em","attributes":{},"children":["(Gdyby pole ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["meta"]}," nie wystąpiło wcale, ciąg kończyłby się na ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["...|123123123123|keyFromPanel"]},")."]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Tak przygotowany ciąg przekazujesz do funkcji hashującej ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["sha256"]}," i porównujesz z polem ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["signature"]}," z powiadomienia."]},{"$$mdtype":"Tag","name":"hr","attributes":{},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"przykłady-implementacji-gotowe-sdk","__idx":5},"children":["Przykłady implementacji (Gotowe SDK)"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Aby ułatwić Ci bezpieczną integrację, przygotowaliśmy gotowe klasy walidatorów w najpopularniejszych językach"," ","programowania. Automatycznie radzą one sobie z elastycznością obiektu ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["data"]},"."]},{"$$mdtype":"Tag","name":"Tabs","attributes":{"size":"medium"},"children":[{"$$mdtype":"Tag","name":"div","attributes":{"label":"PHP","disable":false},"children":[{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"php","header":{"controls":{"copy":{}}},"source":"<?php\n\nclass SimPaySignatureValidator\n{\n    public function isValid(): bool\n    {\n        $payload = json_decode(@file_get_contents('php://input'), true);\n        if (empty($payload)) {\n            return false;\n        }\n\n        $data = $this->flattenArray($payload);\n        $data[] = 'KLUCZ_IPN_USŁUGI';\n\n        $signature = hash('sha256', implode('|', $data));\n\n        return hash_equals($signature, $payload['signature']);\n    }\n\n    private function flattenArray(array $array): array\n    {\n        unset($array['signature']);\n\n        $return = [];\n\n        array_walk_recursive($array, function ($a) use (&$return) {\n            $return[] = $a;\n        });\n\n        return $return;\n    }\n}\n\n$validator = new SimPaySignatureValidator();\nif(!$validator->isValid()) {\n  http_response_code(403);\n  echo 'INVALID_SIGNATURE';\n  die();\n}\n\n// reszta ipn\n","lang":"php"},"children":[]}]},{"$$mdtype":"Tag","name":"div","attributes":{"label":"Node","disable":false},"children":[{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"js","header":{"controls":{"copy":{}}},"source":"const crypto = require('crypto');\n\nclass SimPaySignatureValidator {\n    constructor(payload) {\n        this.payload = payload;\n    }\n\n    isValidHex(str) {\n        // Sprawdź czy string ma odpowiednią długość dla SHA-256 (64 znaki)\n        if (typeof str !== 'string' || str.length !== 64) {\n            return false;\n        }\n\n        // Sprawdź czy zawiera tylko znaki hex (0-9, a-f, A-F)\n        return /^[0-9a-fA-F]+$/.test(str);\n    }\n\n    isValid() {\n        if (!this.payload || typeof this.payload !== 'object') {\n            return false;\n        }\n\n        const data = this.flattenArray(this.payload);\n        data.push('SERVICE_IPN_KEY');\n\n        const signature = crypto\n            .createHash('sha256')\n            .update(data.join('|'))\n            .digest('hex');\n\n        const payloadSignature = this.payload.signature || '';\n\n        // Sprawdź czy sygnatura z payload jest prawidłowym hexem\n        if (!this.isValidHex(payloadSignature)) {\n            return false;\n        }\n\n        // Bezpieczne porównanie używając timingSafeEqual\n        return crypto.timingSafeEqual(\n            Buffer.from(signature, 'hex'),\n            Buffer.from(payloadSignature, 'hex')\n        );\n    }\n\n    flattenArray(array) {\n        const arrayClone = { ...array };\n        delete arrayClone.signature;\n\n        const result = [];\n\n        const flatten = (obj) => {\n            if (Array.isArray(obj)) {\n                obj.forEach(item => flatten(item));\n            } else if (typeof obj === 'object' && obj !== null) {\n                Object.values(obj).forEach(value => flatten(value));\n            } else {\n                result.push(obj);\n            }\n        };\n\n        flatten(arrayClone);\n        return result;\n    }\n}\n\n// Przykład użycia z Express.js\nconst express = require('express');\nconst app = express();\n\napp.use(express.json());\n\napp.post('/webhook', (req, res) => {\n    const validator = new SimPaySignatureValidator(req.body);\n\n    if (!validator.isValid()) {\n        return res.status(403).send('INVALID_SIGNATURE');\n    }\n\n    res.send('OK');\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n    console.log(`Server running on port ${PORT}`);\n});\n\n// Eksport klasy do użycia w innych modułach\nmodule.exports = SimPaySignatureValidator;\n\n","lang":"js"},"children":[]}]},{"$$mdtype":"Tag","name":"div","attributes":{"label":"Python (Flask)","disable":false},"children":[{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"python","header":{"controls":{"copy":{}}},"source":"import hashlib\nimport hmac\nimport json\nfrom flask import Flask, request, abort\n\napp = Flask(__name__)\n\nclass SimPaySignatureValidator:\n    SECRET_KEY = 'SERVICE_IPN_KEY'\n\n    def is_valid(self, payload: dict) -> bool:\n        if not payload:\n            return False\n\n        signature_from_payload = payload.get('signature')\n        if not signature_from_payload:\n            return False\n\n        data = self.flatten_array(payload)\n        data.append(self.SECRET_KEY)\n        signature = hashlib.sha256('|'.join(data).encode()).hexdigest()\n\n        return hmac.compare_digest(signature, signature_from_payload)\n\n    def flatten_array(self, obj, exclude_key='signature'):\n        result = []\n\n        def _recurse(o):\n            if isinstance(o, dict):\n                for k, v in o.items():\n                    if k == exclude_key:\n                        continue\n                    _recurse(v)\n            elif isinstance(o, list):\n                for item in o:\n                    _recurse(item)\n            else:\n                # Zamiana None na pusty string\n                result.append(str(o) if o is not None else '')\n\n        _recurse(obj)\n        return result\n\n@app.route('/', methods=['POST'])\ndef validate_signature():\n    try:\n        payload = request.get_json(force=True)\n    except Exception:\n        abort(403, 'INVALID_SIGNATURE')\n\n    validator = SimPaySignatureValidator()\n    if not validator.is_valid(payload):\n        abort(403, 'INVALID_SIGNATURE')\n\n    return Response(\"OK\", status=200, mimetype=\"text/plain\")\n\nif __name__ == '__main__':\n    app.run(port=5000)\n","lang":"python"},"children":[]}]},{"$$mdtype":"Tag","name":"div","attributes":{"label":"Laravel SDK","disable":false},"children":[{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"php","header":{"controls":{"copy":{}}},"source":"// for more details visit https://github.com/SimPaypl/simpay-laravel\n<?php\n\nuse SimPay\\Laravel\\Facades\\SimPay;\n\nif(!SimPay::payment()->ipnSignatureValid(request())) {\n  abort(403, 'invalid signature');\n}\n","lang":"php"},"children":[]}]},{"$$mdtype":"Tag","name":"div","attributes":{"label":"TypeScript SDK","disable":false},"children":[{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"ts","header":{"controls":{"copy":{}}},"source":"// for more details visit https://github.com/SimPaypl/simpay-typescript\nimport express from \"express\";\nimport {\n    SimPayClient,\n    SimPayIpnError,\n    type PaymentIpnNotification,\n} from \"@simpay/typescript\";\n\nconst app = express();\napp.use(express.json());\n\nconst simpay = new SimPayClient({\n    api: {\n        password: process.env.SIMPAY_API_PASSWORD!,\n    },\n    service: {\n        id: process.env.SIMPAY_SERVICE_ID!,\n    },\n    ipn: {\n        signatureKey: process.env.SIMPAY_IPN_SIGNATURE_KEY!,\n        validateSourceIp: true,\n    },\n});\n\napp.post(\"/webhooks/simpay/payment\", async (req, res) => {\n    try {\n        await simpay.notifications.payment.verify({\n            payload: req.body,\n            sourceIp: req.ip,\n        });\n\n        const payload = req.body as PaymentIpnNotification;\n\n        // handle rest of your ipn logic here, e.g. update order status in database\n\n        res.status(200).send(\"OK\");\n    } catch (error) {\n        if (error instanceof SimPayIpnError) {\n            res.status(400).send(error.code);\n            return;\n        }\n\n        res.status(500).send(\"ERROR\");\n    }\n});\n","lang":"ts"},"children":[]}]}]}]},"headings":[{"value":"Weryfikacja sygnatury","id":"weryfikacja-sygnatury","depth":1},{"value":"Jak wyliczana jest sygnatura?","id":"jak-wyliczana-jest-sygnatura","depth":2},{"value":"Zasady wyliczania","id":"zasady-wyliczania","depth":3},{"value":"Elastyczność struktury (Bardzo ważne!)","id":"elastyczność-struktury-bardzo-ważne","depth":2},{"value":"Przykładowy ciąg znaków","id":"przykładowy-ciąg-znaków","depth":2},{"value":"Przykłady implementacji (Gotowe SDK)","id":"przykłady-implementacji-gotowe-sdk","depth":2}],"frontmatter":{"seo":{"title":"Weryfikacja sygnatury"}},"lastModified":"2026-04-21T23:37:53.000Z","pagePropGetterError":{"message":"","name":""}},"slug":"/notifications/payment/signature","userData":{"isAuthenticated":false,"teams":["anonymous"]},"isPublic":true}