Przelewy24 REST API: a payment from registration to verification

You register the transaction, send the customer to Przelewy24, receive the notification and confirm the payment with verify. Without verification the money never reaches you. The code needs PHP 8.1 or newer; the sign and the access test were run against the Przelewy24 sandbox.

What you will do

Przelewy24 (P24) is a Polish payment gateway that handles BLIK, bank transfers and cards. The customer clicks "Pay", pays at Przelewy24 and comes back to the store, and the order turns paid on its own. Behind it are four calls and one rule many integrations forget: a transaction is confirmed only after verification.

The Przelewy24 documentation says it plainly: if the customer pays and the merchant does not verify the transaction, the amount reaches neither the merchant nor the settlements and stays with the customer as a prepayment.

Level
intermediate
Code
PHP
Steps
7 steps
  1. Your store Register transaction/register returns a token.
  2. Customer Pays at P24 Redirect to /trnRequest/{token}.
  3. P24 Notification Signed JSON to your urlStatus.
  4. Your store Verify transaction/verify confirms the payment.

What you need

  • A Przelewy24 sandbox account

    The sandbox uses test data and separate keys. From the panel you need the merchant ID, the shop ID (posId), the CRC key and the reports key, which is the API password.

  • PHP 8.1 or newer with curl and json

    The class in the example uses readonly properties from PHP 8.1. We ran it on PHP 8.3.

  • A public HTTPS address for notifications

    Przelewy24 posts the payment result to urlStatus from the internet. On a local machine you need a tunnel or a test server.

  • An orders table with the amount

    Before registering you store the sessionId and the amount so you can compare them with the notification later. The documentation asks for exactly that.

Addresses and calls

WhatAddressMethod
Sandboxhttps://sandbox.przelewy24.pl-
Productionhttps://secure.przelewy24.pl-
Access test/api/v1/testAccessGET
Register/api/v1/transaction/registerPOST
Verify/api/v1/transaction/verifyPUT
Refund/api/v1/transaction/refundPOST

Step by step

Each step with commands to copy. The list on the left shows where you are.

01

Write the API client and the sign

Authentication is HTTP Basic: the user is the posId and the password is the reports key. Every important request carries a sign field: the SHA-384 hash of a JSON object with specific fields in a specific order, always ending with the CRC key.

The documentation requires the JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES flags. Without them a slash in an address or a Polish letter in a description changes the hash and the sign fails.

