diff --git a/CHANGELOG.md b/CHANGELOG.md index 4149a65..6772265 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to Tahseel are documented here. This project follows [Semant ### Added +- **Tamara driver** (`Tahseel::gateway('tamara')`), the eighteenth international driver and the second buy-now-pay-later one, for Saudi Arabia, the UAE, Bahrain, Kuwait and Oman: hosted checkout session via `POST /checkout` with major-unit `{amount, currency}` objects, consumer, items, risk assessment and the three merchant redirect urls; notifications authenticated the way Tamara documents it - an HS256 JWT signed with the merchant's notification token, arriving both as `Authorization: Bearer` and as the `tamaraToken` query parameter, verified in the driver with a constant-time compare, an expiry check and a refusal of any other algorithm; the documented event set mapped and an unknown event refused; `approved` reported pending and `authorised` paid, with the documented `authorise()` call exposed as `authorise()`; refunds through `/payments/simplified-refund/{orderId}` requiring their amount; config + `TAMARA_*` env vars, and 16 fixture tests. Capture is not wrapped, and the README says why. Fixture-tested only, no live account has run it yet. - **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. diff --git a/README.md b/README.md index 1c7b605..9a84a1f 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-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. +Tahseel gives you one clean API for starting a payment, verifying the gateway's callback, and getting a normalised result. Twenty-seven 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) **Tabby** (BNPL checkout across the UAE and Saudi Arabia + capture, refunds and header-authenticated webhooks) and **Tamara** (BNPL across Saudi Arabia and the Gulf + JWT-authenticated notifications, with the documented authorise step). 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, Tabby and Tamara 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.** > @@ -49,6 +49,7 @@ Tahseel gives you one clean API for starting a payment, verifying the gateway's | **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 | +| **Tamara** | `Tahseel::gateway('tamara')` - hosted checkout session (`POST /checkout`) | an HS256 JWT signed with your notification token, arriving both as `Authorization: Bearer` and as the `tamaraToken` query parameter; the driver verifies the signature itself, checks the expiry, and refuses any algorithm other than HS256 | full or partial, amount required, addressed by Tamara's `order_id` | not wrapped: Tamara's capture is a documented call that wants the order's items back, so `authorise()` is the step this driver implements | Saudi Arabia, UAE, Bahrain, Kuwait, Oman; MAJOR-unit amounts in `{amount, currency}`; `approved` is pending and `authorised` is paid; `authorise()` is the documented step after the approved notification; 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) | @@ -303,6 +304,7 @@ $result->succeeded(); // true, false, or false while pending | 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 | +| Tamara | full or partial, amount required | not implemented | Tamara's order id | The details that bite: @@ -999,6 +1001,36 @@ Four Tabby details worth knowing: Fixture-tested only, no Tabby account has run it yet. +## Tamara + +Tamara is the eighteenth international driver and the second buy-now-pay-later one, for Saudi Arabia, the UAE, Bahrain, Kuwait and Oman. Its checkout is hosted, but its flow has one step Tabby's does not: after Tamara approves an order you have to confirm it before it counts as paid. + +```dotenv +TAMARA_BASE_URL=https://api.tamara.co # sandbox: https://api-sandbox.tamara.co +TAMARA_API_TOKEN=... +TAMARA_NOTIFICATION_TOKEN=... # the HS256 secret Tamara signs webhooks with +TAMARA_COUNTRY_CODE=SA +TAMARA_LOCALE=en_US +TAMARA_SUCCESS_URL=https://your-app.test/checkout/done +TAMARA_FAILURE_URL=https://your-app.test/checkout/failed +TAMARA_CANCEL_URL=https://your-app.test/checkout/cancel +``` + +```php +$session = Tahseel::gateway('tamara')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +Four Tamara details worth knowing: + +- **Notifications are a JWT, not a body signature.** Tamara sends `tamaraToken` both as `Authorization: Bearer` and as the `tamaraToken` query parameter. It is an HS256 JWT signed with your notification token. The driver verifies that signature with `hash_hmac` and a constant-time compare, checks the expiry, and refuses any other algorithm rather than accepting an unsigned token. +- **`approved` is not paid.** Tamara's docs are explicit that the order becomes paid at `authorised`, and that you call `POST /orders/{order_id}/authorise` after the approved notification (unless Tamara's auto-authorisation is on for your account). The driver reports `approved` as pending and exposes that call as `authorise()`, so nothing is fulfilled before it is made. +- **Amounts are major units in an object.** `{"amount": 300, "currency": "SAR"}`, with 2 decimals by default and 3 for BHD, KWD and OMR. The currencies are the ones Tamara operates in, and `country_code` is one of `SA`, `AE`, `BH`, `KW`, `OM`. +- **Capture is not wrapped.** Tamara's capture call wants the order's items sent back with it. That is a bigger surface than this driver claims, so it is left to your own call against the documented API and the README says so rather than pretending otherwise. Refunds need their amount: Tamara has no amount-less full refund. + +Fixture-tested only, no Tamara 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 6dc72c9..626faca 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, Tabby 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, Tamara and manual transfers (Vodafone Cash, InstaPay) behind one gateway contract with signed webhook verification. Experimental.", "keywords": [ "laravel", "payments", @@ -69,7 +69,9 @@ "payu", "poland", "pln", - "tabby" + "tabby", + "tamara", + "saudi-arabia" ], "license": "MIT", "require": { diff --git a/config/tahseel.php b/config/tahseel.php index 1e6e783..c4be5e5 100644 --- a/config/tahseel.php +++ b/config/tahseel.php @@ -477,6 +477,40 @@ 'idempotency_ttl' => (int) env('PAYTABS_IDEMPOTENCY_TTL', 86400), ], + 'tamara' => [ + // Tamara's sandbox is https://api-sandbox.tamara.co and its + // production API https://api.tamara.co. + 'base_url' => env('TAMARA_BASE_URL', 'https://api.tamara.co'), + + // The API token from Tamara's partner portal. + 'api_token' => env('TAMARA_API_TOKEN'), + + // The notification token, which is the HS256 secret Tamara signs + // its webhook JWTs with. + 'notification_token' => env('TAMARA_NOTIFICATION_TOKEN'), + + // Tamara operates in SA, AE, BH, KW and OM. + 'country_code' => env('TAMARA_COUNTRY_CODE', 'SA'), + 'locale' => env('TAMARA_LOCALE', 'en_US'), + 'platform' => env('TAMARA_PLATFORM', 'web'), + 'currency' => env('TAMARA_CURRENCY', 'SAR'), + 'item_type' => env('TAMARA_ITEM_TYPE', 'Physical'), + + 'success_url' => env('TAMARA_SUCCESS_URL'), + 'failure_url' => env('TAMARA_FAILURE_URL'), + 'cancel_url' => env('TAMARA_CANCEL_URL'), + + 'shipping_line1' => env('TAMARA_SHIPPING_LINE1'), + 'shipping_region' => env('TAMARA_SHIPPING_REGION'), + 'shipping_city' => env('TAMARA_SHIPPING_CITY'), + 'account_creation_date' => env('TAMARA_ACCOUNT_CREATION_DATE'), + 'total_order_count' => (int) env('TAMARA_TOTAL_ORDER_COUNT', 0), + + 'timeout' => (int) env('TAMARA_TIMEOUT', 30), + 'webhook_tolerance' => (int) env('TAMARA_WEBHOOK_TOLERANCE', 300), + 'idempotency_ttl' => (int) env('TAMARA_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 diff --git a/docs/ar/README.md b/docs/ar/README.md index 3d32bff..619f768 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) و**Tabby** (تقسيط في الإمارات والسعودية + capture واسترداد وwebhooks متأمّنة بهيدر). ودرايفر الخمسة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr وViva.com وPayU وTabby متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. + فيه لحد دلوقتي سبعة وعشرين درايفر لبوابات: **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 متأمّنة بهيدر) و**Tamara** (تقسيط في السعودية والخليج + إشعارات متأمّنة بـ JWT مع خطوة authorise الموثّقة). ودرايفر الخمسة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr وViva.com وPayU وTabby وTamara متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. > **الحالة: 0.3.0، نسخة تجريبية (EXPERIMENTAL). ماتستلمش فلوس حقيقية بيها لسه.** > @@ -40,6 +40,7 @@ | **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` مدفوعة؛ متجرب على بيانات مسجلة بس لسه | +| **Tamara** | `Tahseel::gateway('tamara')` — جلسة checkout مستضافة (`POST /checkout`) | JWT بـ HS256 متوقّع بمفتاح الإشعارات بتاعك، وبييجي في `Authorization: Bearer` وكمان في query parameter اسمه `tamaraToken`؛ الدرايفر بيتحقق من التوقيع بنفسه، ويتشيك على الانتهاء، ويرفض أي خوارزمية غير HS256 | كامل أو جزئي، المبلغ مطلوب، برقم `order_id` بتاع Tamara | مش متغلّف: capture عند Tamara نداء موثّق بيطلب أصناف الأمر معاه، فاللي الدرايفر بيعمله هو `authorise()` | السعودية والإمارات والبحرين والكويت وعُمان؛ المبالغ بوحدات رئيسية في `{amount, currency}`؛ `approved` معلّقة و`authorised` مدفوعة؛ `authorise()` هي الخطوة الموثّقة بعد إشعار الموافقة؛ متجرب على بيانات مسجلة بس لسه | | **يدوي** (فودافون كاش، إنستاباي) | `Tahseel::gateway('manual')` — مرجع، تحويل على محفظتك، وقرار من حد من فريقك | مفيش: التأكيد من اللوحة | مش منطبق | مش منطبق | مفيش API تجار تكلّمه؛ واللوحة مقفولة لحد ما تحدد Gate ability | | **محافظ وتقسيط وميزة وإنستاباي** | عن طريق وسائل Paymob أو Kashier أو Geidea | - | - | - | مفيش API تجار معلن لأي منهم، شوف القسم تحت | @@ -260,6 +261,7 @@ $result->succeeded(); | Xendit | كامل أو جزئي، المبلغ بأصغر وحدة ومطلوب؛ `PENDING` لحد ما webhook الاسترداد يحسمها | مش مدعوم | رقم `payment_id` بتاع Xendit اللي webhook الجلسة بيجيبه | | PayU | كامل (من غير مبلغ، زي ما موثّق) أو جزئي، المبلغ بأصغر وحدة | مش مدعوم | رقم الأمر بتاع PayU | | Tabby | كامل أو جزئي، المبلغ مطلوب | مش مدعوم | رقم الدفع بتاع Tabby | +| Tamara | كامل أو جزئي، المبلغ مطلوب | مش مدعوم | رقم الأمر بتاع Tamara | التفاصيل اللي بتوجع: @@ -952,6 +954,36 @@ header('Location: '.$session->checkoutUrl); متجرب على بيانات مسجلة بس، مفيش حساب Tabby حقيقي شغّال لسه. +## Tamara + +Tamara هو الداريفر الدولي الثامن عشر وتاني واحد للتقسيط، للسعودية والإمارات والبحرين والكويت وعُمان. الـ checkout مستضاف، بس في خطوة Tabby ماعندهاش: بعد ما Tamara توافق على الأمر، لازم تأكّده انت قبل ما يتحسب مدفوع. + +```dotenv +TAMARA_BASE_URL=https://api.tamara.co # ساندبوكس: https://api-sandbox.tamara.co +TAMARA_API_TOKEN=... +TAMARA_NOTIFICATION_TOKEN=... # مفتاح HS256 اللي Tamara بتوقّع بيه الـ webhooks +TAMARA_COUNTRY_CODE=SA +TAMARA_LOCALE=en_US +TAMARA_SUCCESS_URL=https://your-app.test/checkout/done +TAMARA_FAILURE_URL=https://your-app.test/checkout/failed +TAMARA_CANCEL_URL=https://your-app.test/checkout/cancel +``` + +```php +$session = Tahseel::gateway('tamara')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +أربع تفاصيل مهمة في Tamara: + +- **الإشعارات JWT مش توقيع على البودي.** Tamara بتبعت `tamaraToken` في `Authorization: Bearer` وكمان في query parameter اسمه `tamaraToken`. ده JWT بـ HS256 متوقّع بمفتاح الإشعارات بتاعك. الدرايفر بيتحقق من التوقيع بـ `hash_hmac` ومقارنة ثابتة الزمن، ويتشيك على الانتهاء، ويرفض أي خوارزمية تانية بدل ما يقبل توكن من غير توقيع. +- **`approved` مش مدفوعة.** وثائق Tamara صريحة إن الأمر بيبقى مدفوع عند `authorised`، وإنك بتنده `POST /orders/{order_id}/authorise` بعد إشعار الموافقة (إلا لو الـ auto-authorisation شغّال على حسابك). الدرايفر بيرجّع `approved` معلّقة وبيكشف النداء ده كـ `authorise()`، فمفيش حاجة بتتسلّم قبل ما يتعمل. +- **المبالغ بوحدات رئيسية في object.** `{"amount": 300, "currency": "SAR"}`، بمنزلتين عشريتين افتراضيًا و3 لـ BHD وKWD وOMR. والعملات اللي Tamara بتشتغل بيها، و`country_code` واحد من `SA` و`AE` و`BH` و`KW` و`OM`. +- **الـ capture مش متغلّف.** نداء الـ capture عند Tamara بيطلب أصناف الأمر معاه. ده سطح أكبر من اللي الدرايفر بيدّعيه، فسايبه لنداء بتعمله انت على الـ API الموثّق، والـ README بيقول كده بدل ما يدّعي غير كده. والاسترداد بيطلب مبلغه: Tamara ماعندهاش استرداد كامل من غير مبلغ. + +متجرب على بيانات مسجلة بس، مفيش حساب Tamara حقيقي شغّال لسه. + ## الدفع اليدوي: فودافون كاش وإنستاباي فودافون كاش وإنستاباي مفيش لهم API تجار، فالطريقة الصادقة لقبولهم هي الطريقة اللي المحلات المصرية بتعملها فعلاً: العميل يحوّل على محفظتك أو عنوان إنستاباي بتاعك، يقولك رقم العملية أو يرفع صورة التحويل، وحد من فريقك يأكد إن الفلوس وصلت. الباكدج بيوفّر ده كدرايفر اسمه `manual`. diff --git a/src/Gateways/Tamara/TamaraClient.php b/src/Gateways/Tamara/TamaraClient.php new file mode 100644 index 0000000..12fb844 --- /dev/null +++ b/src/Gateways/Tamara/TamaraClient.php @@ -0,0 +1,105 @@ + $payload + * @return array + */ + public function createCheckout(array $payload): array + { + return $this->unwrap('create checkout', $this->request()->post($this->url('checkout'), $payload)); + } + + /** + * GET /merchants/orders/{orderId} - the order's current state. + * + * @return array + */ + public function getOrder(string $orderId): array + { + return $this->unwrap('get order', $this->request()->get($this->url('merchants/orders/'.rawurlencode($orderId)))); + } + + /** + * POST /orders/{orderId}/authorise - confirms an approved order. + * + * @return array + */ + public function authorise(string $orderId): array + { + return $this->unwrap('authorise', $this->request()->post($this->url('orders/'.rawurlencode($orderId).'/authorise'))); + } + + /** + * POST /payments/simplified-refund/{orderId} - a full or partial refund. + * + * @param array $payload + * @return array + */ + public function refund(string $orderId, array $payload): array + { + return $this->unwrap('refund', $this->request()->post($this->url('payments/simplified-refund/'.rawurlencode($orderId)), $payload)); + } + + private function request(): PendingRequest + { + return Http::withToken($this->apiToken) + ->acceptJson() + ->timeout($this->timeout); + } + + /** + * @return array + */ + private function unwrap(string $operation, Response $response): array + { + if ($response->failed()) { + throw GatewayException::fromResponse('tamara', $operation, $response->status(), $response->json()); + } + + $body = $response->json(); + + if (! is_array($body)) { + throw GatewayException::invalidResponse('tamara', $operation); + } + + return $body; + } + + private function url(string $path): string + { + return rtrim($this->baseUrl, '/').'/'.ltrim($path, '/'); + } +} diff --git a/src/Gateways/Tamara/TamaraGateway.php b/src/Gateways/Tamara/TamaraGateway.php new file mode 100644 index 0000000..0648cb1 --- /dev/null +++ b/src/Gateways/Tamara/TamaraGateway.php @@ -0,0 +1,539 @@ + PaymentStatus::Pending, + 'approved' => PaymentStatus::Pending, + 'authorised' => PaymentStatus::Succeeded, + 'authorized' => PaymentStatus::Succeeded, + 'partially_captured' => PaymentStatus::Succeeded, + 'fully_captured' => PaymentStatus::Succeeded, + 'partially_refunded' => PaymentStatus::Refunded, + 'fully_refunded' => PaymentStatus::Refunded, + 'canceled' => PaymentStatus::Failed, + 'cancelled' => PaymentStatus::Failed, + 'declined' => PaymentStatus::Failed, + 'expired' => PaymentStatus::Failed, + ]; + + /** + * The documented webhook event types, and the status each one reports. + */ + private const EVENTS = [ + 'order_approved' => PaymentStatus::Pending, + 'order_authorised' => PaymentStatus::Succeeded, + 'order_captured' => PaymentStatus::Succeeded, + 'order_refunded' => PaymentStatus::Refunded, + 'order_canceled' => PaymentStatus::Failed, + 'order_declined' => PaymentStatus::Failed, + 'order_expired' => PaymentStatus::Failed, + ]; + + /** + * @param array $config + */ + public function __construct( + private readonly array $config, + private readonly ?IdempotencyStore $idempotency = null, + private readonly ?TamaraClient $client = null, + ) {} + + public function name(): string + { + return self::NAME; + } + + public function createPayment(PaymentRequest $request): PaymentSession + { + $this->assertConfigured(['api_token', 'notification_token', 'country_code']); + + return IdempotentCreation::run( + $this->idempotency, + $request->idempotencyKey, + $this->integer('idempotency_ttl', 86400), + function () use ($request): PaymentSession { + $body = $this->client()->createCheckout($this->payload($request)); + + $orderId = $body['order_id'] ?? null; + $checkoutUrl = $body['checkout_url'] ?? null; + + if (! is_scalar($orderId) || (string) $orderId === '' || ! is_string($checkoutUrl) || $checkoutUrl === '') { + throw GatewayException::invalidResponse(self::NAME, 'create checkout'); + } + + return new PaymentSession( + gateway: self::NAME, + reference: $request->reference, + intentionId: (string) $orderId, + orderId: (string) $orderId, + checkoutUrl: $checkoutUrl, + raw: $body, + ); + }, + ); + } + + /** + * Tamara authenticates a notification with an HS256 JWT signed with the + * merchant's notification token. The token arrives both as + * `Authorization: Bearer ` and as the `tamaraToken` query parameter. + * + * @param array $payload + * @param array $query + * @param array $headers + */ + public function verifyAndParseWebhook(array $payload, array $query = [], array $headers = []): WebhookEvent + { + $secret = $this->string('notification_token'); + + if ($secret === null) { + throw ConfigurationException::missing(self::NAME, ['tahseel.drivers.tamara.notification_token']); + } + + $token = $this->bearer($headers) ?? (is_scalar($query['tamaraToken'] ?? null) ? (string) $query['tamaraToken'] : null); + + if ($token === null || $token === '') { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $this->assertToken($token, $secret); + + $eventType = $payload['event_type'] ?? null; + + if (! is_string($eventType) || $eventType === '') { + throw GatewayException::invalidResponse(self::NAME, 'webhook'); + } + + $status = self::EVENTS[$eventType] ?? throw InvalidWebhookException::unsupportedType(self::NAME, 'event ['.$eventType.']'); + + $orderId = $payload['order_id'] ?? null; + + if (! is_scalar($orderId) || (string) $orderId === '') { + throw GatewayException::invalidResponse(self::NAME, 'webhook'); + } + + $data = is_array($payload['data'] ?? null) ? $payload['data'] : []; + $amount = null; + + foreach (['captured_amount', 'refunded_amount', 'canceled_amount', 'authorised_amount'] as $key) { + $candidate = $data[$key] ?? null; + + if (is_array($candidate)) { + $amount = $this->money($candidate); + + if ($amount instanceof Money) { + break; + } + } + } + + return new WebhookEvent( + gateway: self::NAME, + status: $status, + transactionId: (string) $orderId, + orderId: (string) $orderId, + reference: is_scalar($payload['order_reference_id'] ?? null) ? (string) $payload['order_reference_id'] : null, + amount: $amount ?? Money::minor(0, (string) ($this->string('currency') ?? 'SAR')), + success: $status === PaymentStatus::Succeeded, + pending: $status === PaymentStatus::Pending, + refunded: $status === PaymentStatus::Refunded, + voided: false, + raw: $payload, + ); + } + + /** + * POST /orders/{orderId}/authorise - Tamara's documented step after the + * approved notification. Until this succeeds the order is not paid. + */ + public function authorise(string $orderId): OperationResult + { + $this->assertConfigured(['api_token']); + + if (trim($orderId) === '') { + throw new InvalidPaymentRequestException('Authorising a Tamara order needs the order id Tamara returned.'); + } + + $body = $this->client()->authorise($orderId); + $status = $this->status($body['status'] ?? 'authorised'); + + return new OperationResult( + gateway: self::NAME, + operation: 'authorise', + status: $status, + transactionId: $orderId, + orderId: $orderId, + raw: $body, + ); + } + + public function refund(RefundRequest $request): OperationResult + { + $this->assertConfigured(['api_token']); + + $orderId = $request->orderId ?? $request->transactionId; + + if (! is_string($orderId) || trim($orderId) === '') { + throw new InvalidPaymentRequestException('A Tamara refund needs the order id Tamara returned.'); + } + + $amount = $request->amount; + + // Tamara's refund request always names the amount it refunds, so a + // refund without one cannot be built from what the docs describe. + if (! $amount instanceof Money) { + throw new InvalidPaymentRequestException('A Tamara refund needs the amount to refund; Tamara has no amount-less full refund.'); + } + + $body = $this->client()->refund($orderId, [ + 'total_amount' => $this->amount($amount), + 'merchant_refund_id' => 'refund-'.$orderId, + 'comment' => mb_substr($request->reason ?? 'Refund for order '.$orderId, 0, 255), + ]); + + return new OperationResult( + gateway: self::NAME, + operation: 'refund', + status: PaymentStatus::Refunded, + transactionId: $orderId, + orderId: $orderId, + amount: $amount, + raw: $body, + ); + } + + /** + * @return array + */ + private function payload(PaymentRequest $request): array + { + $customer = $request->customer; + $firstName = trim($customer->firstName); + $lastName = trim($customer->lastName); + $email = $customer->email; + $phone = trim($customer->phone); + + if ($firstName === '' || $lastName === '') { + throw new InvalidPaymentRequestException('Tamara needs the customer\'s first and last name.'); + } + + if ($phone === '') { + throw new InvalidPaymentRequestException('Tamara needs the customer\'s phone number.'); + } + + $success = $request->redirectionUrl ?? $this->string('success_url'); + $failure = $this->string('failure_url'); + $cancel = $this->string('cancel_url'); + + if (! is_string($success) || $success === '' || $failure === null || $cancel === null) { + throw ConfigurationException::missing(self::NAME, [ + 'tahseel.drivers.tamara.success_url', + 'tahseel.drivers.tamara.failure_url', + 'tahseel.drivers.tamara.cancel_url', + ]); + } + + $currency = $request->amount->currency; + $items = []; + + foreach ($request->items as $item) { + $items[] = [ + 'reference_id' => $item->id ?? mb_substr((string) $item->name, 0, 64), + 'type' => $this->string('item_type') ?? 'Physical', + 'name' => mb_substr($item->name, 0, 255), + 'sku' => mb_substr($item->id ?? $item->name, 0, 128), + 'quantity' => $item->quantity, + 'unit_price' => $this->amount($item->amount), + 'total_amount' => $this->amount($item->amount), + ]; + } + + if ($items === []) { + $items[] = [ + 'reference_id' => $request->reference, + 'type' => $this->string('item_type') ?? 'Physical', + 'name' => mb_substr($request->description ?? $request->reference, 0, 255), + 'sku' => mb_substr($request->reference, 0, 128), + 'quantity' => 1, + 'unit_price' => $this->amount($request->amount), + 'total_amount' => $this->amount($request->amount), + ]; + } + + return [ + 'order_reference_id' => $request->reference, + 'order_number' => $request->reference, + 'description' => mb_substr($request->description ?? 'Order '.$request->reference, 0, 255), + 'country_code' => (string) $this->string('country_code'), + 'locale' => $this->string('locale') ?? 'en_US', + 'platform' => $this->string('platform') ?? 'web', + 'is_mobile' => false, + 'total_amount' => $this->amount($request->amount), + 'shipping_amount' => ['amount' => 0, 'currency' => $currency], + 'tax_amount' => ['amount' => 0, 'currency' => $currency], + 'risk_assessment' => [ + 'is_premium_customer' => false, + 'account_creation_date' => $this->string('account_creation_date') ?? '01-01-2020', + 'total_order_count' => $this->integer('total_order_count', 0), + 'date_first_paid' => null, + 'date_last_paid' => null, + ], + 'consumer' => array_filter([ + 'first_name' => $firstName, + 'last_name' => $lastName, + 'phone_number' => mb_substr($phone, 0, 32), + 'email' => is_string($email) && trim($email) !== '' ? mb_substr(trim($email), 0, 128) : null, + ], static fn (mixed $value): bool => $value !== null && $value !== ''), + 'items' => $items, + 'merchant_url' => [ + 'success' => $success, + 'failure' => $failure, + 'cancel' => $cancel, + ], + 'shipping_address' => [ + 'first_name' => $firstName, + 'last_name' => $lastName, + 'line1' => $this->string('shipping_line1') ?? 'NA', + 'region' => $this->string('shipping_region') ?? 'NA', + 'city' => $this->string('shipping_city') ?? 'NA', + 'country_code' => (string) $this->string('country_code'), + 'phone_number' => mb_substr($phone, 0, 32), + ], + ]; + } + + /** + * @return array{amount: float, currency: string} + */ + private function amount(Money $money): array + { + return [ + 'amount' => $money->toMajor(), + 'currency' => $money->currency, + ]; + } + + /** + * @param array $candidate + */ + private function money(array $candidate): ?Money + { + $amount = $candidate['amount'] ?? null; + $currency = $candidate['currency'] ?? null; + + if (! is_numeric($amount) || ! is_scalar($currency)) { + return null; + } + + $code = strtoupper(trim((string) $currency)); + + if ($code === '') { + return null; + } + + $scale = in_array($code, ['BHD', 'KWD', 'OMR'], true) ? 3 : 2; + + return Money::minor((int) round(((float) $amount) * (10 ** $scale)), $code); + } + + /** + * Verify the HS256 JWT against the merchant's notification token. + */ + private function assertToken(string $token, string $secret): void + { + $parts = explode('.', $token); + + if (count($parts) !== 3) { + throw new InvalidSignatureException(self::NAME.': the notification token is not a signed JWT'); + } + + [$header, $payload, $signature] = $parts; + + $decodedHeader = json_decode($this->base64UrlDecode($header), true); + + if (! is_array($decodedHeader) || strtoupper((string) ($decodedHeader['alg'] ?? '')) !== 'HS256') { + throw new InvalidWebhookException(self::NAME.': the notification token is not signed with HS256, which is the only algorithm Tamara documents'); + } + + $expected = hash_hmac('sha256', $header.'.'.$payload, $secret, true); + + if (! hash_equals($expected, $this->base64UrlDecode($signature))) { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $claims = json_decode($this->base64UrlDecode($payload), true); + + if (! is_array($claims)) { + throw new InvalidWebhookException(self::NAME.': the notification token has no readable claims'); + } + + $expires = $claims['exp'] ?? null; + + if (is_numeric($expires) && (int) $expires < time() - $this->integer('webhook_tolerance', 300)) { + throw new InvalidSignatureException(self::NAME.': the notification token has expired'); + } + } + + private function base64UrlDecode(string $value): string + { + $padded = strtr($value, '-_', '+/'); + $remainder = strlen($padded) % 4; + + if ($remainder !== 0) { + $padded .= str_repeat('=', 4 - $remainder); + } + + $decoded = base64_decode($padded, true); + + if ($decoded === false) { + throw new InvalidSignatureException(self::NAME.': the notification token is not valid base64url'); + } + + return $decoded; + } + + /** + * @param array $headers + */ + private function bearer(array $headers): ?string + { + foreach ($headers as $key => $value) { + if (strtolower((string) $key) !== 'authorization') { + continue; + } + + if (is_array($value)) { + $value = $value[0] ?? null; + } + + if (! is_scalar($value)) { + return null; + } + + $header = trim((string) $value); + + if (stripos($header, 'bearer ') === 0) { + return trim(substr($header, 7)); + } + + return null; + } + + return null; + } + + private function status(mixed $status): PaymentStatus + { + $code = strtolower(trim((string) $status)); + + if ($code === '') { + throw GatewayException::invalidResponse(self::NAME, 'order'); + } + + return self::STATUSES[$code] ?? throw InvalidWebhookException::unsupportedType(self::NAME, 'status ['.$code.']'); + } + + private function client(): TamaraClient + { + if ($this->client instanceof TamaraClient) { + return $this->client; + } + + return new TamaraClient( + $this->string('base_url') ?? 'https://api.tamara.co', + (string) $this->string('api_token'), + $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.tamara.'.$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 1ec650f..4411f1b 100644 --- a/src/TahseelManager.php +++ b/src/TahseelManager.php @@ -41,6 +41,7 @@ use Tahseel\Gateways\Square\SquareGateway; use Tahseel\Gateways\Stripe\StripeGateway; use Tahseel\Gateways\Tabby\TabbyGateway; +use Tahseel\Gateways\Tamara\TamaraGateway; use Tahseel\Gateways\Tap\TapGateway; use Tahseel\Gateways\Telr\TelrGateway; use Tahseel\Gateways\Viva\VivaGateway; @@ -214,6 +215,11 @@ protected function createAdyenDriver(): Gateway return new AdyenGateway($this->configuration(AdyenGateway::NAME), $this->idempotencyStore()); } + protected function createTamaraDriver(): Gateway + { + return new TamaraGateway($this->configuration(TamaraGateway::NAME), $this->idempotencyStore()); + } + protected function createTabbyDriver(): Gateway { return new TabbyGateway($this->configuration(TabbyGateway::NAME), $this->idempotencyStore()); diff --git a/tests/Feature/TamaraGatewayTest.php b/tests/Feature/TamaraGatewayTest.php new file mode 100644 index 0000000..d5814e6 --- /dev/null +++ b/tests/Feature/TamaraGatewayTest.php @@ -0,0 +1,216 @@ + $claims + */ +function tamaraToken(array $claims = [], string $secret = 'tamara-notification-token'): string +{ + $header = tamaraBase64((string) json_encode(['typ' => 'JWT', 'alg' => 'HS256'])); + $payload = tamaraBase64((string) json_encode($claims + ['iss' => 'Tamara', 'iat' => time(), 'exp' => time() + 300])); + $signature = tamaraBase64(hash_hmac('sha256', $header.'.'.$payload, $secret, true)); + + return $header.'.'.$payload.'.'.$signature; +} + +/** + * @return array> + */ +function tamaraHeaders(string $token): array +{ + return ['Authorization' => ['Bearer '.$token]]; +} + +it('resolves the tamara driver by name', function () { + expect(Tahseel::gateway('tamara'))->toBeInstanceOf(TamaraGateway::class) + ->and(Tahseel::gateway('tamara')->name())->toBe('tamara'); +}); + +it('creates a checkout session and returns its url', function () { + Http::fake([ + 'api-sandbox.tamara.co/checkout' => Http::response($this->fixture('tamara/checkout-created.json'), 200), + ]); + + $session = Tahseel::gateway('tamara')->createPayment(tamaraRequest()); + + expect($session->gateway)->toBe('tamara') + ->and($session->intentionId)->toBe('4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3') + ->and($session->checkoutUrl)->toContain('https://checkout.tamara.co/checkout/'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api-sandbox.tamara.co/checkout' + && $request->hasHeader('Authorization', 'Bearer tamara-api-token') + && $request['order_reference_id'] === 'order-1001' + && $request['country_code'] === 'SA' + && $request['locale'] === 'en_US' + && $request['total_amount']['amount'] === 300.0 + && $request['total_amount']['currency'] === 'SAR' + && $request['consumer']['phone_number'] === '566027755' + && $request['items'][0]['total_amount']['currency'] === 'SAR' + && $request['merchant_url']['success'] === 'https://example.test/checkout/done' + && $request['risk_assessment']['total_order_count'] === 3); +}); + +it('demands the country code', function () { + config()->set('tahseel.drivers.tamara.country_code', null); + + Tahseel::gateway('tamara')->createPayment(tamaraRequest()); +})->throws(ConfigurationException::class); + +it('treats an approved order as pending, because approved is not paid', function () { + $event = Tahseel::gateway('tamara')->verifyAndParseWebhook( + $this->fixture('tamara/webhook-approved.json'), + [], + tamaraHeaders(tamaraToken()), + ); + + expect($event->status)->toBe(PaymentStatus::Pending) + ->and($event->pending)->toBeTrue() + ->and($event->success)->toBeFalse() + ->and($event->transactionId)->toBe('4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3') + ->and($event->reference)->toBe('order-1001'); +}); + +it('treats an authorised order as paid', function () { + $event = Tahseel::gateway('tamara')->verifyAndParseWebhook( + $this->fixture('tamara/webhook-authorised.json'), + [], + tamaraHeaders(tamaraToken()), + ); + + expect($event->status)->toBe(PaymentStatus::Succeeded) + ->and($event->success)->toBeTrue(); +}); + +it('reads a refund notification and its amount', function () { + $event = Tahseel::gateway('tamara')->verifyAndParseWebhook( + $this->fixture('tamara/webhook-refunded.json'), + [], + tamaraHeaders(tamaraToken()), + ); + + expect($event->status)->toBe(PaymentStatus::Refunded) + ->and($event->refunded)->toBeTrue() + ->and($event->amount?->toMinor())->toBe(30000) + ->and($event->amount?->currency)->toBe('SAR'); +}); + +it('accepts the token from the query parameter too', function () { + $event = Tahseel::gateway('tamara')->verifyAndParseWebhook( + $this->fixture('tamara/webhook-approved.json'), + ['tamaraToken' => tamaraToken()], + ); + + expect($event->status)->toBe(PaymentStatus::Pending); +}); + +it('rejects a token signed with the wrong secret', function () { + Tahseel::gateway('tamara')->verifyAndParseWebhook( + $this->fixture('tamara/webhook-approved.json'), + [], + tamaraHeaders(tamaraToken([], 'some-other-secret')), + ); +})->throws(InvalidSignatureException::class); + +it('rejects a notification with no token at all', function () { + Tahseel::gateway('tamara')->verifyAndParseWebhook($this->fixture('tamara/webhook-approved.json')); +})->throws(InvalidSignatureException::class); + +it('refuses an algorithm other than the one Tamara documents', function () { + $header = tamaraBase64((string) json_encode(['typ' => 'JWT', 'alg' => 'RS256'])); + $payload = tamaraBase64((string) json_encode(['iss' => 'Tamara', 'exp' => time() + 300])); + $token = $header.'.'.$payload.'.'.tamaraBase64('signature'); + + Tahseel::gateway('tamara')->verifyAndParseWebhook($this->fixture('tamara/webhook-approved.json'), [], tamaraHeaders($token)); +})->throws(InvalidWebhookException::class); + +it('rejects an expired token', function () { + Tahseel::gateway('tamara')->verifyAndParseWebhook( + $this->fixture('tamara/webhook-approved.json'), + [], + tamaraHeaders(tamaraToken(['exp' => time() - 4000])), + ); +})->throws(InvalidSignatureException::class); + +it('refuses an event type outside the documented set', function () { + $payload = $this->fixture('tamara/webhook-approved.json'); + $payload['event_type'] = 'order_shipped'; + + Tahseel::gateway('tamara')->verifyAndParseWebhook($payload, [], tamaraHeaders(tamaraToken())); +})->throws(InvalidWebhookException::class); + +it('authorises an approved order', function () { + Http::fake([ + 'api-sandbox.tamara.co/orders/*/authorise' => Http::response($this->fixture('tamara/authorise-response.json'), 200), + ]); + + $result = Tahseel::gateway('tamara')->authorise('4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3'); + + expect($result->operation)->toBe('authorise') + ->and($result->status)->toBe(PaymentStatus::Succeeded); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api-sandbox.tamara.co/orders/4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3/authorise' + && $request->method() === 'POST'); +}); + +it('refunds with the amount, reference and comment Tamara requires', function () { + Http::fake([ + 'api-sandbox.tamara.co/payments/simplified-refund/*' => Http::response($this->fixture('tamara/refund-response.json'), 200), + ]); + + $result = Tahseel::gateway('tamara')->refund(new RefundRequest( + orderId: '4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3', + amount: Money::minor(30000, 'SAR'), + reason: 'Returned the lego', + )); + + expect($result->status)->toBe(PaymentStatus::Refunded); + + Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/payments/simplified-refund/4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3') + && $request['total_amount']['amount'] === 300.0 + && $request['total_amount']['currency'] === 'SAR' + && is_string($request['merchant_refund_id']) + && $request['comment'] === 'Returned the lego'); +}); + +it('refuses a refund without an amount, because Tamara has no amount-less full refund', function () { + Tahseel::gateway('tamara')->refund(new RefundRequest(orderId: '4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3')); +})->throws(InvalidPaymentRequestException::class); + +it('surfaces a tamara error instead of inventing a session', function () { + Http::fake([ + 'api-sandbox.tamara.co/checkout' => Http::response(['message' => 'Invalid Phone Number'], 400), + ]); + + Tahseel::gateway('tamara')->createPayment(tamaraRequest()); +})->throws(GatewayException::class); diff --git a/tests/Fixtures/tamara/authorise-response.json b/tests/Fixtures/tamara/authorise-response.json new file mode 100644 index 0000000..d8b7879 --- /dev/null +++ b/tests/Fixtures/tamara/authorise-response.json @@ -0,0 +1,5 @@ +{ + "order_id": "4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3", + "status": "authorised", + "order_reference_id": "order-1001" +} diff --git a/tests/Fixtures/tamara/checkout-created.json b/tests/Fixtures/tamara/checkout-created.json new file mode 100644 index 0000000..772ca6a --- /dev/null +++ b/tests/Fixtures/tamara/checkout-created.json @@ -0,0 +1,7 @@ +{ + "order_id": "4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3", + "checkout_id": "9c1d2b3a-0000-4000-8000-000000000001", + "status": "new", + "checkout_url": "https://checkout.tamara.co/checkout/4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3", + "order_reference_id": "order-1001" +} diff --git a/tests/Fixtures/tamara/refund-response.json b/tests/Fixtures/tamara/refund-response.json new file mode 100644 index 0000000..21a9a9b --- /dev/null +++ b/tests/Fixtures/tamara/refund-response.json @@ -0,0 +1,5 @@ +{ + "order_id": "4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3", + "status": "fully_refunded", + "refund_id": "c172e227-903a-4091-b57f-695b6a5a3681" +} diff --git a/tests/Fixtures/tamara/webhook-approved.json b/tests/Fixtures/tamara/webhook-approved.json new file mode 100644 index 0000000..6d5a067 --- /dev/null +++ b/tests/Fixtures/tamara/webhook-approved.json @@ -0,0 +1,7 @@ +{ + "order_id": "4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3", + "order_reference_id": "order-1001", + "order_number": "90001860", + "event_type": "order_approved", + "data": [] +} diff --git a/tests/Fixtures/tamara/webhook-authorised.json b/tests/Fixtures/tamara/webhook-authorised.json new file mode 100644 index 0000000..62c644b --- /dev/null +++ b/tests/Fixtures/tamara/webhook-authorised.json @@ -0,0 +1,7 @@ +{ + "order_id": "4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3", + "order_reference_id": "order-1001", + "order_number": "90001860", + "event_type": "order_authorised", + "data": [] +} diff --git a/tests/Fixtures/tamara/webhook-refunded.json b/tests/Fixtures/tamara/webhook-refunded.json new file mode 100644 index 0000000..dcfff2c --- /dev/null +++ b/tests/Fixtures/tamara/webhook-refunded.json @@ -0,0 +1,14 @@ +{ + "order_id": "4fdb781f-5e13-4ae2-9dc6-3ee49e3878a3", + "order_reference_id": "order-1001", + "order_number": "90001860", + "event_type": "order_refunded", + "data": { + "refund_id": "c172e227-903a-4091-b57f-695b6a5a3681", + "capture_id": "14c594f8-84ec-4f45-8fec-6ef1e2fde2ff", + "refunded_amount": { + "amount": 300, + "currency": "SAR" + } + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 0b68364..120634b 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.tamara', [ + 'base_url' => 'https://api-sandbox.tamara.co', + 'api_token' => 'tamara-api-token', + 'notification_token' => 'tamara-notification-token', + 'country_code' => 'SA', + 'locale' => 'en_US', + 'platform' => 'web', + 'currency' => 'SAR', + 'item_type' => 'Physical', + 'success_url' => 'https://example.test/checkout/done', + 'failure_url' => 'https://example.test/checkout/failed', + 'cancel_url' => 'https://example.test/checkout/cancel', + 'shipping_line1' => '3764 Al Urubah Rd', + 'shipping_region' => 'As Sulimaniyah', + 'shipping_city' => 'Riyadh', + 'account_creation_date' => '31-01-2019', + 'total_order_count' => 3, + 'timeout' => 10, + ]); + $app['config']->set('tahseel.drivers.tabby', [ 'base_url' => 'https://api.tabby.ai', 'secret_key' => 'sk_test_0192a1b2c3d4',