From 7c54f7046b5f60fe62f3c8902d2a396694997bc3 Mon Sep 17 00:00:00 2001 From: Ahmed Elbanby Date: Fri, 4 Dec 2026 05:23:42 +0200 Subject: [PATCH] Add Tabby driver (BNPL, UAE and Saudi Arabia) - TabbyClient: checkout session, payment retrieve, capture, refunds, region-pinned base URL - TabbyGateway: hosted checkout redirect, header-authenticated webhooks, capture, refunds - AUTHORIZED reported pending, only captured CLOSED payments paid - Config + TABBY_* env vars, 14 fixture tests - README EN + AR, CHANGELOG, composer metadata --- CHANGELOG.md | 1 + README.md | 34 +- composer.json | 5 +- config/tahseel.php | 36 ++ docs/ar/README.md | 34 +- src/Gateways/Tabby/TabbyClient.php | 106 ++++ src/Gateways/Tabby/TabbyGateway.php | 494 +++++++++++++++++++ src/TahseelManager.php | 6 + tests/Feature/TabbyGatewayTest.php | 169 +++++++ tests/Fixtures/tabby/capture-response.json | 12 + tests/Fixtures/tabby/refund-response.json | 12 + tests/Fixtures/tabby/session-created.json | 23 + tests/Fixtures/tabby/session-rejected.json | 9 + tests/Fixtures/tabby/webhook-authorized.json | 12 + tests/Fixtures/tabby/webhook-closed.json | 17 + tests/TestCase.php | 20 + 16 files changed, 986 insertions(+), 4 deletions(-) create mode 100644 src/Gateways/Tabby/TabbyClient.php create mode 100644 src/Gateways/Tabby/TabbyGateway.php create mode 100644 tests/Feature/TabbyGatewayTest.php create mode 100644 tests/Fixtures/tabby/capture-response.json create mode 100644 tests/Fixtures/tabby/refund-response.json create mode 100644 tests/Fixtures/tabby/session-created.json create mode 100644 tests/Fixtures/tabby/session-rejected.json create mode 100644 tests/Fixtures/tabby/webhook-authorized.json create mode 100644 tests/Fixtures/tabby/webhook-closed.json diff --git a/CHANGELOG.md b/CHANGELOG.md index a72d6af..4149a65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to Tahseel are documented here. This project follows [Semant ### Added +- **Tabby driver** (`Tahseel::gateway('tabby')`), the seventeenth international driver and the first buy-now-pay-later one, for the UAE and Saudi Arabia: hosted checkout session via `POST /api/v2/checkout` with decimal-string amounts, buyer, shipping address and order items, redirecting to the hosted page url from `configuration.available_products`; a `rejected` pre-scoring answer reported as a refusal rather than a fake checkout page; webhooks authenticated the only way Tabby documents it - the custom header you register, compared in constant time, with no body signature claimed; lowercase webhook statuses and uppercase retrieve statuses both read, the documented status set closed; `AUTHORIZED` reported pending and only captured (`CLOSED`) payments paid, with capture implemented; refunds requiring their amount because Tabby has no amount-less full refund; region-pinned base URL, config + `TABBY_*` env vars, and 14 fixture tests. Fixture-tested only, no live account has run it yet. - **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. diff --git a/README.md b/README.md index bbfa96a..1c7b605 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-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. +Tahseel gives you one clean API for starting a payment, verifying the gateway's callback, and getting a normalised result. Twenty-six 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) **PayU** (the European PayU platform + MD5-signed notifications) and **Tabby** (BNPL checkout across the UAE and Saudi Arabia + capture, refunds and header-authenticated 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, Viva.com, PayU and Tabby 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.** > @@ -48,6 +48,7 @@ Tahseel gives you one clean API for starting a payment, verifying the gateway's | **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 | +| **Tabby** | `Tahseel::gateway('tabby')` - hosted checkout session (`POST /api/v2/checkout`) | Tabby has no body signature: you register a custom header with your own secret and the driver compares it in constant time, as Tabby's docs prescribe | full or partial, amount required (Tabby has no amount-less full refund), addressed by Tabby's payment id | `POST /api/v2/payments/{id}/captures`; only a captured payment is `CLOSED` and settles | UAE and Saudi Arabia (region-pinned base URL: api.tabby.ai / api.tabby.sa); DECIMAL string amounts in AED or SAR; `AUTHORIZED` is pending, only `CLOSED` 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) | @@ -301,6 +302,7 @@ $result->succeeded(); // true, false, or false while pending | 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 | +| Tabby | full or partial, amount required | not implemented | Tabby's payment id | The details that bite: @@ -967,6 +969,36 @@ Four PayU details worth knowing: Fixture-tested only, no PayU account has run it yet. +## Tabby + +Tabby is the seventeenth international driver and the first buy-now-pay-later one: the customer is redirected to Tabby's hosted checkout, approved or declined there, and you capture the payment afterwards. Tabby operates in the UAE and Saudi Arabia, and its docs say every call has to go to the base URL of your own region. + +```dotenv +TABBY_BASE_URL=https://api.tabby.ai # Saudi Arabia: https://api.tabby.sa +TABBY_SECRET_KEY=sk_test_... # or sk_... in production +TABBY_MERCHANT_CODE=merchant-ae +TABBY_WEBHOOK_AUTH_HEADER=X-Auth-Key +TABBY_WEBHOOK_AUTH_VALUE=... # the value you registered with Tabby +TABBY_SUCCESS_URL=https://your-app.test/checkout/done +TABBY_CANCEL_URL=https://your-app.test/checkout/cancel +TABBY_FAILURE_URL=https://your-app.test/checkout/failed +``` + +```php +$session = Tahseel::gateway('tabby')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +Four Tabby details worth knowing: + +- **Tabby does not sign its webhooks, and the driver does not pretend otherwise.** Tabby's documented check is a custom header you choose when you register the webhook (`X-Auth-Key` with your own value). The driver compares that header with the configured value in constant time and refuses anything else. That is the whole documented authentication, so nothing stronger is claimed. +- **`AUTHORIZED` is not money.** Tabby authorises, and only a captured payment becomes `CLOSED` and settles to you. The driver reports `AUTHORIZED` as pending, implements capture (`POST /api/v2/payments/{id}/captures`) and reports `CLOSED` as paid. Tabby may auto-capture after 21 days, which is a reason to capture, not a reason to skip it. +- **Statuses arrive in two spellings.** Webhooks send lowercase (`authorized`), the retrieve endpoint answers uppercase (`AUTHORIZED`). Both are read. The documented set is closed - `CREATED`, `AUTHORIZED`, `CLOSED`, `REJECTED`, `EXPIRED` - and anything else is refused. +- **Amounts are decimal strings, not minor units.** `"340.00"` is 340 dirhams, and the documented currencies are `AED` and `SAR`. A refund always carries its amount: Tabby has no amount-less full refund, so a refund request without one is refused before a request is made. + +Fixture-tested only, no Tabby 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 0047ed1..6dc72c9 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, PayU 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, Tabby and manual transfers (Vodafone Cash, InstaPay) behind one gateway contract with signed webhook verification. Experimental.", "keywords": [ "laravel", "payments", @@ -68,7 +68,8 @@ "smart checkout", "payu", "poland", - "pln" + "pln", + "tabby" ], "license": "MIT", "require": { diff --git a/config/tahseel.php b/config/tahseel.php index ddc5a09..1e6e783 100644 --- a/config/tahseel.php +++ b/config/tahseel.php @@ -477,6 +477,42 @@ 'idempotency_ttl' => (int) env('PAYTABS_IDEMPOTENCY_TTL', 86400), ], + 'tabby' => [ + // Tabby's region decides the base URL: https://api.tabby.ai for + // the UAE, https://api.tabby.sa for Saudi Arabia. Tabby's docs + // warn that a cross-region call can answer 404 or 403. + 'base_url' => env('TABBY_BASE_URL', 'https://api.tabby.ai'), + + // The secret key from the Tabby merchant dashboard. + 'secret_key' => env('TABBY_SECRET_KEY'), + + // The merchant code Tabby gave you. + 'merchant_code' => env('TABBY_MERCHANT_CODE'), + + // Tabby has no webhook signature: you register a header of your + // own with a value you choose, and that header is the whole + // documented check. Set both here. + 'webhook_auth_header' => env('TABBY_WEBHOOK_AUTH_HEADER', 'X-Auth-Key'), + 'webhook_auth_value' => env('TABBY_WEBHOOK_AUTH_VALUE'), + + 'lang' => env('TABBY_LANG', 'en'), + 'currency' => env('TABBY_CURRENCY', 'AED'), + 'item_category' => env('TABBY_ITEM_CATEGORY', 'General'), + + 'success_url' => env('TABBY_SUCCESS_URL'), + 'cancel_url' => env('TABBY_CANCEL_URL'), + 'failure_url' => env('TABBY_FAILURE_URL'), + + 'shipping_city' => env('TABBY_SHIPPING_CITY'), + 'shipping_address' => env('TABBY_SHIPPING_ADDRESS'), + 'shipping_zip' => env('TABBY_SHIPPING_ZIP'), + 'buyer_registered_since' => env('TABBY_BUYER_REGISTERED_SINCE'), + 'buyer_loyalty_level' => (int) env('TABBY_BUYER_LOYALTY_LEVEL', 0), + + 'timeout' => (int) env('TABBY_TIMEOUT', 30), + 'idempotency_ttl' => (int) env('TABBY_IDEMPOTENCY_TTL', 86400), + ], + 'payu' => [ // PayU Global (Europe): https://secure.payu.com. Sandbox: // https://secure.snd.payu.com. diff --git a/docs/ar/README.md b/docs/ar/README.md index 864d82a..3d32bff 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) و**PayU** (منصة PayU الأوروبية + إشعارات موقّعة بـ MD5). ودرايفر الخمسة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr وViva.com وPayU متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. + فيه لحد دلوقتي ستة وعشرين درايفر لبوابات: **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) و**Tabby** (تقسيط في الإمارات والسعودية + capture واسترداد وwebhooks متأمّنة بهيدر). ودرايفر الخمسة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr وViva.com وPayU وTabby متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. > **الحالة: 0.3.0، نسخة تجريبية (EXPERIMENTAL). ماتستلمش فلوس حقيقية بيها لسه.** > @@ -39,6 +39,7 @@ | **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` مدفوعة؛ متجرب على بيانات مسجلة بس لسه | +| **Tabby** | `Tahseel::gateway('tabby')` — جلسة checkout مستضافة (`POST /api/v2/checkout`) | Tabby مابتوقّعش البودي: بتسجّل هيدر باسمك وقيمة من عندك، والدرايفر بيقارنها بزمن ثابت زي ما وثائق Tabby بتقول | كامل أو جزئي، المبلغ مطلوب (Tabby ماعندهاش استرداد كامل من غير مبلغ)، برقم الدفع بتاع Tabby | `POST /api/v2/payments/{id}/captures`؛ وبس الدفعة المتعمولها capture بتبقى `CLOSED` وبتتسوّى | الإمارات والسعودية (base URL حسب المنطقة: api.tabby.ai / api.tabby.sa)؛ المبالغ نصوص عشرية بـ AED أو SAR؛ `AUTHORIZED` معلّقة وبس `CLOSED` مدفوعة؛ متجرب على بيانات مسجلة بس لسه | | **يدوي** (فودافون كاش، إنستاباي) | `Tahseel::gateway('manual')` — مرجع، تحويل على محفظتك، وقرار من حد من فريقك | مفيش: التأكيد من اللوحة | مش منطبق | مش منطبق | مفيش API تجار تكلّمه؛ واللوحة مقفولة لحد ما تحدد Gate ability | | **محافظ وتقسيط وميزة وإنستاباي** | عن طريق وسائل Paymob أو Kashier أو Geidea | - | - | - | مفيش API تجار معلن لأي منهم، شوف القسم تحت | @@ -258,6 +259,7 @@ $result->succeeded(); | Square | كامل أو جزئي، المبلغ بالوحدة الصغرى ومطلوب؛ `PENDING` لحد ما Square توافق | مش مدعوم | رقم الدفع بتاع Square | | Xendit | كامل أو جزئي، المبلغ بأصغر وحدة ومطلوب؛ `PENDING` لحد ما webhook الاسترداد يحسمها | مش مدعوم | رقم `payment_id` بتاع Xendit اللي webhook الجلسة بيجيبه | | PayU | كامل (من غير مبلغ، زي ما موثّق) أو جزئي، المبلغ بأصغر وحدة | مش مدعوم | رقم الأمر بتاع PayU | +| Tabby | كامل أو جزئي، المبلغ مطلوب | مش مدعوم | رقم الدفع بتاع Tabby | التفاصيل اللي بتوجع: @@ -920,6 +922,36 @@ header('Location: '.$session->checkoutUrl); متجرب على بيانات مسجلة بس، مفيش حساب PayU حقيقي شغّال لسه. +## Tabby + +Tabby هو الداريفر الدولي السابع عشر وأول واحد للتقسيط (BNPL): العميل بيتحوّل لصفحة Tabby المستضافة، بيتوافق عليه أو بيترفض هناك، وانت بتعمل capture للدفع بعدها. Tabby شغالة في الإمارات والسعودية، ووثائقها بتقول إن كل نداء لازم يروح على base URL بتاع منطقتك. + +```dotenv +TABBY_BASE_URL=https://api.tabby.ai # السعودية: https://api.tabby.sa +TABBY_SECRET_KEY=sk_test_... # أو sk_... في الإنتاج +TABBY_MERCHANT_CODE=merchant-ae +TABBY_WEBHOOK_AUTH_HEADER=X-Auth-Key +TABBY_WEBHOOK_AUTH_VALUE=... # القيمة اللي سجلتها عند Tabby +TABBY_SUCCESS_URL=https://your-app.test/checkout/done +TABBY_CANCEL_URL=https://your-app.test/checkout/cancel +TABBY_FAILURE_URL=https://your-app.test/checkout/failed +``` + +```php +$session = Tahseel::gateway('tabby')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +أربع تفاصيل مهمة في Tabby: + +- **Tabby مابتوقّعش الـ webhooks، والدرايفر مابيدّعيش غير كده.** الشيك الموثّق عند Tabby هو هيدر باسمك انت تختاره وقت تسجيل الـ webhook (`X-Auth-Key` بقيمة من عندك). الدرايفر بيقارن الهيدر ده بالقيمة اللي في الإعدادات بزمن ثابت ويرفض أي حاجة تانية. ده كل التوثيق الموثّق، فمفيش ادعاء بأقوى من كده. +- **`AUTHORIZED` مش فلوس.** Tabby بتعمل authorize، وبس الدفعة اللي اتعملها capture بتبقى `CLOSED` وبتتسوّى ليك. الدرايفر بيرجّع `AUTHORIZED` معلّقة، وبيدعم الـ capture (`POST /api/v2/payments/{id}/captures`)، وبيعتبر `CLOSED` مدفوعة. Tabby ممكن تعمل capture تلقائي بعد 21 يوم، وده سبب إنك تعمل capture مش سبب تسيبه. +- **الحالات بتيجي بإملاءين.** الـ webhooks بتبعت lowercase (`authorized`)، وendpoint الاستعلام بيرجّع uppercase (`AUTHORIZED`). الاتنين مقروءين. المجموعة الموثّقة مقفولة — `CREATED` و`AUTHORIZED` و`CLOSED` و`REJECTED` و`EXPIRED` — وأي حاجة تانية بتترفض. +- **المبالغ نصوص عشرية مش أصغر وحدة.** `"340.00"` يعني 340 درهم، والعملات الموثّقة `AED` و`SAR`. والاسترداد دايمًا بيحمل مبلغه: Tabby ماعندهاش استرداد كامل من غير مبلغ، فالطلب من غير مبلغ بيترفض قبل ما أي نداء يتبعت. + +متجرب على بيانات مسجلة بس، مفيش حساب Tabby حقيقي شغّال لسه. + ## الدفع اليدوي: فودافون كاش وإنستاباي فودافون كاش وإنستاباي مفيش لهم API تجار، فالطريقة الصادقة لقبولهم هي الطريقة اللي المحلات المصرية بتعملها فعلاً: العميل يحوّل على محفظتك أو عنوان إنستاباي بتاعك، يقولك رقم العملية أو يرفع صورة التحويل، وحد من فريقك يأكد إن الفلوس وصلت. الباكدج بيوفّر ده كدرايفر اسمه `manual`. diff --git a/src/Gateways/Tabby/TabbyClient.php b/src/Gateways/Tabby/TabbyClient.php new file mode 100644 index 0000000..b5ef929 --- /dev/null +++ b/src/Gateways/Tabby/TabbyClient.php @@ -0,0 +1,106 @@ + $payload + * @return array + */ + public function createSession(array $payload): array + { + return $this->unwrap('create session', $this->request()->post($this->url('api/v2/checkout'), $payload)); + } + + /** + * GET /api/v2/payments/{id} - the payment's current state. + * + * @return array + */ + public function retrievePayment(string $paymentId): array + { + return $this->unwrap('retrieve payment', $this->request()->get($this->url('api/v2/payments/'.rawurlencode($paymentId)))); + } + + /** + * POST /api/v2/payments/{id}/captures - captures an authorised payment. + * + * @param array $payload + * @return array + */ + public function capture(string $paymentId, array $payload): array + { + return $this->unwrap('capture', $this->request()->post($this->url('api/v2/payments/'.rawurlencode($paymentId).'/captures'), $payload)); + } + + /** + * POST /api/v2/payments/{id}/refunds - refunds a closed payment. + * + * @param array $payload + * @return array + */ + public function refund(string $paymentId, array $payload): array + { + return $this->unwrap('refund', $this->request()->post($this->url('api/v2/payments/'.rawurlencode($paymentId).'/refunds'), $payload)); + } + + private function request(): PendingRequest + { + return Http::withToken($this->secretKey) + ->acceptJson() + ->timeout($this->timeout); + } + + /** + * @return array + */ + private function unwrap(string $operation, Response $response): array + { + if ($response->failed()) { + throw GatewayException::fromResponse('tabby', $operation, $response->status(), $response->json()); + } + + $body = $response->json(); + + if (! is_array($body)) { + throw GatewayException::invalidResponse('tabby', $operation); + } + + return $body; + } + + private function url(string $path): string + { + return rtrim($this->baseUrl, '/').'/'.ltrim($path, '/'); + } +} diff --git a/src/Gateways/Tabby/TabbyGateway.php b/src/Gateways/Tabby/TabbyGateway.php new file mode 100644 index 0000000..b5a7e76 --- /dev/null +++ b/src/Gateways/Tabby/TabbyGateway.php @@ -0,0 +1,494 @@ + PaymentStatus::Pending, + 'AUTHORIZED' => PaymentStatus::Pending, + 'CLOSED' => PaymentStatus::Succeeded, + 'REJECTED' => PaymentStatus::Failed, + 'EXPIRED' => PaymentStatus::Failed, + ]; + + /** + * @param array $config + */ + public function __construct( + private readonly array $config, + private readonly ?IdempotencyStore $idempotency = null, + private readonly ?TabbyClient $client = null, + ) {} + + public function name(): string + { + return self::NAME; + } + + public function createPayment(PaymentRequest $request): PaymentSession + { + $this->assertConfigured(['secret_key', 'merchant_code']); + + return IdempotentCreation::run( + $this->idempotency, + $request->idempotencyKey, + $this->integer('idempotency_ttl', 86400), + function () use ($request): PaymentSession { + $payload = [ + 'payment' => $this->paymentPayload($request), + 'lang' => $this->string('lang') ?? 'en', + 'merchant_code' => (string) $this->string('merchant_code'), + ]; + + $urls = $this->merchantUrls($request); + + if ($urls !== []) { + $payload['merchant_urls'] = $urls; + } + + $body = $this->client()->createSession($payload); + $status = strtolower((string) ($body['status'] ?? '')); + + $payment = is_array($body['payment'] ?? null) ? $body['payment'] : []; + $paymentId = $payment['id'] ?? null; + + if (! is_scalar($paymentId) || (string) $paymentId === '') { + throw GatewayException::invalidResponse(self::NAME, 'create session'); + } + + $paymentId = (string) $paymentId; + + // Tabby answers "rejected" when its pre-scoring says no: that + // is not an error, but there is no page to send the customer + // to either, so it is reported as one with Tabby's own reason. + if ($status === 'rejected') { + throw new GatewayException('tabby: the session was rejected by Tabby pre-scoring, so there is no checkout page to send the customer to.'); + } + + $checkoutUrl = $this->webUrl($body); + + if ($checkoutUrl === null) { + throw GatewayException::invalidResponse(self::NAME, 'create session'); + } + + return new PaymentSession( + gateway: self::NAME, + reference: $request->reference, + intentionId: $paymentId, + orderId: $paymentId, + checkoutUrl: $checkoutUrl, + raw: $body, + ); + }, + ); + } + + /** + * Tabby's documented webhook authentication is a header you register + * yourself: the request carries it, and you compare it with the value you + * gave Tabby. There is no signature over the body. + * + * @param array $payload + * @param array $query + * @param array $headers + */ + public function verifyAndParseWebhook(array $payload, array $query = [], array $headers = []): WebhookEvent + { + $secret = $this->string('webhook_auth_value'); + + if ($secret === null) { + throw ConfigurationException::missing(self::NAME, ['tahseel.drivers.tabby.webhook_auth_value']); + } + + $header = strtolower($this->string('webhook_auth_header') ?? 'X-Auth-Key'); + $sent = $this->header($headers, $header); + + if ($sent === null || ! hash_equals($secret, $sent)) { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $status = $this->status($payload['status'] ?? null); + $paymentId = $payload['id'] ?? null; + + if (! is_scalar($paymentId) || (string) $paymentId === '') { + throw GatewayException::invalidResponse(self::NAME, 'webhook'); + } + + $order = is_array($payload['order'] ?? null) ? $payload['order'] : []; + $captures = is_array($payload['captures'] ?? null) ? $payload['captures'] : []; + $refunds = is_array($payload['refunds'] ?? null) ? $payload['refunds'] : []; + + return new WebhookEvent( + gateway: self::NAME, + status: $status, + transactionId: (string) $paymentId, + orderId: (string) $paymentId, + reference: is_scalar($order['reference_id'] ?? null) ? (string) $order['reference_id'] : null, + amount: $this->money($payload['amount'] ?? null, $payload['currency'] ?? null) + ?? Money::minor(0, (string) ($this->string('currency') ?? 'AED')), + success: $status === PaymentStatus::Succeeded, + pending: $status === PaymentStatus::Pending, + refunded: $refunds !== [] && $status === PaymentStatus::Succeeded && $this->fullyRefunded($payload, $refunds), + voided: false, + createdAt: is_string($payload['created_at'] ?? null) ? $payload['created_at'] : null, + raw: $payload + ['_captures' => $captures], + ); + } + + public function capture(CaptureRequest $request): OperationResult + { + $this->assertConfigured(['secret_key']); + + $payload = []; + + if ($request->amount instanceof Money) { + $payload['amount'] = $request->amount->toDecimalString(); + } + + $payload['reference_id'] = 'capture-'.$request->transactionId; + + $body = $this->client()->capture($request->transactionId, $payload); + $status = $this->status($body['status'] ?? null); + + return new OperationResult( + gateway: self::NAME, + operation: 'capture', + status: $status, + transactionId: $request->transactionId, + orderId: $request->transactionId, + amount: $request->amount, + raw: $body, + ); + } + + public function refund(RefundRequest $request): OperationResult + { + $this->assertConfigured(['secret_key']); + + $paymentId = $request->transactionId ?? $request->orderId; + + if (! is_string($paymentId) || trim($paymentId) === '') { + throw new InvalidPaymentRequestException('A Tabby refund needs the payment id Tabby returned.'); + } + + $amount = $request->amount; + + // Tabby's refund request always carries an amount: the same call + // serves full and partial refunds, and the full one has to name the + // captured total. + if (! $amount instanceof Money) { + throw new InvalidPaymentRequestException('A Tabby refund needs the amount to refund; Tabby has no amount-less full refund.'); + } + + $body = $this->client()->refund($paymentId, [ + 'amount' => $amount->toDecimalString(), + 'reference_id' => 'refund-'.$paymentId, + ]); + + // Tabby's docs say a refund reflects instantly and cannot be + // cancelled, so a 200 is a refund that happened. + return new OperationResult( + gateway: self::NAME, + operation: 'refund', + status: PaymentStatus::Refunded, + transactionId: $paymentId, + orderId: $paymentId, + amount: $amount, + raw: $body, + ); + } + + /** + * @return array + */ + private function paymentPayload(PaymentRequest $request): array + { + $customer = $request->customer; + $name = trim($customer->firstName.' '.$customer->lastName); + + if ($name === '') { + throw new InvalidPaymentRequestException('Tabby needs the buyer\'s name.'); + } + + $email = $customer->email; + + if (! is_string($email) || trim($email) === '') { + throw new InvalidPaymentRequestException('Tabby needs the buyer\'s email.'); + } + + $phone = $customer->phone; + + if (trim($phone) === '') { + throw new InvalidPaymentRequestException('Tabby needs the buyer\'s mobile number.'); + } + + $items = []; + + foreach ($request->items as $item) { + $items[] = [ + 'title' => $item->name, + 'quantity' => $item->quantity, + 'unit_price' => $item->amount->toDecimalString(), + 'category' => $this->string('item_category') ?? 'General', + ]; + } + + if ($items === []) { + $items[] = [ + 'title' => mb_substr($request->description ?? $request->reference, 0, 120), + 'quantity' => 1, + 'unit_price' => $request->amount->toDecimalString(), + 'category' => $this->string('item_category') ?? 'General', + ]; + } + + return [ + 'amount' => $request->amount->toDecimalString(), + 'currency' => $request->amount->currency, + 'buyer' => array_filter([ + 'name' => $name, + 'email' => $email, + 'phone' => $phone, + 'dob' => $this->string('buyer_dob'), + ], static fn (mixed $value): bool => $value !== null && $value !== ''), + 'shipping_address' => [ + 'city' => $this->string('shipping_city') ?? 'Dubai', + 'address' => $this->string('shipping_address') ?? 'Dubai', + 'zip' => $this->string('shipping_zip') ?? '00000', + ], + 'order' => [ + 'reference_id' => $request->reference, + 'items' => $items, + 'tax_amount' => '0.00', + 'shipping_amount' => '0.00', + 'discount_amount' => '0.00', + ], + 'buyer_history' => [ + 'registered_since' => $this->string('buyer_registered_since') ?? '2020-01-01T00:00:00Z', + 'loyalty_level' => $this->integer('buyer_loyalty_level', 0), + ], + 'order_history' => [], + ]; + } + + /** + * @return array + */ + private function merchantUrls(PaymentRequest $request): array + { + $urls = []; + + $success = $request->redirectionUrl ?? $this->string('success_url'); + + if (is_string($success) && $success !== '') { + $urls['success'] = $success; + } + + foreach (['cancel' => 'cancel_url', 'failure' => 'failure_url'] as $key => $config) { + $url = $this->string($config); + + if ($url !== null) { + $urls[$key] = $url; + } + } + + return $urls; + } + + /** + * @param array $body + */ + private function webUrl(array $body): ?string + { + $products = $body['configuration']['available_products'] ?? null; + + if (! is_array($products)) { + return null; + } + + foreach ($products as $product) { + if (! is_array($product) || ! is_array($product[0] ?? null)) { + continue; + } + + $url = $product[0]['web_url'] ?? null; + + if (is_string($url) && $url !== '') { + return $url; + } + } + + return null; + } + + /** + * @param array $payload + * @param array $refunds + */ + private function fullyRefunded(array $payload, array $refunds): bool + { + $amount = $payload['amount'] ?? null; + + if (! is_scalar($amount)) { + return false; + } + + $total = 0.0; + + foreach ($refunds as $refund) { + if (is_array($refund) && is_scalar($refund['amount'] ?? null)) { + $total += (float) $refund['amount']; + } + } + + return $total > 0.0 && $total >= (float) $amount; + } + + 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, 'status ['.$code.']'); + } + + private function money(mixed $amount, mixed $currency): ?Money + { + if (! is_scalar($amount) || ! is_numeric($amount)) { + return null; + } + + $code = is_scalar($currency) ? strtoupper(trim((string) $currency)) : ''; + + if ($code === '') { + return null; + } + + $minor = (int) round(((float) $amount) * (10 ** ($code === 'KWD' ? 3 : 2))); + + return Money::minor($minor, $code); + } + + /** + * @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(): TabbyClient + { + if ($this->client instanceof TabbyClient) { + return $this->client; + } + + return new TabbyClient( + $this->string('base_url') ?? 'https://api.tabby.ai', + (string) $this->string('secret_key'), + $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.tabby.'.$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 629c279..1ec650f 100644 --- a/src/TahseelManager.php +++ b/src/TahseelManager.php @@ -40,6 +40,7 @@ use Tahseel\Gateways\Razorpay\RazorpayGateway; use Tahseel\Gateways\Square\SquareGateway; use Tahseel\Gateways\Stripe\StripeGateway; +use Tahseel\Gateways\Tabby\TabbyGateway; use Tahseel\Gateways\Tap\TapGateway; use Tahseel\Gateways\Telr\TelrGateway; use Tahseel\Gateways\Viva\VivaGateway; @@ -213,6 +214,11 @@ protected function createAdyenDriver(): Gateway return new AdyenGateway($this->configuration(AdyenGateway::NAME), $this->idempotencyStore()); } + protected function createTabbyDriver(): Gateway + { + return new TabbyGateway($this->configuration(TabbyGateway::NAME), $this->idempotencyStore()); + } + protected function createPayuDriver(): Gateway { return new PayUGateway($this->configuration(PayUGateway::NAME), $this->idempotencyStore()); diff --git a/tests/Feature/TabbyGatewayTest.php b/tests/Feature/TabbyGatewayTest.php new file mode 100644 index 0000000..1208fb7 --- /dev/null +++ b/tests/Feature/TabbyGatewayTest.php @@ -0,0 +1,169 @@ +> + */ +function tabbyHeaders(): array +{ + return ['X-Auth-Key' => ['tabby-webhook-secret']]; +} + +it('resolves the tabby driver by name', function () { + expect(Tahseel::gateway('tabby'))->toBeInstanceOf(TabbyGateway::class) + ->and(Tahseel::gateway('tabby')->name())->toBe('tabby'); +}); + +it('creates a session and returns the hosted checkout url', function () { + Http::fake([ + 'api.tabby.ai/api/v2/checkout' => Http::response($this->fixture('tabby/session-created.json'), 200), + ]); + + $session = Tahseel::gateway('tabby')->createPayment(tabbyRequest()); + + expect($session->gateway)->toBe('tabby') + ->and($session->intentionId)->toBe('3b0a1c2e-0000-4000-8000-000000000002') + ->and($session->checkoutUrl)->toBe('https://checkout.tabby.ai/pay/3b0a1c2e-0000-4000-8000-000000000002'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.tabby.ai/api/v2/checkout' + && $request->hasHeader('Authorization', 'Bearer sk_test_0192a1b2c3d4') + && $request['merchant_code'] === 'merchant-ae' + && $request['lang'] === 'en' + && $request['payment']['amount'] === '340.00' + && $request['payment']['currency'] === 'AED' + && $request['payment']['buyer']['phone'] === '+971500000001' + && $request['payment']['order']['reference_id'] === 'order-1001' + && $request['payment']['order']['items'][0]['unit_price'] === '340.00' + && $request['merchant_urls']['success'] === 'https://example.test/checkout/done'); +}); + +it('reports a rejected session instead of inventing a checkout page', function () { + Http::fake([ + 'api.tabby.ai/api/v2/checkout' => Http::response($this->fixture('tabby/session-rejected.json'), 200), + ]); + + Tahseel::gateway('tabby')->createPayment(tabbyRequest()); +})->throws(GatewayException::class); + +it('demands the merchant code', function () { + config()->set('tahseel.drivers.tabby.merchant_code', null); + + Tahseel::gateway('tabby')->createPayment(tabbyRequest()); +})->throws(ConfigurationException::class); + +it('treats an authorized payment as pending, not paid', function () { + $event = Tahseel::gateway('tabby')->verifyAndParseWebhook($this->fixture('tabby/webhook-authorized.json'), [], tabbyHeaders()); + + expect($event->status)->toBe(PaymentStatus::Pending) + ->and($event->pending)->toBeTrue() + ->and($event->success)->toBeFalse() + ->and($event->transactionId)->toBe('3b0a1c2e-0000-4000-8000-000000000002') + ->and($event->reference)->toBe('order-1001') + ->and($event->amount?->toMinor())->toBe(34000) + ->and($event->amount?->currency)->toBe('AED'); +}); + +it('treats a closed payment as paid', function () { + $event = Tahseel::gateway('tabby')->verifyAndParseWebhook($this->fixture('tabby/webhook-closed.json'), [], tabbyHeaders()); + + expect($event->status)->toBe(PaymentStatus::Succeeded) + ->and($event->success)->toBeTrue(); +}); + +it('rejects a notification whose auth header does not match', function () { + Tahseel::gateway('tabby')->verifyAndParseWebhook( + $this->fixture('tabby/webhook-closed.json'), + [], + ['X-Auth-Key' => ['wrong-secret']], + ); +})->throws(InvalidSignatureException::class); + +it('rejects a notification with no auth header at all', function () { + Tahseel::gateway('tabby')->verifyAndParseWebhook($this->fixture('tabby/webhook-closed.json')); +})->throws(InvalidSignatureException::class); + +it('demands the webhook auth value in configuration', function () { + config()->set('tahseel.drivers.tabby.webhook_auth_value', null); + + Tahseel::gateway('tabby')->verifyAndParseWebhook($this->fixture('tabby/webhook-closed.json'), [], tabbyHeaders()); +})->throws(ConfigurationException::class); + +it('refuses a status outside the documented set', function () { + $payload = $this->fixture('tabby/webhook-closed.json'); + $payload['status'] = 'settled'; + + Tahseel::gateway('tabby')->verifyAndParseWebhook($payload, [], tabbyHeaders()); +})->throws(InvalidWebhookException::class); + +it('captures an authorised payment', function () { + Http::fake([ + 'api.tabby.ai/api/v2/payments/*/captures' => Http::response($this->fixture('tabby/capture-response.json'), 200), + ]); + + $result = Tahseel::gateway('tabby')->capture(new CaptureRequest( + transactionId: '3b0a1c2e-0000-4000-8000-000000000002', + amount: Money::minor(34000, 'AED'), + )); + + expect($result->status)->toBe(PaymentStatus::Succeeded); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.tabby.ai/api/v2/payments/3b0a1c2e-0000-4000-8000-000000000002/captures' + && $request['amount'] === '340.00' + && is_string($request['reference_id'])); +}); + +it('refunds a closed payment with the amount Tabby requires', function () { + Http::fake([ + 'api.tabby.ai/api/v2/payments/*/refunds' => Http::response($this->fixture('tabby/refund-response.json'), 200), + ]); + + $result = Tahseel::gateway('tabby')->refund(new RefundRequest( + transactionId: '3b0a1c2e-0000-4000-8000-000000000002', + amount: Money::minor(34000, 'AED'), + )); + + expect($result->status)->toBe(PaymentStatus::Refunded) + ->and($result->transactionId)->toBe('3b0a1c2e-0000-4000-8000-000000000002'); + + Http::assertSent(fn (Request $request): bool => $request['amount'] === '340.00' + && is_string($request['reference_id'])); +}); + +it('refuses a refund with no amount, because Tabby has no amount-less full refund', function () { + Tahseel::gateway('tabby')->refund(new RefundRequest(transactionId: '3b0a1c2e-0000-4000-8000-000000000002')); +})->throws(InvalidPaymentRequestException::class); + +it('surfaces a tabby error instead of inventing a session', function () { + Http::fake([ + 'api.tabby.ai/api/v2/checkout' => Http::response(['error' => 'invalid'], 400), + ]); + + Tahseel::gateway('tabby')->createPayment(tabbyRequest()); +})->throws(GatewayException::class); diff --git a/tests/Fixtures/tabby/capture-response.json b/tests/Fixtures/tabby/capture-response.json new file mode 100644 index 0000000..6dc2d57 --- /dev/null +++ b/tests/Fixtures/tabby/capture-response.json @@ -0,0 +1,12 @@ +{ + "id": "3b0a1c2e-0000-4000-8000-000000000002", + "amount": "340.00", + "currency": "AED", + "status": "CLOSED", + "captures": [ + { + "id": "capture-1", + "amount": "340.00" + } + ] +} diff --git a/tests/Fixtures/tabby/refund-response.json b/tests/Fixtures/tabby/refund-response.json new file mode 100644 index 0000000..5c24239 --- /dev/null +++ b/tests/Fixtures/tabby/refund-response.json @@ -0,0 +1,12 @@ +{ + "id": "3b0a1c2e-0000-4000-8000-000000000002", + "amount": "340.00", + "currency": "AED", + "status": "CLOSED", + "refunds": [ + { + "id": "refund-1", + "amount": "340.00" + } + ] +} diff --git a/tests/Fixtures/tabby/session-created.json b/tests/Fixtures/tabby/session-created.json new file mode 100644 index 0000000..9eb74c2 --- /dev/null +++ b/tests/Fixtures/tabby/session-created.json @@ -0,0 +1,23 @@ +{ + "id": "3b0a1c2e-0000-4000-8000-000000000001", + "status": "created", + "payment": { + "id": "3b0a1c2e-0000-4000-8000-000000000002", + "status": "CREATED", + "amount": "340.00", + "currency": "AED", + "order": { + "reference_id": "order-1001" + } + }, + "configuration": { + "available_products": { + "installments": [ + { + "web_url": "https://checkout.tabby.ai/pay/3b0a1c2e-0000-4000-8000-000000000002", + "type": "installments" + } + ] + } + } +} diff --git a/tests/Fixtures/tabby/session-rejected.json b/tests/Fixtures/tabby/session-rejected.json new file mode 100644 index 0000000..476dcc9 --- /dev/null +++ b/tests/Fixtures/tabby/session-rejected.json @@ -0,0 +1,9 @@ +{ + "status": "rejected", + "payment": { + "id": "3b0a1c2e-0000-4000-8000-000000000003", + "status": "REJECTED", + "amount": "340.00", + "currency": "AED" + } +} diff --git a/tests/Fixtures/tabby/webhook-authorized.json b/tests/Fixtures/tabby/webhook-authorized.json new file mode 100644 index 0000000..62ef178 --- /dev/null +++ b/tests/Fixtures/tabby/webhook-authorized.json @@ -0,0 +1,12 @@ +{ + "id": "3b0a1c2e-0000-4000-8000-000000000002", + "created_at": "2026-12-04T10:00:00Z", + "amount": "340.00", + "currency": "AED", + "status": "authorized", + "captures": [], + "refunds": [], + "order": { + "reference_id": "order-1001" + } +} diff --git a/tests/Fixtures/tabby/webhook-closed.json b/tests/Fixtures/tabby/webhook-closed.json new file mode 100644 index 0000000..7882342 --- /dev/null +++ b/tests/Fixtures/tabby/webhook-closed.json @@ -0,0 +1,17 @@ +{ + "id": "3b0a1c2e-0000-4000-8000-000000000002", + "created_at": "2026-12-04T10:00:00Z", + "amount": "340.00", + "currency": "AED", + "status": "closed", + "captures": [ + { + "id": "capture-1", + "amount": "340.00" + } + ], + "refunds": [], + "order": { + "reference_id": "order-1001" + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 6d17e83..0b68364 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -221,6 +221,26 @@ protected function defineEnvironment($app): void 'timeout' => 10, ]); + $app['config']->set('tahseel.drivers.tabby', [ + 'base_url' => 'https://api.tabby.ai', + 'secret_key' => 'sk_test_0192a1b2c3d4', + 'merchant_code' => 'merchant-ae', + 'webhook_auth_header' => 'X-Auth-Key', + 'webhook_auth_value' => 'tabby-webhook-secret', + 'lang' => 'en', + 'currency' => 'AED', + 'item_category' => 'Shoes', + 'success_url' => 'https://example.test/checkout/done', + 'cancel_url' => 'https://example.test/checkout/cancel', + 'failure_url' => 'https://example.test/checkout/failed', + 'shipping_city' => 'Dubai', + 'shipping_address' => 'Sheikh Zayed Rd', + 'shipping_zip' => '00000', + 'buyer_registered_since' => '2024-03-01T00:00:00Z', + 'buyer_loyalty_level' => 0, + 'timeout' => 10, + ]); + $app['config']->set('tahseel.drivers.payu', [ 'base_url' => 'https://secure.payu.com', 'client_id' => '460718',