From 230f1a972eba0aab801256c8f8a0b67c6e7dc50c Mon Sep 17 00:00:00 2001 From: Ahmed Elbanby Date: Fri, 4 Dec 2026 05:20:58 +0200 Subject: [PATCH] Add PayU driver (PayU Global, Europe) - PayUClient: OAuth2 client-credentials token as a form post, order create, refunds - PayUGateway: redirect checkout, MD5 second-key notification verification, refunds - Notifications: closed status set, algorithm refused rather than approximated - Config + PAYU_* env vars, 15 fixture tests - README EN + AR, CHANGELOG, composer metadata --- CHANGELOG.md | 1 + README.md | 35 +- composer.json | 7 +- config/tahseel.php | 23 ++ docs/ar/README.md | 35 +- src/Gateways/PayU/PayUClient.php | 123 ++++++ src/Gateways/PayU/PayUGateway.php | 354 ++++++++++++++++++ src/TahseelManager.php | 6 + tests/Feature/PayUGatewayTest.php | 195 ++++++++++ .../Fixtures/payu/notification-completed.json | 21 ++ tests/Fixtures/payu/order-created.json | 8 + tests/Fixtures/payu/refund-response.json | 8 + tests/Fixtures/payu/token.json | 6 + tests/TestCase.php | 14 + 14 files changed, 832 insertions(+), 4 deletions(-) create mode 100644 src/Gateways/PayU/PayUClient.php create mode 100644 src/Gateways/PayU/PayUGateway.php create mode 100644 tests/Feature/PayUGatewayTest.php create mode 100644 tests/Fixtures/payu/notification-completed.json create mode 100644 tests/Fixtures/payu/order-created.json create mode 100644 tests/Fixtures/payu/refund-response.json create mode 100644 tests/Fixtures/payu/token.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 7efa7de..a72d6af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to Tahseel are documented here. This project follows [Semant ### Added +- **PayU driver** (`Tahseel::gateway('payu')`), the sixteenth international driver, on the European PayU Global platform (secure.payu.com - explicitly not PayU India): OAuth2 client-credentials token as a form post to `/pl/standard/user/oauth/authorize`, `POST /api/v2_1/orders` with lowest-unit string amounts, the merchant reference as `extOrderId`, notify and continue urls, and the `redirectUri` returned as the checkout url; notifications verified as documented - MD5 of the raw body concatenated with the POS's second key, parsed out of `OpenPayu-Signature`, constant-time, a body without raw bytes refused, and an algorithm the docs do not show refused rather than approximated; the closed status set honoured (`COMPLETED` paid, `PENDING`/`WAITING_FOR_CONFIRMATION` pending, `CANCELED` failed, anything else refused); refunds through `POST /api/v2_1/orders/{orderId}/refunds` with the amount omitted for a full refund as documented, reporting pending unless PayU says the refund is final; config + `PAYU_*` env vars, and 15 fixture tests. Fixture-tested only, no live account has run it yet. - **Viva.com driver** (`Tahseel::gateway('viva')`), the fifteenth international driver (a Greek acquirer with a wide European footprint), on Smart Checkout: OAuth2 client-credentials token from the accounts host, `POST /checkout/v2/orders` on the API host with MINOR-unit amounts and the 4-digit payment source, the 16-digit order code kept as a string and turned into the documented `?ref={OrderCode}` checkout url; webhooks verified over the raw body - hex HMAC-SHA-256 in `Viva-Signature-256` with the documented SHA-1 `Viva-Signature` as fallback, constant-time, a body without raw bytes refused - reading only the documented events (1796, 1797, 1798, 4865) and requiring the event and the transaction's own `StatusId` to agree, with the closed status set honoured (`F` paid, `A`/`C` pending, `R` refunded, `E`/`X` failed, anything else refused) and the ISO numeric currency code mapped before Money; config + `VIVA_*` env vars, and 13 fixture tests. Refunds are not wrapped and there is no transaction re-read; the docs say both. Fixture-tested only, no live account has run it yet. - **Telr driver** (`Tahseel::gateway('telr')`), the fourteenth international driver and a Gulf acquirer (UAE, Saudi Arabia and the wider region), on the hosted payment page: `POST /gateway/order.json` with method `create`, store id and auth key in the body as documented, MAJOR-unit decimal-string amounts, the `order.ref` + `order.url` pair returned as the checkout url; transaction advice verified exactly as Telr documents it - SHA1 of the secret key followed by the fourteen transaction fields colon-joined in order, percent-encoded values decoded first, a missing field contributing an empty value, compared in constant time - with the documented status set honoured (`A` paid, `H` authorised-but-held pending, `D`/`C`/`E` failed, anything else refused); `fetchPaymentStatus()` through the documented `check` method with the status text matched and an unrecognised one refused; config + `TELR_*` env vars, and 16 fixture tests. Refunds are not wrapped and the docs say so. Fixture-tested only, no live account has run it yet. - **Xendit driver** (`Tahseel::gateway('xendit')`), the thirteenth international driver and the South-East Asia specialist (Indonesia, the Philippines, Malaysia, Thailand, Vietnam, Singapore), on Payment Sessions in `PAYMENT_LINK` mode rather than the legacy Invoice API: `POST /sessions` with Basic auth (secret key as username, empty password) and the documented `api-version` header, smallest-unit amounts, the hosted `payment_link_url` returned as the checkout url; webhooks authenticated the way Xendit documents them - the dashboard's token echoed verbatim in `x-callback-token`, compared in constant time, no HMAC - and only the documented `payment_session.completed` / `payment_session.expired` events read, with a completed event re-checked against the session's own status so a session that is not `COMPLETED` comes through pending, and the closed status set honoured with anything else refused; refunds through `POST /refunds` keyed by Xendit's `payment_id`, amount required, reason mapped to the documented enum (`REQUESTED_BY_CUSTOMER` unless a documented code is passed), `SUCCEEDED`/`PENDING`/`FAILED` mapped and pending refunds left to their own webhook; config + `XENDIT_*` env vars, and 16 fixture tests. No fetch-on-callback, stated plainly. Fixture-tested only, no live account has run it yet. diff --git a/README.md b/README.md index b3db353..bbfa96a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ A small, honest Laravel package for payment gateways, wherever they are. New here? Start with the [quickstart](docs/quickstart.md). -Tahseel gives you one clean API for starting a payment, verifying the gateway's callback, and getting a normalised result. Twenty-four drivers so far: **Paymob** (Intention API + Unified Checkout), **Kashier** (v3 payment sessions), **Fawry** (pay-at-outlet reference numbers), **Geidea** (checkout sessions on the hosted page), **MyFatoorah** (invoice payment links + signed webhook v2), **Tap** (hosted charges + `hashstring` webhooks), **HyperPay** (COPYandPAY widget + AES-256-GCM encrypted webhooks), **Checkout.com** (Hosted Payments Page + `Cko-Signature` webhooks), **PayPal** (Orders v2 + `verify-webhook-signature`), **Stripe** (Checkout Sessions + the documented `Stripe-Signature` HMAC), **Paystack** (hosted checkout for Nigeria, Ghana, South Africa and Kenya + two documented webhook schemes) **Moyasar** (Saudi cards, mada, Apple/Samsung Pay and STC Pay over one API + shared-token webhooks) **Razorpay** (hosted Payment Links for India + HMAC-SHA-256 everything), **Mercado Pago** (Checkout Pro hosted pages for Latin America + manifest-signed notifications) and **Mollie** (hosted checkout for Europe - iDEAL, Bancontact, SEPA, Klarna, cards and more + deliberately unsigned webhooks verified by fetch) and **Adyen** (hosted Checkout sessions for global enterprise + HMAC-signed Standard webhooks) **Flutterwave** (hosted checkout across Africa + `verif-hash` webhooks re-checked through the API) and **PayTabs** (hosted payment pages across the Gulf + raw-body `Signature` callbacks) **Klarna** (hosted payment pages for Europe and the US + one-time-token callbacks re-checked through the API, with the documented place-order step) **Square** (hosted payment links + notifications signed over the notification URL and raw body) **Xendit** (hosted Payment Sessions across South-East Asia + `x-callback-token` webhooks) **Telr** (hosted payment pages across the Gulf + SHA1-signed transaction advice) and **Viva.com** (Smart Checkout across Europe + HMAC-signed webhooks). Another, **manual**, covers what no wallet publishes an API for: a transfer to your Vodafone Cash number or InstaPay handle, confirmed by a human in a small approval panel. The Gulf drivers, PayPal, Stripe, Paystack, Moyasar, Razorpay, Mercado Pago, Mollie, Adyen, Flutterwave, PayTabs, Klarna, Square, Xendit, Telr and Viva.com are fixture-tested only, no live account has run them yet. +Tahseel gives you one clean API for starting a payment, verifying the gateway's callback, and getting a normalised result. Twenty-five drivers so far: **Paymob** (Intention API + Unified Checkout), **Kashier** (v3 payment sessions), **Fawry** (pay-at-outlet reference numbers), **Geidea** (checkout sessions on the hosted page), **MyFatoorah** (invoice payment links + signed webhook v2), **Tap** (hosted charges + `hashstring` webhooks), **HyperPay** (COPYandPAY widget + AES-256-GCM encrypted webhooks), **Checkout.com** (Hosted Payments Page + `Cko-Signature` webhooks), **PayPal** (Orders v2 + `verify-webhook-signature`), **Stripe** (Checkout Sessions + the documented `Stripe-Signature` HMAC), **Paystack** (hosted checkout for Nigeria, Ghana, South Africa and Kenya + two documented webhook schemes) **Moyasar** (Saudi cards, mada, Apple/Samsung Pay and STC Pay over one API + shared-token webhooks) **Razorpay** (hosted Payment Links for India + HMAC-SHA-256 everything), **Mercado Pago** (Checkout Pro hosted pages for Latin America + manifest-signed notifications) and **Mollie** (hosted checkout for Europe - iDEAL, Bancontact, SEPA, Klarna, cards and more + deliberately unsigned webhooks verified by fetch) and **Adyen** (hosted Checkout sessions for global enterprise + HMAC-signed Standard webhooks) **Flutterwave** (hosted checkout across Africa + `verif-hash` webhooks re-checked through the API) and **PayTabs** (hosted payment pages across the Gulf + raw-body `Signature` callbacks) **Klarna** (hosted payment pages for Europe and the US + one-time-token callbacks re-checked through the API, with the documented place-order step) **Square** (hosted payment links + notifications signed over the notification URL and raw body) **Xendit** (hosted Payment Sessions across South-East Asia + `x-callback-token` webhooks) **Telr** (hosted payment pages across the Gulf + SHA1-signed transaction advice) **Viva.com** (Smart Checkout across Europe + HMAC-signed webhooks) and **PayU** (the European PayU platform + MD5-signed notifications). Another, **manual**, covers what no wallet publishes an API for: a transfer to your Vodafone Cash number or InstaPay handle, confirmed by a human in a small approval panel. The Gulf drivers, PayPal, Stripe, Paystack, Moyasar, Razorpay, Mercado Pago, Mollie, Adyen, Flutterwave, PayTabs, Klarna, Square, Xendit, Telr, Viva.com and PayU are fixture-tested only, no live account has run them yet. > **Status: v0.3.0, EXPERIMENTAL pre-release. Do not take real money through it yet.** > @@ -47,6 +47,7 @@ Tahseel gives you one clean API for starting a payment, verifying the gateway's | **Xendit** | `Tahseel::gateway('xendit')` - Payment Session in `PAYMENT_LINK` mode (`POST /sessions`) | no HMAC: the dashboard's callback token comes back verbatim in `x-callback-token`, compared in constant time, and the documented session status set is closed, so an unknown status is refused rather than guessed | refund, amount required, addressed by Xendit's `payment_id`; `PENDING` until the refund webhook settles it | none: the callback token is the documented authentication | Indonesia, the Philippines, Malaysia, Thailand, Vietnam, Singapore; smallest-unit amounts; fixture-tested only, no live run yet | | **Telr** | `Tahseel::gateway('telr')` - hosted payment page (`POST /gateway/order.json`, method `create`) | SHA1 of the secret key followed by the documented transaction fields, colon-joined, in `tran_check`, constant-time; percent-encoded values decoded first, a missing field contributing an empty value, exactly as the docs say | not wrapped: Telr documents refunds on a different product surface, so the driver does not claim them | server-side `fetchPaymentStatus()` through the documented `check` method | UAE, Saudi Arabia and the wider Gulf; MAJOR-unit decimal strings; `H` (authorised, on hold) is pending, not paid; fixture-tested only, no live run yet | | **Viva.com** | `Tahseel::gateway('viva')` - Smart Checkout payment order (`POST /checkout/v2/orders`) | hex HMAC-SHA-256 of the raw body in `Viva-Signature-256`, with the documented SHA-1 `Viva-Signature` as a fallback, constant-time; the event id and the transaction's own `StatusId` have to agree or the notification is refused | not wrapped: Viva documents refunds on a separate product surface, so the driver does not claim them | none: Viva's docs say to confirm with `OrderCode` plus `TransactionId`, `StatusId` and `Amount`, which the driver checks | Europe (Viva.com is a Greek acquirer with a wide European footprint); MINOR units; `F` is finished, `A`/`C` are pending, `R` is refunded; fixture-tested only, no live run yet | +| **PayU** | `Tahseel::gateway('payu')` - PayU Global order + redirect (`POST /api/v2_1/orders`) | MD5 of the raw body concatenated with the POS's second key, in `OpenPayu-Signature`, constant-time; an algorithm the driver has not been grounded in is refused rather than approximated | full (no amount) or partial, lowest-currency-unit amount, addressed by PayU's order id; anything PayU does not spell out stays pending | none: the signed notification is the state | Europe (PayU Global, secure.payu.com - not PayU India); lowest-unit amounts as strings; PENDING and WAITING_FOR_CONFIRMATION are pending, only COMPLETED is paid; fixture-tested only, no live run yet | | **Manual** (Vodafone Cash, InstaPay) | `Tahseel::gateway('manual')` - a reference, a transfer to your wallet, a human decision | none: a human confirms in the panel | not applicable | not applicable | No merchant API to call; the panel stays closed until you name a Gate ability | | **Wallets, BNPL, Meeza, InstaPay** | through Paymob, Kashier or Geidea methods | - | - | - | None publishes a merchant API of its own; see [Wallets, BNPL, Meeza and InstaPay](#wallets-bnpl-meeza-and-instapay) | @@ -299,6 +300,7 @@ $result->succeeded(); // true, false, or false while pending | Klarna | full or partial, MINOR-unit amount required; synchronous against a captured order | not implemented | Klarna's own order id from `placeOrder()`, not your reference | | Square | full or partial, MINOR-unit amount required; `PENDING` until Square approves it | not implemented | the Square payment id | | Xendit | full or partial, smallest-unit amount required; `PENDING` until the refund webhook settles it | not implemented | Xendit's `payment_id`, which the session webhook carries | +| PayU | full (no amount, as documented) or partial, lowest-unit amount | not implemented | the PayU order id | The details that bite: @@ -934,6 +936,37 @@ Four Viva.com details worth knowing: Refunds are not wrapped: Viva documents them on a separate product surface that this driver has not been grounded in. Fixture-tested only, no Viva account has run it yet. +## PayU + +PayU is the sixteenth international driver, on the European platform at secure.payu.com. That is PayU Global, not PayU India, which is a different product with a different API: if you are on the Indian platform, this driver is not the one. + +```dotenv +PAYU_BASE_URL=https://secure.payu.com # sandbox: https://secure.snd.payu.com +PAYU_CLIENT_ID=... # from the POS in the management panel +PAYU_CLIENT_SECRET=... +PAYU_POS_ID=145227 +PAYU_SECOND_KEY=... # the POS's second key, which signs notifications +PAYU_NOTIFY_URL=https://your-app.test/tahseel/webhooks/payu +PAYU_CONTINUE_URL=https://your-app.test/checkout/done +PAYU_CUSTOMER_IP=127.0.0.1 +PAYU_LANGUAGE=en +``` + +```php +$session = Tahseel::gateway('payu')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +Four PayU details worth knowing: + +- **The token endpoint wants a form.** `POST /pl/standard/user/oauth/authorize` with `grant_type=client_credentials`, the client id and secret in the body, and the form content type: PayU's docs are explicit that without it the call is a 401. The driver fetches the token once per instance and reuses it. +- **Notifications are signed with the POS's second key.** `OpenPayu-Signature` carries `signature=;algorithm=MD5;content=DOCUMENT`, and the hash is MD5 of the raw body concatenated with that second key. The driver parses the header, compares in constant time, refuses a body whose raw bytes it cannot see, and refuses an algorithm it has not been grounded in rather than approximating one. +- **Only `COMPLETED` is money.** The documented statuses are `PENDING`, `WAITING_FOR_CONFIRMATION`, `COMPLETED` and `CANCELED`: the first two are pending, `CANCELED` fails, and anything else is refused. Your reference rides along as `extOrderId` and comes back in the notification. +- **Amounts are the lowest currency unit, as strings.** `"9500"` is 95.00 PLN. A refund omits the amount for a full refund and sends it for a partial one, exactly as PayU documents; when PayU's answer does not say the refund is final, the driver reports pending rather than claiming money has moved. + +Fixture-tested only, no PayU account has run it yet. + ## Manual payments: Vodafone Cash and InstaPay Vodafone Cash and InstaPay publish no merchant API, so the honest way to accept them is the way Egyptian shops already do it: the customer transfers to your wallet or InstaPay handle, quotes a reference, and you confirm the money arrived. Tahseel ships that as a driver named `manual`. diff --git a/composer.json b/composer.json index 382e152..0047ed1 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "elbanbydev/tahseel", - "description": "Tahseel (تحصيل) - a clean, framework-native Laravel package for payment gateways: Paymob, Kashier, Fawry, Geidea, MyFatoorah, Tap, HyperPay, Checkout.com, PayPal, Stripe, Paystack, Moyasar, Razorpay, Mercado Pago, Mollie, Adyen, Flutterwave, PayTabs, Klarna, Square, Xendit, Telr, Viva.com and manual transfers (Vodafone Cash, InstaPay) behind one gateway contract with signed webhook verification. Experimental.", + "description": "Tahseel (تحصيل) - a clean, framework-native Laravel package for payment gateways: Paymob, Kashier, Fawry, Geidea, MyFatoorah, Tap, HyperPay, Checkout.com, PayPal, Stripe, Paystack, Moyasar, Razorpay, Mercado Pago, Mollie, Adyen, Flutterwave, PayTabs, Klarna, Square, Xendit, Telr, Viva.com, PayU and manual transfers (Vodafone Cash, InstaPay) behind one gateway contract with signed webhook verification. Experimental.", "keywords": [ "laravel", "payments", @@ -65,7 +65,10 @@ "aed", "viva", "vivawallet", - "smart checkout" + "smart checkout", + "payu", + "poland", + "pln" ], "license": "MIT", "require": { diff --git a/config/tahseel.php b/config/tahseel.php index e701d96..ddc5a09 100644 --- a/config/tahseel.php +++ b/config/tahseel.php @@ -477,6 +477,29 @@ 'idempotency_ttl' => (int) env('PAYTABS_IDEMPOTENCY_TTL', 86400), ], + 'payu' => [ + // PayU Global (Europe): https://secure.payu.com. Sandbox: + // https://secure.snd.payu.com. + 'base_url' => env('PAYU_BASE_URL', 'https://secure.payu.com'), + + // From the POS in the management panel. + 'client_id' => env('PAYU_CLIENT_ID'), + 'client_secret' => env('PAYU_CLIENT_SECRET'), + 'pos_id' => env('PAYU_POS_ID'), + + // The POS's second key, which signs notifications. + 'second_key' => env('PAYU_SECOND_KEY'), + + 'notify_url' => env('PAYU_NOTIFY_URL'), + 'continue_url' => env('PAYU_CONTINUE_URL'), + 'customer_ip' => env('PAYU_CUSTOMER_IP', '127.0.0.1'), + 'language' => env('PAYU_LANGUAGE', 'en'), + 'currency' => env('PAYU_CURRENCY', 'PLN'), + + 'timeout' => (int) env('PAYU_TIMEOUT', 30), + 'idempotency_ttl' => (int) env('PAYU_IDEMPOTENCY_TTL', 86400), + ], + 'viva' => [ // Production: https://api.vivapayments.com. Demo: // https://demo-api.vivapayments.com. diff --git a/docs/ar/README.md b/docs/ar/README.md index 097c46a..864d82a 100644 --- a/docs/ar/README.md +++ b/docs/ar/README.md @@ -1,7 +1,7 @@ # تحصيل (Tahseel) باكدج Laravel صغير وواضح لبوابات الدفع، في مصر والخليج وأي مكان. **جديد هنا؟ ابدأ من [البداية السريعة](quickstart.md).** - فيه لحد دلوقتي أربعة وعشرين درايفر لبوابات: **Paymob** (Intention API مع Unified Checkout)، **Kashier** (Payment Sessions v3)، **فوري** (أرقام دفع من أي منفذ فوري)، **Geidea** (جلسات دفع على صفحتهم المستضافة)، **MyFatoorah** (روابط دفع الفواتير + webhook v2 موقّع)، **Tap** (صفحة دفع مستضافة + webhook بتوقيع `hashstring`)، **HyperPay** (ودجت COPYandPAY + webhook متشفّر AES-256-GCM)، **Checkout.com** (صفحة دفع مستضافة + webhook بتوقيع `Cko-Signature`)، **PayPal** (Orders v2 + تحقق `verify-webhook-signature`) و**Stripe** (Checkout Sessions + توقيع HMAC الموثّق في `Stripe-Signature`) و**Paystack** (صفحة دفع مستضافة لنيجيريا وغانا وجنوب أفريقيا وكينيا + نظامَي توقيع webhook موثّقين) و**Moyasar** (كروت سعودية ومدى وApple/Samsung Pay وSTC Pay على API واحد + webhooks بتوكن مشترك) و**Razorpay** (روابط دفع مستضافة للهند + HMAC-SHA-256 في كل حاجة) و**Mercado Pago** (صفحات Checkout Pro المستضافة لأمريكا اللاتينية + إشعارات موقّعة بالمانيفست) و**Mollie** (صفحة دفع مستضافة لأوروبا: iDEAL وBancontact وSEPA وKlarna وكروت وأكتر + webhooks مش موقّعة عمد، التحقق فيها بالجلب) و**Adyen** (جلسات Checkout مستضافة للشركات العالمية + webhooks قياسية موقّعة بـ HMAC) و**Flutterwave** (رابط دفع مستضاف في أفريقيا + webhooks بـ `verif-hash` بتتحقق تاني من الـ API) و**PayTabs** (صفحات دفع مستضافة في الخليج + webhooks بتوقيع على البودي الخام) **Klarna** (صفحات دفع مستضافة لأوروبا وأمريكا + callbacks بتوكن لمرة واحدة بتتحقق تاني من الـ API، مع خطوة تثبيت الأوردر الموثّقة) **Square** (روابط دفع مستضافة + إشعارات موقّعة على رابط الإشعار والبودي الخام) **Xendit** (جلسات دفع مستضافة في جنوب شرق آسيا + webhooks بتوكن `x-callback-token`) **Telr** (صفحات دفع مستضافة في الخليج + إشعارات موقّعة بـ SHA1) و**Viva.com** (Smart Checkout في أوروبا + webhooks موقّعة بـ HMAC). ودرايفر الأربعة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr وViva.com متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. + فيه لحد دلوقتي خمسة وعشرين درايفر لبوابات: **Paymob** (Intention API مع Unified Checkout)، **Kashier** (Payment Sessions v3)، **فوري** (أرقام دفع من أي منفذ فوري)، **Geidea** (جلسات دفع على صفحتهم المستضافة)، **MyFatoorah** (روابط دفع الفواتير + webhook v2 موقّع)، **Tap** (صفحة دفع مستضافة + webhook بتوقيع `hashstring`)، **HyperPay** (ودجت COPYandPAY + webhook متشفّر AES-256-GCM)، **Checkout.com** (صفحة دفع مستضافة + webhook بتوقيع `Cko-Signature`)، **PayPal** (Orders v2 + تحقق `verify-webhook-signature`) و**Stripe** (Checkout Sessions + توقيع HMAC الموثّق في `Stripe-Signature`) و**Paystack** (صفحة دفع مستضافة لنيجيريا وغانا وجنوب أفريقيا وكينيا + نظامَي توقيع webhook موثّقين) و**Moyasar** (كروت سعودية ومدى وApple/Samsung Pay وSTC Pay على API واحد + webhooks بتوكن مشترك) و**Razorpay** (روابط دفع مستضافة للهند + HMAC-SHA-256 في كل حاجة) و**Mercado Pago** (صفحات Checkout Pro المستضافة لأمريكا اللاتينية + إشعارات موقّعة بالمانيفست) و**Mollie** (صفحة دفع مستضافة لأوروبا: iDEAL وBancontact وSEPA وKlarna وكروت وأكتر + webhooks مش موقّعة عمد، التحقق فيها بالجلب) و**Adyen** (جلسات Checkout مستضافة للشركات العالمية + webhooks قياسية موقّعة بـ HMAC) و**Flutterwave** (رابط دفع مستضاف في أفريقيا + webhooks بـ `verif-hash` بتتحقق تاني من الـ API) و**PayTabs** (صفحات دفع مستضافة في الخليج + webhooks بتوقيع على البودي الخام) **Klarna** (صفحات دفع مستضافة لأوروبا وأمريكا + callbacks بتوكن لمرة واحدة بتتحقق تاني من الـ API، مع خطوة تثبيت الأوردر الموثّقة) **Square** (روابط دفع مستضافة + إشعارات موقّعة على رابط الإشعار والبودي الخام) **Xendit** (جلسات دفع مستضافة في جنوب شرق آسيا + webhooks بتوكن `x-callback-token`) **Telr** (صفحات دفع مستضافة في الخليج + إشعارات موقّعة بـ SHA1) **Viva.com** (Smart Checkout في أوروبا + webhooks موقّعة بـ HMAC) و**PayU** (منصة PayU الأوروبية + إشعارات موقّعة بـ MD5). ودرايفر الخمسة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr وViva.com وPayU متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. > **الحالة: 0.3.0، نسخة تجريبية (EXPERIMENTAL). ماتستلمش فلوس حقيقية بيها لسه.** > @@ -38,6 +38,7 @@ | **Xendit** | `Tahseel::gateway('xendit')` — جلسة دفع بوضع `PAYMENT_LINK` (`POST /sessions`) | مفيش HMAC: توكن الـ callback من الداشبورد بيرجع زي ما هو في هيدر `x-callback-token`، بيتقارن بزمن ثابت، ومجموعة حالات الجلسة الموثّقة مقفولة، فأي حالة برّاها بتترفض مش بتتخمّن | استرداد بمبلغ مطلوب، برقم `payment_id` بتاع Xendit؛ `PENDING` لحد ما webhook الاسترداد يحسمها | مفيش: توكن الـ callback هو التوثيق الموثّق | إندونيسيا والفلبين وماليزيا وتايلاند وفييتنام وسنغافورة؛ المبالغ بأصغر وحدة؛ متجرب على بيانات مسجلة بس لسه | | **Telr** | `Tahseel::gateway('telr')` — صفحة دفع مستضافة (`POST /gateway/order.json` بالطريقة `create`) | SHA1 على المفتاح السري وبعده حقول العملية الموثّقة، متوصّلة بنقطتين، في `tran_check`، مقارنة ثابتة الزمن؛ والقيم المرمّزة بتتفك قبل الحساب، والحقل الغايب بيساهم بقيمة فاضية، زي ما الوثائق بتقول بالحرف | مش ملفوف: Telr موثّقة الاسترداد على منتج تاني، فالدرايفر مابيدّعيهوش | تحقق من السيرفر بـ `fetchPaymentStatus()` عن طريق الطريقة الموثّقة `check` | الإمارات والسعودية والخليج؛ المبالغ بالوحدة الكبرى كنص عشري؛ و`H` (مفوّض ومعلّق) بترجع pending مش مدفوعة؛ متجرب على بيانات مسجلة بس لسه | | **Viva.com** | `Tahseel::gateway('viva')` — أمر دفع Smart Checkout (`POST /checkout/v2/orders`) | HMAC-SHA-256 بنظام hex على البودي الخام في `Viva-Signature-256`، و`Viva-Signature` بـ SHA-1 كبديل موثّق، مقارنة ثابتة الزمن؛ ومعرّف الحدث وحالة العملية `StatusId` لازم يتفقوا وإلا الإشعار بيترفض | مش ملفوف: Viva موثّقة الاسترداد على منتج منفصل، فالدرايفر مابيدّعيهوش | مفيش: وثائق Viva بتقول أكّد بـ `OrderCode` و`TransactionId` و`StatusId` و`Amount`، وده اللي الدرايفر بيتحقق منه | أوروبا (Viva.com مُحصّل يوناني بانتشار أوروبي واسع)؛ الوحدة الصغرى؛ `F` منتهية، `A`/`C` معلّقة، `R` مستردة؛ متجرب على بيانات مسجلة بس لسه | +| **PayU** | `Tahseel::gateway('payu')` — أمر PayU Global وتحويل (`POST /api/v2_1/orders`) | MD5 على البودي الخام متوصّل بالمفتاح التاني للـ POS، في `OpenPayu-Signature`، مقارنة ثابتة الزمن؛ وأي خوارزمية الدرايفر ماتأسّسش عليها بتترفض مش بتتخمّن | كامل (من غير مبلغ) أو جزئي، المبلغ بأصغر وحدة، برقم الأمر بتاع PayU؛ وأي حاجة PayU ماتقولهاش صريحة تفضل pending | مفيش: الإشعار الموقّع هو الحالة | أوروبا (PayU Global على secure.payu.com — مش PayU India)؛ المبالغ بأصغر وحدة كنصوص؛ `PENDING` و`WAITING_FOR_CONFIRMATION` معلّقة، وبس `COMPLETED` مدفوعة؛ متجرب على بيانات مسجلة بس لسه | | **يدوي** (فودافون كاش، إنستاباي) | `Tahseel::gateway('manual')` — مرجع، تحويل على محفظتك، وقرار من حد من فريقك | مفيش: التأكيد من اللوحة | مش منطبق | مش منطبق | مفيش API تجار تكلّمه؛ واللوحة مقفولة لحد ما تحدد Gate ability | | **محافظ وتقسيط وميزة وإنستاباي** | عن طريق وسائل Paymob أو Kashier أو Geidea | - | - | - | مفيش API تجار معلن لأي منهم، شوف القسم تحت | @@ -256,6 +257,7 @@ $result->succeeded(); | Klarna | كامل أو جزئي، المبلغ بالوحدة الصغرى ومطلوب؛ فوري على أوردر متحصّل | مش مدعوم | رقم الأوردر بتاع Klarna من `placeOrder()`، مش مرجعك | | Square | كامل أو جزئي، المبلغ بالوحدة الصغرى ومطلوب؛ `PENDING` لحد ما Square توافق | مش مدعوم | رقم الدفع بتاع Square | | Xendit | كامل أو جزئي، المبلغ بأصغر وحدة ومطلوب؛ `PENDING` لحد ما webhook الاسترداد يحسمها | مش مدعوم | رقم `payment_id` بتاع Xendit اللي webhook الجلسة بيجيبه | +| PayU | كامل (من غير مبلغ، زي ما موثّق) أو جزئي، المبلغ بأصغر وحدة | مش مدعوم | رقم الأمر بتاع PayU | التفاصيل اللي بتوجع: @@ -887,6 +889,37 @@ header('Location: '.$session->checkoutUrl); الاسترداد مش ملفوف: Viva موثّقة على منتج منفصل والدرايفر ماتأسّسش عليه. متجرب على بيانات مسجلة بس، مفيش حساب Viva حقيقي شغّال لسه. +## PayU + +PayU هو الداريفر الدولي السادس عشر، على المنصة الأوروبية secure.payu.com. ده PayU Global مش PayU India، اللي منتج تاني و API تاني: لو انت على المنصة الهندية، الداريفر ده مش بتاعك. + +```dotenv +PAYU_BASE_URL=https://secure.payu.com # ساندبوكس: https://secure.snd.payu.com +PAYU_CLIENT_ID=... # من الـ POS في لوحة الإدارة +PAYU_CLIENT_SECRET=... +PAYU_POS_ID=145227 +PAYU_SECOND_KEY=... # المفتاح التاني للـ POS اللي بيوقّع الإشعارات +PAYU_NOTIFY_URL=https://your-app.test/tahseel/webhooks/payu +PAYU_CONTINUE_URL=https://your-app.test/checkout/done +PAYU_CUSTOMER_IP=127.0.0.1 +PAYU_LANGUAGE=en +``` + +```php +$session = Tahseel::gateway('payu')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +أربع تفاصيل مهمة في PayU: + +- **التوكن محتاج فورم.** `POST /pl/standard/user/oauth/authorize` بـ `grant_type=client_credentials`، والـ client id والسيكرت في البودي، ومعاهم نوع المحتوى form: وثائق PayU صريحة إنه من غيرهم النداء بيرجع 401. الدرايفر بيجيب التوكن مرة لكل نسخة وبيعيد استخدامه. +- **الإشعارات موقّعة بالمفتاح التاني للـ POS.** هيدر `OpenPayu-Signature` بيحمل `signature=;algorithm=MD5;content=DOCUMENT`، والتوقيع MD5 على البودي الخام متوصّل بالمفتاح التاني ده. الدرايفر بيقرا الهيدر، بيقارن بزمن ثابت، بيرفض أي بودي مش شايف بايتاته الخام، وبيرفض أي خوارزمية ماتأسّسش عليها بدل ما يقرّبها. +- **بس `COMPLETED` فلوس.** الحالات الموثّقة `PENDING` و`WAITING_FOR_CONFIRMATION` و`COMPLETED` و`CANCELED`: الاتنين الأولانيين معلّقة، و`CANCELED` فشل، وأي حاجة تانية بتترفض. ومرجعك بيمشي كـ `extOrderId` ويرجع في الإشعار. +- **المبالغ بأصغر وحدة في العملة كنصوص.** `"9500"` يعني 95.00 زلوتي. والاسترداد بيسيب المبلغ برّه للاسترداد الكامل وبيبعته للجزئي، زي ما PayU موثّقة بالحرف؛ ولما رد PayU مايقولش إن الاسترداد نهائي، الدرايفر بيرجّع pending بدل ما يدّعي إن فلوس اتحركت. + +متجرب على بيانات مسجلة بس، مفيش حساب PayU حقيقي شغّال لسه. + ## الدفع اليدوي: فودافون كاش وإنستاباي فودافون كاش وإنستاباي مفيش لهم API تجار، فالطريقة الصادقة لقبولهم هي الطريقة اللي المحلات المصرية بتعملها فعلاً: العميل يحوّل على محفظتك أو عنوان إنستاباي بتاعك، يقولك رقم العملية أو يرفع صورة التحويل، وحد من فريقك يأكد إن الفلوس وصلت. الباكدج بيوفّر ده كدرايفر اسمه `manual`. diff --git a/src/Gateways/PayU/PayUClient.php b/src/Gateways/PayU/PayUClient.php new file mode 100644 index 0000000..97eafaa --- /dev/null +++ b/src/Gateways/PayU/PayUClient.php @@ -0,0 +1,123 @@ +token) && $this->token !== '') { + return $this->token; + } + + $response = $this->transport('payu', 'token', fn (): Response => Http::asForm() + ->acceptJson() + ->timeout($this->timeout) + ->post($this->url('pl/standard/user/oauth/authorize'), [ + 'grant_type' => 'client_credentials', + 'client_id' => $this->clientId, + 'client_secret' => $this->clientSecret, + ])); + + $body = $this->unwrap('token', $response); + $token = $body['access_token'] ?? null; + + if (! is_string($token) || $token === '') { + throw GatewayException::invalidResponse('payu', 'token'); + } + + return $token; + } + + /** + * POST /api/v2_1/orders - the order the buyer is sent to pay. + * + * @param array $payload + * @return array + */ + public function createOrder(array $payload): array + { + $response = $this->transport('payu', 'create order', fn (): Response => $this->request()->post($this->url('api/v2_1/orders'), $payload)); + + return $this->unwrap('create order', $response); + } + + /** + * POST /api/v2_1/orders/{orderId}/refunds - an omitted amount is a full + * refund, as PayU documents. + * + * @param array $payload + * @return array + */ + public function refund(string $orderId, array $payload): array + { + $response = $this->transport('payu', 'refund', fn (): Response => $this->request()->post($this->url('api/v2_1/orders/'.rawurlencode($orderId).'/refunds'), $payload)); + + return $this->unwrap('refund', $response); + } + + private function request(): PendingRequest + { + return Http::withToken($this->token()) + ->acceptJson() + ->timeout($this->timeout); + } + + /** + * @return array + */ + private function unwrap(string $operation, Response $response): array + { + if ($response->failed()) { + throw GatewayException::fromResponse('payu', $operation, $response->status(), $response->json()); + } + + $body = $response->json(); + + if (! is_array($body)) { + throw GatewayException::invalidResponse('payu', $operation); + } + + return $body; + } + + private function url(string $path): string + { + return rtrim($this->baseUrl, '/').'/'.ltrim($path, '/'); + } +} diff --git a/src/Gateways/PayU/PayUGateway.php b/src/Gateways/PayU/PayUGateway.php new file mode 100644 index 0000000..52a97fc --- /dev/null +++ b/src/Gateways/PayU/PayUGateway.php @@ -0,0 +1,354 @@ + PaymentStatus::Succeeded, + 'PENDING' => PaymentStatus::Pending, + 'WAITING_FOR_CONFIRMATION' => PaymentStatus::Pending, + 'CANCELED' => PaymentStatus::Failed, + ]; + + /** + * The refund states PayU answers with, when it answers with one. + */ + private const REFUND_STATES = [ + 'SUCCESS' => PaymentStatus::Refunded, + 'FINAL' => PaymentStatus::Refunded, + 'COMPLETED' => PaymentStatus::Refunded, + 'PENDING' => PaymentStatus::Pending, + 'NEW' => PaymentStatus::Pending, + 'IN_PROGRESS' => PaymentStatus::Pending, + 'CANCELED' => PaymentStatus::Failed, + 'REJECTED' => PaymentStatus::Failed, + 'DECLINED' => PaymentStatus::Failed, + ]; + + /** + * @param array $config + */ + public function __construct( + private readonly array $config, + private readonly ?IdempotencyStore $idempotency = null, + private readonly ?PayUClient $client = null, + ) {} + + public function name(): string + { + return self::NAME; + } + + public function createPayment(PaymentRequest $request): PaymentSession + { + $this->assertConfigured(['client_id', 'client_secret', 'pos_id']); + + return IdempotentCreation::run( + $this->idempotency, + $request->idempotencyKey, + $this->integer('idempotency_ttl', 86400), + function () use ($request): PaymentSession { + $amount = (string) $request->amount->toMinor(); + + $payload = [ + 'customerIp' => (string) ($this->string('customer_ip') ?? '127.0.0.1'), + 'merchantPosId' => (string) $this->string('pos_id'), + 'description' => mb_substr($request->description ?? $request->reference, 0, 255), + 'currencyCode' => $request->amount->currency, + 'totalAmount' => $amount, + // PayU's own field for the merchant's reference. + 'extOrderId' => $request->reference, + 'products' => [[ + 'name' => mb_substr($request->description ?? $request->reference, 0, 255), + 'unitPrice' => $amount, + 'quantity' => '1', + ]], + 'buyer' => [ + 'email' => (string) ($request->customer->email ?? ''), + 'firstName' => $request->customer->firstName, + 'lastName' => $request->customer->lastName, + 'phone' => $request->customer->phone, + 'language' => (string) ($this->string('language') ?? 'en'), + ], + ]; + + $notify = $request->notificationUrl ?? $this->string('notify_url'); + + if ($notify !== null) { + $payload['notifyUrl'] = $notify; + } + + $continue = $request->redirectionUrl ?? $this->string('continue_url'); + + if ($continue !== null) { + $payload['continueUrl'] = $continue; + } + + $body = $this->client()->createOrder($payload); + + $redirect = $body['redirectUri'] ?? null; + $orderId = $body['orderId'] ?? null; + + if (! is_string($redirect) || $redirect === '' || ! is_scalar($orderId) || (string) $orderId === '') { + throw GatewayException::invalidResponse(self::NAME, 'create order'); + } + + return new PaymentSession( + gateway: self::NAME, + reference: $request->reference, + intentionId: (string) $orderId, + orderId: $request->reference, + checkoutUrl: $redirect, + raw: $body, + ); + }, + ); + } + + public function refund(RefundRequest $request): OperationResult + { + $this->assertConfigured(['client_id', 'client_secret']); + + // PayU addresses a refund by its own order id, which createPayment() + // returns as the intention id and the notification carries. + $orderId = $request->orderId ?? $request->transactionId; + + if ($orderId === null || trim($orderId) === '') { + throw new InvalidPaymentRequestException('A PayU refund needs the PayU order id the order carried.'); + } + + $refund = ['description' => $request->reason !== null && trim($request->reason) !== '' + ? mb_substr(trim($request->reason), 0, 255) + : 'Refund']; + + // An omitted amount is a full refund, as PayU documents. + if ($request->amount !== null) { + $refund['amount'] = (string) $request->amount->toMinor(); + } + + $body = $this->client()->refund(trim($orderId), ['refund' => $refund]); + $state = is_array($body['refund'] ?? null) ? ($body['refund']['status'] ?? null) : null; + + return new OperationResult( + gateway: self::NAME, + operation: 'refund', + // PayU does not promise the refund is final when it answers, so + // anything it does not spell out stays pending rather than + // claiming money has moved. + status: is_string($state) ? (self::REFUND_STATES[strtoupper(trim($state))] ?? PaymentStatus::Pending) : PaymentStatus::Pending, + transactionId: is_scalar($body['refund']['refundId'] ?? null) ? (string) $body['refund']['refundId'] : trim($orderId), + orderId: trim($orderId), + amount: $request->amount, + raw: $body, + ); + } + + /** + * PayU signs a notification as MD5 of the raw body plus the POS's second + * key, in `OpenPayu-Signature: sender=...;signature=...;algorithm=MD5; + * content=DOCUMENT`. + * + * @param array $payload + * @param array $query + * @param array $headers + */ + public function verifyAndParseWebhook(array $payload, array $query = [], array $headers = []): WebhookEvent + { + $secondKey = $this->string('second_key'); + + if ($secondKey === null) { + throw ConfigurationException::missing(self::NAME, ['tahseel.drivers.payu.second_key']); + } + + $raw = $payload['_raw'] ?? null; + + if (! is_string($raw) || $raw === '') { + throw InvalidWebhookException::unsupportedType(self::NAME, 'raw body'); + } + + $header = $this->header($headers, 'openpayu-signature'); + + if ($header === null || $header === '') { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $parts = []; + + foreach (explode(';', $header) as $pair) { + $bits = explode('=', $pair, 2); + + if (count($bits) === 2) { + $parts[strtolower(trim($bits[0]))] = trim($bits[1]); + } + } + + $signature = $parts['signature'] ?? null; + $algorithm = strtoupper($parts['algorithm'] ?? 'MD5'); + + if ($signature === null || $signature === '') { + throw InvalidSignatureException::forGateway(self::NAME); + } + + if ($algorithm !== 'MD5') { + // Only the documented MD5 scheme is implemented; guessing at a + // hash the docs do not show would be worse than refusing. + throw InvalidWebhookException::unsupportedType(self::NAME, 'signature algorithm ['.$algorithm.']'); + } + + if (! hash_equals(md5($raw.$secondKey), strtolower($signature))) { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $order = is_array($payload['order'] ?? null) ? $payload['order'] : []; + $status = $this->status($order['status'] ?? null); + + return new WebhookEvent( + gateway: self::NAME, + status: $status, + transactionId: is_scalar($order['orderId'] ?? null) ? (string) $order['orderId'] : '', + orderId: is_string($order['extOrderId'] ?? null) ? $order['extOrderId'] : null, + reference: is_string($order['extOrderId'] ?? null) ? $order['extOrderId'] : null, + amount: $this->money($order['totalAmount'] ?? null, $order['currencyCode'] ?? null) + ?? Money::minor(0, (string) ($this->string('currency') ?? 'PLN')), + success: $status === PaymentStatus::Succeeded, + pending: $status === PaymentStatus::Pending, + refunded: false, + voided: false, + createdAt: is_string($order['orderCreateDate'] ?? null) ? $order['orderCreateDate'] : null, + raw: $order, + ); + } + + private function status(mixed $status): PaymentStatus + { + $code = strtoupper(trim((string) $status)); + + if ($code === '') { + throw GatewayException::invalidResponse(self::NAME, 'webhook'); + } + + return self::STATUSES[$code] ?? throw InvalidWebhookException::unsupportedType(self::NAME, 'order status ['.$code.']'); + } + + private function money(mixed $amount, mixed $currency): ?Money + { + if (! is_int($amount) && ! (is_string($amount) && ctype_digit($amount))) { + return null; + } + + if (! is_string($currency) || $currency === '') { + return null; + } + + return Money::minor((int) $amount, strtoupper($currency)); + } + + /** + * @param array $headers + */ + private function header(array $headers, string $name): ?string + { + foreach ($headers as $key => $value) { + if (strtolower((string) $key) !== $name) { + continue; + } + + if (is_array($value)) { + $value = $value[0] ?? null; + } + + return is_scalar($value) ? (string) $value : null; + } + + return null; + } + + private function client(): PayUClient + { + if ($this->client instanceof PayUClient) { + return $this->client; + } + + return new PayUClient( + $this->string('base_url') ?? 'https://secure.payu.com', + (string) $this->string('client_id'), + (string) $this->string('client_secret'), + $this->integer('timeout', 30), + ); + } + + /** + * @param list $required + */ + private function assertConfigured(array $required): void + { + $missing = []; + + foreach ($required as $key) { + if ($this->string($key) === null) { + $missing[] = 'tahseel.drivers.payu.'.$key; + } + } + + if ($missing !== []) { + throw ConfigurationException::missing(self::NAME, $missing); + } + } + + private function string(string $key): ?string + { + $value = $this->config[$key] ?? null; + + if (! is_string($value) || trim($value) === '') { + return null; + } + + return trim($value); + } + + private function integer(string $key, int $default): int + { + $value = $this->config[$key] ?? null; + + return is_numeric($value) ? (int) $value : $default; + } +} diff --git a/src/TahseelManager.php b/src/TahseelManager.php index dd672fe..629c279 100644 --- a/src/TahseelManager.php +++ b/src/TahseelManager.php @@ -36,6 +36,7 @@ use Tahseel\Gateways\PayPal\PayPalGateway; use Tahseel\Gateways\Paystack\PaystackGateway; use Tahseel\Gateways\PayTabs\PayTabsGateway; +use Tahseel\Gateways\PayU\PayUGateway; use Tahseel\Gateways\Razorpay\RazorpayGateway; use Tahseel\Gateways\Square\SquareGateway; use Tahseel\Gateways\Stripe\StripeGateway; @@ -212,6 +213,11 @@ protected function createAdyenDriver(): Gateway return new AdyenGateway($this->configuration(AdyenGateway::NAME), $this->idempotencyStore()); } + protected function createPayuDriver(): Gateway + { + return new PayUGateway($this->configuration(PayUGateway::NAME), $this->idempotencyStore()); + } + protected function createVivaDriver(): Gateway { return new VivaGateway($this->configuration(VivaGateway::NAME), $this->idempotencyStore()); diff --git a/tests/Feature/PayUGatewayTest.php b/tests/Feature/PayUGatewayTest.php new file mode 100644 index 0000000..81007b7 --- /dev/null +++ b/tests/Feature/PayUGatewayTest.php @@ -0,0 +1,195 @@ + $payload + * @return array{0: array, 1: array>} + */ +function payuSigned(array $payload): array +{ + $raw = json_encode($payload, JSON_UNESCAPED_SLASHES); + $signature = md5($raw.'payu-second-key'); + + return [ + $payload + ['_raw' => $raw], + ['OpenPayu-Signature' => ['sender=checkout;signature='.$signature.';algorithm=MD5;content=DOCUMENT']], + ]; +} + +it('resolves the payu driver by name', function () { + expect(Tahseel::gateway('payu'))->toBeInstanceOf(PayUGateway::class) + ->and(Tahseel::gateway('payu')->name())->toBe('payu'); +}); + +it('gets a token and creates an order the buyer is redirected to', function () { + Http::fake([ + 'secure.payu.com/pl/standard/user/oauth/authorize' => Http::response($this->fixture('payu/token.json'), 200), + 'secure.payu.com/api/v2_1/orders' => Http::response($this->fixture('payu/order-created.json'), 200), + ]); + + $session = Tahseel::gateway('payu')->createPayment(payuRequest()); + + expect($session->gateway)->toBe('payu') + ->and($session->intentionId)->toBe('LDLW5N7MF4140324GUEST000P01') + ->and($session->checkoutUrl)->toContain('https://secure.payu.com/pay/?orderId='); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://secure.payu.com/pl/standard/user/oauth/authorize' + && $request['grant_type'] === 'client_credentials' + && $request['client_id'] === '460718'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://secure.payu.com/api/v2_1/orders' + && $request->hasHeader('Authorization', 'Bearer 3e5cac39-7e38-4139-8fd6-30adc06a61bd') + && $request['merchantPosId'] === '145227' + && $request['totalAmount'] === '9500' + && $request['currencyCode'] === 'PLN' + && $request['extOrderId'] === 'ORDER-6112' + && $request['notifyUrl'] === 'https://example.test/tahseel/webhooks/payu' + && $request['continueUrl'] === 'https://example.test/checkout/done' + && $request['buyer']['email'] === 'ahmed@example.com' + && $request['products'][0]['unitPrice'] === '9500'); +}); + +it('demands the point of sale id', function () { + config()->set('tahseel.drivers.payu.pos_id', null); + + Tahseel::gateway('payu')->createPayment(payuRequest()); +})->throws(ConfigurationException::class); + +it('verifies a signed notification and reads it as paid', function () { + [$payload, $headers] = payuSigned($this->fixture('payu/notification-completed.json')); + + $event = Tahseel::gateway('payu')->verifyAndParseWebhook($payload, [], $headers); + + expect($event->gateway)->toBe('payu') + ->and($event->status)->toBe(PaymentStatus::Succeeded) + ->and($event->success)->toBeTrue() + ->and($event->transactionId)->toBe('LDLW5N7MF4140324GUEST000P01') + ->and($event->reference)->toBe('ORDER-6112') + ->and($event->amount?->toMinor())->toBe(9500) + ->and($event->amount?->currency)->toBe('PLN'); +}); + +it('rejects a notification with the wrong signature', function () { + [$payload] = payuSigned($this->fixture('payu/notification-completed.json')); + + expect(fn () => Tahseel::gateway('payu')->verifyAndParseWebhook($payload, [], ['OpenPayu-Signature' => ['sender=checkout;signature=deadbeef;algorithm=MD5;content=DOCUMENT']])) + ->toThrow(InvalidSignatureException::class); +}); + +it('rejects a notification with no signature header', function () { + [$payload] = payuSigned($this->fixture('payu/notification-completed.json')); + + expect(fn () => Tahseel::gateway('payu')->verifyAndParseWebhook($payload)) + ->toThrow(InvalidSignatureException::class); +}); + +it('refuses a body it cannot see the raw bytes of', function () { + expect(fn () => Tahseel::gateway('payu')->verifyAndParseWebhook($this->fixture('payu/notification-completed.json'), [], ['OpenPayu-Signature' => ['sender=checkout;signature=x;algorithm=MD5;content=DOCUMENT']])) + ->toThrow(InvalidWebhookException::class); +}); + +it('refuses a signature algorithm it has not been grounded in', function () { + [$payload] = payuSigned($this->fixture('payu/notification-completed.json')); + + Tahseel::gateway('payu')->verifyAndParseWebhook($payload, [], ['OpenPayu-Signature' => ['sender=checkout;signature=abc;algorithm=SHA-256;content=DOCUMENT']]); +})->throws(InvalidWebhookException::class); + +it('maps a canceled order to failed', function () { + $notification = $this->fixture('payu/notification-completed.json'); + $notification['order']['status'] = 'CANCELED'; + + [$payload, $headers] = payuSigned($notification); + + expect(Tahseel::gateway('payu')->verifyAndParseWebhook($payload, [], $headers)->status)->toBe(PaymentStatus::Failed); +}); + +it('reports a waiting order as pending', function () { + $notification = $this->fixture('payu/notification-completed.json'); + $notification['order']['status'] = 'WAITING_FOR_CONFIRMATION'; + + [$payload, $headers] = payuSigned($notification); + + $event = Tahseel::gateway('payu')->verifyAndParseWebhook($payload, [], $headers); + + expect($event->status)->toBe(PaymentStatus::Pending) + ->and($event->pending)->toBeTrue(); +}); + +it('refuses an order status outside the documented set', function () { + $notification = $this->fixture('payu/notification-completed.json'); + $notification['order']['status'] = 'SETTLED'; + + [$payload, $headers] = payuSigned($notification); + + Tahseel::gateway('payu')->verifyAndParseWebhook($payload, [], $headers); +})->throws(InvalidWebhookException::class); + +it('refunds an order in the lowest currency unit', function () { + Http::fake([ + 'secure.payu.com/pl/standard/user/oauth/authorize' => Http::response($this->fixture('payu/token.json'), 200), + 'secure.payu.com/api/v2_1/orders/*/refunds' => Http::response($this->fixture('payu/refund-response.json'), 200), + ]); + + $result = Tahseel::gateway('payu')->refund(new RefundRequest( + orderId: 'LDLW5N7MF4140324GUEST000P01', + amount: Money::minor(9500, 'PLN'), + reason: 'Returned the shoes', + )); + + expect($result->status)->toBe(PaymentStatus::Refunded) + ->and($result->orderId)->toBe('LDLW5N7MF4140324GUEST000P01'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://secure.payu.com/api/v2_1/orders/LDLW5N7MF4140324GUEST000P01/refunds' + && $request['refund']['amount'] === '9500' + && $request['refund']['description'] === 'Returned the shoes'); +}); + +it('sends no amount for a full refund, as PayU documents', function () { + Http::fake([ + 'secure.payu.com/pl/standard/user/oauth/authorize' => Http::response($this->fixture('payu/token.json'), 200), + 'secure.payu.com/api/v2_1/orders/*/refunds' => Http::response($this->fixture('payu/refund-response.json'), 200), + ]); + + Tahseel::gateway('payu')->refund(new RefundRequest(orderId: 'LDLW5N7MF4140324GUEST000P01')); + + Http::assertSent(fn (Request $request): bool => ! isset($request['refund']['amount'])); +}); + +it('demands the payu order id for a refund', function () { + Tahseel::gateway('payu')->refund(new RefundRequest(orderId: ' ', amount: Money::minor(1, 'PLN'))); +})->throws(InvalidPaymentRequestException::class); + +it('surfaces a payu error instead of inventing an order', function () { + Http::fake([ + 'secure.payu.com/pl/standard/user/oauth/authorize' => Http::response($this->fixture('payu/token.json'), 200), + 'secure.payu.com/api/v2_1/orders' => Http::response(['status' => ['statusCode' => 'ERROR_VALUE_INVALID']], 400), + ]); + + Tahseel::gateway('payu')->createPayment(payuRequest()); +})->throws(GatewayException::class); diff --git a/tests/Fixtures/payu/notification-completed.json b/tests/Fixtures/payu/notification-completed.json new file mode 100644 index 0000000..45384e6 --- /dev/null +++ b/tests/Fixtures/payu/notification-completed.json @@ -0,0 +1,21 @@ +{ + "order": { + "orderId": "LDLW5N7MF4140324GUEST000P01", + "extOrderId": "ORDER-6112", + "orderCreateDate": "2026-12-04T12:00:00", + "notifyUrl": "https://example.test/tahseel/webhooks/payu", + "customerIp": "127.0.0.1", + "merchantPosId": "145227", + "description": "Order ORDER-6112", + "currencyCode": "PLN", + "totalAmount": "9500", + "status": "COMPLETED" + }, + "localReceiptDateTime": "2026-12-04T12:58:14.828+01:00", + "properties": [ + { + "name": "PAYMENT_ID", + "value": "151471228" + } + ] +} diff --git a/tests/Fixtures/payu/order-created.json b/tests/Fixtures/payu/order-created.json new file mode 100644 index 0000000..1ccb4be --- /dev/null +++ b/tests/Fixtures/payu/order-created.json @@ -0,0 +1,8 @@ +{ + "status": { + "statusCode": "SUCCESS" + }, + "redirectUri": "https://secure.payu.com/pay/?orderId=LDLW5N7MF4140324GUEST000P01&token=abc", + "orderId": "LDLW5N7MF4140324GUEST000P01", + "extOrderId": "ORDER-6112" +} diff --git a/tests/Fixtures/payu/refund-response.json b/tests/Fixtures/payu/refund-response.json new file mode 100644 index 0000000..ae4f683 --- /dev/null +++ b/tests/Fixtures/payu/refund-response.json @@ -0,0 +1,8 @@ +{ + "refund": { + "refundId": "1000027649", + "status": "SUCCESS", + "amount": "9500", + "currencyCode": "PLN" + } +} diff --git a/tests/Fixtures/payu/token.json b/tests/Fixtures/payu/token.json new file mode 100644 index 0000000..65cbd7c --- /dev/null +++ b/tests/Fixtures/payu/token.json @@ -0,0 +1,6 @@ +{ + "access_token": "3e5cac39-7e38-4139-8fd6-30adc06a61bd", + "token_type": "bearer", + "expires_in": 43199, + "grant_type": "client_credentials" +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 6d310b9..6d17e83 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -221,6 +221,20 @@ protected function defineEnvironment($app): void 'timeout' => 10, ]); + $app['config']->set('tahseel.drivers.payu', [ + 'base_url' => 'https://secure.payu.com', + 'client_id' => '460718', + 'client_secret' => '22f4175da9f0f72bcce976dd8bd7504f', + 'pos_id' => '145227', + 'second_key' => 'payu-second-key', + 'notify_url' => 'https://example.test/tahseel/webhooks/payu', + 'continue_url' => 'https://example.test/checkout/done', + 'customer_ip' => '127.0.0.1', + 'language' => 'en', + 'currency' => 'PLN', + 'timeout' => 10, + ]); + $app['config']->set('tahseel.drivers.viva', [ 'base_url' => 'https://api.vivapayments.com', 'accounts_url' => 'https://accounts.vivapayments.com',