From 1f1ff38d6cc79ee4b5a4e2b4205083a658ac6a76 Mon Sep 17 00:00:00 2001 From: Ahmed Elbanby Date: Fri, 4 Dec 2026 05:19:30 +0200 Subject: [PATCH] Add Viva.com driver Viva.com is a Greek acquirer with a wide European footprint, on Smart Checkout: - createPayment() takes an OAuth2 client-credentials token from the accounts host, creates the payment order and returns the documented ?ref={OrderCode} checkout url, keeping the 16-digit order code a string. - Webhooks are signed over the raw body: Viva-Signature-256 is the hex HMAC-SHA-256 under the webhook secret, Viva-Signature the SHA-1 one. - Only the documented events are read, the event and the transaction's own StatusId have to agree, and F is the only status treated as money. - Refunds are not wrapped: Viva documents them on a separate surface. --- CHANGELOG.md | 1 + README.md | 34 ++- composer.json | 7 +- config/tahseel.php | 28 ++ docs/ar/README.md | 34 ++- src/Gateways/Viva/VivaClient.php | 107 +++++++ src/Gateways/Viva/VivaGateway.php | 357 +++++++++++++++++++++++ src/TahseelManager.php | 6 + tests/Feature/VivaGatewayTest.php | 162 ++++++++++ tests/Fixtures/viva/order-created.json | 3 + tests/Fixtures/viva/payment-created.json | 14 + tests/Fixtures/viva/payment-failed.json | 11 + tests/Fixtures/viva/token.json | 5 + tests/TestCase.php | 14 + 14 files changed, 779 insertions(+), 4 deletions(-) create mode 100644 src/Gateways/Viva/VivaClient.php create mode 100644 src/Gateways/Viva/VivaGateway.php create mode 100644 tests/Feature/VivaGatewayTest.php create mode 100644 tests/Fixtures/viva/order-created.json create mode 100644 tests/Fixtures/viva/payment-created.json create mode 100644 tests/Fixtures/viva/payment-failed.json create mode 100644 tests/Fixtures/viva/token.json diff --git a/CHANGELOG.md b/CHANGELOG.md index d34030d..7efa7de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to Tahseel are documented here. This project follows [Semant ### Added +- **Viva.com driver** (`Tahseel::gateway('viva')`), the fifteenth international driver (a Greek acquirer with a wide European footprint), on Smart Checkout: OAuth2 client-credentials token from the accounts host, `POST /checkout/v2/orders` on the API host with MINOR-unit amounts and the 4-digit payment source, the 16-digit order code kept as a string and turned into the documented `?ref={OrderCode}` checkout url; webhooks verified over the raw body - hex HMAC-SHA-256 in `Viva-Signature-256` with the documented SHA-1 `Viva-Signature` as fallback, constant-time, a body without raw bytes refused - reading only the documented events (1796, 1797, 1798, 4865) and requiring the event and the transaction's own `StatusId` to agree, with the closed status set honoured (`F` paid, `A`/`C` pending, `R` refunded, `E`/`X` failed, anything else refused) and the ISO numeric currency code mapped before Money; config + `VIVA_*` env vars, and 13 fixture tests. Refunds are not wrapped and there is no transaction re-read; the docs say both. Fixture-tested only, no live account has run it yet. - **Telr driver** (`Tahseel::gateway('telr')`), the fourteenth international driver and a Gulf acquirer (UAE, Saudi Arabia and the wider region), on the hosted payment page: `POST /gateway/order.json` with method `create`, store id and auth key in the body as documented, MAJOR-unit decimal-string amounts, the `order.ref` + `order.url` pair returned as the checkout url; transaction advice verified exactly as Telr documents it - SHA1 of the secret key followed by the fourteen transaction fields colon-joined in order, percent-encoded values decoded first, a missing field contributing an empty value, compared in constant time - with the documented status set honoured (`A` paid, `H` authorised-but-held pending, `D`/`C`/`E` failed, anything else refused); `fetchPaymentStatus()` through the documented `check` method with the status text matched and an unrecognised one refused; config + `TELR_*` env vars, and 16 fixture tests. Refunds are not wrapped and the docs say so. Fixture-tested only, no live account has run it yet. - **Xendit driver** (`Tahseel::gateway('xendit')`), the thirteenth international driver and the South-East Asia specialist (Indonesia, the Philippines, Malaysia, Thailand, Vietnam, Singapore), on Payment Sessions in `PAYMENT_LINK` mode rather than the legacy Invoice API: `POST /sessions` with Basic auth (secret key as username, empty password) and the documented `api-version` header, smallest-unit amounts, the hosted `payment_link_url` returned as the checkout url; webhooks authenticated the way Xendit documents them - the dashboard's token echoed verbatim in `x-callback-token`, compared in constant time, no HMAC - and only the documented `payment_session.completed` / `payment_session.expired` events read, with a completed event re-checked against the session's own status so a session that is not `COMPLETED` comes through pending, and the closed status set honoured with anything else refused; refunds through `POST /refunds` keyed by Xendit's `payment_id`, amount required, reason mapped to the documented enum (`REQUESTED_BY_CUSTOMER` unless a documented code is passed), `SUCCEEDED`/`PENDING`/`FAILED` mapped and pending refunds left to their own webhook; config + `XENDIT_*` env vars, and 16 fixture tests. No fetch-on-callback, stated plainly. Fixture-tested only, no live account has run it yet. - **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. diff --git a/README.md b/README.md index 3874b78..b3db353 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-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. +Tahseel gives you one clean API for starting a payment, verifying the gateway's callback, and getting a normalised result. Twenty-four drivers so far: **Paymob** (Intention API + Unified Checkout), **Kashier** (v3 payment sessions), **Fawry** (pay-at-outlet reference numbers), **Geidea** (checkout sessions on the hosted page), **MyFatoorah** (invoice payment links + signed webhook v2), **Tap** (hosted charges + `hashstring` webhooks), **HyperPay** (COPYandPAY widget + AES-256-GCM encrypted webhooks), **Checkout.com** (Hosted Payments Page + `Cko-Signature` webhooks), **PayPal** (Orders v2 + `verify-webhook-signature`), **Stripe** (Checkout Sessions + the documented `Stripe-Signature` HMAC), **Paystack** (hosted checkout for Nigeria, Ghana, South Africa and Kenya + two documented webhook schemes) **Moyasar** (Saudi cards, mada, Apple/Samsung Pay and STC Pay over one API + shared-token webhooks) **Razorpay** (hosted Payment Links for India + HMAC-SHA-256 everything), **Mercado Pago** (Checkout Pro hosted pages for Latin America + manifest-signed notifications) and **Mollie** (hosted checkout for Europe - iDEAL, Bancontact, SEPA, Klarna, cards and more + deliberately unsigned webhooks verified by fetch) and **Adyen** (hosted Checkout sessions for global enterprise + HMAC-signed Standard webhooks) **Flutterwave** (hosted checkout across Africa + `verif-hash` webhooks re-checked through the API) and **PayTabs** (hosted payment pages across the Gulf + raw-body `Signature` callbacks) **Klarna** (hosted payment pages for Europe and the US + one-time-token callbacks re-checked through the API, with the documented place-order step) **Square** (hosted payment links + notifications signed over the notification URL and raw body) **Xendit** (hosted Payment Sessions across South-East Asia + `x-callback-token` webhooks) **Telr** (hosted payment pages across the Gulf + SHA1-signed transaction advice) and **Viva.com** (Smart Checkout across Europe + HMAC-signed webhooks). Another, **manual**, covers what no wallet publishes an API for: a transfer to your Vodafone Cash number or InstaPay handle, confirmed by a human in a small approval panel. The Gulf drivers, PayPal, Stripe, Paystack, Moyasar, Razorpay, Mercado Pago, Mollie, Adyen, Flutterwave, PayTabs, Klarna, Square, Xendit, Telr and Viva.com are fixture-tested only, no live account has run them yet. > **Status: v0.3.0, EXPERIMENTAL pre-release. Do not take real money through it yet.** > @@ -46,6 +46,7 @@ Tahseel gives you one clean API for starting a payment, verifying the gateway's | **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 | +| **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 | | **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) | @@ -903,6 +904,36 @@ Four Telr details worth knowing: 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. +## Viva.com + +Viva.com is the fifteenth international driver: a Greek acquirer with a wide European footprint, on Smart Checkout. You create a payment order, send the customer to the checkout page it belongs to, and Viva tells you what happened with a signed webhook. + +```dotenv +VIVA_BASE_URL=https://api.vivapayments.com # demo: https://demo-api.vivapayments.com +VIVA_ACCOUNTS_URL=https://accounts.vivapayments.com # demo: https://demo-accounts.vivapayments.com +VIVA_CLIENT_ID=... # Smart Checkout client credentials +VIVA_CLIENT_SECRET=... +VIVA_SOURCE_CODE=8362 # the 4-digit payment source from the Viva app +VIVA_WEBHOOK_SECRET=... # the webhook signing secret +VIVA_CHECKOUT_URL=https://www.vivapayments.com/web/checkout +VIVA_REQUEST_LANGUAGE=en-GB +``` + +```php +$session = Tahseel::gateway('viva')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +Four Viva.com details worth knowing: + +- **Two hosts and an OAuth2 token.** Orders go to the API host, the token to the accounts host: client credentials, `grant_type=client_credentials`, the client id and secret as Basic auth. The driver fetches the token once per instance and reuses it. +- **The order code is a 16-digit string.** Viva's docs are explicit that it must be handled as a string, because a JavaScript number cannot hold it. The driver keeps it a string everywhere and builds the documented checkout url (`?ref={OrderCode}`) from it. +- **Webhooks are signed over the raw body.** `Viva-Signature-256` is the hex HMAC-SHA-256 of the body under the webhook secret, `Viva-Signature` the SHA-1 equivalent; the driver prefers the 256 one, falls back to the 1 one, compares in constant time, and refuses a body whose raw bytes it cannot see. It then reads only the documented events (1796 payment created, 1797 reversal created, 1798 payment failed, 4865 order updated) and requires the event and the transaction's own `StatusId` to agree - a notification that claims success for a failed transaction is refused, not believed. +- **`F` is finished, and only `F` is money.** The documented statuses are `F` finished, `A` active, `C` captured, `E` error, `R` refunded, `X` cancelled: `F` is paid, `A` and `C` come through pending, `R` refunded, `E` and `X` failed, and anything else is refused. Amounts arrive in minor units with the currency as an ISO numeric code (`978` is EUR), which the driver maps before building `Money`. + +Refunds are not wrapped: Viva documents them on a separate product surface that this driver has not been grounded in. Fixture-tested only, no Viva account has run it yet. + ## 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`. @@ -997,6 +1028,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 Viva.com refunds or transaction re-read.** Viva documents refunds elsewhere, and its docs point at the webhook fields (order code, transaction id, status, amount) rather than a re-read, which is what the driver checks. - **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. diff --git a/composer.json b/composer.json index 3dc6bd3..382e152 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 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 and manual transfers (Vodafone Cash, InstaPay) behind one gateway contract with signed webhook verification. Experimental.", "keywords": [ "laravel", "payments", @@ -62,7 +62,10 @@ "idr", "southeast asia", "telr", - "aed" + "aed", + "viva", + "vivawallet", + "smart checkout" ], "license": "MIT", "require": { diff --git a/config/tahseel.php b/config/tahseel.php index 9e431a6..e701d96 100644 --- a/config/tahseel.php +++ b/config/tahseel.php @@ -477,6 +477,34 @@ 'idempotency_ttl' => (int) env('PAYTABS_IDEMPOTENCY_TTL', 86400), ], + 'viva' => [ + // Production: https://api.vivapayments.com. Demo: + // https://demo-api.vivapayments.com. + 'base_url' => env('VIVA_BASE_URL', 'https://api.vivapayments.com'), + + // Production: https://accounts.vivapayments.com. Demo: + // https://demo-accounts.vivapayments.com. + 'accounts_url' => env('VIVA_ACCOUNTS_URL', 'https://accounts.vivapayments.com'), + + // Smart Checkout client credentials. + 'client_id' => env('VIVA_CLIENT_ID'), + 'client_secret' => env('VIVA_CLIENT_SECRET'), + + // The 4-digit payment source code from the Viva banking app. + 'source_code' => env('VIVA_SOURCE_CODE'), + + // The webhook signing secret, and the checkout page host. + 'webhook_secret' => env('VIVA_WEBHOOK_SECRET'), + 'checkout_url' => env('VIVA_CHECKOUT_URL', 'https://www.vivapayments.com/web/checkout'), + + 'request_language' => env('VIVA_REQUEST_LANGUAGE'), + 'payment_timeout' => (int) env('VIVA_PAYMENT_TIMEOUT', 0), + 'currency' => env('VIVA_CURRENCY', 'EUR'), + + 'timeout' => (int) env('VIVA_TIMEOUT', 30), + 'idempotency_ttl' => (int) env('VIVA_IDEMPOTENCY_TTL', 86400), + ], + 'telr' => [ 'base_url' => env('TELR_BASE_URL', 'https://secure.telr.com/gateway'), diff --git a/docs/ar/README.md b/docs/ar/README.md index 307183f..097c46a 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). ودرايفر التلاتة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. + فيه لحد دلوقتي أربعة وعشرين درايفر لبوابات: **Paymob** (Intention API مع Unified Checkout)، **Kashier** (Payment Sessions v3)، **فوري** (أرقام دفع من أي منفذ فوري)، **Geidea** (جلسات دفع على صفحتهم المستضافة)، **MyFatoorah** (روابط دفع الفواتير + webhook v2 موقّع)، **Tap** (صفحة دفع مستضافة + webhook بتوقيع `hashstring`)، **HyperPay** (ودجت COPYandPAY + webhook متشفّر AES-256-GCM)، **Checkout.com** (صفحة دفع مستضافة + webhook بتوقيع `Cko-Signature`)، **PayPal** (Orders v2 + تحقق `verify-webhook-signature`) و**Stripe** (Checkout Sessions + توقيع HMAC الموثّق في `Stripe-Signature`) و**Paystack** (صفحة دفع مستضافة لنيجيريا وغانا وجنوب أفريقيا وكينيا + نظامَي توقيع webhook موثّقين) و**Moyasar** (كروت سعودية ومدى وApple/Samsung Pay وSTC Pay على API واحد + webhooks بتوكن مشترك) و**Razorpay** (روابط دفع مستضافة للهند + HMAC-SHA-256 في كل حاجة) و**Mercado Pago** (صفحات Checkout Pro المستضافة لأمريكا اللاتينية + إشعارات موقّعة بالمانيفست) و**Mollie** (صفحة دفع مستضافة لأوروبا: iDEAL وBancontact وSEPA وKlarna وكروت وأكتر + webhooks مش موقّعة عمد، التحقق فيها بالجلب) و**Adyen** (جلسات Checkout مستضافة للشركات العالمية + webhooks قياسية موقّعة بـ HMAC) و**Flutterwave** (رابط دفع مستضاف في أفريقيا + webhooks بـ `verif-hash` بتتحقق تاني من الـ API) و**PayTabs** (صفحات دفع مستضافة في الخليج + webhooks بتوقيع على البودي الخام) **Klarna** (صفحات دفع مستضافة لأوروبا وأمريكا + callbacks بتوكن لمرة واحدة بتتحقق تاني من الـ API، مع خطوة تثبيت الأوردر الموثّقة) **Square** (روابط دفع مستضافة + إشعارات موقّعة على رابط الإشعار والبودي الخام) **Xendit** (جلسات دفع مستضافة في جنوب شرق آسيا + webhooks بتوكن `x-callback-token`) **Telr** (صفحات دفع مستضافة في الخليج + إشعارات موقّعة بـ SHA1) و**Viva.com** (Smart Checkout في أوروبا + webhooks موقّعة بـ HMAC). ودرايفر الأربعة وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit وTelr وViva.com متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. > **الحالة: 0.3.0، نسخة تجريبية (EXPERIMENTAL). ماتستلمش فلوس حقيقية بيها لسه.** > @@ -37,6 +37,7 @@ | **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 مش مدفوعة؛ متجرب على بيانات مسجلة بس لسه | +| **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` مستردة؛ متجرب على بيانات مسجلة بس لسه | | **يدوي** (فودافون كاش، إنستاباي) | `Tahseel::gateway('manual')` — مرجع، تحويل على محفظتك، وقرار من حد من فريقك | مفيش: التأكيد من اللوحة | مش منطبق | مش منطبق | مفيش API تجار تكلّمه؛ واللوحة مقفولة لحد ما تحدد Gate ability | | **محافظ وتقسيط وميزة وإنستاباي** | عن طريق وسائل Paymob أو Kashier أو Geidea | - | - | - | مفيش API تجار معلن لأي منهم، شوف القسم تحت | @@ -856,6 +857,36 @@ header('Location: '.$session->checkoutUrl); الاسترداد مش ملفوف: Telr موثّقة على منتج تاني، والدرايفر مابيدّعيش حاجة ماتأسّسش عليها. متجرب على بيانات مسجلة بس، مفيش حساب Telr حقيقي شغّال لسه. +## Viva.com + +Viva.com هو الداريفر الدولي الخامس عشر: مُحصّل يوناني بانتشار أوروبي واسع، على Smart Checkout. بتنشئ أمر دفع، وتبعته العميل على صفحة الدفع بتاعته، وViva بتقولك إيه اللي حصل بـ webhook موقّع. + +```dotenv +VIVA_BASE_URL=https://api.vivapayments.com # ديمو: https://demo-api.vivapayments.com +VIVA_ACCOUNTS_URL=https://accounts.vivapayments.com # ديمو: https://demo-accounts.vivapayments.com +VIVA_CLIENT_ID=... # بيانات عميل Smart Checkout +VIVA_CLIENT_SECRET=... +VIVA_SOURCE_CODE=8362 # كود مصدر الدفع الرباعي من تطبيق Viva +VIVA_WEBHOOK_SECRET=... # مفتاح توقيع الـ webhook +VIVA_CHECKOUT_URL=https://www.vivapayments.com/web/checkout +VIVA_REQUEST_LANGUAGE=en-GB +``` + +```php +$session = Tahseel::gateway('viva')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +أربع تفاصيل مهمة في Viva.com: + +- **هوستين وتوكن OAuth2.** الأوامر على هوست الـ API، والتوكن على هوست الحسابات: client credentials، بـ `grant_type=client_credentials`، والـ client id والسيكرت Basic auth. الدرايفر بيجيب التوكن مرة لكل نسخة وبيعيد استخدامه. +- **كود الأمر 16 رقم ونص مش رقم.** وثائق Viva صريحة إنه لازم يتعامل كنص، لأن رقم JavaScript مايشيلوش. الدرايفر بيحتفظ بيه نص في كل حتة وبيبني رابط الدفع الموثّق (`?ref={OrderCode}`) منه. +- **الـ webhooks موقّعة على البودي الخام.** `Viva-Signature-256` هو HMAC-SHA-256 بنظام hex على البودي بمفتاح الـ webhook، و`Viva-Signature` نفس الحاجة بـ SHA-1؛ الدرايفر بيفضّل 256 ويرجع لـ 1، بيقارن بزمن ثابت، ويرفض أي بودي مش شايف بايتاته الخام. وبعدها بيقرا الأحداث الموثّقة بس (1796 دفع اتعمل، 1797 استرداد، 1798 دفع فشل، 4865 الأوردر اتحدّث) وبيطلب إن الحدث وحالة العملية `StatusId` يتفقوا — إشعار بيقول نجاح لعملية فاشلة بيترفض مش بيتصدّق. +- **`F` منتهية، وبس `F` فلوس.** الحالات الموثّقة: `F` منتهية، `A` نشطة، `C` متحصّلة، `E` خطأ، `R` مستردة، `X` ملغية: `F` مدفوعة، `A` و`C` معلّقة، `R` مستردة، `E` و`X` فشل، وأي حاجة تانية بتترفض. والمبالغ بتيجي بالوحدة الصغرى والعملة كود ISO رقمي (`978` يعني يورو)، والدرايفر بيحوّله قبل ما يبني `Money`. + +الاسترداد مش ملفوف: Viva موثّقة على منتج منفصل والدرايفر ماتأسّسش عليه. متجرب على بيانات مسجلة بس، مفيش حساب Viva حقيقي شغّال لسه. + ## الدفع اليدوي: فودافون كاش وإنستاباي فودافون كاش وإنستاباي مفيش لهم API تجار، فالطريقة الصادقة لقبولهم هي الطريقة اللي المحلات المصرية بتعملها فعلاً: العميل يحوّل على محفظتك أو عنوان إنستاباي بتاعك، يقولك رقم العملية أو يرفع صورة التحويل، وحد من فريقك يأكد إن الفلوس وصلت. الباكدج بيوفّر ده كدرايفر اسمه `manual`. @@ -950,6 +981,7 @@ Gate::define('manage-payments', fn (User $user) => $user->is_admin); - **مفيش capture على Kashier.** الاسترداد والإلغاء مغلّفين؛ الكابتشر لأ. - **مفيش كارت ولا محفظة في فوري.** أرقام دفع بس، للأسباب اللي فوق. - **مفيش إلغاء ولا كروت محفوظة على Geidea.** الاسترداد مغلّف؛ Geidea بتذكر Void للمدفوعات المصرّح بها وغير المحصّلة بس، ومفيش وصف إندبوينت منشور، فمش بنخمّن. +- **مفيش استرداد ولا إعادة قراءة للعملية في Viva.com.** Viva موثّقة الاسترداد في مكان تاني، ووثائقها بتوجّه لحقول الـ webhook (كود الأمر ورقم العملية والحالة والمبلغ) مش لإعادة قراءة، وده اللي الدرايفر بيتحقق منه. - **مفيش استرداد في Telr.** Telr موثّقة الاسترداد على منتج تاني، فالدرايفر بياخد المدفوعات ويقرا الحالة بس بدل ما يدّعي مسار استرداد ماتأسّسش عليه. - **مفيش إعادة قراءة للدفعة في Xendit.** Xendit موثّقة توكن callback مش HMAC في الفلو ده، والدرايفر مابيجيبش الدفعة بعد كده؛ لو عايز نظرة تانية قبل التسليم، نادي API Xendit من تطبيقك. - **مفيش capture ولا void في Square.** الـ Payments API بتاعة Square بتقدر تكمّل capture مؤجّل؛ الباكدج بيلف الاسترداد بس، فالدفعة `APPROVED` بتفضل pending هنا. diff --git a/src/Gateways/Viva/VivaClient.php b/src/Gateways/Viva/VivaClient.php new file mode 100644 index 0000000..76b9b2a --- /dev/null +++ b/src/Gateways/Viva/VivaClient.php @@ -0,0 +1,107 @@ +token) && $this->token !== '') { + return $this->token; + } + + $response = $this->transport('viva', 'token', fn (): Response => Http::withBasicAuth($this->clientId, $this->clientSecret) + ->asForm() + ->acceptJson() + ->timeout($this->timeout) + ->post(rtrim($this->accountsUrl, '/').'/connect/token', ['grant_type' => 'client_credentials'])); + + $body = $this->unwrap('token', $response); + $token = $body['access_token'] ?? null; + + if (! is_string($token) || $token === '') { + throw GatewayException::invalidResponse('viva', 'token'); + } + + return $token; + } + + /** + * POST /checkout/v2/orders - the payment order the customer's checkout + * page is opened for. Returns a 16-digit order code. + * + * @param array $payload + * @return array + */ + public function createOrder(array $payload): array + { + $response = $this->transport('viva', 'create order', fn (): Response => $this->request()->post($this->url('checkout/v2/orders'), $payload)); + + return $this->unwrap('create order', $response); + } + + private function request(): PendingRequest + { + return Http::withToken($this->token()) + ->acceptJson() + ->timeout($this->timeout); + } + + /** + * @return array + */ + private function unwrap(string $operation, Response $response): array + { + if ($response->failed()) { + throw GatewayException::fromResponse('viva', $operation, $response->status(), $response->json()); + } + + $body = $response->json(); + + if (! is_array($body)) { + throw GatewayException::invalidResponse('viva', $operation); + } + + return $body; + } + + private function url(string $path): string + { + return rtrim($this->baseUrl, '/').'/'.ltrim($path, '/'); + } +} diff --git a/src/Gateways/Viva/VivaGateway.php b/src/Gateways/Viva/VivaGateway.php new file mode 100644 index 0000000..a950e3c --- /dev/null +++ b/src/Gateways/Viva/VivaGateway.php @@ -0,0 +1,357 @@ + PaymentStatus::Succeeded, + 'C' => PaymentStatus::Pending, + 'A' => PaymentStatus::Pending, + 'E' => PaymentStatus::Failed, + 'R' => PaymentStatus::Refunded, + 'X' => PaymentStatus::Failed, + ]; + + /** + * The documented event ids that matter to a payment. + */ + private const EVENT_PAYMENT_CREATED = 1796; + + private const EVENT_REVERSAL_CREATED = 1797; + + private const EVENT_PAYMENT_FAILED = 1798; + + private const EVENT_ORDER_UPDATED = 4865; + + /** + * @param array $config + */ + public function __construct( + private readonly array $config, + private readonly ?IdempotencyStore $idempotency = null, + private readonly ?VivaClient $client = null, + ) {} + + public function name(): string + { + return self::NAME; + } + + public function createPayment(PaymentRequest $request): PaymentSession + { + $this->assertConfigured(['client_id', 'client_secret', 'source_code']); + + return IdempotentCreation::run( + $this->idempotency, + $request->idempotencyKey, + $this->integer('idempotency_ttl', 86400), + function () use ($request): PaymentSession { + $payload = [ + 'amount' => $request->amount->toMinor(), + 'sourceCode' => (string) $this->string('source_code'), + 'customerTrns' => mb_substr($request->description ?? $request->reference, 0, 200), + ]; + + $email = $request->customer->email; + $name = trim($request->customer->firstName.' '.$request->customer->lastName); + + if (is_string($email) && $email !== '') { + $payload['email'] = $email; + } + + if ($name !== '') { + $payload['fullName'] = $name; + } + + $language = $this->string('request_language'); + + if ($language !== null) { + $payload['requestLang'] = $language; + } + + $timeout = $this->integer('payment_timeout', 0); + + if ($timeout > 0) { + $payload['paymentTimeout'] = $timeout; + } + + $body = $this->client()->createOrder($payload); + + // Viva's order code is a 16-digit number and its docs insist + // it is handled as a string, not an integer. + $orderCode = $body['orderCode'] ?? null; + + if (! is_scalar($orderCode) || (string) $orderCode === '') { + throw GatewayException::invalidResponse(self::NAME, 'create order'); + } + + $orderCode = (string) $orderCode; + + return new PaymentSession( + gateway: self::NAME, + reference: $request->reference, + intentionId: $orderCode, + orderId: $orderCode, + checkoutUrl: rtrim($this->string('checkout_url') ?? 'https://www.vivapayments.com/web/checkout', '/').'?ref='.rawurlencode($orderCode), + raw: $body, + ); + }, + ); + } + + /** + * Viva signs the raw body: Viva-Signature-256 is the hex HMAC-SHA-256 + * under the webhook secret, Viva-Signature the SHA-1 one. + * + * @param array $payload + * @param array $query + * @param array $headers + */ + public function verifyAndParseWebhook(array $payload, array $query = [], array $headers = []): WebhookEvent + { + $secret = $this->string('webhook_secret'); + + if ($secret === null) { + throw ConfigurationException::missing(self::NAME, ['tahseel.drivers.viva.webhook_secret']); + } + + $raw = $payload['_raw'] ?? null; + + if (! is_string($raw) || $raw === '') { + throw InvalidWebhookException::unsupportedType(self::NAME, 'raw body'); + } + + $sha256 = $this->header($headers, 'viva-signature-256'); + $sha1 = $this->header($headers, 'viva-signature'); + + if (is_string($sha256) && $sha256 !== '') { + if (! hash_equals(hash_hmac('sha256', $raw, $secret), strtolower(trim($sha256)))) { + throw InvalidSignatureException::forGateway(self::NAME); + } + } elseif (is_string($sha1) && $sha1 !== '') { + if (! hash_equals(hash_hmac('sha1', $raw, $secret), strtolower(trim($sha1)))) { + throw InvalidSignatureException::forGateway(self::NAME); + } + } else { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $eventId = $payload['EventTypeId'] ?? null; + + if (! is_numeric($eventId)) { + throw GatewayException::invalidResponse(self::NAME, 'webhook'); + } + + $eventId = (int) $eventId; + $data = is_array($payload['EventData'] ?? null) ? $payload['EventData'] : []; + $status = $this->status($data['StatusId'] ?? null); + + $expected = match ($eventId) { + self::EVENT_PAYMENT_CREATED => PaymentStatus::Succeeded, + self::EVENT_REVERSAL_CREATED => PaymentStatus::Refunded, + self::EVENT_PAYMENT_FAILED => PaymentStatus::Failed, + // An order update is a cancellation or an API-driven change. + self::EVENT_ORDER_UPDATED => PaymentStatus::Failed, + default => throw InvalidWebhookException::unsupportedType(self::NAME, 'event ['.$eventId.']'), + }; + + // The event and the transaction's own status have to agree; the + // status wins when the event is the broad one. + if ($eventId === self::EVENT_ORDER_UPDATED) { + $status = $expected; + } elseif ($status !== $expected && $eventId !== self::EVENT_REVERSAL_CREATED) { + throw new InvalidWebhookException('viva: event '.$eventId.' and transaction status disagree'); + } + + return new WebhookEvent( + gateway: self::NAME, + status: $status, + transactionId: is_scalar($data['TransactionId'] ?? null) ? (string) $data['TransactionId'] : '', + orderId: is_scalar($data['OrderCode'] ?? null) ? (string) $data['OrderCode'] : null, + reference: is_scalar($data['OrderCode'] ?? null) ? (string) $data['OrderCode'] : null, + amount: $this->money($data['Amount'] ?? null, $data['CurrencyCode'] ?? null) + ?? Money::minor(0, (string) ($this->string('currency') ?? 'EUR')), + success: $status === PaymentStatus::Succeeded, + pending: $status === PaymentStatus::Pending, + refunded: $status === PaymentStatus::Refunded, + voided: false, + createdAt: is_string($data['InsDate'] ?? null) ? $data['InsDate'] : null, + raw: $data, + ); + } + + private function status(mixed $status): PaymentStatus + { + $code = strtoupper(trim((string) $status)); + + if ($code === '') { + throw GatewayException::invalidResponse(self::NAME, 'webhook'); + } + + return self::STATUSES[$code] ?? throw InvalidWebhookException::unsupportedType(self::NAME, 'status ['.$code.']'); + } + + /** + * Viva sends the amount in minor units and the currency as an ISO 4217 + * numeric code (978 is EUR), so the numeric code is mapped to its letter + * code before it becomes Money. + */ + private function money(mixed $amount, mixed $currency): ?Money + { + if (! is_int($amount) && ! (is_string($amount) && ctype_digit($amount))) { + return null; + } + + $code = is_scalar($currency) ? strtoupper(trim((string) $currency)) : ''; + + $iso = self::NUMERIC_CURRENCIES[$code] ?? null; + + if ($iso === null) { + return null; + } + + return Money::minor((int) $amount, $iso); + } + + /** + * The ISO 4217 numeric codes Viva uses for the currencies this driver is + * likely to see. Anything else is left unmapped rather than guessed. + */ + private const NUMERIC_CURRENCIES = [ + '978' => 'EUR', + '840' => 'USD', + '826' => 'GBP', + '682' => 'SAR', + '971' => 'AFN', + '364' => 'IRR', + '784' => 'AED', + '414' => 'KWD', + '634' => 'QAR', + '048' => 'BHD', + '512' => 'OMR', + '818' => 'EGP', + '400' => 'JOD', + '949' => 'TRY', + '985' => 'PLN', + '203' => 'CZK', + '348' => 'HUF', + '946' => 'RON', + '975' => 'BGN', + '756' => 'CHF', + '752' => 'SEK', + '578' => 'NOK', + '208' => 'DKK', + ]; + + /** + * @param array $headers + */ + private function header(array $headers, string $name): ?string + { + foreach ($headers as $key => $value) { + if (strtolower((string) $key) !== $name) { + continue; + } + + if (is_array($value)) { + $value = $value[0] ?? null; + } + + return is_scalar($value) ? (string) $value : null; + } + + return null; + } + + private function client(): VivaClient + { + if ($this->client instanceof VivaClient) { + return $this->client; + } + + return new VivaClient( + $this->string('base_url') ?? 'https://api.vivapayments.com', + $this->string('accounts_url') ?? 'https://accounts.vivapayments.com', + (string) $this->string('client_id'), + (string) $this->string('client_secret'), + $this->integer('timeout', 30), + ); + } + + /** + * @param list $required + */ + private function assertConfigured(array $required): void + { + $missing = []; + + foreach ($required as $key) { + if ($this->string($key) === null) { + $missing[] = 'tahseel.drivers.viva.'.$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 38a7db1..dd672fe 100644 --- a/src/TahseelManager.php +++ b/src/TahseelManager.php @@ -41,6 +41,7 @@ use Tahseel\Gateways\Stripe\StripeGateway; use Tahseel\Gateways\Tap\TapGateway; use Tahseel\Gateways\Telr\TelrGateway; +use Tahseel\Gateways\Viva\VivaGateway; use Tahseel\Gateways\Xendit\XenditGateway; /** @@ -211,6 +212,11 @@ protected function createAdyenDriver(): Gateway return new AdyenGateway($this->configuration(AdyenGateway::NAME), $this->idempotencyStore()); } + protected function createVivaDriver(): Gateway + { + return new VivaGateway($this->configuration(VivaGateway::NAME), $this->idempotencyStore()); + } + protected function createTelrDriver(): Gateway { return new TelrGateway($this->configuration(TelrGateway::NAME), $this->idempotencyStore()); diff --git a/tests/Feature/VivaGatewayTest.php b/tests/Feature/VivaGatewayTest.php new file mode 100644 index 0000000..61be8d0 --- /dev/null +++ b/tests/Feature/VivaGatewayTest.php @@ -0,0 +1,162 @@ + $payload + * @return array{0: array, 1: array>} + */ +function vivaSigned(array $payload, string $algo = 'sha256'): array +{ + $raw = json_encode($payload, JSON_UNESCAPED_SLASHES); + $signature = hash_hmac($algo, $raw, 'viva-webhook-secret'); + + $header = $algo === 'sha256' ? 'viva-signature-256' : 'viva-signature'; + + return [$payload + ['_raw' => $raw], [$header => [$signature]]]; +} + +it('resolves the viva driver by name', function () { + expect(Tahseel::gateway('viva'))->toBeInstanceOf(VivaGateway::class) + ->and(Tahseel::gateway('viva')->name())->toBe('viva'); +}); + +it('gets a token and creates a payment order the checkout page opens', function () { + Http::fake([ + 'accounts.vivapayments.com/connect/token' => Http::response($this->fixture('viva/token.json'), 200), + 'api.vivapayments.com/checkout/v2/orders' => Http::response($this->fixture('viva/order-created.json'), 200), + ]); + + $session = Tahseel::gateway('viva')->createPayment(vivaRequest()); + + expect($session->gateway)->toBe('viva') + ->and($session->intentionId)->toBe('2271655739472609') + ->and($session->checkoutUrl)->toBe('https://www.vivapayments.com/web/checkout?ref=2271655739472609'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://accounts.vivapayments.com/connect/token' + && $request->hasHeader('Authorization', 'Basic '.base64_encode('viva-client-id:viva-client-secret')) + && $request['grant_type'] === 'client_credentials'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.vivapayments.com/checkout/v2/orders' + && $request->hasHeader('Authorization', 'Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.viva-demo-token.signature') + && $request['amount'] === 9500 + && $request['sourceCode'] === '8362' + && $request['customerTrns'] === 'Order ORDER-6112' + && $request['email'] === 'ahmed@example.com' + && $request['fullName'] === 'Ahmed Elbanby' + && $request['requestLang'] === 'en-GB'); +}); + +it('demands the payment source code', function () { + config()->set('tahseel.drivers.viva.source_code', null); + + Tahseel::gateway('viva')->createPayment(vivaRequest()); +})->throws(ConfigurationException::class); + +it('verifies a signed payment notification and reads it as paid', function () { + [$payload, $headers] = vivaSigned($this->fixture('viva/payment-created.json')); + + $event = Tahseel::gateway('viva')->verifyAndParseWebhook($payload, [], $headers); + + expect($event->gateway)->toBe('viva') + ->and($event->status)->toBe(PaymentStatus::Succeeded) + ->and($event->success)->toBeTrue() + ->and($event->transactionId)->toBe('997ab1e3-e6ce-45c9-970d-4d902f27ce71') + ->and($event->orderId)->toBe('2271655739472609') + ->and($event->amount?->toMinor())->toBe(9500) + ->and($event->amount?->currency)->toBe('EUR'); +}); + +it('accepts the sha1 header when the sha256 one is absent', function () { + [$payload, $headers] = vivaSigned($this->fixture('viva/payment-created.json'), 'sha1'); + + expect(Tahseel::gateway('viva')->verifyAndParseWebhook($payload, [], $headers)->status) + ->toBe(PaymentStatus::Succeeded); +}); + +it('rejects a notification with the wrong signature', function () { + [$payload] = vivaSigned($this->fixture('viva/payment-created.json')); + + expect(fn () => Tahseel::gateway('viva')->verifyAndParseWebhook($payload, [], ['viva-signature-256' => [hash_hmac('sha256', 'something else', 'viva-webhook-secret')]])) + ->toThrow(InvalidSignatureException::class); +}); + +it('rejects a notification with no signature at all', function () { + [$payload] = vivaSigned($this->fixture('viva/payment-created.json')); + + expect(fn () => Tahseel::gateway('viva')->verifyAndParseWebhook($payload)) + ->toThrow(InvalidSignatureException::class); +}); + +it('refuses a body it cannot see the raw bytes of', function () { + expect(fn () => Tahseel::gateway('viva')->verifyAndParseWebhook($this->fixture('viva/payment-created.json'), [], ['viva-signature-256' => ['anything']])) + ->toThrow(InvalidWebhookException::class); +}); + +it('maps a failed payment event to failed', function () { + [$payload, $headers] = vivaSigned($this->fixture('viva/payment-failed.json')); + + $event = Tahseel::gateway('viva')->verifyAndParseWebhook($payload, [], $headers); + + expect($event->status)->toBe(PaymentStatus::Failed) + ->and($event->success)->toBeFalse(); +}); + +it('refuses an event id it does not understand', function () { + $payload = $this->fixture('viva/payment-created.json'); + $payload['EventTypeId'] = 1799; + + [$signed, $headers] = vivaSigned($payload); + + Tahseel::gateway('viva')->verifyAndParseWebhook($signed, [], $headers); +})->throws(InvalidWebhookException::class); + +it('refuses an event whose status contradicts the transaction', function () { + $payload = $this->fixture('viva/payment-created.json'); + $payload['EventData']['StatusId'] = 'E'; + + [$signed, $headers] = vivaSigned($payload); + + Tahseel::gateway('viva')->verifyAndParseWebhook($signed, [], $headers); +})->throws(InvalidWebhookException::class); + +it('refuses a status id outside the documented set', function () { + $payload = $this->fixture('viva/payment-created.json'); + $payload['EventData']['StatusId'] = 'Z'; + + [$signed, $headers] = vivaSigned($payload); + + Tahseel::gateway('viva')->verifyAndParseWebhook($signed, [], $headers); +})->throws(InvalidWebhookException::class); + +it('surfaces a viva error instead of inventing an order', function () { + Http::fake([ + 'accounts.vivapayments.com/connect/token' => Http::response($this->fixture('viva/token.json'), 200), + 'api.vivapayments.com/checkout/v2/orders' => Http::response(['error' => 'invalid_source'], 400), + ]); + + Tahseel::gateway('viva')->createPayment(vivaRequest()); +})->throws(GatewayException::class); diff --git a/tests/Fixtures/viva/order-created.json b/tests/Fixtures/viva/order-created.json new file mode 100644 index 0000000..7e1fb29 --- /dev/null +++ b/tests/Fixtures/viva/order-created.json @@ -0,0 +1,3 @@ +{ + "orderCode": 2271655739472609 +} diff --git a/tests/Fixtures/viva/payment-created.json b/tests/Fixtures/viva/payment-created.json new file mode 100644 index 0000000..9d24771 --- /dev/null +++ b/tests/Fixtures/viva/payment-created.json @@ -0,0 +1,14 @@ +{ + "Url": "https://example.test/tahseel/webhooks/viva", + "EventTypeId": 1796, + "EventData": { + "Amount": 9500, + "OrderCode": 2271655739472609, + "StatusId": "F", + "TransactionId": "997ab1e3-e6ce-45c9-970d-4d902f27ce71", + "CurrencyCode": "978", + "InsDate": "2026-12-04T02:39:28.73", + "Email": "ahmed@example.com", + "FullName": "Ahmed Elbanby" + } +} diff --git a/tests/Fixtures/viva/payment-failed.json b/tests/Fixtures/viva/payment-failed.json new file mode 100644 index 0000000..5e2d62c --- /dev/null +++ b/tests/Fixtures/viva/payment-failed.json @@ -0,0 +1,11 @@ +{ + "Url": "https://example.test/tahseel/webhooks/viva", + "EventTypeId": 1798, + "EventData": { + "Amount": 9500, + "OrderCode": 2271655739472609, + "StatusId": "E", + "TransactionId": "997ab1e3-e6ce-45c9-970d-4d902f27ce71", + "CurrencyCode": "978" + } +} diff --git a/tests/Fixtures/viva/token.json b/tests/Fixtures/viva/token.json new file mode 100644 index 0000000..1af649e --- /dev/null +++ b/tests/Fixtures/viva/token.json @@ -0,0 +1,5 @@ +{ + "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.viva-demo-token.signature", + "expires_in": 3600, + "token_type": "Bearer" +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 94db49a..6d310b9 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -221,6 +221,20 @@ protected function defineEnvironment($app): void 'timeout' => 10, ]); + $app['config']->set('tahseel.drivers.viva', [ + 'base_url' => 'https://api.vivapayments.com', + 'accounts_url' => 'https://accounts.vivapayments.com', + 'client_id' => 'viva-client-id', + 'client_secret' => 'viva-client-secret', + 'source_code' => '8362', + 'webhook_secret' => 'viva-webhook-secret', + 'checkout_url' => 'https://www.vivapayments.com/web/checkout', + 'request_language' => 'en-GB', + 'payment_timeout' => 0, + 'currency' => 'EUR', + 'timeout' => 10, + ]); + $app['config']->set('tahseel.drivers.telr', [ 'base_url' => 'https://secure.telr.com/gateway', 'store' => 1234,