diff --git a/CHANGELOG.md b/CHANGELOG.md index e4ca53e..2ad73ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to Tahseel are documented here. This project follows [Semant ### Added +- **Xendit driver** (`Tahseel::gateway('xendit')`), the thirteenth international driver and the South-East Asia specialist (Indonesia, the Philippines, Malaysia, Thailand, Vietnam, Singapore), on Payment Sessions in `PAYMENT_LINK` mode rather than the legacy Invoice API: `POST /sessions` with Basic auth (secret key as username, empty password) and the documented `api-version` header, smallest-unit amounts, the hosted `payment_link_url` returned as the checkout url; webhooks authenticated the way Xendit documents them - the dashboard's token echoed verbatim in `x-callback-token`, compared in constant time, no HMAC - and only the documented `payment_session.completed` / `payment_session.expired` events read, with a completed event re-checked against the session's own status so a session that is not `COMPLETED` comes through pending, and the closed status set honoured with anything else refused; refunds through `POST /refunds` keyed by Xendit's `payment_id`, amount required, reason mapped to the documented enum (`REQUESTED_BY_CUSTOMER` unless a documented code is passed), `SUCCEEDED`/`PENDING`/`FAILED` mapped and pending refunds left to their own webhook; config + `XENDIT_*` env vars, and 16 fixture tests. No fetch-on-callback, stated plainly. Fixture-tested only, no live account has run it yet. - **Square driver** (`Tahseel::gateway('square')`), the twelfth international driver (US, Canada, UK, Ireland, Australia, Japan, France, Spain), on the hosted Checkout product: `POST /v2/online-checkout/payment-links` with a pinned `Square-Version` header, MINOR-unit amounts, the merchant reference carried back as the payment `note`; notifications verified exactly as Square documents them - HMAC-SHA-256 of the notification URL followed by the raw body under the subscription's signature key, base64, in `x-square-hmacsha256-signature`, constant-time, and the docs' own published example vector as a fixture test - then the authenticated `GET /v2/payments/{id}` read decides the status, a body without raw bytes is refused rather than reconstructed, and the documented `APPROVED`/`PENDING`/`COMPLETED`/`CANCELED`/`FAILED` set is honoured with `APPROVED` (authorised, not captured) coming through as pending; refund notifications parsed (`APPROVED` refunded, `PENDING` pending, `REJECTED`/`FAILED` failed); refunds through `POST /v2/refunds` with the required amount, addressed by the Square payment id, idempotency key kept inside Square's 45-character limit; `fetchPaymentStatus()`, config + `SQUARE_*` env vars, and 18 fixture tests. Fixture-tested only, no live account has run it yet. - **Klarna driver** (`Tahseel::gateway('klarna')`), the eleventh international driver and the BNPL specialist (Sweden and the Nordics, most of Europe, the UK, the US), on the documented hosted payment page product: `POST /payments/v1/sessions` for the purchase session, then `POST /hpp/v1/sessions` for the page the customer pays on, MINOR-unit amounts, and the third step Klarna documents made explicit instead of hidden - `placeOrder($authorizationToken, $request)` creates the order that is actually paid, returns the Klarna `order_id`, and maps the fraud assessment (`REJECTED` fails, `PENDING` stays pending); callbacks carry no HMAC, so the documented one-time token in the `status_update` url is compared in constant time and the session is then re-read through the authenticated API, a post without the token is refused before any API call, and the session's closed status set is honoured with anything else refused rather than guessed; refunds with the required `refunded_amount` and the documented `Klarna-Idempotency-Key` header, addressed by Klarna's own order id; the `{{session_id}}` / `{{authorization_token}}` placeholders are sent literally as Klarna documents them rather than percent-encoded; config + `KLARNA_*` env vars, and 16 fixture tests. No `fetchPaymentStatus()`, and the callback carries no amount, so amounts are compared from `placeOrder()`. Fixture-tested only, no live account has run it yet. - **PayTabs driver** (`Tahseel::gateway('paytabs')`), the Gulf's own processor (Saudi Arabia, UAE, Egypt, Oman, Jordan, Kuwait, Qatar, Morocco, Iraq), on the hosted payment page product: `POST /payment/request` page creation with the `redirect_url` hop, MAJOR-unit amounts, callbacks verified as documented (hex HMAC-SHA-256 of the whole raw body under the profile's Server Key, in the `Signature` header, constant-time), the browser return post's different documented recipe offered as `verifyReturnSignature()` and never trusted for money, the closed status set honoured - only `A` is paid, `H` (anti-fraud hold) and `P` (pending) come through as pending, `V`/`E`/`D`/`X` fail, and a code outside the set is refused instead of guessed; refunds with the required amount addressed by the original `tran_ref` (a `P` result is a manual refund still pending), `fetchPaymentStatus()` through `POST /payment/query`, the docs' own return-URL signature vector as a fixture test, config + `PAYTABS_*` env vars, and 26 fixture tests. Fixture-tested only, no live account has run it yet. diff --git a/README.md b/README.md index 00a4a6d..d828e2a 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-one 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) and **Square** (hosted payment links + notifications signed over the notification URL and raw body). 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 and Square 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-two drivers so far: **Paymob** (Intention API + Unified Checkout), **Kashier** (v3 payment sessions), **Fawry** (pay-at-outlet reference numbers), **Geidea** (checkout sessions on the hosted page), **MyFatoorah** (invoice payment links + signed webhook v2), **Tap** (hosted charges + `hashstring` webhooks), **HyperPay** (COPYandPAY widget + AES-256-GCM encrypted webhooks), **Checkout.com** (Hosted Payments Page + `Cko-Signature` webhooks), **PayPal** (Orders v2 + `verify-webhook-signature`), **Stripe** (Checkout Sessions + the documented `Stripe-Signature` HMAC), **Paystack** (hosted checkout for Nigeria, Ghana, South Africa and Kenya + two documented webhook schemes) **Moyasar** (Saudi cards, mada, Apple/Samsung Pay and STC Pay over one API + shared-token webhooks) **Razorpay** (hosted Payment Links for India + HMAC-SHA-256 everything), **Mercado Pago** (Checkout Pro hosted pages for Latin America + manifest-signed notifications) and **Mollie** (hosted checkout for Europe - iDEAL, Bancontact, SEPA, Klarna, cards and more + deliberately unsigned webhooks verified by fetch) and **Adyen** (hosted Checkout sessions for global enterprise + HMAC-signed Standard webhooks) **Flutterwave** (hosted checkout across Africa + `verif-hash` webhooks re-checked through the API) and **PayTabs** (hosted payment pages across the Gulf + raw-body `Signature` callbacks) **Klarna** (hosted payment pages for Europe and the US + one-time-token callbacks re-checked through the API, with the documented place-order step) **Square** (hosted payment links + notifications signed over the notification URL and raw body) and **Xendit** (hosted Payment Sessions across South-East Asia + `x-callback-token` webhooks). Another, **manual**, covers what no wallet publishes an API for: a transfer to your Vodafone Cash number or InstaPay handle, confirmed by a human in a small approval panel. The Gulf drivers, PayPal, Stripe, Paystack, Moyasar, Razorpay, Mercado Pago, Mollie, Adyen, Flutterwave, PayTabs, Klarna, Square and Xendit are fixture-tested only, no live account has run them yet. > **Status: v0.3.0, EXPERIMENTAL pre-release. Do not take real money through it yet.** > @@ -44,6 +44,7 @@ Tahseel gives you one clean API for starting a payment, verifying the gateway's | **PayTabs** | `Tahseel::gateway('paytabs')` - hosted payment page (`POST /payment/request`) | hex HMAC-SHA-256 of the whole raw callback body under the profile's Server Key, in a `Signature` header, constant-time; the documented status set is closed, so an unknown code is refused rather than guessed | refund, amount required, addressed by the original `tran_ref`; `P` is a manual refund still pending | server-side `fetchPaymentStatus()` via `POST /payment/query` | Saudi Arabia, UAE, Egypt, Oman, Jordan, Kuwait, Qatar, Morocco, Iraq; MAJOR units; fixture-tested only, no live run yet | | **Klarna** | `Tahseel::gateway('klarna')` - payment session + hosted page (`POST /payments/v1/sessions`, then `POST /hpp/v1/sessions`) | no HMAC: the documented one-time token in the `status_update` URL is compared in constant time, then the session is re-read through the API, so a forged call can never mark anything paid | refund, amount required, addressed by Klarna's own order id; there is no full-refund default | `placeOrder()` after the customer authorises: an authorization is not money | Europe and the US; BNPL and pay-now; MINOR units; fixture-tested only, no live run yet | | **Square** | `Tahseel::gateway('square')` - Square-hosted payment link (`POST /v2/online-checkout/payment-links`) | HMAC-SHA-256, base64, of the notification URL followed by the raw body, keyed by the subscription's signature key, in `x-square-hmacsha256-signature`, constant-time; the notification is the signal, the authenticated payment read is the truth | refund, amount required, addressed by the Square payment id; `PENDING` until Square approves it | server-side `fetchPaymentStatus()`; an `APPROVED` payment is authorised, not captured, and comes through pending | US, Canada, UK, Ireland, Australia, Japan, France, Spain; MINOR units; fixture-tested only, no live run yet | +| **Xendit** | `Tahseel::gateway('xendit')` - Payment Session in `PAYMENT_LINK` mode (`POST /sessions`) | no HMAC: the dashboard's callback token comes back verbatim in `x-callback-token`, compared in constant time, and the documented session status set is closed, so an unknown status is refused rather than guessed | refund, amount required, addressed by Xendit's `payment_id`; `PENDING` until the refund webhook settles it | none: the callback token is the documented authentication | Indonesia, the Philippines, Malaysia, Thailand, Vietnam, Singapore; smallest-unit amounts; fixture-tested only, no live run yet | | **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) | @@ -295,6 +296,7 @@ $result->succeeded(); // true, false, or false while pending | PayTabs | full or partial, MAJOR-unit amount required; only on an authorised sale or capture; `P` means a manual refund is pending | not implemented | the original `tran_ref`; the refund's own `tran_ref` comes back | | Klarna | full or partial, MINOR-unit amount required; synchronous against a captured order | not implemented | Klarna's own order id from `placeOrder()`, not your reference | | Square | full or partial, MINOR-unit amount required; `PENDING` until Square approves it | not implemented | the Square payment id | +| Xendit | full or partial, smallest-unit amount required; `PENDING` until the refund webhook settles it | not implemented | Xendit's `payment_id`, which the session webhook carries | The details that bite: @@ -840,6 +842,36 @@ Four Square details worth knowing: Refunds also arrive as `refund.created` / `refund.updated` notifications, which the driver parses: `APPROVED` is refunded, `PENDING` is pending, `REJECTED` and `FAILED` fail. Fixture-tested only, no Square account has run it yet. +## Xendit + +Xendit is the thirteenth international driver and the South-East Asia specialist: Indonesia, the Philippines, Malaysia, Thailand, Vietnam and Singapore, on Payment Sessions in `PAYMENT_LINK` mode - the product Xendit's own docs point new integrations at, with the older Invoice API listed under "migrate to Payment Session". + +```dotenv +XENDIT_BASE_URL=https://api.xendit.co +XENDIT_SECRET_KEY=... # Dashboard -> Settings -> Developers -> API keys +XENDIT_API_VERSION=2024-11-11 # the documented version header +XENDIT_CALLBACK_TOKEN=... # Dashboard -> Settings -> Developers -> Webhooks +XENDIT_COUNTRY=ID +XENDIT_CURRENCY=IDR +XENDIT_RETURN_URL=https://your-app.test/checkout/done +XENDIT_CANCEL_URL=https://your-app.test/checkout/cancelled +``` + +```php +$session = Tahseel::gateway('xendit')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +Four Xendit details worth knowing: + +- **Authentication is Basic with the secret key as the username and an empty password.** Xendit documents it that way, colon included, and the driver sends it that way. Every call also carries the `api-version` header, because Xendit versions its API per request rather than per host. +- **Webhooks are authenticated by `x-callback-token`, and nothing else.** There is no HMAC to compute: Xendit echoes the token from your dashboard's webhook settings in that header, and its docs are explicit that comparing it is how you know an event came from them. The driver compares it in constant time, refuses a missing or wrong token, and then reads only the documented events: `payment_session.completed` and `payment_session.expired`. There is no fetch-on-callback here, because Xendit's documented authentication for this flow is the token; the driver compensates by refusing any status outside the documented set rather than guessing. +- **A completed event is checked against the session's own status.** The documented statuses are `COMPLETED`, `ACTIVE`, `EXPIRED` and `CANCELED`: only `COMPLETED` is paid, `ACTIVE` comes through as pending, the other two fail. An event that says completed while the session says otherwise comes through pending, never paid. +- **Refunds are keyed by Xendit's `payment_id`, not by the session or your reference.** The session webhook carries that id when a payment completes, which is where you take it from. The amount is required, and the reason is a fixed enum rather than free text: a documented code you pass through is kept, anything else becomes `REQUESTED_BY_CUSTOMER`. The result is `SUCCEEDED`, `PENDING` or `FAILED`, and a pending refund settles through its own webhook. + +Amounts are the currency's smallest unit, the same convention as most drivers here. Fixture-tested only, no Xendit 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`. @@ -934,6 +966,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 Xendit payment re-read.** Xendit documents a callback token rather than an HMAC for this flow, and the driver does not fetch the payment afterwards; if you want a second look before fulfilling, call Xendit's own API from your application. - **No Square capture or voids.** Square's Payments API can complete a delayed capture; Tahseel wraps refunds only, so an `APPROVED` payment stays pending here. - **No Klarna capture or order reads.** Klarna's Order Management API also captures and reads orders; Tahseel wraps refunds only, and the place-order step is left to `placeOrder()`. - **Null handling in HMAC is a best guess.** Paymob does not document how it stringifies a `null` field. Tahseel treats `null` as an empty string, the PHP default. If a callback with a null signed field ever fails verification, capture the raw payload and check it against Paymob's HMAC troubleshooter. diff --git a/composer.json b/composer.json index b741951..187d5a1 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 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 and manual transfers (Vodafone Cash, InstaPay) behind one gateway contract with signed webhook verification. Experimental.", "keywords": [ "laravel", "payments", @@ -56,7 +56,11 @@ "sek", "square", "squareup", - "usd" + "usd", + "xendit", + "indonesia", + "idr", + "southeast asia" ], "license": "MIT", "require": { diff --git a/config/tahseel.php b/config/tahseel.php index 317b61e..8f5a4f3 100644 --- a/config/tahseel.php +++ b/config/tahseel.php @@ -477,6 +477,31 @@ 'idempotency_ttl' => (int) env('PAYTABS_IDEMPOTENCY_TTL', 86400), ], + 'xendit' => [ + 'base_url' => env('XENDIT_BASE_URL', 'https://api.xendit.co'), + + // Dashboard -> Settings -> Developers -> API keys. Sent as the + // Basic auth username with an empty password. + 'secret_key' => env('XENDIT_SECRET_KEY'), + + // The documented API version header. + 'api_version' => env('XENDIT_API_VERSION', '2024-11-11'), + + // Dashboard -> Settings -> Developers -> Webhooks: the callback + // token Xendit echoes in the x-callback-token header. + 'callback_token' => env('XENDIT_CALLBACK_TOKEN'), + + // The market and currency a session defaults to. + 'country' => env('XENDIT_COUNTRY', 'ID'), + 'currency' => env('XENDIT_CURRENCY', 'IDR'), + + 'return_url' => env('XENDIT_RETURN_URL'), + 'cancel_url' => env('XENDIT_CANCEL_URL'), + + 'timeout' => (int) env('XENDIT_TIMEOUT', 30), + 'idempotency_ttl' => (int) env('XENDIT_IDEMPOTENCY_TTL', 86400), + ], + 'square' => [ // Live: https://connect.squareup.com. Sandbox: // https://connect.squareupsandbox.com. diff --git a/docs/ar/README.md b/docs/ar/README.md index 654a1e5..360c776 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** (روابط دفع مستضافة + إشعارات موقّعة على رابط الإشعار والبودي الخام). ودرايفر الواحد والعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. + فيه لحد دلوقتي اتنين وعشرين درايفر لبوابات: **Paymob** (Intention API مع Unified Checkout)، **Kashier** (Payment Sessions v3)، **فوري** (أرقام دفع من أي منفذ فوري)، **Geidea** (جلسات دفع على صفحتهم المستضافة)، **MyFatoorah** (روابط دفع الفواتير + webhook v2 موقّع)، **Tap** (صفحة دفع مستضافة + webhook بتوقيع `hashstring`)، **HyperPay** (ودجت COPYandPAY + webhook متشفّر AES-256-GCM)، **Checkout.com** (صفحة دفع مستضافة + webhook بتوقيع `Cko-Signature`)، **PayPal** (Orders v2 + تحقق `verify-webhook-signature`) و**Stripe** (Checkout Sessions + توقيع HMAC الموثّق في `Stripe-Signature`) و**Paystack** (صفحة دفع مستضافة لنيجيريا وغانا وجنوب أفريقيا وكينيا + نظامَي توقيع webhook موثّقين) و**Moyasar** (كروت سعودية ومدى وApple/Samsung Pay وSTC Pay على API واحد + webhooks بتوكن مشترك) و**Razorpay** (روابط دفع مستضافة للهند + HMAC-SHA-256 في كل حاجة) و**Mercado Pago** (صفحات Checkout Pro المستضافة لأمريكا اللاتينية + إشعارات موقّعة بالمانيفست) و**Mollie** (صفحة دفع مستضافة لأوروبا: iDEAL وBancontact وSEPA وKlarna وكروت وأكتر + webhooks مش موقّعة عمد، التحقق فيها بالجلب) و**Adyen** (جلسات Checkout مستضافة للشركات العالمية + webhooks قياسية موقّعة بـ HMAC) و**Flutterwave** (رابط دفع مستضاف في أفريقيا + webhooks بـ `verif-hash` بتتحقق تاني من الـ API) و**PayTabs** (صفحات دفع مستضافة في الخليج + webhooks بتوقيع على البودي الخام) **Klarna** (صفحات دفع مستضافة لأوروبا وأمريكا + callbacks بتوكن لمرة واحدة بتتحقق تاني من الـ API، مع خطوة تثبيت الأوردر الموثّقة) **Square** (روابط دفع مستضافة + إشعارات موقّعة على رابط الإشعار والبودي الخام) و**Xendit** (جلسات دفع مستضافة في جنوب شرق آسيا + webhooks بتوكن `x-callback-token`). ودرايفر الاتنين وعشرين، **manual**، بيغطي الحاجة اللي مفيش محفظة بتنشر API ليها: تحويل على رقم فودافون كاش أو عنوان إنستاباي، وحد من فريقك بيأكده من لوحة صغيرة. الدرايفرات الخليجية وPayPal وStripe وPaystack وMoyasar وRazorpay وMercado Pago وMollie وAdyen وFlutterwave وPayTabs وKlarna وSquare وXendit متجربين على بيانات مسجلة بس لحد دلوقتي، لسه ماتشغلوش على حساب حقيقي. > **الحالة: 0.3.0، نسخة تجريبية (EXPERIMENTAL). ماتستلمش فلوس حقيقية بيها لسه.** > @@ -35,6 +35,7 @@ | **PayTabs** | `Tahseel::gateway('paytabs')` — صفحة دفع مستضافة (`POST /payment/request`) | HMAC-SHA-256 بنظام hex على البودي الخام الكامل للـ callback بمفتاح الـ Server Key بتاع البروفايل، في هيدر `Signature`، مقارنة ثابتة الزمن؛ مجموعة الحالات الموثّقة مقفولة، فأي كود برّاها بيترفض مش بيتخمّن | استرداد بمبلغ مطلوب، برقم `tran_ref` الأصلي؛ و`P` يعني استرداد يدوي لسه pending | تحقق من السيرفر بـ `fetchPaymentStatus()` عن طريق `POST /payment/query` | السعودية والإمارات ومصر وعمان والأردن والكويت وقطر والمغرب والعراق؛ الوحدة الكبرى؛ متجرب على بيانات مسجلة بس لسه | | **Klarna** | `Tahseel::gateway('klarna')` — جلسة دفع + صفحة مستضافة (`POST /payments/v1/sessions` وبعدها `POST /hpp/v1/sessions`) | مفيش HMAC: التوكن الموثّق لمرة واحدة اللي في رابط `status_update` بيتقارن بزمن ثابت، وبعدها الجلسة بتتجاب تاني من الـ API، فمكالمة مزوّرة عمرها ما تعلّم حاجة مدفوعة | استرداد بمبلغ مطلوب، برقم الأوردر بتاع Klarna نفسه؛ مفيش استرداد كامل افتراضي | `placeOrder()` بعد ما العميل يفوّض: التفويض مش فلوس | أوروبا وأمريكا؛ تقسيط ودفع فوري؛ الوحدة الصغرى؛ متجرب على بيانات مسجلة بس لسه | | **Square** | `Tahseel::gateway('square')` — رابط دفع مستضاف عند Square (`POST /v2/online-checkout/payment-links`) | HMAC-SHA-256 بترميز base64 على رابط الإشعار وبعده البودي الخام، بمفتاح التوقيع بتاع الاشتراك، في هيدر `x-square-hmacsha256-signature`، مقارنة ثابتة الزمن؛ الإشعار إشارة، وقراءة الدفع الموثّقة هي الحقيقة | استرداد بمبلغ مطلوب، برقم الدفع بتاع Square؛ `PENDING` لحد ما Square توافق | تحقق من السيرفر بـ `fetchPaymentStatus()`؛ الدفعة `APPROVED` مفوّضة مش متحصّلة، فبترجع pending | أمريكا وكندا وبريطانيا وأيرلندا وأستراليا واليابان وفرنسا وإسبانيا؛ الوحدة الصغرى؛ متجرب على بيانات مسجلة بس لسه | +| **Xendit** | `Tahseel::gateway('xendit')` — جلسة دفع بوضع `PAYMENT_LINK` (`POST /sessions`) | مفيش HMAC: توكن الـ callback من الداشبورد بيرجع زي ما هو في هيدر `x-callback-token`، بيتقارن بزمن ثابت، ومجموعة حالات الجلسة الموثّقة مقفولة، فأي حالة برّاها بتترفض مش بتتخمّن | استرداد بمبلغ مطلوب، برقم `payment_id` بتاع Xendit؛ `PENDING` لحد ما webhook الاسترداد يحسمها | مفيش: توكن الـ callback هو التوثيق الموثّق | إندونيسيا والفلبين وماليزيا وتايلاند وفييتنام وسنغافورة؛ المبالغ بأصغر وحدة؛ متجرب على بيانات مسجلة بس لسه | | **يدوي** (فودافون كاش، إنستاباي) | `Tahseel::gateway('manual')` — مرجع، تحويل على محفظتك، وقرار من حد من فريقك | مفيش: التأكيد من اللوحة | مش منطبق | مش منطبق | مفيش API تجار تكلّمه؛ واللوحة مقفولة لحد ما تحدد Gate ability | | **محافظ وتقسيط وميزة وإنستاباي** | عن طريق وسائل Paymob أو Kashier أو Geidea | - | - | - | مفيش API تجار معلن لأي منهم، شوف القسم تحت | @@ -252,6 +253,7 @@ $result->succeeded(); | PayTabs | كامل أو جزئي، المبلغ بالوحدة الكبرى ومطلوب؛ على عملية sale أو capture متأكدة بس؛ `P` يعني استرداد يدوي لسه pending | مش مدعوم | الـ `tran_ref` الأصلي؛ و`tran_ref` بتاع الاسترداد بيرجع | | Klarna | كامل أو جزئي، المبلغ بالوحدة الصغرى ومطلوب؛ فوري على أوردر متحصّل | مش مدعوم | رقم الأوردر بتاع Klarna من `placeOrder()`، مش مرجعك | | Square | كامل أو جزئي، المبلغ بالوحدة الصغرى ومطلوب؛ `PENDING` لحد ما Square توافق | مش مدعوم | رقم الدفع بتاع Square | +| Xendit | كامل أو جزئي، المبلغ بأصغر وحدة ومطلوب؛ `PENDING` لحد ما webhook الاسترداد يحسمها | مش مدعوم | رقم `payment_id` بتاع Xendit اللي webhook الجلسة بيجيبه | التفاصيل اللي بتوجع: @@ -793,6 +795,36 @@ header('Location: '.$session->checkoutUrl); الاسترداد كمان بييجي كإشعارات `refund.created` / `refund.updated`، والدرايفر بيقراها: `APPROVED` يعني مسترد، `PENDING` معلّق، `REJECTED` و`FAILED` فشل. متجرب على بيانات مسجلة بس، مفيش حساب Square حقيقي شغّال لسه. +## Xendit + +Xendit هو الداريفر الدولي التالت عشر ومتخصص جنوب شرق آسيا: إندونيسيا والفلبين وماليزيا وتايلاند وفييتنام وسنغافورة، على Payment Sessions بوضع `PAYMENT_LINK` — المنتج اللي وثائق Xendit نفسها بتوجّه التكاملات الجديدة ليه، وInvoice API القديم مذكور عندها تحت "migrate to Payment Session". + +```dotenv +XENDIT_BASE_URL=https://api.xendit.co +XENDIT_SECRET_KEY=... # Dashboard -> Settings -> Developers -> API keys +XENDIT_API_VERSION=2024-11-11 # هيدر النسخة الموثّق +XENDIT_CALLBACK_TOKEN=... # Dashboard -> Settings -> Developers -> Webhooks +XENDIT_COUNTRY=ID +XENDIT_CURRENCY=IDR +XENDIT_RETURN_URL=https://your-app.test/checkout/done +XENDIT_CANCEL_URL=https://your-app.test/checkout/cancelled +``` + +```php +$session = Tahseel::gateway('xendit')->createPayment($request); + +header('Location: '.$session->checkoutUrl); +``` + +أربع تفاصيل مهمة في Xendit: + +- **التوثيق Basic بالمفتاح السري كاسم مستخدم وباسورد فاضي.** Xendit موثّقة كده بالنقطتين، والدرايفر بيبعتها كده. وكل نداء بيحمل هيدر `api-version`، لأن Xendit بتعمل نسخ للـ API لكل طلب مش لكل هوست. +- **الـ webhooks بتتوثّق بـ `x-callback-token` وبس.** مفيش HMAC تحسبه: Xendit بترجّع التوكن اللي في إعدادات الـ webhooks بتاعتك زي ما هو في الهيدر ده، ووثائقها صريحة إن مقارنته هي الطريقة اللي تعرف بيها إن الإشعار منها. الدرايفر بيقارنه بزمن ثابت، بيرفض التوكن الغايب أو الغلط، وبعدها بيقرا الأحداث الموثّقة بس: `payment_session.completed` و`payment_session.expired`. مفيش جلب للدفعة بعد الـ callback هنا، لأن التوثيق الموثّق في الفلو ده هو التوكن؛ والدرايفر بيعوّض ده بأنه بيرفض أي حالة برّه المجموعة الموثّقة بدل ما يتخمّن. +- **حدث "مكتمل" بيتقارن بحالة الجلسة نفسها.** الحالات الموثّقة هي `COMPLETED` و`ACTIVE` و`EXPIRED` و`CANCELED`: بس `COMPLETED` مدفوعة، `ACTIVE` بتيجي معلّقة، والاتنين التانيين فشل. وأي حدث بيقول مكتمل والجلسة بتقول حاجة تانية بييجي معلّق، مش مدفوع. +- **الاسترداد بيتعنون بـ `payment_id` بتاع Xendit، مش بالجلسة ولا بمرجعك.** webhook الجلسة بيحمل الرقم ده لما الدفع يكتمل، وهو مصدره. المبلغ مطلوب، والسبب enum ثابت مش نص حر: أي كود موثّق تبعته بيعدّي زي ما هو، وأي حاجة تانية بتبقى `REQUESTED_BY_CUSTOMER`. والنتيجة `SUCCEEDED` أو `PENDING` أو `FAILED`، والاسترداد المعلّق بيتحسم بـ webhook بتاعه. + +المبالغ بأصغر وحدة في العملة، نفس العُرف في معظم الدرايفرات هنا. متجرب على بيانات مسجلة بس، مفيش حساب Xendit حقيقي شغّال لسه. + ## الدفع اليدوي: فودافون كاش وإنستاباي فودافون كاش وإنستاباي مفيش لهم API تجار، فالطريقة الصادقة لقبولهم هي الطريقة اللي المحلات المصرية بتعملها فعلاً: العميل يحوّل على محفظتك أو عنوان إنستاباي بتاعك، يقولك رقم العملية أو يرفع صورة التحويل، وحد من فريقك يأكد إن الفلوس وصلت. الباكدج بيوفّر ده كدرايفر اسمه `manual`. @@ -887,6 +919,7 @@ Gate::define('manage-payments', fn (User $user) => $user->is_admin); - **مفيش capture على Kashier.** الاسترداد والإلغاء مغلّفين؛ الكابتشر لأ. - **مفيش كارت ولا محفظة في فوري.** أرقام دفع بس، للأسباب اللي فوق. - **مفيش إلغاء ولا كروت محفوظة على Geidea.** الاسترداد مغلّف؛ Geidea بتذكر Void للمدفوعات المصرّح بها وغير المحصّلة بس، ومفيش وصف إندبوينت منشور، فمش بنخمّن. +- **مفيش إعادة قراءة للدفعة في Xendit.** Xendit موثّقة توكن callback مش HMAC في الفلو ده، والدرايفر مابيجيبش الدفعة بعد كده؛ لو عايز نظرة تانية قبل التسليم، نادي API Xendit من تطبيقك. - **مفيش capture ولا void في Square.** الـ Payments API بتاعة Square بتقدر تكمّل capture مؤجّل؛ الباكدج بيلف الاسترداد بس، فالدفعة `APPROVED` بتفضل pending هنا. - **مفيش capture ولا قراءة أوردرات في Klarna.** الـ Order Management API بتاعت Klarna بتعمل capture وبتقرا الأوردرات كمان؛ الباكدج بيلف الاسترداد بس، وخطوة تثبيت الأوردر سايبها لـ `placeOrder()`. - **تعامل الـ null في الـ HMAC اجتهاد.** Paymob مش موضحة إزاي بتحوّل الـ `null` لنص. الباكدج بيعتبرها نص فاضي، وده سلوك PHP الافتراضي. لو callback فيه حقل null فشل في التحقق، سجّل الـ payload الخام وجرّبه على أداة HMAC بتاعتهم. diff --git a/src/Gateways/Xendit/XenditClient.php b/src/Gateways/Xendit/XenditClient.php new file mode 100644 index 0000000..7a5187c --- /dev/null +++ b/src/Gateways/Xendit/XenditClient.php @@ -0,0 +1,93 @@ + $payload + * @return array + */ + public function createSession(array $payload): array + { + $response = $this->transport('xendit', 'create session', fn (): Response => $this->request()->post($this->url('sessions'), $payload)); + + return $this->unwrap('create session', $response); + } + + /** + * POST /refunds - refunds are keyed by Xendit's payment id, not by the + * session, and always carry an explicit amount. + * + * @param array $payload + * @return array + */ + public function refund(array $payload): array + { + $response = $this->transport('xendit', 'refund', fn (): Response => $this->request()->post($this->url('refunds'), $payload)); + + return $this->unwrap('refund', $response); + } + + private function request(): PendingRequest + { + return Http::withBasicAuth($this->secretKey, '') + ->withHeader('api-version', $this->apiVersion) + ->acceptJson() + ->timeout($this->timeout); + } + + /** + * @return array + */ + private function unwrap(string $operation, Response $response): array + { + if ($response->failed()) { + throw GatewayException::fromResponse('xendit', $operation, $response->status(), $response->json()); + } + + $body = $response->json(); + + if (! is_array($body)) { + throw GatewayException::invalidResponse('xendit', $operation); + } + + return $body; + } + + private function url(string $path): string + { + return rtrim($this->baseUrl, '/').'/'.ltrim($path, '/'); + } +} diff --git a/src/Gateways/Xendit/XenditGateway.php b/src/Gateways/Xendit/XenditGateway.php new file mode 100644 index 0000000..f60de61 --- /dev/null +++ b/src/Gateways/Xendit/XenditGateway.php @@ -0,0 +1,354 @@ + PaymentStatus::Succeeded, + 'ACTIVE' => PaymentStatus::Pending, + 'EXPIRED' => PaymentStatus::Failed, + 'CANCELED' => PaymentStatus::Failed, + ]; + + /** + * The documented refund statuses. + */ + private const REFUND_STATUSES = [ + 'SUCCEEDED' => PaymentStatus::Refunded, + 'PENDING' => PaymentStatus::Pending, + 'FAILED' => PaymentStatus::Failed, + ]; + + /** + * @param array $config + */ + public function __construct( + private readonly array $config, + private readonly ?IdempotencyStore $idempotency = null, + private readonly ?XenditClient $client = null, + ) {} + + public function name(): string + { + return self::NAME; + } + + public function createPayment(PaymentRequest $request): PaymentSession + { + $this->assertConfigured(['secret_key', 'callback_token']); + + return IdempotentCreation::run( + $this->idempotency, + $request->idempotencyKey, + $this->integer('idempotency_ttl', 86400), + function () use ($request): PaymentSession { + $payload = [ + 'reference_id' => $request->reference, + 'mode' => 'PAYMENT_LINK', + 'amount' => $request->amount->toMinor(), + 'currency' => $request->amount->currency, + 'country' => (string) ($this->string('country') ?? 'ID'), + 'description' => $request->description ?? $request->reference, + ]; + + $success = $request->redirectionUrl ?? $this->string('return_url'); + $cancel = $this->string('cancel_url'); + + if ($success !== null) { + $payload['success_return_url'] = $success; + } + + if ($cancel !== null) { + $payload['cancel_return_url'] = $cancel; + } + + $body = $this->client()->createSession($payload); + + $url = $body['payment_link_url'] ?? null; + $sessionId = $body['payment_session_id'] ?? null; + + if (! is_string($url) || $url === '' || ! is_scalar($sessionId) || (string) $sessionId === '') { + throw GatewayException::invalidResponse(self::NAME, 'create session'); + } + + return new PaymentSession( + gateway: self::NAME, + reference: $request->reference, + intentionId: (string) $sessionId, + orderId: $request->reference, + checkoutUrl: $url, + expiresAt: is_string($body['expires_at'] ?? null) ? $body['expires_at'] : null, + raw: $body, + ); + }, + ); + } + + public function refund(RefundRequest $request): OperationResult + { + $this->assertConfigured(['secret_key']); + + // Refunds are addressed by Xendit's payment id, which the session + // webhook carries once the payment completes. + $paymentId = $request->transactionId ?? $request->orderId; + + if ($paymentId === null || trim($paymentId) === '') { + throw new InvalidPaymentRequestException('A Xendit refund needs the Xendit payment id (transactionId) the session webhook carried.'); + } + + if ($request->amount === null) { + throw new InvalidPaymentRequestException('Xendit refunds need an explicit amount; the API has no full-refund default.'); + } + + $paymentId = trim($paymentId); + + $payload = [ + 'payment_id' => $paymentId, + 'amount' => $request->amount->toMinor(), + // Xendit documents a fixed enum here, not free text. + 'reason' => $this->refundReason($request->reason), + ]; + + $body = $this->client()->refund($payload); + + $refundId = $body['refund_id'] ?? null; + + if (! is_scalar($refundId)) { + throw GatewayException::invalidResponse(self::NAME, 'refund'); + } + + return new OperationResult( + gateway: self::NAME, + operation: 'refund', + status: $this->refundStatus($body['status'] ?? null), + transactionId: (string) $refundId, + orderId: $paymentId, + amount: $request->amount, + raw: $body, + ); + } + + /** + * Xendit authenticates webhooks with the `x-callback-token` header and + * documents no HMAC, so the token is the whole authentication. + * + * @param array $payload + * @param array $query + * @param array $headers + */ + public function verifyAndParseWebhook(array $payload, array $query = [], array $headers = []): WebhookEvent + { + unset($payload['_raw']); + + $token = $this->string('callback_token'); + + if ($token === null) { + throw ConfigurationException::missing(self::NAME, ['tahseel.drivers.xendit.callback_token']); + } + + $received = $this->header($headers, 'x-callback-token'); + + if ($received === null || $received === '' || ! hash_equals($token, $received)) { + throw InvalidSignatureException::forGateway(self::NAME); + } + + $event = is_string($payload['event'] ?? null) ? $payload['event'] : ''; + $data = is_array($payload['data'] ?? null) ? $payload['data'] : []; + + $status = match ($event) { + 'payment_session.completed' => PaymentStatus::Succeeded, + 'payment_session.expired' => PaymentStatus::Failed, + default => throw InvalidWebhookException::unsupportedType(self::NAME, $event === '' ? 'unknown event' : $event), + }; + + // A completed session that says anything else is not a paid session. + if ($status === PaymentStatus::Succeeded) { + $status = $this->sessionStatus($data['status'] ?? null); + } + + $sessionId = $data['payment_session_id'] ?? null; + $paymentId = $data['payment_id'] ?? null; + + return new WebhookEvent( + gateway: self::NAME, + status: $status, + transactionId: is_scalar($paymentId) && (string) $paymentId !== '' + ? (string) $paymentId + : (is_scalar($sessionId) ? (string) $sessionId : ''), + orderId: is_scalar($sessionId) ? (string) $sessionId : null, + reference: is_string($data['reference_id'] ?? null) ? $data['reference_id'] : null, + amount: $this->money($data['amount'] ?? null, $data['currency'] ?? null) + ?? Money::minor(0, (string) ($this->string('currency') ?? 'IDR')), + success: $status === PaymentStatus::Succeeded, + pending: $status === PaymentStatus::Pending, + refunded: false, + voided: false, + createdAt: is_string($data['updated'] ?? null) ? $data['updated'] : (is_string($data['created'] ?? null) ? $data['created'] : null), + raw: $data, + ); + } + + private function sessionStatus(mixed $status): PaymentStatus + { + $code = strtoupper(trim((string) $status)); + + if ($code === '') { + throw GatewayException::invalidResponse(self::NAME, 'session status'); + } + + return self::SESSION_STATUSES[$code] ?? throw InvalidWebhookException::unsupportedType(self::NAME, 'session status ['.$code.']'); + } + + private function refundStatus(mixed $status): PaymentStatus + { + $code = strtoupper(trim((string) $status)); + + if ($code === '') { + throw GatewayException::invalidResponse(self::NAME, 'refund status'); + } + + return self::REFUND_STATUSES[$code] ?? throw InvalidWebhookException::unsupportedType(self::NAME, 'refund status ['.$code.']'); + } + + /** + * Xendit documents a fixed reason enum. A caller that passes one of the + * documented codes keeps it; anything else becomes the customer-request + * default, because free text would be rejected by the API. + */ + private function refundReason(?string $reason): string + { + $reason = strtoupper(trim((string) $reason)); + + if ($reason !== '' && preg_match('/^[A-Z_]{3,64}$/', $reason) === 1) { + return $reason; + } + + return 'REQUESTED_BY_CUSTOMER'; + } + + private function money(mixed $amount, mixed $currency): ?Money + { + if (! is_int($amount) && ! (is_string($amount) && ctype_digit($amount))) { + return null; + } + + if (! is_string($currency) || $currency === '') { + return null; + } + + return Money::minor((int) $amount, $currency); + } + + /** + * @param array $headers + */ + private function header(array $headers, string $name): ?string + { + foreach ($headers as $key => $value) { + if (strtolower((string) $key) !== $name) { + continue; + } + + if (is_array($value)) { + $value = $value[0] ?? null; + } + + return is_scalar($value) ? (string) $value : null; + } + + return null; + } + + private function client(): XenditClient + { + if ($this->client instanceof XenditClient) { + return $this->client; + } + + return new XenditClient( + $this->string('base_url') ?? 'https://api.xendit.co', + (string) $this->string('secret_key'), + $this->string('api_version') ?? '2024-11-11', + $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.xendit.'.$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 6a22c23..937c730 100644 --- a/src/TahseelManager.php +++ b/src/TahseelManager.php @@ -40,6 +40,7 @@ use Tahseel\Gateways\Square\SquareGateway; use Tahseel\Gateways\Stripe\StripeGateway; use Tahseel\Gateways\Tap\TapGateway; +use Tahseel\Gateways\Xendit\XenditGateway; /** * Resolves configured gateways. Laravel's Manager gives us `extend()` so an @@ -209,6 +210,11 @@ protected function createAdyenDriver(): Gateway return new AdyenGateway($this->configuration(AdyenGateway::NAME), $this->idempotencyStore()); } + protected function createXenditDriver(): Gateway + { + return new XenditGateway($this->configuration(XenditGateway::NAME), $this->idempotencyStore()); + } + protected function createSquareDriver(): Gateway { return new SquareGateway($this->configuration(SquareGateway::NAME), $this->idempotencyStore()); diff --git a/tests/Feature/XenditGatewayTest.php b/tests/Feature/XenditGatewayTest.php new file mode 100644 index 0000000..c0b999c --- /dev/null +++ b/tests/Feature/XenditGatewayTest.php @@ -0,0 +1,212 @@ +> + */ +function xenditHeaders(string $token = 'xendit-callback-token'): array +{ + return ['x-callback-token' => [$token]]; +} + +it('resolves the xendit driver by name', function () { + expect(Tahseel::gateway('xendit'))->toBeInstanceOf(XenditGateway::class) + ->and(Tahseel::gateway('xendit')->name())->toBe('xendit'); +}); + +it('creates a payment session and returns the hosted link', function () { + Http::fake([ + 'api.xendit.co/sessions' => Http::response($this->fixture('xendit/session-created.json'), 200), + ]); + + $session = Tahseel::gateway('xendit')->createPayment(xenditRequest()); + + expect($session->gateway)->toBe('xendit') + ->and($session->reference)->toBe('ORDER-6112') + ->and($session->intentionId)->toBe('ps-661f87c614802d6c402cd82d') + ->and($session->checkoutUrl)->toBe('https://xen.to/kGxPCi60') + ->and($session->expiresAt)->toBe('2027-12-31T23:59:59Z'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.xendit.co/sessions' + && $request->hasHeader('Authorization', 'Basic '.base64_encode('xnd_development_secret_key:')) + && $request->hasHeader('api-version', '2024-11-11') + && $request['reference_id'] === 'ORDER-6112' + && $request['mode'] === 'PAYMENT_LINK' + && $request['amount'] === 9500 + && $request['currency'] === 'IDR' + && $request['country'] === 'ID' + && $request['success_return_url'] === 'https://example.test/checkout/done' + && $request['cancel_return_url'] === 'https://example.test/checkout/cancelled'); +}); + +it('demands the callback token it needs to authenticate webhooks', function () { + config()->set('tahseel.drivers.xendit.callback_token', null); + + Tahseel::gateway('xendit')->createPayment(xenditRequest()); +})->throws(ConfigurationException::class); + +it('parses a completed session and keeps the payment id for refunds', function () { + Http::fake(); + + $event = Tahseel::gateway('xendit')->verifyAndParseWebhook( + $this->fixture('xendit/session-completed.json'), + [], + xenditHeaders(), + ); + + expect($event->gateway)->toBe('xendit') + ->and($event->status)->toBe(PaymentStatus::Succeeded) + ->and($event->success)->toBeTrue() + ->and($event->transactionId)->toBe('py-661f87c614802d6c402cd82d') + ->and($event->orderId)->toBe('ps-661f87c614802d6c402cd82d') + ->and($event->reference)->toBe('ORDER-6112') + ->and($event->amount?->toMinor())->toBe(9500) + ->and($event->amount?->currency)->toBe('IDR'); + + Http::assertNothingSent(); +}); + +it('rejects a webhook with the wrong callback token', function () { + expect(fn () => Tahseel::gateway('xendit')->verifyAndParseWebhook( + $this->fixture('xendit/session-completed.json'), + [], + xenditHeaders('guessed-token'), + ))->toThrow(InvalidSignatureException::class); +}); + +it('rejects a webhook with no callback token', function () { + expect(fn () => Tahseel::gateway('xendit')->verifyAndParseWebhook($this->fixture('xendit/session-completed.json'))) + ->toThrow(InvalidSignatureException::class); +}); + +it('maps an expired session to failed', function () { + $event = Tahseel::gateway('xendit')->verifyAndParseWebhook( + $this->fixture('xendit/session-expired.json'), + [], + xenditHeaders(), + ); + + expect($event->status)->toBe(PaymentStatus::Failed) + ->and($event->success)->toBeFalse(); +}); + +it('does not treat a completed event with an unpaid status as paid', function () { + $payload = $this->fixture('xendit/session-completed.json'); + $payload['data']['status'] = 'ACTIVE'; + + $event = Tahseel::gateway('xendit')->verifyAndParseWebhook($payload, [], xenditHeaders()); + + expect($event->status)->toBe(PaymentStatus::Pending) + ->and($event->pending)->toBeTrue() + ->and($event->success)->toBeFalse(); +}); + +it('refuses an event type it does not understand', function () { + Tahseel::gateway('xendit')->verifyAndParseWebhook( + ['event' => 'payment.captured', 'data' => ['payment_session_id' => 'ps-1']], + [], + xenditHeaders(), + ); +})->throws(InvalidWebhookException::class); + +it('refuses a session status outside the documented set', function () { + $payload = $this->fixture('xendit/session-completed.json'); + $payload['data']['status'] = 'SETTLED'; + + Tahseel::gateway('xendit')->verifyAndParseWebhook($payload, [], xenditHeaders()); +})->throws(InvalidWebhookException::class); + +it('refunds by payment id with the documented reason enum', function () { + Http::fake([ + 'api.xendit.co/refunds' => Http::response($this->fixture('xendit/refund-succeeded.json'), 200), + ]); + + $result = Tahseel::gateway('xendit')->refund(new RefundRequest( + transactionId: 'py-661f87c614802d6c402cd82d', + amount: Money::minor(9500, 'IDR'), + reason: 'customer asked', + )); + + expect($result->status)->toBe(PaymentStatus::Refunded) + ->and($result->transactionId)->toBe('rfd-1402feb0-8b79-85ae-9d1e-e69394d3949c') + ->and($result->orderId)->toBe('py-661f87c614802d6c402cd82d'); + + Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.xendit.co/refunds' + && $request->hasHeader('api-version', '2024-11-11') + && $request['payment_id'] === 'py-661f87c614802d6c402cd82d' + && $request['amount'] === 9500 + && $request['reason'] === 'REQUESTED_BY_CUSTOMER'); +}); + +it('passes a documented reason code straight through', function () { + Http::fake([ + 'api.xendit.co/refunds' => Http::response($this->fixture('xendit/refund-succeeded.json'), 200), + ]); + + Tahseel::gateway('xendit')->refund(new RefundRequest( + transactionId: 'py-661f87c614802d6c402cd82d', + amount: Money::minor(9500, 'IDR'), + reason: 'DUPLICATE', + )); + + Http::assertSent(fn (Request $request): bool => $request['reason'] === 'DUPLICATE'); +}); + +it('reports a pending refund as pending', function () { + Http::fake([ + 'api.xendit.co/refunds' => Http::response($this->fixture('xendit/refund-pending.json'), 200), + ]); + + $result = Tahseel::gateway('xendit')->refund(new RefundRequest( + transactionId: 'py-661f87c614802d6c402cd82d', + amount: Money::minor(9500, 'IDR'), + )); + + expect($result->status)->toBe(PaymentStatus::Pending); +}); + +it('demands an explicit amount for a refund', function () { + Tahseel::gateway('xendit')->refund(new RefundRequest(transactionId: 'py-661f87c614802d6c402cd82d')); +})->throws(InvalidPaymentRequestException::class); + +it('demands the xendit payment id for a refund', function () { + Tahseel::gateway('xendit')->refund(new RefundRequest(orderId: ' ', amount: Money::minor(1, 'IDR'))); +})->throws(InvalidPaymentRequestException::class); + +it('surfaces a xendit error instead of inventing a status', function () { + Http::fake([ + 'api.xendit.co/sessions' => Http::response([ + 'error_code' => 'API_VALIDATION_ERROR', + 'message' => 'There was an error with the format submitted to the server.', + ], 400), + ]); + + Tahseel::gateway('xendit')->createPayment(xenditRequest()); +})->throws(GatewayException::class); diff --git a/tests/Fixtures/xendit/refund-pending.json b/tests/Fixtures/xendit/refund-pending.json new file mode 100644 index 0000000..a74e689 --- /dev/null +++ b/tests/Fixtures/xendit/refund-pending.json @@ -0,0 +1,7 @@ +{ + "refund_id": "rfd-1402feb0-8b79-85ae-9d1e-e69394d3949c", + "payment_id": "py-661f87c614802d6c402cd82d", + "status": "PENDING", + "amount": 9500, + "reason": "REQUESTED_BY_CUSTOMER" +} diff --git a/tests/Fixtures/xendit/refund-succeeded.json b/tests/Fixtures/xendit/refund-succeeded.json new file mode 100644 index 0000000..797bb52 --- /dev/null +++ b/tests/Fixtures/xendit/refund-succeeded.json @@ -0,0 +1,8 @@ +{ + "refund_id": "rfd-1402feb0-8b79-85ae-9d1e-e69394d3949c", + "payment_id": "py-661f87c614802d6c402cd82d", + "status": "SUCCEEDED", + "amount": 9500, + "reason": "REQUESTED_BY_CUSTOMER", + "created": "2026-12-31T23:59:59Z" +} diff --git a/tests/Fixtures/xendit/session-completed.json b/tests/Fixtures/xendit/session-completed.json new file mode 100644 index 0000000..948db0d --- /dev/null +++ b/tests/Fixtures/xendit/session-completed.json @@ -0,0 +1,17 @@ +{ + "event": "payment_session.completed", + "business_id": "661f87c614802d6c402cd82d", + "created": "2026-12-31T23:59:59Z", + "data": { + "payment_session_id": "ps-661f87c614802d6c402cd82d", + "reference_id": "ORDER-6112", + "status": "COMPLETED", + "amount": 9500, + "currency": "IDR", + "country": "ID", + "mode": "PAYMENT_LINK", + "payment_id": "py-661f87c614802d6c402cd82d", + "created": "2026-12-30T23:59:59Z", + "updated": "2026-12-31T23:59:59Z" + } +} diff --git a/tests/Fixtures/xendit/session-created.json b/tests/Fixtures/xendit/session-created.json new file mode 100644 index 0000000..30d207f --- /dev/null +++ b/tests/Fixtures/xendit/session-created.json @@ -0,0 +1,11 @@ +{ + "payment_session_id": "ps-661f87c614802d6c402cd82d", + "mode": "PAYMENT_LINK", + "status": "ACTIVE", + "reference_id": "ORDER-6112", + "amount": 9500, + "currency": "IDR", + "country": "ID", + "expires_at": "2027-12-31T23:59:59Z", + "payment_link_url": "https://xen.to/kGxPCi60" +} diff --git a/tests/Fixtures/xendit/session-expired.json b/tests/Fixtures/xendit/session-expired.json new file mode 100644 index 0000000..508906a --- /dev/null +++ b/tests/Fixtures/xendit/session-expired.json @@ -0,0 +1,13 @@ +{ + "event": "payment_session.expired", + "business_id": "661f87c614802d6c402cd82d", + "created": "2026-12-31T23:59:59Z", + "data": { + "payment_session_id": "ps-661f87c614802d6c402cd82d", + "reference_id": "ORDER-6112", + "status": "EXPIRED", + "amount": 9500, + "currency": "IDR", + "updated": "2026-12-31T23:59:59Z" + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index beaa8ad..1ff28fc 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -221,6 +221,18 @@ protected function defineEnvironment($app): void 'timeout' => 10, ]); + $app['config']->set('tahseel.drivers.xendit', [ + 'base_url' => 'https://api.xendit.co', + 'secret_key' => 'xnd_development_secret_key', + 'api_version' => '2024-11-11', + 'callback_token' => 'xendit-callback-token', + 'country' => 'ID', + 'currency' => 'IDR', + 'return_url' => 'https://example.test/checkout/done', + 'cancel_url' => 'https://example.test/checkout/cancelled', + 'timeout' => 10, + ]); + $app['config']->set('tahseel.drivers.square', [ 'base_url' => 'https://connect.squareup.com', 'access_token' => 'sandbox-access-token',