diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ad73ab..d34030d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to Tahseel are documented here. This project follows [Semant ### Added +- **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. - **Square driver** (`Tahseel::gateway('square')`), the twelfth international driver (US, Canada, UK, Ireland, Australia, Japan, France, Spain), on the hosted Checkout product: `POST /v2/online-checkout/payment-links` with a pinned `Square-Version` header, MINOR-unit amounts, the merchant reference carried back as the payment `note`; notifications verified exactly as Square documents them - HMAC-SHA-256 of the notification URL followed by the raw body under the subscription's signature key, base64, in `x-square-hmacsha256-signature`, constant-time, and the docs' own published example vector as a fixture test - then the authenticated `GET /v2/payments/{id}` read decides the status, a body without raw bytes is refused rather than reconstructed, and the documented `APPROVED`/`PENDING`/`COMPLETED`/`CANCELED`/`FAILED` set is honoured with `APPROVED` (authorised, not captured) coming through as pending; refund notifications parsed (`APPROVED` refunded, `PENDING` pending, `REJECTED`/`FAILED` failed); refunds through `POST /v2/refunds` with the required amount, addressed by the Square payment id, idempotency key kept inside Square's 45-character limit; `fetchPaymentStatus()`, config + `SQUARE_*` env vars, and 18 fixture tests. Fixture-tested only, no live account has run it yet. - **Klarna driver** (`Tahseel::gateway('klarna')`), the eleventh international driver and the BNPL specialist (Sweden and the Nordics, most of Europe, the UK, the US), on the documented hosted payment page product: `POST /payments/v1/sessions` for the purchase session, then `POST /hpp/v1/sessions` for the page the customer pays on, MINOR-unit amounts, and the third step Klarna documents made explicit instead of hidden - `placeOrder($authorizationToken, $request)` creates the order that is actually paid, returns the Klarna `order_id`, and maps the fraud assessment (`REJECTED` fails, `PENDING` stays pending); callbacks carry no HMAC, so the documented one-time token in the `status_update` url is compared in constant time and the session is then re-read through the authenticated API, a post without the token is refused before any API call, and the session's closed status set is honoured with anything else refused rather than guessed; refunds with the required `refunded_amount` and the documented `Klarna-Idempotency-Key` header, addressed by Klarna's own order id; the `{{session_id}}` / `{{authorization_token}}` placeholders are sent literally as Klarna documents them rather than percent-encoded; config + `KLARNA_*` env vars, and 16 fixture tests. No `fetchPaymentStatus()`, and the callback carries no amount, so amounts are compared from `placeOrder()`. Fixture-tested only, no live account has run it yet. diff --git a/README.md b/README.md index d828e2a..3874b78 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-two 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) and **Xendit** (hosted Payment Sessions across South-East Asia + `x-callback-token` 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 and Xendit 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-three 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) and **Telr** (hosted payment pages across the Gulf + SHA1-signed transaction advice). 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 and Telr 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.** > @@ -45,6 +45,7 @@ Tahseel gives you one clean API for starting a payment, verifying the gateway's | **Klarna** | `Tahseel::gateway('klarna')` - payment session + hosted page (`POST /payments/v1/sessions`, then `POST /hpp/v1/sessions`) | no HMAC: the documented one-time token in the `status_update` URL is compared in constant time, then the session is re-read through the API, so a forged call can never mark anything paid | refund, amount required, addressed by Klarna's own order id; there is no full-refund default | `placeOrder()` after the customer authorises: an authorization is not money | Europe and the US; BNPL and pay-now; MINOR units; fixture-tested only, no live run yet | | **Square** | `Tahseel::gateway('square')` - Square-hosted payment link (`POST /v2/online-checkout/payment-links`) | HMAC-SHA-256, base64, of the notification URL followed by the raw body, keyed by the subscription's signature key, in `x-square-hmacsha256-signature`, constant-time; the notification is the signal, the authenticated payment read is the truth | refund, amount required, addressed by the Square payment id; `PENDING` until Square approves it | server-side `fetchPaymentStatus()`; an `APPROVED` payment is authorised, not captured, and comes through pending | US, Canada, UK, Ireland, Australia, Japan, France, Spain; MINOR units; fixture-tested only, no live run yet | | **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 | | **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) | @@ -872,6 +873,36 @@ Four Xendit details worth knowing: Amounts are the currency's smallest unit, the same convention as most drivers here. Fixture-tested only, no Xendit account has run it yet. +## Telr + +Telr is the fourteenth international driver and a Gulf acquirer: the UAE, Saudi Arabia and the wider region, on the hosted payment page. One endpoint does the work - `POST /gateway/order.json` - with a `method` of `create` for the page and `check` for a status read. + +```dotenv +TELR_BASE_URL=https://secure.telr.com/gateway +TELR_STORE=1234 # Merchant Administration System -> store id +TELR_AUTH_KEY=... # the API auth key +TELR_SECRET_KEY=... # the secret key the advice hash is keyed by +TELR_TEST_MODE=0 # 1 puts the payment page in test mode +TELR_AUTHORISED_URL=https://your-app.test/checkout/done +TELR_DECLINED_URL=https://your-app.test/checkout/declined +TELR_CANCELLED_URL=https://your-app.test/checkout/cancelled +``` + +```php +$session = Tahseel::gateway('telr')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +Four Telr details worth knowing: + +- **The advice hash is SHA1 over a fixed field list.** Telr documents it as the secret key followed by fourteen transaction fields - store, type, class, test flag, ref, previous ref, first ref, currency, amount, cart id, description, status, auth code, auth message - joined with colons in that order, with percent-encoded characters decoded first and a missing field contributing an empty value. The driver builds exactly that string and compares in constant time. `card_check`, `bill_check` and `acquirer_check` exist for the other sections; the transaction hash is the one that decides a payment. +- **`H` is not paid.** The documented statuses are `A` authorised, `H` authorised but placed on hold for manual inspection, `D` declined, `C` cancelled and `E` error. Only `A` comes through as paid, `H` as pending, and a status outside the set is refused rather than guessed. +- **Amounts are major units as decimal strings.** `95.00`, not `9500`, the same convention as Kashier and PayTap; the driver formats from your `Money` so nothing rounds through a float. +- **The store id and auth key travel in the body, not a header.** That is how Telr documents the call, and it is configuration here, never a constant. + +Refunds are not wrapped: Telr documents them through a different product surface, and this driver does not claim what it has not been grounded in. Fixture-tested only, no Telr 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`. @@ -966,6 +997,7 @@ Being explicit, so nobody discovers it in production: - **No capture on Kashier.** Refund and void are wrapped; capture is not. - **No Fawry card or wallet payments.** Reference numbers only, for the reasons above. - **No Geidea voids or saved cards.** Refund is wrapped; Geidea documents a void only for pre-authorised, uncaptured payments and publishes no endpoint recipe for it, so it is not guessed. +- **No Telr refunds.** Telr documents refunds on a different product surface, so the driver takes payments and reads status only rather than claiming a refund path it has not been grounded in. - **No Xendit payment re-read.** Xendit documents a callback token rather than an HMAC for this flow, and the driver does not fetch the payment afterwards; if you want a second look before fulfilling, call Xendit's own API from your application. - **No Square capture or voids.** Square's Payments API can complete a delayed capture; Tahseel wraps refunds only, so an `APPROVED` payment stays pending here. - **No Klarna capture or order reads.** Klarna's Order Management API also captures and reads orders; Tahseel wraps refunds only, and the place-order step is left to `placeOrder()`. diff --git a/composer.json b/composer.json index 187d5a1..3dc6bd3 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 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 and manual transfers (Vodafone Cash, InstaPay) behind one gateway contract with signed webhook verification. Experimental.", "keywords": [ "laravel", "payments", @@ -60,7 +60,9 @@ "xendit", "indonesia", "idr", - "southeast asia" + "southeast asia", + "telr", + "aed" ], "license": "MIT", "require": { diff --git a/config/tahseel.php b/config/tahseel.php index 8f5a4f3..9e431a6 100644 --- a/config/tahseel.php +++ b/config/tahseel.php @@ -477,6 +477,34 @@ 'idempotency_ttl' => (int) env('PAYTABS_IDEMPOTENCY_TTL', 86400), ], + 'telr' => [ + 'base_url' => env('TELR_BASE_URL', 'https://secure.telr.com/gateway'), + + // Merchant Administration System -> your store id and the API + // auth key. Both travel in the request body, not a header. + 'store' => env('TELR_STORE'), + 'auth_key' => env('TELR_AUTH_KEY'), + + // The secret key used to sign transaction advice messages. + 'secret_key' => env('TELR_SECRET_KEY'), + + // 1 puts the payment page in test mode. + 'test_mode' => (int) env('TELR_TEST_MODE', 0), + + 'transaction_type' => env('TELR_TRANSACTION_TYPE', 'sale'), + 'framed' => (int) env('TELR_FRAMED', 0), + + // Where Telr sends the shopper back, per outcome. + 'authorised_url' => env('TELR_AUTHORISED_URL'), + 'declined_url' => env('TELR_DECLINED_URL'), + 'cancelled_url' => env('TELR_CANCELLED_URL'), + + 'currency' => env('TELR_CURRENCY', 'AED'), + + 'timeout' => (int) env('TELR_TIMEOUT', 30), + 'idempotency_ttl' => (int) env('TELR_IDEMPOTENCY_TTL', 86400), + ], + 'xendit' => [ 'base_url' => env('XENDIT_BASE_URL', 'https://api.xendit.co'), diff --git a/docs/ar/README.md b/docs/ar/README.md index 360c776..307183f 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`). ودرايفر الاتنين وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. + فيه لحد دلوقتي تلاتة وعشرين درايفر لبوابات: **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). ودرايفر التلاتة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. > **الحالة: 0.3.0، نسخة تجريبية (EXPERIMENTAL). ماتستلمش فلوس حقيقية بيها لسه.** > @@ -36,6 +36,7 @@ | **Klarna** | `Tahseel::gateway('klarna')` — جلسة دفع + صفحة مستضافة (`POST /payments/v1/sessions` وبعدها `POST /hpp/v1/sessions`) | مفيش HMAC: التوكن الموثّق لمرة واحدة اللي في رابط `status_update` بيتقارن بزمن ثابت، وبعدها الجلسة بتتجاب تاني من الـ API، فمكالمة مزوّرة عمرها ما تعلّم حاجة مدفوعة | استرداد بمبلغ مطلوب، برقم الأوردر بتاع Klarna نفسه؛ مفيش استرداد كامل افتراضي | `placeOrder()` بعد ما العميل يفوّض: التفويض مش فلوس | أوروبا وأمريكا؛ تقسيط ودفع فوري؛ الوحدة الصغرى؛ متجرب على بيانات مسجلة بس لسه | | **Square** | `Tahseel::gateway('square')` — رابط دفع مستضاف عند Square (`POST /v2/online-checkout/payment-links`) | HMAC-SHA-256 بترميز base64 على رابط الإشعار وبعده البودي الخام، بمفتاح التوقيع بتاع الاشتراك، في هيدر `x-square-hmacsha256-signature`، مقارنة ثابتة الزمن؛ الإشعار إشارة، وقراءة الدفع الموثّقة هي الحقيقة | استرداد بمبلغ مطلوب، برقم الدفع بتاع Square؛ `PENDING` لحد ما Square توافق | تحقق من السيرفر بـ `fetchPaymentStatus()`؛ الدفعة `APPROVED` مفوّضة مش متحصّلة، فبترجع pending | أمريكا وكندا وبريطانيا وأيرلندا وأستراليا واليابان وفرنسا وإسبانيا؛ الوحدة الصغرى؛ متجرب على بيانات مسجلة بس لسه | | **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 مش مدفوعة؛ متجرب على بيانات مسجلة بس لسه | | **يدوي** (فودافون كاش، إنستاباي) | `Tahseel::gateway('manual')` — مرجع، تحويل على محفظتك، وقرار من حد من فريقك | مفيش: التأكيد من اللوحة | مش منطبق | مش منطبق | مفيش API تجار تكلّمه؛ واللوحة مقفولة لحد ما تحدد Gate ability | | **محافظ وتقسيط وميزة وإنستاباي** | عن طريق وسائل Paymob أو Kashier أو Geidea | - | - | - | مفيش API تجار معلن لأي منهم، شوف القسم تحت | @@ -825,6 +826,36 @@ header('Location: '.$session->checkoutUrl); المبالغ بأصغر وحدة في العملة، نفس العُرف في معظم الدرايفرات هنا. متجرب على بيانات مسجلة بس، مفيش حساب Xendit حقيقي شغّال لسه. +## Telr + +Telr هو الداريفر الدولي الرابع عشر ومُحصّل خليجي: الإمارات والسعودية والمنطقة، على صفحة الدفع المستضافة. نداء واحد بيعمل الشغل — `POST /gateway/order.json` — بالطريقة `create` للصفحة و`check` لقراءة الحالة. + +```dotenv +TELR_BASE_URL=https://secure.telr.com/gateway +TELR_STORE=1234 # من نظام إدارة التاجر -> رقم المتجر +TELR_AUTH_KEY=... # مفتاح التوثيق +TELR_SECRET_KEY=... # المفتاح السري اللي توقيع الإشعار بيتعمل بيه +TELR_TEST_MODE=0 # 1 بيحط صفحة الدفع في وضع الاختبار +TELR_AUTHORISED_URL=https://your-app.test/checkout/done +TELR_DECLINED_URL=https://your-app.test/checkout/declined +TELR_CANCELLED_URL=https://your-app.test/checkout/cancelled +``` + +```php +$session = Tahseel::gateway('telr')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +أربع تفاصيل مهمة في Telr: + +- **توقيع الإشعار SHA1 على قايمة حقول ثابتة.** Telr موثّقة إنه المفتاح السري وبعده أربعتاشر حقل بتاع العملية — المتجر والنوع والكلاس وعلامة الاختبار والمرجع والمرجع السابق وأول مرجع والعملة والمبلغ ورقم السلة والوصف والحالة وكود التوثيق ورسالة التوثيق — متوصّلين بنقطتين بالترتيب ده، والقيم المرمّزة بتتفك الأول، والحقل الغايب بيساهم بقيمة فاضية. الدرايفر بيبني النص ده بالحرف ويقارن بزمن ثابت. فيه `card_check` و`bill_check` و`acquirer_check` لأقسام تانية؛ توقيع العملية هو اللي بيحسم الدفع. +- **`H` مش مدفوعة.** الحالات الموثّقة: `A` مفوّضة، `H` مفوّضة بس معلّقة لمراجعة يدوية، `D` مرفوضة، `C` ملغية، `E` خطأ. بس `A` بتيجي مدفوعة، و`H` معلّقة، وأي حالة برّه المجموعة بتترفض مش بتتخمّن. +- **المبالغ بالوحدة الكبرى كنص عشري.** `95.00` مش `9500`، نفس عُرف Kashier وPayTabs؛ والدرايفر بيصيغ من `Money` بتاعك فمفيش تقريب عبر float. +- **رقم المتجر والمفتاح بيمشوا في البودي مش في هيدر.** ده اللي Telr موثّقاه، وهو إعداد عندنا مش ثابت في الكود. + +الاسترداد مش ملفوف: Telr موثّقة على منتج تاني، والدرايفر مابيدّعيش حاجة ماتأسّسش عليها. متجرب على بيانات مسجلة بس، مفيش حساب Telr حقيقي شغّال لسه. + ## الدفع اليدوي: فودافون كاش وإنستاباي فودافون كاش وإنستاباي مفيش لهم API تجار، فالطريقة الصادقة لقبولهم هي الطريقة اللي المحلات المصرية بتعملها فعلاً: العميل يحوّل على محفظتك أو عنوان إنستاباي بتاعك، يقولك رقم العملية أو يرفع صورة التحويل، وحد من فريقك يأكد إن الفلوس وصلت. الباكدج بيوفّر ده كدرايفر اسمه `manual`. @@ -919,6 +950,7 @@ Gate::define('manage-payments', fn (User $user) => $user->is_admin); - **مفيش capture على Kashier.** الاسترداد والإلغاء مغلّفين؛ الكابتشر لأ. - **مفيش كارت ولا محفظة في فوري.** أرقام دفع بس، للأسباب اللي فوق. - **مفيش إلغاء ولا كروت محفوظة على Geidea.** الاسترداد مغلّف؛ Geidea بتذكر Void للمدفوعات المصرّح بها وغير المحصّلة بس، ومفيش وصف إندبوينت منشور، فمش بنخمّن. +- **مفيش استرداد في Telr.** Telr موثّقة الاسترداد على منتج تاني، فالدرايفر بياخد المدفوعات ويقرا الحالة بس بدل ما يدّعي مسار استرداد ماتأسّسش عليه. - **مفيش إعادة قراءة للدفعة في Xendit.** Xendit موثّقة توكن callback مش HMAC في الفلو ده، والدرايفر مابيجيبش الدفعة بعد كده؛ لو عايز نظرة تانية قبل التسليم، نادي API Xendit من تطبيقك. - **مفيش capture ولا void في Square.** الـ Payments API بتاعة Square بتقدر تكمّل capture مؤجّل؛ الباكدج بيلف الاسترداد بس، فالدفعة `APPROVED` بتفضل pending هنا. - **مفيش capture ولا قراءة أوردرات في Klarna.** الـ Order Management API بتاعت Klarna بتعمل capture وبتقرا الأوردرات كمان؛ الباكدج بيلف الاسترداد بس، وخطوة تثبيت الأوردر سايبها لـ `placeOrder()`. diff --git a/src/Gateways/Telr/TelrClient.php b/src/Gateways/Telr/TelrClient.php new file mode 100644 index 0000000..79d73b2 --- /dev/null +++ b/src/Gateways/Telr/TelrClient.php @@ -0,0 +1,95 @@ + $payload + * @return array + */ + public function createOrder(array $payload): array + { + $response = $this->transport('telr', 'create order', fn (): Response => $this->request()->post($this->url(), $payload)); + + return $this->unwrap('create order', $response); + } + + /** + * POST /gateway/order.json {method: check} - the documented status read. + * + * @return array + */ + public function checkOrder(string $orderRef): array + { + $payload = [ + 'method' => 'check', + 'store' => $this->store, + 'authkey' => $this->authKey, + 'order' => ['ref' => $orderRef], + ]; + + $response = $this->transport('telr', 'check order', fn (): Response => $this->request()->post($this->url(), $payload)); + + return $this->unwrap('check order', $response); + } + + private function request(): PendingRequest + { + return Http::acceptJson()->timeout($this->timeout); + } + + /** + * @return array + */ + private function unwrap(string $operation, Response $response): array + { + if ($response->failed()) { + throw GatewayException::fromResponse('telr', $operation, $response->status(), $response->json()); + } + + $body = $response->json(); + + if (! is_array($body)) { + throw GatewayException::invalidResponse('telr', $operation); + } + + return $body; + } + + private function url(): string + { + return rtrim($this->baseUrl, '/').'/order.json'; + } +} diff --git a/src/Gateways/Telr/TelrGateway.php b/src/Gateways/Telr/TelrGateway.php new file mode 100644 index 0000000..ee07661 --- /dev/null +++ b/src/Gateways/Telr/TelrGateway.php @@ -0,0 +1,348 @@ + PaymentStatus::Succeeded, + 'H' => PaymentStatus::Pending, + 'D' => PaymentStatus::Failed, + 'C' => PaymentStatus::Failed, + 'E' => PaymentStatus::Failed, + ]; + + /** + * The transaction fields Telr documents for the advice hash, in order. + */ + private const SIGNED_FIELDS = [ + 'tran_store', + 'tran_type', + 'tran_class', + 'tran_test', + 'tran_ref', + 'tran_prevref', + 'tran_firstref', + 'tran_currency', + 'tran_amount', + 'tran_cartid', + 'tran_desc', + 'tran_status', + 'tran_authcode', + 'tran_authmessage', + ]; + + /** + * @param array $config + */ + public function __construct( + private readonly array $config, + private readonly ?IdempotencyStore $idempotency = null, + private readonly ?TelrClient $client = null, + ) {} + + public function name(): string + { + return self::NAME; + } + + public function createPayment(PaymentRequest $request): PaymentSession + { + $this->assertConfigured(['store', 'auth_key', 'authorised_url', 'declined_url', 'cancelled_url']); + + return IdempotentCreation::run( + $this->idempotency, + $request->idempotencyKey, + $this->integer('idempotency_ttl', 86400), + function () use ($request): PaymentSession { + $authorised = $request->redirectionUrl ?? (string) $this->string('authorised_url'); + + $payload = [ + 'method' => 'create', + 'store' => $this->integer('store', 0), + 'authkey' => (string) $this->string('auth_key'), + 'framed' => $this->integer('framed', 0), + 'order' => [ + // Telr caps the cart id at 63 characters. + 'cartid' => mb_substr($request->reference, 0, 63), + 'test' => (string) $this->integer('test_mode', 0), + 'amount' => $request->amount->toDecimalString(), + 'currency' => $request->amount->currency, + 'description' => mb_substr($request->description ?? $request->reference, 0, 63), + 'trantype' => (string) ($this->string('transaction_type') ?? 'sale'), + ], + 'return' => [ + 'authorised' => $authorised, + 'declined' => (string) $this->string('declined_url'), + 'cancelled' => (string) $this->string('cancelled_url'), + ], + ]; + + $body = $this->client()->createOrder($payload); + $order = is_array($body['order'] ?? null) ? $body['order'] : []; + + $ref = $order['ref'] ?? null; + $url = $order['url'] ?? null; + + if (! is_scalar($ref) || (string) $ref === '' || ! is_string($url) || $url === '') { + throw GatewayException::invalidResponse(self::NAME, 'create order'); + } + + return new PaymentSession( + gateway: self::NAME, + reference: $request->reference, + intentionId: (string) $ref, + orderId: $request->reference, + checkoutUrl: $url, + raw: $body, + ); + }, + ); + } + + /** + * POST /gateway/order.json {method: check}: the documented status read. + */ + public function fetchPaymentStatus(string $orderRef): OperationResult + { + $this->assertConfigured(['store', 'auth_key']); + + $orderRef = trim($orderRef); + + if ($orderRef === '') { + throw new InvalidPaymentRequestException('A Telr status read needs the order reference Telr returned.'); + } + + $body = $this->client()->checkOrder($orderRef); + $order = is_array($body['order'] ?? null) ? $body['order'] : []; + $status = is_array($order['status'] ?? null) ? $order['status'] : []; + + return new OperationResult( + gateway: self::NAME, + operation: 'status', + status: $this->statusText($status['text'] ?? null), + transactionId: is_scalar($order['ref'] ?? null) ? (string) $order['ref'] : $orderRef, + orderId: is_string($order['cartid'] ?? null) ? $order['cartid'] : null, + amount: $this->money($order['amount'] ?? null, $order['currency'] ?? null), + raw: $body, + ); + } + + /** + * Telr's transaction advice: form fields, authenticated with a SHA1 hash + * of the secret key and the documented field list, colon-joined. + * + * @param array $payload + * @param array $query + * @param array $headers + */ + public function verifyAndParseWebhook(array $payload, array $query = [], array $headers = []): WebhookEvent + { + unset($payload['_raw']); + + $secret = $this->string('secret_key'); + + if ($secret === null) { + throw ConfigurationException::missing(self::NAME, ['tahseel.drivers.telr.secret_key']); + } + + $received = $payload['tran_check'] ?? null; + + if (! is_string($received) || $received === '') { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $string = $secret; + + foreach (self::SIGNED_FIELDS as $field) { + $string .= ':'.$this->field($payload, $field); + } + + if (! hash_equals(sha1($string), strtolower(trim($received)))) { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $status = $this->transactionStatus($payload['tran_status'] ?? null); + + return new WebhookEvent( + gateway: self::NAME, + status: $status, + transactionId: $this->field($payload, 'tran_ref'), + orderId: $this->field($payload, 'tran_order') ?: null, + reference: $this->field($payload, 'tran_cartid') ?: null, + amount: $this->money($payload['tran_amount'] ?? null, $payload['tran_currency'] ?? null) + ?? Money::minor(0, (string) ($this->string('currency') ?? 'AED')), + success: $status === PaymentStatus::Succeeded, + pending: $status === PaymentStatus::Pending, + refunded: false, + voided: false, + createdAt: $this->field($payload, 'actual_payment_date') ?: null, + raw: $payload, + ); + } + + /** + * @param array $payload + */ + private function field(array $payload, string $name): string + { + $value = $payload[$name] ?? null; + + if (! is_scalar($value)) { + return ''; + } + + // The docs are explicit: percent-encoded characters are decoded + // before the hash is computed. + return trim(rawurldecode((string) $value)); + } + + private function transactionStatus(mixed $status): PaymentStatus + { + $code = strtoupper(trim((string) $status)); + + if ($code === '') { + throw GatewayException::invalidResponse(self::NAME, 'webhook'); + } + + return self::TRANSACTION_STATUSES[$code] ?? throw InvalidWebhookException::unsupportedType(self::NAME, 'transaction status ['.$code.']'); + } + + /** + * The check endpoint answers with a human-readable status. The documented + * messages are matched here, and anything unrecognised is refused. + */ + private function statusText(mixed $text): PaymentStatus + { + $text = strtolower(trim((string) $text)); + + return match (true) { + $text === '' => throw GatewayException::invalidResponse(self::NAME, 'check order'), + $text === 'authorised' => PaymentStatus::Succeeded, + $text === 'pending' => PaymentStatus::Pending, + str_contains($text, 'on hold') => PaymentStatus::Pending, + str_contains($text, 'declin'), str_contains($text, 'cancel'), str_contains($text, 'not authorised') => PaymentStatus::Failed, + default => throw InvalidWebhookException::unsupportedType(self::NAME, 'order status ['.$text.']'), + }; + } + + private function money(mixed $amount, mixed $currency): ?Money + { + if (! is_string($amount) || trim($amount) === '' || ! is_numeric($amount)) { + return null; + } + + if (! is_string($currency) || $currency === '') { + return null; + } + + return Money::of($amount, strtoupper($currency)); + } + + private function client(): TelrClient + { + if ($this->client instanceof TelrClient) { + return $this->client; + } + + return new TelrClient( + $this->string('base_url') ?? 'https://secure.telr.com/gateway', + $this->integer('store', 0), + (string) $this->string('auth_key'), + $this->integer('timeout', 30), + ); + } + + /** + * @param list $required + */ + private function assertConfigured(array $required): void + { + $missing = []; + + foreach ($required as $key) { + if (! $this->present($key)) { + $missing[] = 'tahseel.drivers.telr.'.$key; + } + } + + if ($missing !== []) { + throw ConfigurationException::missing(self::NAME, $missing); + } + } + + /** + * A key counts as configured when it holds anything but an empty value: + * the store id is a number, not a string. + */ + private function present(string $key): bool + { + $value = $this->config[$key] ?? null; + + if (is_string($value)) { + return trim($value) !== ''; + } + + return $value !== null; + } + + 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 937c730..38a7db1 100644 --- a/src/TahseelManager.php +++ b/src/TahseelManager.php @@ -40,6 +40,7 @@ use Tahseel\Gateways\Square\SquareGateway; use Tahseel\Gateways\Stripe\StripeGateway; use Tahseel\Gateways\Tap\TapGateway; +use Tahseel\Gateways\Telr\TelrGateway; use Tahseel\Gateways\Xendit\XenditGateway; /** @@ -210,6 +211,11 @@ protected function createAdyenDriver(): Gateway return new AdyenGateway($this->configuration(AdyenGateway::NAME), $this->idempotencyStore()); } + protected function createTelrDriver(): Gateway + { + return new TelrGateway($this->configuration(TelrGateway::NAME), $this->idempotencyStore()); + } + protected function createXenditDriver(): Gateway { return new XenditGateway($this->configuration(XenditGateway::NAME), $this->idempotencyStore()); diff --git a/tests/Feature/TelrGatewayTest.php b/tests/Feature/TelrGatewayTest.php new file mode 100644 index 0000000..19e685b --- /dev/null +++ b/tests/Feature/TelrGatewayTest.php @@ -0,0 +1,232 @@ + $payload + */ +function telrSign(array $payload, string $secret = 'telr-secret-key'): string +{ + $fields = [ + 'tran_store', 'tran_type', 'tran_class', 'tran_test', 'tran_ref', + 'tran_prevref', 'tran_firstref', 'tran_currency', 'tran_amount', + 'tran_cartid', 'tran_desc', 'tran_status', 'tran_authcode', 'tran_authmessage', + ]; + + $string = $secret; + + foreach ($fields as $field) { + $value = $payload[$field] ?? ''; + $string .= ':'.(is_scalar($value) ? trim(rawurldecode((string) $value)) : ''); + } + + return sha1($string); +} + +/** + * @return array + */ +function telrAdvice(string $status = 'A'): array +{ + return [ + 'tran_store' => '1234', + 'tran_type' => 'sale', + 'tran_class' => 'ecom', + 'tran_test' => '1', + 'tran_ref' => 'TST-241210-123456', + 'tran_prevref' => 'TST-241210-123456', + 'tran_firstref' => 'TST-241210-123456', + 'tran_currency' => 'AED', + 'tran_amount' => '95.00', + 'tran_cartid' => 'ORDER-6112', + 'tran_desc' => 'Order ORDER-6112', + 'tran_status' => $status, + 'tran_authcode' => 'AUTH01', + 'tran_authmessage' => 'Authorised', + ]; +} + +it('resolves the telr driver by name', function () { + expect(Tahseel::gateway('telr'))->toBeInstanceOf(TelrGateway::class) + ->and(Tahseel::gateway('telr')->name())->toBe('telr'); +}); + +it('creates a hosted payment page and returns its url', function () { + Http::fake([ + 'secure.telr.com/gateway/order.json' => Http::response($this->fixture('telr/create-session.json'), 200), + ]); + + $session = Tahseel::gateway('telr')->createPayment(telrRequest()); + + expect($session->gateway)->toBe('telr') + ->and($session->intentionId)->toBe('A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763') + ->and($session->checkoutUrl)->toContain('https://secure.telr.com/gateway/process.html?o='); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://secure.telr.com/gateway/order.json' + && $request['method'] === 'create' + && $request['store'] === 1234 + && $request['authkey'] === 'mykey1234' + && $request['order']['cartid'] === 'ORDER-6112' + && $request['order']['amount'] === '95.00' + && $request['order']['currency'] === 'AED' + && $request['order']['test'] === '1' + && $request['order']['trantype'] === 'sale' + && $request['return']['authorised'] === 'https://example.test/checkout/done' + && $request['return']['declined'] === 'https://example.test/checkout/declined' + && $request['return']['cancelled'] === 'https://example.test/checkout/cancelled'); +}); + +it('demands the store, the auth key and the return urls', function () { + config()->set('tahseel.drivers.telr.auth_key', null); + + Tahseel::gateway('telr')->createPayment(telrRequest()); +})->throws(ConfigurationException::class); + +it('verifies a transaction advice and reports it as paid', function () { + $payload = telrAdvice('A'); + $payload['tran_check'] = telrSign($payload); + + $event = Tahseel::gateway('telr')->verifyAndParseWebhook($payload); + + expect($event->gateway)->toBe('telr') + ->and($event->status)->toBe(PaymentStatus::Succeeded) + ->and($event->success)->toBeTrue() + ->and($event->transactionId)->toBe('TST-241210-123456') + ->and($event->reference)->toBe('ORDER-6112') + ->and($event->amount?->toMinor())->toBe(9500) + ->and($event->amount?->currency)->toBe('AED'); +}); + +it('rejects an advice with the wrong hash', function () { + $payload = telrAdvice('A'); + $payload['tran_check'] = sha1('not-the-right-string'); + + expect(fn () => Tahseel::gateway('telr')->verifyAndParseWebhook($payload)) + ->toThrow(InvalidSignatureException::class); +}); + +it('rejects an advice with no hash at all', function () { + expect(fn () => Tahseel::gateway('telr')->verifyAndParseWebhook(telrAdvice('A'))) + ->toThrow(InvalidSignatureException::class); +}); + +it('decodes percent-encoded values before hashing, as the docs say', function () { + $payload = telrAdvice('A'); + $payload['tran_desc'] = 'Order%20ORDER-6112'; + $payload['tran_check'] = telrSign($payload); + + $event = Tahseel::gateway('telr')->verifyAndParseWebhook($payload); + + expect($event->status)->toBe(PaymentStatus::Succeeded); +}); + +it('treats a missing signed field as an empty value, as the docs say', function () { + $payload = telrAdvice('A'); + unset($payload['tran_authmessage']); + $payload['tran_check'] = telrSign($payload); + + $event = Tahseel::gateway('telr')->verifyAndParseWebhook($payload); + + expect($event->status)->toBe(PaymentStatus::Succeeded); +}); + +it('reports an authorised-but-held transaction as pending', function () { + $payload = telrAdvice('H'); + $payload['tran_check'] = telrSign($payload); + + $event = Tahseel::gateway('telr')->verifyAndParseWebhook($payload); + + expect($event->status)->toBe(PaymentStatus::Pending) + ->and($event->pending)->toBeTrue() + ->and($event->success)->toBeFalse(); +}); + +it('maps a declined transaction to failed', function () { + $payload = telrAdvice('D'); + $payload['tran_check'] = telrSign($payload); + + expect(Tahseel::gateway('telr')->verifyAndParseWebhook($payload)->status)->toBe(PaymentStatus::Failed); +}); + +it('refuses a transaction status outside the documented set', function () { + $payload = telrAdvice('Z'); + $payload['tran_check'] = telrSign($payload); + + Tahseel::gateway('telr')->verifyAndParseWebhook($payload); +})->throws(InvalidWebhookException::class); + +it('reads a transaction status through the documented check call', function () { + Http::fake([ + 'secure.telr.com/gateway/order.json' => Http::response($this->fixture('telr/check-authorised.json'), 200), + ]); + + $result = Tahseel::gateway('telr')->fetchPaymentStatus('A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763'); + + expect($result->status)->toBe(PaymentStatus::Succeeded) + ->and($result->orderId)->toBe('ORDER-6112') + ->and($result->amount?->toMinor())->toBe(9500); + + Http::assertSent(fn (Request $request): bool => $request['method'] === 'check' + && $request['store'] === 1234 + && $request['order']['ref'] === 'A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763'); +}); + +it('reports a pending check as pending', function () { + Http::fake([ + 'secure.telr.com/gateway/order.json' => Http::response($this->fixture('telr/check-pending.json'), 200), + ]); + + expect(Tahseel::gateway('telr')->fetchPaymentStatus('A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763')->status) + ->toBe(PaymentStatus::Pending); +}); + +it('refuses a status text it does not recognise', function () { + $fixture = $this->fixture('telr/check-pending.json'); + $fixture['order']['status']['text'] = 'Something new'; + + Http::fake([ + 'secure.telr.com/gateway/order.json' => Http::response($fixture, 200), + ]); + + Tahseel::gateway('telr')->fetchPaymentStatus('A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763'); +})->throws(InvalidWebhookException::class); + +it('demands an order reference for a status read', function () { + Tahseel::gateway('telr')->fetchPaymentStatus(' '); +})->throws(InvalidPaymentRequestException::class); + +it('surfaces a telr error instead of inventing a status', function () { + Http::fake([ + 'secure.telr.com/gateway/order.json' => Http::response(['error' => ['code' => 4, 'message' => 'Invalid store ID']], 400), + ]); + + Tahseel::gateway('telr')->createPayment(telrRequest()); +})->throws(GatewayException::class); diff --git a/tests/Fixtures/telr/check-authorised.json b/tests/Fixtures/telr/check-authorised.json new file mode 100644 index 0000000..69cfbe8 --- /dev/null +++ b/tests/Fixtures/telr/check-authorised.json @@ -0,0 +1,17 @@ +{ + "method": "check", + "trace": "4000/521489/64a6f264", + "order": { + "ref": "A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763", + "url": "https://secure.telr.com/gateway/process.html?o=A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763", + "cartid": "ORDER-6112", + "test": 1, + "amount": "95.00", + "currency": "AED", + "description": "Order ORDER-6112", + "status": { + "code": 2, + "text": "Authorised" + } + } +} diff --git a/tests/Fixtures/telr/check-pending.json b/tests/Fixtures/telr/check-pending.json new file mode 100644 index 0000000..cdba69e --- /dev/null +++ b/tests/Fixtures/telr/check-pending.json @@ -0,0 +1,15 @@ +{ + "method": "check", + "trace": "4000/521489/64a6f264", + "order": { + "ref": "A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763", + "cartid": "ORDER-6112", + "test": 1, + "amount": "95.00", + "currency": "AED", + "status": { + "code": 1, + "text": "Pending" + } + } +} diff --git a/tests/Fixtures/telr/create-session.json b/tests/Fixtures/telr/create-session.json new file mode 100644 index 0000000..8d162d6 --- /dev/null +++ b/tests/Fixtures/telr/create-session.json @@ -0,0 +1,6 @@ +{ + "order": { + "ref": "A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763", + "url": "https://secure.telr.com/gateway/process.html?o=A08299C25E0644F309FE2DE42F292BE7D02298F807B3C1CE00C47DC88C9BA763" + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 1ff28fc..94db49a 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -221,6 +221,21 @@ protected function defineEnvironment($app): void 'timeout' => 10, ]); + $app['config']->set('tahseel.drivers.telr', [ + 'base_url' => 'https://secure.telr.com/gateway', + 'store' => 1234, + 'auth_key' => 'mykey1234', + 'secret_key' => 'telr-secret-key', + 'test_mode' => 1, + 'transaction_type' => 'sale', + 'framed' => 0, + 'authorised_url' => 'https://example.test/checkout/done', + 'declined_url' => 'https://example.test/checkout/declined', + 'cancelled_url' => 'https://example.test/checkout/cancelled', + 'currency' => 'AED', + 'timeout' => 10, + ]); + $app['config']->set('tahseel.drivers.xendit', [ 'base_url' => 'https://api.xendit.co', 'secret_key' => 'xnd_development_secret_key',