Przelewy24.php
<?phpdeclare(strict_types=1);final class Przelewy24{ public function __construct( public readonly string $baseUrl, // https://sandbox.przelewy24.pl public readonly int $merchantId, public readonly int $posId, private string $apiKey, // reports (API) key from the panel private string $crc, // CRC key from the panel ) {} /** SHA-384 of JSON with a fixed field order, always ending with the CRC key. */ public function sign(array $fields): string { $fields['crc'] = $this->crc; return hash('sha384', json_encode($fields, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); } public function call(string $method, string $path, ?array $body = null): array { $curl = curl_init($this->baseUrl . $path); curl_setopt_array($curl, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_USERPWD => $this->posId . ':' . $this->apiKey, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, ]); if ($body !== null) { curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); } $raw = (string) curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE); curl_close($curl); return [$status, json_decode($raw, true)]; }}
02

Check the credentials

GET /api/v1/testAccess answers 200 with good credentials. With bad ones you get 401 and "Incorrect authentication". Do it once during setup, before you hunt for a bug in the sign.

config.php
$p24 = new Przelewy24( 'https://sandbox.przelewy24.pl', (int) getenv('P24_MERCHANT_ID'), (int) getenv('P24_POS_ID'), getenv('P24_API_KEY'), getenv('P24_CRC'),);[$status, $body] = $p24->call('GET', '/api/v1/testAccess');// 200 with valid credentials, 401 {"error":"Incorrect authentication"} with invalid ones
03

Store the order before registering

The sessionId is your unique transaction id. Amounts are sent in grosze, the hundredth part of a zloty: PLN 123.00 is 12300. Store both fields with the order, because you will compare the notification against them.

checkout.php
$sessionId = 'order-' . $order->id; // unique in your system$amount = 12300; // in grosze: 123.00 PLN$db->prepare('UPDATE orders SET p24_session = ?, p24_amount = ? WHERE id = ?') ->execute([$sessionId, $amount, $order->id]);
04

Register the transaction and redirect the customer

The required fields are merchantId, posId, sessionId, amount, currency, description, email, country, language, urlReturn and sign. urlStatus is optional in the schema, but without it you get no notification, so in practice it is mandatory.

The registration sign covers sessionId, merchantId, amount, currency and crc, in that order. The response carries a token, and you send the customer to /trnRequest/{token} on the same environment.

checkout.php
[$status, $body] = $p24->call('POST', '/api/v1/transaction/register', [ 'merchantId' => $p24->merchantId, 'posId' => $p24->posId, 'sessionId' => $sessionId, 'amount' => $amount, 'currency' => 'PLN', 'description' => 'Order ' . $order->id, 'email' => $order->email, 'country' => 'PL', 'language' => 'pl', 'urlReturn' => 'https://shop.example/order/' . $order->id, 'urlStatus' => 'https://shop.example/p24/notification', 'sign' => $p24->sign([ 'sessionId' => $sessionId, 'merchantId' => $p24->merchantId, 'amount' => $amount, 'currency' => 'PLN', ]),]);if ($status !== 200) { throw new RuntimeException('P24 register: ' . json_encode($body));}header('Location: ' . $p24->baseUrl . '/trnRequest/' . $body['data']['token']);
05

Receive and check the notification

After payment Przelewy24 posts JSON to urlStatus, whether or not the customer came back to the store. Notifications arrive only for correctly paid transactions.

First you compute the sign from ten fields (merchantId through statement plus crc) and compare it in constant time. Then you check that the amount and currency match the order. Only then do you move on to verification.

p24-notification.php
$n = json_decode(file_get_contents('php://input'), true);$expected = $p24->sign([ 'merchantId' => $n['merchantId'], 'posId' => $n['posId'], 'sessionId' => $n['sessionId'], 'amount' => $n['amount'], 'originAmount' => $n['originAmount'], 'currency' => $n['currency'], 'orderId' => $n['orderId'], 'methodId' => $n['methodId'], 'statement' => $n['statement'],]);if (!hash_equals($expected, (string) ($n['sign'] ?? ''))) { http_response_code(400); exit;}$order = findOrderBySessionId($n['sessionId']);if ($order === null || $order->p24_amount !== $n['amount'] || $n['currency'] !== 'PLN') { http_response_code(400); exit;}
06

Verify the transaction

PUT /api/v1/transaction/verify with the orderId from the notification. The sign covers sessionId, orderId, amount, currency and crc. A data.status of "success" means the money is yours: only now do you mark the order paid.

If verification does not happen, Przelewy24 resends the notification after 3, 5, 15, 30, 60, 150 and 450 minutes. Your code must therefore survive the same notification several times without marking the order twice.

p24-notification.php
[$status, $body] = $p24->call('PUT', '/api/v1/transaction/verify', [ 'merchantId' => $p24->merchantId, 'posId' => $p24->posId, 'sessionId' => $n['sessionId'], 'amount' => $n['amount'], 'currency' => $n['currency'], 'orderId' => $n['orderId'], 'sign' => $p24->sign([ 'sessionId' => $n['sessionId'], 'orderId' => $n['orderId'], 'amount' => $n['amount'], 'currency' => $n['currency'], ]),]);if ($status === 200 && ($body['data']['status'] ?? null) === 'success') { markOrderPaid($order, $n['orderId']); // only now is the order paid}http_response_code(200);
07

Handle the customer coming back

urlReturn is only where the browser comes back to. Coming back is no proof of payment: the customer may return before the notification arrives, or return without paying. Show the order status from your database.

order.php
// order.php, the urlReturn addressif ($order->paid_at === null) { echo 'Waiting for payment confirmation from Przelewy24. Refresh the page in a moment.';} else { echo 'Payment received. Thank you!';}

How to check it works

We ran the class and the sign on PHP 8.3. The access test with a deliberately wrong key got 401 from the sandbox, and the sign for the sample data is a 96-character SHA-384 hash. Compute the same hash in your environment to check that your JSON encoding matches.

Environment
Przelewy24 sandbox, PHP 8.3
Result
401 for a deliberately wrong key and a 96-character SHA-384 sign

What you should see

  • testAccess returns 200 with your sandbox credentials.
  • Registration returns a token and /trnRequest/{token} opens the payment page.
  • After a test payment, JSON with a valid sign reaches urlStatus.
  • transaction/verify returns data.status "success" and the order changes state once.
php test.php, sandbox
Command
php test.php
Output
401 {"error":"Incorrect authentication","code":401}sign(order-1042, 11111, 12300, PLN, crc abcdef1234567890):462eb5152029424e64749fbd948ad8a5cf4b43e3b9efd61b759b02756066b16c62576451ee19c8ba376da1fca0a92139
  1. 2
    Access test with a deliberately wrong key

    The sandbox answered 401 "Incorrect authentication". With your sandbox credentials testAccess returns 200.

  2. 3
    The fields of the registration sign

    sessionId, merchantId, the amount in grosze, the currency and crc last, in this order.

  3. 4-5
    The SHA-384 sign

    96 hex characters over two lines. The same hash on your side means your JSON encoding matches.

Przelewy24 in Flaem

How it looks in our project

Hand the integration over when the store has refunds, split payments or several gateways at once. A Przelewy24 integration is part of our API and integrations service, from PLN 999, and covers registration, verification and refunds.

Flaem supports Przelewy24 as one of its payment gateways, in przelewy24.rs. We build the sign by hand, field by field, instead of from a map, because key order in a map is the library's decision, not ours.

For us a notification without verification is not a payment. We check the sign in constant time, and then whether the notification's merchantId and posId are ours, before anything reaches the ledger.

See the project
An order in the store panel with the history of its Przelewy24 payment events
the Przelewy24 integration in a store panel: the order history from registering the transaction through the notification to verification
przelewy24.rs
fn notification_sign(&self, body: &serde_json::Value) -> Option<String> { Some(Self::sign(&[ ("merchantId", SignValue::Int(body["merchantId"].as_i64()?)), ("posId", SignValue::Int(body["posId"].as_i64()?)), ("sessionId", SignValue::Str(body["sessionId"].as_str()?)), ("amount", SignValue::Int(body["amount"].as_i64()?)), ("originAmount", SignValue::Int(body["originAmount"].as_i64()?)), ("currency", SignValue::Str(body["currency"].as_str()?)), ("orderId", SignValue::Int(body["orderId"].as_i64()?)), ("methodId", SignValue::Int(body["methodId"].as_i64()?)), ("statement", SignValue::Str(body["statement"].as_str()?)), ("crc", SignValue::Str(&self.crc)), ]))}

Common errors

Symptom, cause and fix, with the number of the step where the error shows up.

StepSymptomCauseFix
02 401 "Incorrect authentication" A wrong posId or reports key, often a production key used on the sandbox. The sandbox has separate credentials. Check them with testAccess.
04 400 on register, invalid sign A different field order, no crc at the end, or JSON with escaped slashes or Polish characters. Keep the documented order and the JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES flags. In Python json.dumps adds spaces: use separators=(",", ":") and ensure_ascii=False.
06 The customer paid, but the money is not in the settlement transaction/verify was never called. Verify inside the notification handler. Without it the amount stays with the customer as a prepayment.
06 An order marked paid twice A resent notification handled as a new one. Mark the order conditionally, for example UPDATE ... WHERE paid_at IS NULL, and store the orderId.
05 The notification amount differs from the order The amount was given in zloty instead of grosze, or changed after registering. Keep amounts in grosze as integers and reject a notification with a different amount.

Frequently asked questions

The questions that come up with this setup.

How much does a Przelewy24 integration for a store or an app cost?
A Przelewy24 integration costs from PLN 999 and is part of our API and integrations service. The price depends on whether the store also needs refunds, split payments or several gateways at once.
Can I treat the payment as done when the customer returns to urlReturn?
No. A browser coming back proves nothing. Payment is decided by a notification with a valid sign and a successful verification.
How is the CRC key different from the reports key?
The reports key is the API password in Basic authentication. The CRC key is never sent: it only serves to compute the sign field on both sides.
How many times does Przelewy24 resend the notification?
After 3, 5, 15, 30, 60, 150 and 450 minutes, give or take 5 minutes, unless you verify the transaction earlier.
How do I make a refund?
With POST /api/v1/transaction/refund. The refund result arrives asynchronously as a separate notification to the urlStatus given in the refund request.
How do I move from the Przelewy24 sandbox to production?
Change the base address to https://secure.przelewy24.pl and use the production merchant ID, posId, reports key and CRC key from the production panel. The sandbox has separate credentials, so test keys return 401 on production.

Sources

The documentation and specifications we compared the commands with.

Other guides

  • KSeF API 2.0 step by stepThe KSeF token, an online session, encryption and the invoice's KSeF number, with Python code.
  • InPost ShipX APIA locker and a courier shipment, the PDF label and the status webhook from Node.js.

Glossary terms

Tell us what you want to build.

A free quote comes back within an hour during working hours. You talk to the person who writes the code.