diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e622f61 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,107 @@ +name: Validate and package + +on: + push: + branches: + - "**" + tags: + - "v*" + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + lint: + name: PHP ${{ matrix.php }} lint + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: ["7.4", "8.1", "8.2", "8.3"] + + steps: + - name: Check out source + uses: actions/checkout@v7 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: curl, json, zip + coverage: none + + - name: Lint module PHP files + shell: bash + run: | + set -euo pipefail + find modules -type f -name '*.php' -print0 \ + | xargs -0 -n1 php -l + + package: + name: Build release archive + needs: lint + runs-on: ubuntu-latest + + steps: + - name: Check out source + uses: actions/checkout@v7 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.3" + extensions: zip + coverage: none + + - name: Build archive + shell: bash + run: | + set -euo pipefail + version="$(php -r '$manifest = json_decode(file_get_contents("modules/gateways/sslcommerz/whmcs.json"), true); echo $manifest["version"];')" + archive="dist/SSLCommerz-WHMCS-Module-${version}.zip" + mkdir -p dist + zip -q -r "$archive" modules README.md CHANGELOG.md LICENSE + unzip -t "$archive" + + - name: Upload archive + uses: actions/upload-artifact@v7 + with: + name: SSLCommerz-WHMCS-Module + path: dist/*.zip + if-no-files-found: error + + release: + name: Publish tagged release + if: startsWith(github.ref, 'refs/tags/v') + needs: package + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Check out source + uses: actions/checkout@v7 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: "8.3" + extensions: zip + coverage: none + + - name: Build release archive + shell: bash + run: | + set -euo pipefail + version="$(php -r '$manifest = json_decode(file_get_contents("modules/gateways/sslcommerz/whmcs.json"), true); echo $manifest["version"];')" + archive="dist/SSLCommerz-WHMCS-Module-${version}.zip" + mkdir -p dist + zip -q -r "$archive" modules README.md CHANGELOG.md LICENSE + unzip -t "$archive" + + - name: Publish tagged release + env: + GH_TOKEN: ${{ github.token }} + run: gh release create "$GITHUB_REF_NAME" dist/*.zip --title "$GITHUB_REF_NAME" --generate-notes diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fa04309 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/dist/ +/.idea/ +/.vscode/ +*.log +*.tmp +*.zip +.DS_Store +Thumbs.db diff --git a/ACKNOWLEDGEMENTS.md b/ACKNOWLEDGEMENTS.md new file mode 100644 index 0000000..4925cd1 --- /dev/null +++ b/ACKNOWLEDGEMENTS.md @@ -0,0 +1,24 @@ +# Acknowledgements + +SSLCommerz for WHMCS 1.0.0 was built and verified with the following platforms, technologies, tools, and community references. + +## Project and platform + +- **[Extent Technologies Limited](https://extentit.com/)** - project author and maintainer. +- **[SSLCommerz](https://sslcommerz.com/)** - payment gateway and v4 API integrated by this module. SSLCommerz and related marks belong to their respective owners. +- **[WHMCS](https://www.whmcs.com/)** - billing and automation platform, module APIs, gateway callbacks, administrator authentication, and database integration surface. +- **[PHP](https://www.php.net/)** - runtime language, including the cURL and JSON extensions used for API communication and payload handling. + +## Development and release tooling + +- **[Git](https://git-scm.com/)** and **[GitHub](https://github.com/)** - source control, collaboration, issue tracking, and public release hosting. +- **[GitHub Actions](https://github.com/features/actions)** - automated multi-version PHP syntax validation, packaging, and tagged releases. +- **[Setup PHP](https://github.com/shivammathur/setup-php)** by Shivam Mathur and contributors - PHP runtime provisioning in GitHub Actions. +- **[`zip` and `unzip`](https://infozip.sourceforge.net/)** - command-line release packaging and archive integrity validation. + +## Community references + +- **[rtraselbd/SSLCommerzWHMCS](https://github.com/rtraselbd/SSLCommerzWHMCS)** - earlier open-source WHMCS integration reviewed as a compatibility and API reference. +- **[Pull request #3](https://github.com/rtraselbd/SSLCommerzWHMCS/pull/3)** and its contributors - community discussion used to review refund and integration edge cases. + +This acknowledgement does not imply endorsement by or affiliation with the named vendors or projects. Their respective licenses and terms continue to apply. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c9e96c5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +All notable public changes are documented here. + +## 1.0.0 - 2026-09-14 + +First public production release. + +### Added + +- EasyCheckout popup, Legacy Hosted, and New Hosted checkout modes. +- Secure server-side invoice reload and signed checkout requests. +- Shared browser callback and IPN validation with idempotent settlement. +- Customer-currency and settled-BDT reconciliation. +- Full and partial refunds based on the captured exchange rate. +- Durable refund reservations and cumulative captured-balance limits. +- Administrator transaction lookup, recent-transaction selector, focused detail views, refund-status queries, and CSV export. +- Redacted diagnostic logging for session and provider failures. +- Multi-version PHP syntax checks, release packaging, and GitHub Release workflow. + +### Security + +- Restricted gateway redirects to documented exact SSLCommerz HTTPS hosts. +- Added strict signature, transaction identity, amount, currency, status, and risk checks. +- Prevented callback requests from replacing the customer's WHMCS session cookie. +- Added atomic settlement claims and duplicate WHMCS transaction guards. +- Masked card data, redacted credentials, and neutralized spreadsheet formulas in exports. + +### Fixed + +- Accepted SSLCommerz's live EasyCheckout `cart_json` callback wrapper. +- Correctly routed the live New Hosted checkout while retaining Legacy Hosted behavior. +- Avoided rejecting empty optional customer address fields before the provider can evaluate a session. +- Corrected foreign-currency records so BDT settlements are never displayed as the invoice currency. +- Recovered invoice identity from legacy merchant transaction IDs when possible. +- Replaced custom lookup token rotation with WHMCS native administrator CSRF validation. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..13b533d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,44 @@ +# Contributing + +Thank you for helping improve SSLCommerz for WHMCS. + +## Before starting + +- Search existing issues and pull requests for related work. +- Open an issue for a significant behavior or API-contract change before investing in a large implementation. +- Report security problems privately according to [SECURITY.md](SECURITY.md). +- Never post real store credentials, customer data, session cookies, full card details, or unredacted production logs. + +## Development setup + +1. Fork the repository and create a focused branch. +2. Install PHP 7.4 or a supported PHP 8.x version with cURL and JSON, plus the command-line `zip` and `unzip` tools for release packaging. +3. Lint the published module files with `find modules -type f -name '*.php' -print0 | xargs -0 -n1 php -l`. +4. Make the smallest compatible implementation and verify the affected WHMCS behavior. +5. Build the distributable archive with the same `zip` command used by GitHub Actions. + +Keep production code compatible with PHP 7.4. Do not commit live WHMCS data, credentials, or production logs. + +## Code and verification expectations + +- Follow the existing plain-PHP style and preserve WHMCS module entry-point contracts. +- Treat callback, IPN, currency, refund, and idempotency logic as security-sensitive. +- Validate provider data before changing invoice or transaction state. +- Keep diagnostics actionable but redact credentials and personal data. +- Document behavior-focused verification for fixes, including failure and retry paths where relevant. +- Keep the release ZIP installable at the WHMCS root and free of tests, scripts, and development files. + +## Pull requests + +A pull request should: + +- Explain the problem and the resulting behavior +- Reference the related issue when one exists +- Include verification evidence for functional changes +- Update README or CHANGELOG when operators need to act differently +- Pass the multi-version PHP syntax and packaging workflow +- Avoid unrelated formatting or refactoring + +By contributing, you agree that your contribution is licensed under the repository's [MIT License](LICENSE). + +Please be respectful, specific, and constructive in all project interactions. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..741a96e --- /dev/null +++ b/LICENSE @@ -0,0 +1,30 @@ +MIT License + +Copyright (c) 2026 Extent Technologies Limited + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +NOTICE + +This software integrates with the SSLCommerz payment gateway API. SSLCommerz +and related marks belong to their respective owners. This project is not +endorsed by or affiliated with SSL Wireless/SSLCommerz or WHMCS. + +Users must obtain their own API credentials and comply with the applicable +SSLCommerz and WHMCS terms. diff --git a/README.md b/README.md new file mode 100644 index 0000000..74a994b --- /dev/null +++ b/README.md @@ -0,0 +1,146 @@ +# SSLCommerz for WHMCS + +[](CHANGELOG.md) +[](https://www.php.net/) +[](LICENSE) + +A production-ready SSLCommerz v4 payment gateway for WHMCS, with secure checkout, callback/IPN settlement, multi-currency reconciliation, refunds, and an optional administrator transaction-lookup add-on. + +Version **1.0.0** is the first public production release. + +> This is an independent community integration. It is not an official product of, sponsored by, or affiliated with SSL Wireless/SSLCommerz or WHMCS. + +## Features + +- EasyCheckout popup, Legacy Hosted, and New Hosted checkout modes +- Server-side invoice reload and short-lived HMAC checkout tokens +- Shared, idempotent browser callback and IPN payment processing +- Strict transaction, amount, currency, risk, and identity validation +- Safe USD/foreign-currency to BDT settlement reconciliation +- Full and partial refunds using the payment's captured exchange rate +- Searchable local transaction ledger, remote refresh, and refund status lookup +- Masked card details and formula-safe CSV export +- PHP 7.4-compatible code with automated PHP 7.4 and PHP 8.x checks + +## Requirements + +- WHMCS 8.x or 9.x +- PHP 7.4 or a supported PHP 8.x release; PHP 8.3 is tested +- PHP cURL and JSON extensions +- A public HTTPS WHMCS System URL with a valid certificate +- SSLCommerz sandbox or live store credentials +- A fixed public outbound/NAT IP registered with SSLCommerz for live refund APIs + +## Installation + +1. Back up the WHMCS database and any existing SSLCommerz module files. +2. Download the release ZIP and extract it. +3. Copy the extracted `modules` directory into the WHMCS installation root, merging it with the existing `modules` directory. +4. Open **Configuration > Apps & Integrations > Payments** and activate **SSLCommerz Payment Gateway**. +5. Enter the store ID and password, select the environment and checkout mode, then save. +6. Optionally activate **SSLCommerz Transaction Lookup** under **System Settings > Addon Modules** and grant access to the required administrator roles. +7. Complete a sandbox payment and verify both the invoice and **Billing > Gateway Log** before enabling live mode. + +For upgrades, replace all gateway, callback, and add-on files together. Keep `legacy_popup` for the first compatibility test and clear any PHP opcode cache after deployment. + + + +## Configuration + +Configure the credentials, Test Mode, checkout mode, invoice transaction-ID preference, and gateway display name from the WHMCS payment gateway page. Never commit or share live store credentials. + + + +The local table `mod_sslcommerz_transactions` is created or upgraded lazily on the first gateway or lookup operation. Existing rows are retained. + +## Checkout modes + +### EasyCheckout popup (`legacy_popup`) + +Uses SSLCommerz's official EasyCheckout embed flow. This is the compatibility default for existing installations. + + + +### Legacy Hosted (`legacy_hosted`) + +Creates the session on the WHMCS server and redirects the browser to SSLCommerz's hosted checkout. + + + +### New Hosted (`new_hosted`) + +Uses the production `pay.sslcommerz.com` experience. Sandbox keeps SSLCommerz's documented sandbox endpoint because a separate sandbox New Hosted endpoint is not published. + + + +Every mode reloads the invoice amount, currency, payment status, and customer data from WHMCS before starting the gateway session. + +## Callback and IPN + +The gateway submits these endpoints with each checkout session: + +- Browser success, failure, and cancellation: `/modules/gateways/callback/sslcommerz.php` +- IPN listener: `/modules/gateways/callback/sslcommerz_ipn.php` + +Register the full HTTPS IPN URL in the SSLCommerz store panel if the account requires a static listener. Do not place either endpoint behind login, CAPTCHA, maintenance authentication, or a cache. The callback and IPN suppress PHP session cookies so a cross-site return cannot replace the customer's active WHMCS session. + +Browser returns and IPNs use the same validation and settlement processor. Atomic ledger claims and WHMCS transaction checks prevent duplicate invoice credit. + +## Currency reconciliation + +The module keeps the customer's invoice amount separate from the BDT amount settled by SSLCommerz. A `0.10 USD` invoice settled as `12.34 BDT` is displayed as those two distinct values, never as `12.34 USD`. + +For non-BDT invoices, refunds reuse the BDT-per-invoice-currency rate captured during payment. Historical foreign-currency payments without a captured rate are refused because applying a current rate could over-refund. Refund totals are capped at the remaining captured BDT balance, and durable reservations keep concurrent attempts idempotent. + +## Refunds + +WHMCS refunds use SSLCommerz's refund API. Before using refunds on a live store, ask SSLCommerz to allowlist the WHMCS server's fixed public outbound/NAT IP. `REQUEST_FROM_INVALID_SOURCE` means the API saw an unapproved source IP; it is an account/network restriction rather than a checkout failure. + +## Transaction lookup add-on + +The administrator add-on provides a minimal dashboard for recent transactions, multi-field search, focused transaction details, reconciliation, refund-status queries, and CSV export. + + + +- The home page can show the latest 10, 20, 50, or 100 attempts. +- Search results replace the recent-transactions list. +- Opening a record shows only its grouped detail table. +- WHMCS native administrator CSRF validation protects state-changing requests. +- Credentials and full card details are excluded or redacted. + +## Troubleshooting + +- **Popup reports an error in communication:** verify all 1.0.0 files were uploaded together and clear the PHP opcode cache. The popup endpoint accepts SSLCommerz's live `cart_json` wrapper while authenticating the signed invoice token. +- **New Hosted opens the legacy page:** confirm `new_hosted` is saved. Live New Hosted rewrites only SSLCommerz's exact approved live session host to `pay.sslcommerz.com`. +- **Unable to start payment:** inspect the newest `SESSION_FAILED` record in the lookup add-on or **Billing > Gateway Log**. Local, transport, and provider failures are logged while the customer sees a generic message. +- **Invoice remains unpaid:** confirm the public HTTPS callback and IPN endpoints are reachable and that the response matches the original invoice currency amount and settled BDT amount. +- **Customer is logged out after return:** confirm the 1.0.0 callback files replaced older scripts and that no proxy or plug-in injects a session cookie into callback responses. +- **Refund returns `REQUEST_FROM_INVALID_SOURCE`:** register the server's public outbound IP with SSLCommerz, then retry the same refund. +- **Lookup View reports an expired token:** clear the opcode cache. Version 1.0.0 uses WHMCS's native administrator CSRF token and has no custom rotating lookup token. + +## Development + +Lint the published module PHP files: + +```bash +find modules -type f -name '*.php' -print0 | xargs -0 -n1 php -l +``` + +Build an installable release archive: + +```bash +version="$(php -r '$manifest = json_decode(file_get_contents("modules/gateways/sslcommerz/whmcs.json"), true); echo $manifest["version"];')" +mkdir -p dist +zip -q -r "dist/SSLCommerz-WHMCS-Module-${version}.zip" modules README.md CHANGELOG.md LICENSE +``` + +GitHub Actions runs multi-version PHP syntax checks and builds the installable ZIP artifact. A `v*` tag also creates a GitHub Release containing that archive. + +## Security, contributing, and credits + +- Read [SECURITY.md](SECURITY.md) before reporting a vulnerability. +- See [CONTRIBUTING.md](CONTRIBUTING.md) for development and pull-request guidance. +- See [ACKNOWLEDGEMENTS.md](ACKNOWLEDGEMENTS.md) for the platforms, tools, projects, and contributors that made this release possible. +- Changes are recorded in [CHANGELOG.md](CHANGELOG.md). + +Released under the [MIT License](LICENSE). Copyright © 2026 Extent Technologies Limited. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c12332b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,36 @@ +# Security Policy + +## Supported versions + +Security fixes are provided for the current `1.x` release line. Upgrade to the latest published release before reporting an issue that may already be resolved. + +## Reporting a vulnerability + +You may report a security concern by opening a GitHub issue. Provide enough information to identify and reproduce the problem, but remove credentials, personal data, payment details, and other sensitive information first. + +For vulnerabilities that could expose sensitive data, enable unauthorized payments, or provide a practical exploit, you may instead use the repository's **Security > Report a vulnerability** option to open a private GitHub Security Advisory. If private reporting is unavailable, open an issue containing only a high-level description and ask the maintainer for a secure communication channel. + +Include: + +- The affected module version, WHMCS version, PHP version, and checkout mode +- A concise impact assessment and reproducible steps +- Relevant request/response structure with secrets and personal data removed +- Whether the issue is reproducible in sandbox, production, or both +- Any mitigation already attempted + +Never include store passwords, checkout tokens, full card data, customer personal data, session cookies, database exports, or unredacted server logs. + +## Security scope + +Reports concerning signature validation, authentication, callback/IPN processing, redirect validation, duplicate settlement, refund authorization, credential exposure, CSRF, CSV injection, or sensitive-data handling are in scope. + +Provider account policy, SSLCommerz service availability, WHMCS core behavior, and unsupported third-party modifications are normally outside this project's control, but integration-specific evidence is still welcome. + +## Operational guidance + +- Use HTTPS for the WHMCS System URL and callback/IPN endpoints. +- Protect production credentials and rotate them if exposure is suspected. +- Restrict lookup add-on access to trusted administrator roles. +- Register only the required fixed outbound IP with SSLCommerz for refund access. +- Keep WHMCS, PHP, this module, and server dependencies supported and patched. +- Review **Billing > Gateway Log** after deployment and remove exported logs when no longer needed. diff --git a/images/Legacy-Hosted-PopUp.png b/images/Legacy-Hosted-PopUp.png new file mode 100644 index 0000000..22e20f9 Binary files /dev/null and b/images/Legacy-Hosted-PopUp.png differ diff --git a/images/Legacy-Hosted.png b/images/Legacy-Hosted.png new file mode 100644 index 0000000..e9899b7 Binary files /dev/null and b/images/Legacy-Hosted.png differ diff --git a/images/Module-Addon-Activation.png b/images/Module-Addon-Activation.png new file mode 100644 index 0000000..d1f2285 Binary files /dev/null and b/images/Module-Addon-Activation.png differ diff --git a/images/New-Hosted-Checkout.png b/images/New-Hosted-Checkout.png new file mode 100644 index 0000000..21ea255 Binary files /dev/null and b/images/New-Hosted-Checkout.png differ diff --git a/images/Transaction-Lookup.png b/images/Transaction-Lookup.png new file mode 100644 index 0000000..76ead35 Binary files /dev/null and b/images/Transaction-Lookup.png differ diff --git a/images/config.png b/images/config.png new file mode 100644 index 0000000..a8e18f8 Binary files /dev/null and b/images/config.png differ diff --git a/modules/addons/sslcommerz_lookup/lib/LookupService.php b/modules/addons/sslcommerz_lookup/lib/LookupService.php new file mode 100644 index 0000000..757d924 --- /dev/null +++ b/modules/addons/sslcommerz_lookup/lib/LookupService.php @@ -0,0 +1,169 @@ +ledger = $ledger; + $this->api = $api; + } + + public function recent($limit = 20) + { + return $this->normalizeRows($this->ledger->recent($limit), 'local'); + } + + public function detail($id) + { + $row = $this->ledger->findById((int) $id); + return $row ? $this->normalizeRow((array) $row, 'local') : null; + } + + public function search($field, $value, $limit = 50) + { + $field = strtolower(trim((string) $field)); + $value = trim((string) $value); + $allowed = array('invoice_id', 'tran_id', 'bank_tran_id', 'val_id', 'sessionkey', 'card_last4'); + if (!in_array($field, $allowed, true)) { + throw new InvalidArgumentException('Unsupported search field.'); + } + if ($value === '') { + throw new InvalidArgumentException('Enter a search value.'); + } + if ($field === 'card_last4') { + $value = substr(preg_replace('/\D/', '', $value), -4); + if (strlen($value) !== 4) { throw new InvalidArgumentException('Enter the last four card digits.'); } + } + + $local = $this->ledger->search($field, $value, $limit); + $remoteCapable = in_array($field, array('tran_id','sessionkey','val_id'), true); + if ($local && (!$remoteCapable || !$this->needsRefresh($local))) { + return $this->normalizeRows($local, 'local'); + } + $remote = array(); + if ($field === 'val_id') { + $remote = array($this->api->validate($value)); + } elseif ($field === 'tran_id' || $field === 'sessionkey') { + $response = $this->api->query(array($field => $value)); + $remote = $this->normalizeQueryResponse($response); + $remote = array_map(function ($row) { unset($row['source']); return $row; }, $remote); + } + foreach ($remote as $transaction) { + if (method_exists($this->ledger, 'upsertFromGateway')) { + $this->ledger->upsertFromGateway($transaction, $field === 'sessionkey' ? $value : null); + } + } + if (!$remote) { return $local ? $this->normalizeRows($local, 'local') : array(); } + return $this->mergeRows($local, $remote); + } + + public function refundStatus($refundRefId) + { + $refundRefId = trim((string) $refundRefId); + if ($refundRefId === '') { throw new InvalidArgumentException('Enter a refund reference ID.'); } + return $this->api->queryRefund($refundRefId); + } + + private function normalizeQueryResponse(array $response) + { + if (isset($response['element']) && is_array($response['element'])) { + return $this->normalizeRows($response['element'], 'remote'); + } + if (isset($response[0]) && is_array($response[0])) { + return $this->normalizeRows($response, 'remote'); + } + if (isset($response['tran_id']) || isset($response['status'])) { + return $this->normalizeRows(array($response), 'remote'); + } + return array(); + } + + private function needsRefresh($rows) + { + foreach ((array)$rows as $row) { + $row = (array)$row; + if (empty($row['bank_tran_id']) || empty($row['val_id']) || empty($row['bdt_amount']) + || in_array(strtolower(isset($row['status'])?$row['status']:''), array('initiated','session_created','validating'), true)) { + return true; + } + } + return false; + } + + private function mergeRows($local, array $remote) + { + $merged = array(); + foreach ((array)$local as $row) { + $row = $this->normalizeRow((array)$row, 'local'); + $merged[isset($row['tran_id'])?$row['tran_id']:'local-'.count($merged)] = $row; + } + foreach ($remote as $row) { + $row = $this->normalizeRow((array)$row, 'remote'); + $key = isset($row['tran_id'])?$row['tran_id']:'remote-'.count($merged); + $merged[$key] = isset($merged[$key]) ? array_merge($merged[$key], $row) : $row; + } + return array_values($merged); + } + + private function normalizeRows($rows, $source) + { + $normalized = array(); + foreach ((array) $rows as $row) { + $normalized[] = $this->normalizeRow((array) $row, $source); + } + return $normalized; + } + + private function normalizeRow(array $row, $source) + { + $raw = array(); + if (!empty($row['raw_response']) && is_string($row['raw_response'])) { + $decoded = json_decode($row['raw_response'], true); + if (is_array($decoded)) { $raw = $decoded; } + } + unset($row['raw_response'], $row['validation_raw']); + + // SSLCommerz reports the original/customer currency as currency_type, + // while currency may be the BDT settlement currency on legacy rows. + $customerCurrency = !empty($row['currency_type']) + ? (string)$row['currency_type'] + : (isset($row['currency']) ? (string)$row['currency'] : 'BDT'); + $row['currency'] = strtoupper($customerCurrency); + + if ((!isset($row['bdt_amount']) || (float)$row['bdt_amount'] <= 0) && isset($row['amount'])) { + $row['bdt_amount'] = (float)$row['amount']; + } + if ((!isset($row['invoice_amount']) || (float)$row['invoice_amount'] <= 0) && isset($row['currency_amount']) && (float)$row['currency_amount'] > 0) { + $row['invoice_amount'] = (float)$row['currency_amount']; + } + if ((!isset($row['invoice_amount']) || (float)$row['invoice_amount'] <= 0) && $row['currency'] === 'BDT' && !empty($row['bdt_amount'])) { + $row['invoice_amount'] = (float)$row['bdt_amount']; + } + if (isset($row['invoice_amount'])) { $row['invoice_amount'] = (float)$row['invoice_amount']; } + if (isset($row['bdt_amount'])) { $row['bdt_amount'] = (float)$row['bdt_amount']; } + + $row['invoice_id'] = isset($row['invoice_id']) ? (int)$row['invoice_id'] : 0; + if ($row['invoice_id'] <= 0 && isset($row['value_a']) && ctype_digit((string)$row['value_a'])) { + $row['invoice_id'] = (int)$row['value_a']; + } + if ($row['invoice_id'] <= 0 && !empty($row['tran_id']) && preg_match('/^INV([0-9]+)-/i', (string)$row['tran_id'], $match)) { + $row['invoice_id'] = (int)$match[1]; + } + + $invoiceAmount = isset($row['invoice_amount']) ? (float)$row['invoice_amount'] : 0.0; + $bdtAmount = isset($row['bdt_amount']) ? (float)$row['bdt_amount'] : 0.0; + $rate = isset($row['currency_rate_bdt']) ? (float)$row['currency_rate_bdt'] : 0.0; + if ($rate <= 0 && $invoiceAmount > 0 && $bdtAmount > 0) { + $row['currency_rate_bdt'] = round($bdtAmount / $invoiceAmount, 8); + } + + if (!empty($raw['failedreason']) && is_scalar($raw['failedreason'])) { + $row['failure_reason'] = trim((string)$raw['failedreason']); + } + $row['source'] = $source; + return $row; + } +} diff --git a/modules/addons/sslcommerz_lookup/lib/PageState.php b/modules/addons/sslcommerz_lookup/lib/PageState.php new file mode 100644 index 0000000..8a8d1aa --- /dev/null +++ b/modules/addons/sslcommerz_lookup/lib/PageState.php @@ -0,0 +1,18 @@ +'; + + $titles = array( + 'home' => 'SSLCommerz Transactions', + 'search' => 'Search Results', + 'detail' => 'Transaction Detail', + 'refund' => 'Refund Status', + ); + + $html = '
Search local records and refresh supported identifiers from SSLCommerz.
Check the latest status using an SSLCommerz refund reference ID.
Customer currency and gateway-settled BDT are shown separately.
Try another identifier or return to the overview.
| ID | Transaction | Invoice | Customer Amount | Settled Amount | ' + . 'Card | Status | Date | Action | ' + . '
|---|---|---|---|---|---|---|---|---|
| ' . ($id ?: '-') . ' | ' + . '' . self::e(isset($row['tran_id']) ? $row['tran_id'] : '-') . ' | '
+ . '' . $invoice . ' | ' . self::e(self::customerAmount($row)) . ' | ' + . '' . self::e(self::settledAmount($row)) . ' | ' + . '' . self::e(self::maskCard(isset($row['card_no']) ? $row['card_no'] : '')) . ' | ' + . '' . self::e($status) . ' | ' + . '' . self::e(self::transactionDate($row)) . ' | ' . $view . ' |
The requested ledger record is no longer available.
Record #' . self::e(isset($detail['id']) ? $detail['id'] : '-') . '
| ' . self::e($group) . ' | |
|---|---|
| ' . self::e($item[0]) . ' | ' . $value . ' |
Latest gateway response for the requested refund.
| ' . self::e($label) . ' | ' . self::e($value) . ' |
|---|
' . self::e($value) . '';
+ }
+
+ public static function csvCell($value)
+ {
+ $value = (string) $value;
+ return preg_match('/^[=+\-@\t\r]/', $value) ? "'" . $value : $value;
+ }
+
+ public static function csvRows(array $rows)
+ {
+ $columns = array('id', 'invoice_id', 'tran_id', 'bank_tran_id', 'val_id', 'sessionkey', 'status', 'currency', 'invoice_amount', 'bdt_amount', 'refunded_bdt', 'refund_ref_id', 'card_no', 'card_type', 'card_brand', 'risk_level', 'created_at', 'updated_at');
+ $stream = fopen('php://temp', 'w+');
+ fputcsv($stream, $columns);
+ foreach ($rows as $row) {
+ $line = array();
+ foreach ($columns as $column) {
+ $value = isset($row[$column]) ? $row[$column] : '';
+ if ($column === 'card_no') { $value = self::maskCard($value); }
+ $line[] = self::csvCell($value);
+ }
+ fputcsv($stream, $line);
+ }
+ rewind($stream);
+ $csv = stream_get_contents($stream);
+ fclose($stream);
+ return $csv;
+ }
+
+ private static function maskCard($value)
+ {
+ $digits = preg_replace('/\D/', '', (string) $value);
+ return strlen($digits) >= 4 ? '****' . substr($digits, -4) : '-';
+ }
+
+ private static function e($value)
+ {
+ return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
+ }
+
+ private static function styles()
+ {
+ return '.sc-wrap{--sc-border:#d9e2ec;--sc-text:#263648;--sc-muted:#66788a;--sc-blue:#1f6fb2;max-width:1480px;color:var(--sc-text)}'
+ . '.sc-wrap *{box-sizing:border-box}.sc-page-head{display:flex;align-items:center;justify-content:space-between;gap:20px;margin:4px 0 18px}'
+ . '.sc-page-head h2{font-size:25px;line-height:1.2;margin:0;font-weight:650}.sc-panel-head p,.sc-card-copy p{color:var(--sc-muted);margin:0}'
+ . '.sc-back{white-space:nowrap}'
+ . '.sc-tools{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(300px,.65fr);gap:16px;margin-bottom:16px}.sc-panel{background:#fff;border:1px solid var(--sc-border);border-radius:10px;box-shadow:0 1px 2px rgba(30,55,80,.04);padding:20px;margin-bottom:16px}'
+ . '.sc-tool-card{position:relative;padding-top:18px}.sc-card-icon{width:38px;height:38px;border-radius:9px;display:flex;align-items:center;justify-content:center;background:#eaf4ff;color:#1768a8;font-size:18px;margin-bottom:12px}.sc-refund-icon{background:#edf9f1;color:#187944}'
+ . '.sc-card-copy h3,.sc-panel-head h3{font-size:17px;margin:0 0 4px;font-weight:650}.sc-card-copy{margin-bottom:16px}.sc-form{display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap}.sc-field{flex:1 1 220px}.sc-field label,.sc-limit-form label{display:block;font-size:12px;font-weight:650;margin:0 0 5px;color:#44576a}'
+ . '.sc-field input,.sc-field select,.sc-limit-form select{width:100%;height:36px;border:1px solid #b8c6d4;border-radius:5px;background:#fff;padding:7px 10px;color:#263648}.sc-field input:focus,.sc-field select:focus,.sc-limit-form select:focus{border-color:#4e95cf;box-shadow:0 0 0 2px rgba(52,136,201,.12);outline:0}'
+ . '.sc-panel-head{display:flex;align-items:center;justify-content:space-between;gap:18px;margin-bottom:14px}.sc-table-actions,.sc-limit-form{display:flex;align-items:center;gap:8px}.sc-table-actions form{margin:0}.sc-limit-form label{margin:0}.sc-limit-form select{width:72px;height:31px;padding:4px 7px}'
+ . '.sc-scroll{overflow-x:auto;border:1px solid #e5ebf1;border-radius:7px}.sc-table,.sc-detail-table{width:100%;border-collapse:separate;border-spacing:0;margin:0}.sc-table th{background:#f5f8fb;color:#53677a;font-size:11px;letter-spacing:.045em;text-transform:uppercase;padding:11px 12px;border-bottom:1px solid #dfe7ef;white-space:nowrap}'
+ . '.sc-table td{padding:11px 12px;border-bottom:1px solid #edf1f5;vertical-align:middle;white-space:nowrap}.sc-table tbody tr:last-child td{border-bottom:0}.sc-table tbody tr:hover{background:#fafcff}.sc-table th,.sc-table td{text-align:left}.sc-money{font-variant-numeric:tabular-nums;font-weight:600}.sc-id{color:#6b7c8e}.sc-code{font-size:11px;color:#b4234d;background:#fff1f5;border-radius:4px;padding:3px 6px}.sc-row-action form{margin:0}.sc-action-col,.sc-row-action{text-align:right!important}'
+ . '.sc-status{display:inline-flex;align-items:center;border-radius:999px;padding:4px 8px;font-size:10px;line-height:1;font-weight:750;letter-spacing:.035em}.sc-status-success{background:#e8f7ee;color:#18733c}.sc-status-danger{background:#fff0f1;color:#a52735}.sc-status-warning{background:#fff5df;color:#8a5a00}.sc-status-neutral{background:#edf2f6;color:#53677a}'
+ . '.sc-detail-panel{max-width:1040px}.sc-detail-table th,.sc-detail-table td{padding:11px 15px;border-bottom:1px solid #edf1f5;text-align:left;vertical-align:top}.sc-detail-table th{width:250px;color:#52677b;font-weight:600}.sc-detail-table td{word-break:break-word}.sc-detail-table tr:last-child th,.sc-detail-table tr:last-child td{border-bottom:0}.sc-detail-table .sc-detail-section th{width:auto;background:#f5f8fb;color:#28445f;text-transform:uppercase;letter-spacing:.055em;font-size:11px;padding:10px 15px}'
+ . '.sc-alert{padding:12px 15px;border-radius:6px;margin-bottom:15px;border:1px solid transparent}.sc-error{background:#fff2f3;color:#941f2c;border-color:#ffd5d9}.sc-success{background:#edfbf2;color:#176538;border-color:#ccefd9}.sc-info{background:#eef7ff;color:#1b5d91;border-color:#d5eaff}'
+ . '.sc-empty{text-align:center;padding:38px 20px;color:var(--sc-muted)}.sc-empty span{display:block;font-size:26px;margin-bottom:8px}.sc-empty strong{display:block;color:#405466;font-size:15px}.sc-empty p{margin:5px 0 0}'
+ . '@media(max-width:980px){.sc-tools{grid-template-columns:1fr}.sc-page-head,.sc-panel-head{align-items:flex-start}.sc-table-actions{align-items:flex-end;flex-direction:column}.sc-detail-panel{max-width:none}}'
+ . '@media(max-width:620px){.sc-page-head{align-items:flex-start;flex-direction:column}.sc-form{align-items:stretch;flex-direction:column}.sc-panel{padding:15px}.sc-panel-head{flex-direction:column}.sc-table-actions{width:100%;align-items:stretch}.sc-limit-form{flex-wrap:wrap}.sc-detail-table th{width:42%}}';
+ }
+}
diff --git a/modules/addons/sslcommerz_lookup/sslcommerz_lookup.php b/modules/addons/sslcommerz_lookup/sslcommerz_lookup.php
new file mode 100644
index 0000000..624ab60
--- /dev/null
+++ b/modules/addons/sslcommerz_lookup/sslcommerz_lookup.php
@@ -0,0 +1,107 @@
+ 'SSLCommerz Transaction Lookup',
+ 'description' => 'Search the local payment ledger, refresh transaction data through the v4 API, export CSV, and query refund status.',
+ 'version' => '1.0.0',
+ 'author' => 'Extent Technologies Limited',
+ 'fields' => array(
+ 'store_id' => array(
+ 'FriendlyName' => 'Store ID', 'Type' => 'text', 'Size' => '40',
+ 'Description' => 'SSLCommerz store ID used for remote lookup.',
+ ),
+ 'store_passwd' => array(
+ 'FriendlyName' => 'Store Password', 'Type' => 'password', 'Size' => '40',
+ 'Description' => 'SSLCommerz store password. It is never rendered in lookup results.',
+ ),
+ 'testmode' => array(
+ 'FriendlyName' => 'Test Mode', 'Type' => 'yesno',
+ 'Description' => 'Query the SSLCommerz sandbox instead of production.',
+ ),
+ ),
+ );
+}
+
+function sslcommerz_lookup_output($vars)
+{
+ $moduleLink = !empty($vars['modulelink']) ? $vars['modulelink'] : 'addonmodules.php?module=sslcommerz_lookup';
+ $rows = array();
+ $detail = null;
+ $refund = null;
+ $notice = null;
+ $request = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
+ $screen = SslCommerzLookupPageState::screen($request);
+ $recentLimit = SslCommerzLookupPageState::recentLimit(isset($request['recent_limit']) ? $request['recent_limit'] : 20);
+
+ try {
+ $api = new SslCommerzApiClient(array(
+ 'store_id' => isset($vars['store_id']) ? $vars['store_id'] : '',
+ 'store_password' => isset($vars['store_passwd']) ? $vars['store_passwd'] : '',
+ 'testmode' => isset($vars['testmode']) && $vars['testmode'] === 'on',
+ ));
+ $service = new SslCommerzLookupService(new SslCommerzLedger(), $api);
+
+ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+ check_token('WHMCS.admin.default');
+
+ if (isset($_POST['export_csv'])) {
+ $csv = SslCommerzLookupRenderer::csvRows($service->recent(5000));
+ while (ob_get_level() > 0) { ob_end_clean(); }
+ header('Content-Type: text/csv; charset=utf-8');
+ header('Content-Disposition: attachment; filename="sslcommerz-transactions-' . date('Y-m-d-His') . '.csv"');
+ header('Cache-Control: no-store');
+ echo "\xEF\xBB\xBF" . $csv;
+ exit;
+ }
+ if (isset($_POST['search_txn'])) {
+ $rows = $service->search(
+ isset($_POST['search_type']) ? $_POST['search_type'] : 'tran_id',
+ isset($_POST['search_value']) ? $_POST['search_value'] : ''
+ );
+ $notice = array('kind' => 'success', 'message' => count($rows) . ' transaction attempt(s) found.');
+ } elseif (isset($_POST['view_detail'])) {
+ $detail = $service->detail((int) $_POST['view_detail']);
+ if (!$detail) { $notice = array('kind' => 'error', 'message' => 'Transaction detail was not found.'); }
+ } elseif (isset($_POST['query_refund'])) {
+ $refund = $service->refundStatus(isset($_POST['refund_ref_id']) ? $_POST['refund_ref_id'] : '');
+ } else {
+ $rows = $service->recent($recentLimit);
+ }
+ } else {
+ $rows = $service->recent($recentLimit);
+ }
+ } catch (Throwable $error) {
+ $notice = array('kind' => 'error', 'message' => $error->getMessage());
+ if (!isset($service)) {
+ $rows = array();
+ } elseif (!$rows) {
+ try {
+ if ($screen === 'home') { $rows = $service->recent($recentLimit); }
+ } catch (Throwable $ignored) {}
+ }
+ if (function_exists('logActivity')) {
+ logActivity('SSLCommerz lookup: ' . $error->getMessage());
+ }
+ }
+
+ $token = generate_token('plain');
+ echo SslCommerzLookupRenderer::page($moduleLink, $token, $rows, $detail, $refund, $notice, array(
+ 'screen' => $screen,
+ 'recent_limit' => $recentLimit,
+ ));
+}
diff --git a/modules/addons/sslcommerz_lookup/whmcs.json b/modules/addons/sslcommerz_lookup/whmcs.json
new file mode 100644
index 0000000..73ddf36
--- /dev/null
+++ b/modules/addons/sslcommerz_lookup/whmcs.json
@@ -0,0 +1,23 @@
+{
+ "schema": "1.0",
+ "type": "whmcs-addons",
+ "name": "sslcommerz_lookup",
+ "version": "1.0.0",
+ "license": "MIT",
+ "category": "utilities",
+ "description": {
+ "name": "SSLCommerz Transaction Lookup",
+ "tagline": "Search, inspect, and reconcile SSLCommerz transactions with full v4 API support.",
+ "long": "A responsive administrator dashboard for recent transactions, multi-field search, focused transaction details, refund status queries, and formula-safe CSV export. Customer-currency amounts and settled BDT amounts are displayed independently."
+ },
+ "support": {
+ "homepage": "https://sslcommerz.com",
+ "docs_url": "https://developer.sslcommerz.com/doc/v4/"
+ },
+ "authors": [
+ {
+ "name": "Extent Technologies Limited",
+ "homepage": "https://extentit.com"
+ }
+ ]
+}
diff --git a/modules/gateways/callback/sslcommerz.php b/modules/gateways/callback/sslcommerz.php
new file mode 100644
index 0000000..0eda096
--- /dev/null
+++ b/modules/gateways/callback/sslcommerz.php
@@ -0,0 +1,30 @@
+process($_POST, 'browser');
+$response = SslCommerzCallbackResponse::browser($result, $systemUrl);
+
+http_response_code($response['status']);
+header('Cache-Control: no-store');
+header('Location: ' . $response['location']);
+exit;
diff --git a/modules/gateways/callback/sslcommerz_checkout.php b/modules/gateways/callback/sslcommerz_checkout.php
new file mode 100644
index 0000000..3b2a8d2
--- /dev/null
+++ b/modules/gateways/callback/sslcommerz_checkout.php
@@ -0,0 +1,27 @@
+ 'FAILED', 'data' => null, 'message' => 'SSLCommerz is not active.'));
+ exit;
+}
+if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
+ http_response_code(405);
+ header('Allow: POST');
+ echo json_encode(array('status' => 'FAILED', 'data' => null, 'message' => 'POST required.'));
+ exit;
+}
+
+$response = SslCommerzCheckoutEndpoint::popup($_POST, $gateway, SslCommerzBootstrap::checkoutService($gateway));
+http_response_code($response['http_status']);
+if ($response['http_status'] !== 200) {
+ $logData = array('request' => SslCommerzSupport::redact($_POST));
+ if (!empty($response['diagnostic'])) { $logData['diagnostic'] = $response['diagnostic']; }
+ logTransaction($gateway['name'], $logData, 'Popup Session Initiation Failed');
+}
+echo json_encode($response['body']);
diff --git a/modules/gateways/callback/sslcommerz_init.php b/modules/gateways/callback/sslcommerz_init.php
new file mode 100644
index 0000000..bdcfc88
--- /dev/null
+++ b/modules/gateways/callback/sslcommerz_init.php
@@ -0,0 +1,27 @@
+ SslCommerzSupport::redact($_POST));
+if (!empty($response['diagnostic'])) { $logData['diagnostic'] = $response['diagnostic']; }
+logTransaction($gateway['name'], $logData, 'Session Initiation Failed');
+http_response_code($response['http_status']);
+echo htmlspecialchars($response['error'], ENT_QUOTES, 'UTF-8');
diff --git a/modules/gateways/callback/sslcommerz_ipn.php b/modules/gateways/callback/sslcommerz_ipn.php
new file mode 100644
index 0000000..2bfcc2c
--- /dev/null
+++ b/modules/gateways/callback/sslcommerz_ipn.php
@@ -0,0 +1,27 @@
+process($_POST, 'ipn');
+$response = SslCommerzCallbackResponse::ipn($result);
+http_response_code($response['status']);
+echo $response['body'];
+exit;
diff --git a/modules/gateways/sslcommerz.php b/modules/gateways/sslcommerz.php
new file mode 100644
index 0000000..5c69867
--- /dev/null
+++ b/modules/gateways/sslcommerz.php
@@ -0,0 +1,97 @@
+ 'SSLCommerz Payment Gateway',
+ 'APIVersion' => '1.1',
+ 'DisableLocalCreditCardInput' => true,
+ 'TokenisedStorage' => false,
+ );
+}
+
+function sslcommerz_config()
+{
+ return array(
+ 'FriendlyName' => array('Type' => 'System', 'Value' => 'SSLCommerz Payment Gateway'),
+ 'store_id' => array('FriendlyName' => 'Store ID', 'Type' => 'text', 'Size' => '40'),
+ 'store_password' => array('FriendlyName' => 'Store Password', 'Type' => 'password', 'Size' => '40'),
+ 'testmode' => array('FriendlyName' => 'Test Mode', 'Type' => 'yesno', 'Description' => 'Enable SSLCommerz Sandbox mode.'),
+ 'ui_mode' => array(
+ 'FriendlyName' => 'Checkout UI Mode',
+ 'Type' => 'dropdown',
+ 'Options' => array(
+ 'legacy_popup' => 'Legacy EasyCheckout Popup',
+ 'legacy_hosted' => 'Legacy Hosted Redirect',
+ 'new_hosted' => 'New Hosted Checkout',
+ ),
+ 'Default' => 'legacy_popup',
+ 'Description' => 'Legacy remains the upgrade default. New Hosted uses the production pay.sslcommerz.com experience.',
+ ),
+ 'transid_source' => array(
+ 'FriendlyName' => 'WHMCS Transaction ID',
+ 'Type' => 'dropdown',
+ 'Options' => array('tran_id' => 'Merchant Transaction ID', 'bank_tran_id' => 'Bank Transaction ID'),
+ 'Default' => 'tran_id',
+ 'Description' => 'Both identifiers are retained in the SSLCommerz ledger.',
+ ),
+ 'button_text' => array('FriendlyName' => 'Payment Button Label', 'Type' => 'text', 'Size' => '30', 'Default' => 'Pay with SSLCommerz'),
+ );
+}
+
+function sslcommerz_link($params)
+{
+ $mode = SslCommerzSupport::checkoutMode(isset($params['ui_mode']) ? $params['ui_mode'] : 'legacy_popup');
+ $invoiceId = (int) $params['invoiceid'];
+ $expires = time() + 900;
+ $token = SslCommerzSupport::checkoutToken($invoiceId, $expires, (string) $params['store_password']);
+ $base = rtrim((string) $params['systemurl'], '/');
+ $button = !empty($params['button_text']) ? (string) $params['button_text'] : (isset($params['langpaynow']) ? (string) $params['langpaynow'] : 'Pay Now');
+
+ if ($mode !== 'legacy_popup') {
+ $action = $base . '/modules/gateways/callback/sslcommerz_init.php';
+ return '';
+ }
+
+ $endpoint = $base . '/modules/gateways/callback/sslcommerz_checkout.php';
+ $embed = isset($params['testmode']) && $params['testmode'] === 'on'
+ ? 'https://sandbox.sslcommerz.com/embed.min.js'
+ : 'https://seamless-epay.sslcommerz.com/embed.min.js';
+ $postData = array('invoice_id' => $invoiceId, 'expires' => $expires, 'checkout_token' => $token);
+ $json = json_encode($postData, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
+
+ return ''
+ . '';
+}
+
+function sslcommerz_escape($value)
+{
+ return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
+}
+
+function sslcommerz_refund($params)
+{
+ if (!class_exists('SslCommerzRefundService')) {
+ require_once __DIR__ . '/sslcommerz/lib/RefundService.php';
+ }
+ return SslCommerzRefundService::fromWhmcs($params)->refund($params);
+}
diff --git a/modules/gateways/sslcommerz/lib/ApiClient.php b/modules/gateways/sslcommerz/lib/ApiClient.php
new file mode 100644
index 0000000..8d25929
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/ApiClient.php
@@ -0,0 +1,145 @@
+storeId = trim((string) $credentials['store_id']);
+ $this->storePassword = trim((string) $credentials['store_password']);
+ $this->testMode = !empty($credentials['testmode']) || !empty($credentials['sandbox']);
+ $this->transport = $transport;
+ if ($this->storeId === '' || $this->storePassword === '') {
+ throw new InvalidArgumentException('SSLCommerz store credentials are required.');
+ }
+ }
+
+ public function createSession(array $payload)
+ {
+ return $this->request('POST', '/gwprocess/v4/api.php', array_merge($payload, $this->credentials()));
+ }
+
+ public function validate($valId)
+ {
+ if (trim((string) $valId) === '') {
+ throw new InvalidArgumentException('Validation ID is required.');
+ }
+ return $this->request('GET', '/validator/api/validationserverAPI.php', array_merge(
+ array('val_id' => (string) $valId, 'v' => 1, 'format' => 'json'),
+ $this->credentials()
+ ));
+ }
+
+ public function query(array $selector)
+ {
+ $params = array();
+ if (!empty($selector['sessionkey'])) {
+ $params['sessionkey'] = (string) $selector['sessionkey'];
+ } elseif (!empty($selector['tran_id'])) {
+ $params['tran_id'] = (string) $selector['tran_id'];
+ } else {
+ throw new InvalidArgumentException('A transaction ID or session key is required.');
+ }
+ return $this->request('GET', '/validator/api/merchantTransIDvalidationAPI.php', array_merge(
+ $params,
+ $this->credentials(),
+ array('v' => 1, 'format' => 'json')
+ ));
+ }
+
+ public function refund(array $payload)
+ {
+ return $this->request('GET', '/validator/api/merchantTransIDvalidationAPI.php', array_merge(
+ $payload,
+ $this->credentials(),
+ array('v' => 1, 'format' => 'json')
+ ));
+ }
+
+ public function queryRefund($refundRefId)
+ {
+ if (trim((string) $refundRefId) === '') {
+ throw new InvalidArgumentException('Refund reference ID is required.');
+ }
+ return $this->request('GET', '/validator/api/merchantTransIDvalidationAPI.php', array_merge(
+ array('refund_ref_id' => (string) $refundRefId),
+ $this->credentials(),
+ array('v' => 1, 'format' => 'json')
+ ));
+ }
+
+ public function lastRequest()
+ {
+ return $this->lastRequest;
+ }
+
+ private function credentials()
+ {
+ return array('store_id' => $this->storeId, 'store_passwd' => $this->storePassword);
+ }
+
+ private function request($method, $path, array $params)
+ {
+ $url = ($this->testMode ? 'https://sandbox.sslcommerz.com' : 'https://securepay.sslcommerz.com') . $path;
+ $this->lastRequest = SslCommerzSupport::redact(array('method' => $method, 'url' => $url, 'params' => $params));
+
+ try {
+ $raw = $this->transport
+ ? call_user_func($this->transport, $method, $url, $params)
+ : $this->curlTransport($method, $url, $params);
+ } catch (Throwable $error) {
+ throw new RuntimeException('SSLCommerz request failed: ' . $error->getMessage(), 0, $error);
+ }
+
+ if (is_array($raw)) {
+ return $raw;
+ }
+ $decoded = json_decode((string) $raw, true);
+ if (!is_array($decoded)) {
+ throw new UnexpectedValueException('SSLCommerz returned malformed JSON.');
+ }
+ return $decoded;
+ }
+
+ private function curlTransport($method, $url, array $params)
+ {
+ if ($method === 'GET') {
+ $url .= '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
+ }
+
+ $handle = curl_init($url);
+ curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 10);
+ curl_setopt($handle, CURLOPT_TIMEOUT, 30);
+ curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, true);
+ curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 2);
+ if (defined('CURL_SSLVERSION_TLSv1_2')) {
+ curl_setopt($handle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
+ }
+ if ($method === 'POST') {
+ curl_setopt($handle, CURLOPT_POST, true);
+ curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($params, '', '&', PHP_QUERY_RFC3986));
+ curl_setopt($handle, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
+ }
+
+ $body = curl_exec($handle);
+ $error = curl_error($handle);
+ $status = (int) curl_getinfo($handle, CURLINFO_HTTP_CODE);
+ curl_close($handle);
+
+ if ($body === false || $error !== '') {
+ throw new RuntimeException('cURL error: ' . $error);
+ }
+ if ($status < 200 || $status >= 300) {
+ throw new RuntimeException('HTTP ' . $status . ' from SSLCommerz.');
+ }
+ return $body;
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/Bootstrap.php b/modules/gateways/sslcommerz/lib/Bootstrap.php
new file mode 100644
index 0000000..6288f08
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/Bootstrap.php
@@ -0,0 +1,122 @@
+ $gateway['store_id'],
+ 'store_password' => $gateway['store_password'],
+ 'testmode' => isset($gateway['testmode']) && $gateway['testmode'] === 'on',
+ ));
+ $ledger = new SslCommerzLedger();
+ $callbacks = array(
+ 'check_invoice' => function ($invoiceId) use ($gateway) {
+ checkCbInvoiceID($invoiceId, $gateway['name']);
+ return (int) $invoiceId;
+ },
+ 'find_transaction' => function ($transId) {
+ $row = \WHMCS\Database\Capsule::table('tblaccounts')
+ ->where('gateway', 'sslcommerz')->where('transid', (string) $transId)->first();
+ return $row ? (int) $row->invoiceid : null;
+ },
+ 'add_payment' => function ($invoiceId, $transId, $amount) {
+ addInvoicePayment($invoiceId, $transId, $amount, 0.00, 'sslcommerz');
+ return true;
+ },
+ 'log' => function ($status, $data) use ($gateway) {
+ logTransaction($gateway['name'], $data, $status);
+ },
+ );
+ return new SslCommerzPaymentProcessor($api, $ledger, $callbacks, $gateway);
+ }
+
+ public static function checkoutService(array $gateway)
+ {
+ $systemUrl = isset($gateway['systemurl']) ? $gateway['systemurl'] : \WHMCS\Config\Setting::getValue('SystemURL');
+ $api = new SslCommerzApiClient(array(
+ 'store_id' => $gateway['store_id'],
+ 'store_password' => $gateway['store_password'],
+ 'testmode' => isset($gateway['testmode']) && $gateway['testmode'] === 'on',
+ ));
+ $ledger = new SslCommerzLedger();
+ $loader = new SslCommerzWhmcsInvoiceLoader($systemUrl);
+ return new SslCommerzCheckoutService($api, $ledger, array($loader, 'load'), $gateway, $systemUrl);
+ }
+}
+
+class SslCommerzWhmcsInvoiceLoader
+{
+ private $systemUrl;
+
+ public function __construct($systemUrl)
+ {
+ $this->systemUrl = rtrim((string) $systemUrl, '/');
+ }
+
+ public function load($invoiceId)
+ {
+ $invoiceModel = \WHMCS\Billing\Invoice::find((int) $invoiceId);
+ if (!$invoiceModel) {
+ return null;
+ }
+ $invoice = \WHMCS\Database\Capsule::table('tblinvoices')
+ ->join('tblclients', 'tblclients.id', '=', 'tblinvoices.userid')
+ ->where('tblinvoices.id', (int) $invoiceId)
+ ->select(
+ 'tblinvoices.id as invoiceid', 'tblinvoices.status',
+ 'tblclients.currency as currency_id', 'tblclients.firstname', 'tblclients.lastname',
+ 'tblclients.email', 'tblclients.address1', 'tblclients.address2', 'tblclients.city',
+ 'tblclients.state', 'tblclients.postcode', 'tblclients.country', 'tblclients.phonenumber'
+ )->first();
+ if (!$invoice) {
+ return null;
+ }
+ $currency = \WHMCS\Database\Capsule::table('tblcurrencies')->where('id', $invoice->currency_id)->value('code');
+ return array(
+ 'invoiceid' => (int) $invoice->invoiceid,
+ 'status' => (string) $invoice->status,
+ 'amount' => (float) $invoiceModel->balance,
+ 'currency' => strtoupper((string) $currency),
+ 'description' => 'Invoice #' . (int) $invoice->invoiceid,
+ 'firstname' => (string) $invoice->firstname,
+ 'lastname' => (string) $invoice->lastname,
+ 'email' => (string) $invoice->email,
+ 'address1' => (string) $invoice->address1,
+ 'address2' => (string) $invoice->address2,
+ 'city' => (string) $invoice->city,
+ 'state' => (string) $invoice->state,
+ 'postcode' => (string) $invoice->postcode,
+ 'country' => (string) $invoice->country,
+ 'phone' => (string) $invoice->phonenumber,
+ 'returnurl' => $this->systemUrl . '/viewinvoice.php?id=' . (int) $invoice->invoiceid,
+ );
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/CallbackResponse.php b/modules/gateways/sslcommerz/lib/CallbackResponse.php
new file mode 100644
index 0000000..17d90bc
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/CallbackResponse.php
@@ -0,0 +1,28 @@
+ 0) {
+ $location = $base . '/viewinvoice.php?id=' . $invoiceId;
+ } else {
+ $location = $base . '/clientarea.php?action=invoices';
+ }
+ $location .= '&' . ($success ? 'paymentsuccess=true' : 'paymentfailed=true');
+
+ return array('status' => 303, 'location' => $location);
+ }
+
+ public static function ipn(array $result)
+ {
+ $code = isset($result['code']) ? strtolower((string) $result['code']) : 'rejected';
+ return array(
+ 'status' => $code === 'retry' ? 500 : 200,
+ 'body' => strtoupper($code),
+ );
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/CheckoutEndpoint.php b/modules/gateways/sslcommerz/lib/CheckoutEndpoint.php
new file mode 100644
index 0000000..383acec
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/CheckoutEndpoint.php
@@ -0,0 +1,110 @@
+ 403, 'body' => array('status' => 'FAILED', 'data' => null, 'message' => 'Checkout request expired. Reload the invoice and try again.'));
+ }
+ try {
+ $session = $service->initiate((int) $request['invoice_id']);
+ return array('http_status' => 200, 'body' => array(
+ 'status' => 'success', 'data' => $session['gateway_url'],
+ 'logo' => isset($session['store_logo']) ? $session['store_logo'] : '',
+ ));
+ } catch (Throwable $error) {
+ $diagnostic = self::diagnostic($error, $gateway, $service);
+ error_log('[SSLCommerz Checkout] ' . $diagnostic['message']);
+ return array(
+ 'http_status' => 502,
+ 'body' => array('status' => 'FAILED', 'data' => null, 'message' => 'Unable to start payment. Please try again or contact support.'),
+ 'diagnostic' => $diagnostic,
+ );
+ }
+ }
+
+ public static function hosted(array $request, array $gateway, $service, $now = null)
+ {
+ $mode = SslCommerzSupport::checkoutMode(isset($gateway['ui_mode']) ? $gateway['ui_mode'] : '');
+ if (!in_array($mode, array('legacy_hosted', 'new_hosted'), true)
+ || !self::authorized($request, $gateway, $now)) {
+ return array('http_status' => 403, 'error' => 'Checkout request expired. Reload the invoice and try again.');
+ }
+ try {
+ $session = $service->initiate((int) $request['invoice_id']);
+ $location = $mode === 'new_hosted'
+ ? SslCommerzSupport::newCheckoutUrl($session['gateway_url'], isset($gateway['testmode']) && $gateway['testmode'] === 'on')
+ : $session['gateway_url'];
+ return array('http_status' => 303, 'location' => $location);
+ } catch (Throwable $error) {
+ $diagnostic = self::diagnostic($error, $gateway, $service);
+ error_log('[SSLCommerz Checkout] ' . $diagnostic['message']);
+ return array(
+ 'http_status' => 502,
+ 'error' => 'Unable to start payment. Please try again or contact support.',
+ 'diagnostic' => $diagnostic,
+ );
+ }
+ }
+
+ private static function diagnostic(Throwable $error, array $gateway, $service)
+ {
+ $message = preg_replace('/[\x00-\x1F\x7F]+/', ' ', (string)$error->getMessage());
+ $password = isset($gateway['store_password']) ? (string)$gateway['store_password'] : '';
+ if ($password !== '') { $message = str_replace($password, '[REDACTED]', $message); }
+ $diagnostic = array(
+ 'type' => get_class($error),
+ 'message' => substr(trim($message), 0, 1000),
+ );
+ if (is_object($service) && method_exists($service, 'lastDiagnostic')) {
+ $context = $service->lastDiagnostic();
+ if (is_array($context) && $context) { $diagnostic['context'] = SslCommerzSupport::redact($context); }
+ }
+ return $diagnostic;
+ }
+
+ private static function authorized(array $request, array $gateway, $now)
+ {
+ return isset($request['invoice_id'], $request['expires'], $request['checkout_token'])
+ && (int) $request['invoice_id'] > 0
+ && SslCommerzSupport::checkoutTokenMatches(
+ (int) $request['invoice_id'], (int) $request['expires'], (string) $request['checkout_token'],
+ isset($gateway['store_password']) ? (string) $gateway['store_password'] : '', $now
+ );
+ }
+
+ private static function normalizePopupRequest(array $request)
+ {
+ $wrapperSeen = false;
+ $wrapperInvalid = false;
+ foreach (array('postdata', 'cart_json') as $wrapper) {
+ if (!array_key_exists($wrapper, $request) || $request[$wrapper] === '' || $request[$wrapper] === null) {
+ continue;
+ }
+ $wrapperSeen = true;
+ $postData = is_array($request[$wrapper])
+ ? $request[$wrapper]
+ : json_decode(html_entity_decode((string) $request[$wrapper], ENT_QUOTES, 'UTF-8'), true);
+ if (!is_array($postData)
+ || !isset($postData['invoice_id'], $postData['expires'], $postData['checkout_token'])) {
+ $wrapperInvalid = true;
+ continue;
+ }
+ $request = array_merge($request, $postData);
+ }
+ $request['_popup_payload_invalid'] = $wrapperInvalid;
+ if (!$wrapperSeen && empty($request['invoice_id']) && !empty($request['order'])) {
+ $request['invoice_id'] = $request['order'];
+ }
+ if (!$wrapperSeen && empty($request['checkout_token']) && !empty($request['token'])) {
+ $request['checkout_token'] = $request['token'];
+ }
+ return $request;
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/CheckoutService.php b/modules/gateways/sslcommerz/lib/CheckoutService.php
new file mode 100644
index 0000000..8afb91e
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/CheckoutService.php
@@ -0,0 +1,134 @@
+api = $api;
+ $this->ledger = $ledger;
+ $this->invoiceLoader = $invoiceLoader;
+ $this->gateway = $gateway;
+ $this->systemUrl = rtrim((string) $systemUrl, '/');
+ }
+
+ public function initiate($invoiceId)
+ {
+ $invoice = call_user_func($this->invoiceLoader, (int) $invoiceId);
+ if (!$invoice || (int) $invoice['invoiceid'] <= 0) {
+ throw new RuntimeException('Invoice was not found.');
+ }
+ if (strcasecmp((string) $invoice['status'], 'Unpaid') !== 0) {
+ throw new RuntimeException('Only unpaid invoices can be paid.');
+ }
+ if ((float) $invoice['amount'] <= 0) {
+ throw new RuntimeException('Invoice balance must be greater than zero.');
+ }
+
+ $tranId = SslCommerzSupport::transactionId($invoice['invoiceid']);
+ $callback = $this->systemUrl . '/modules/gateways/callback/sslcommerz.php';
+ $urls = array(
+ 'success_url' => $callback,
+ 'fail_url' => $callback,
+ 'cancel_url' => $callback,
+ 'ipn_url' => $this->systemUrl . '/modules/gateways/callback/sslcommerz_ipn.php',
+ 'return_url' => isset($invoice['returnurl']) ? $invoice['returnurl'] : $this->systemUrl . '/viewinvoice.php?id=' . (int) $invoice['invoiceid'],
+ );
+ $this->lastDiagnostic = array(
+ 'invoice_id' => (int)$invoice['invoiceid'],
+ 'tran_id' => $tranId,
+ 'amount' => (float)$invoice['amount'],
+ 'currency' => strtoupper((string)$invoice['currency']),
+ 'checkout_mode' => SslCommerzSupport::checkoutMode(isset($this->gateway['ui_mode']) ? $this->gateway['ui_mode'] : ''),
+ 'test_mode' => isset($this->gateway['testmode']) && $this->gateway['testmode'] === 'on',
+ 'customer_fields_present' => array(
+ 'name' => trim((isset($invoice['firstname']) ? (string)$invoice['firstname'] : '') . ' ' . (isset($invoice['lastname']) ? (string)$invoice['lastname'] : '')) !== '',
+ 'email' => isset($invoice['email']) && trim((string)$invoice['email']) !== '',
+ 'address' => isset($invoice['address1']) && trim((string)$invoice['address1']) !== '',
+ 'city' => isset($invoice['city']) && trim((string)$invoice['city']) !== '',
+ 'postcode' => isset($invoice['postcode']) && trim((string)$invoice['postcode']) !== '',
+ 'country' => isset($invoice['country']) && trim((string)$invoice['country']) !== '',
+ 'phone' => isset($invoice['phone']) && trim((string)$invoice['phone']) !== '',
+ ),
+ 'callback_host' => parse_url($callback, PHP_URL_HOST),
+ );
+
+ $this->ledger->begin(array(
+ 'invoice_id' => (int) $invoice['invoiceid'],
+ 'tran_id' => $tranId,
+ 'status' => 'initiated',
+ 'currency' => strtoupper((string) $invoice['currency']),
+ 'invoice_amount' => (float) $invoice['amount'],
+ ));
+
+ try {
+ $payload = SslCommerzPaymentRules::sessionPayload($this->gateway, $invoice, $urls, $tranId);
+ } catch (Throwable $error) {
+ $message = $this->redactDiagnosticText($error->getMessage());
+ $this->lastDiagnostic['preflight_error'] = $message;
+ $this->ledger->update($tranId, array(
+ 'status' => 'session_failed',
+ 'raw_response' => json_encode(array('status'=>'PREFLIGHT_FAILED','failedreason'=>$message)),
+ ));
+ throw $error;
+ }
+
+ try {
+ $response = $this->api->createSession($payload);
+ } catch (Throwable $error) {
+ $message = $this->redactDiagnosticText($error->getMessage());
+ $this->lastDiagnostic['transport_error'] = $message;
+ $this->ledger->update($tranId, array(
+ 'status' => 'session_failed',
+ 'raw_response' => json_encode(array('status'=>'TRANSPORT_FAILED','failedreason'=>$message)),
+ ));
+ throw $error;
+ }
+ $this->lastDiagnostic['gateway_status'] = strtoupper(isset($response['status']) ? (string)$response['status'] : '');
+ if (strtoupper(isset($response['status']) ? (string) $response['status'] : '') !== 'SUCCESS') {
+ $this->lastDiagnostic['gateway_failed_reason'] = isset($response['failedreason'])
+ ? $this->redactDiagnosticText($response['failedreason']) : 'SSLCommerz session creation failed.';
+ $this->ledger->update($tranId, array('status' => 'session_failed', 'raw_response' => json_encode(SslCommerzSupport::redact($response))));
+ throw new RuntimeException(isset($response['failedreason']) ? (string) $response['failedreason'] : 'SSLCommerz session creation failed.');
+ }
+ $gatewayUrl = isset($response['GatewayPageURL']) ? (string) $response['GatewayPageURL'] : '';
+ $this->lastDiagnostic['gateway_host'] = parse_url($gatewayUrl, PHP_URL_HOST);
+ if (!SslCommerzSupport::safeGatewayUrl($gatewayUrl)) {
+ $this->ledger->update($tranId, array(
+ 'status' => 'session_failed',
+ 'raw_response' => json_encode(SslCommerzSupport::redact($response)),
+ ));
+ throw new RuntimeException('SSLCommerz returned an unsafe gateway URL.');
+ }
+
+ $sessionKey = isset($response['sessionkey']) ? (string) $response['sessionkey'] : '';
+ $this->ledger->update($tranId, array(
+ 'status' => 'session_created',
+ 'sessionkey' => $sessionKey,
+ 'raw_response' => json_encode(SslCommerzSupport::redact($response)),
+ ));
+
+ return array('tran_id' => $tranId, 'sessionkey' => $sessionKey, 'gateway_url' => $gatewayUrl, 'store_logo' => isset($response['storeLogo']) ? $response['storeLogo'] : '');
+ }
+
+ public function lastDiagnostic()
+ {
+ return $this->lastDiagnostic;
+ }
+
+ private function redactDiagnosticText($message)
+ {
+ $message = (string)$message;
+ $password = isset($this->gateway['store_password']) ? (string)$this->gateway['store_password'] : '';
+ return $password !== '' ? str_replace($password, '[REDACTED]', $message) : $message;
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/Ledger.php b/modules/gateways/sslcommerz/lib/Ledger.php
new file mode 100644
index 0000000..28d9581
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/Ledger.php
@@ -0,0 +1,408 @@
+adapter = $adapter;
+ }
+
+ public static function schemaDefinition()
+ {
+ return array(
+ 'columns' => array(
+ 'id' => 'increments', 'invoice_id' => 'integer', 'tran_id' => 'string:30',
+ 'val_id' => 'string:100?', 'bank_tran_id' => 'string:100?', 'sessionkey' => 'string:128?',
+ 'status' => 'string:32', 'currency' => 'string:8', 'invoice_amount' => 'decimal:16,2',
+ 'bdt_amount' => 'decimal:16,2', 'currency_rate_bdt' => 'decimal:18,8',
+ 'refunded_bdt' => 'decimal:16,2', 'refund_ref_id' => 'string:100?',
+ 'refund_trans_id' => 'string:30?', 'card_no' => 'string:80?', 'card_type' => 'string:100?',
+ 'card_brand' => 'string:50?', 'card_issuer' => 'string:150?', 'risk_level' => 'integer',
+ 'risk_title' => 'string:80?', 'raw_response' => 'mediumText?',
+ 'settlement_claimed_at' => 'timestamp?', 'paid_at' => 'timestamp?',
+ 'created_at' => 'timestamp?', 'updated_at' => 'timestamp?',
+ ),
+ 'unique' => array('tran_id'),
+ 'indexes' => array('invoice_id', 'bank_tran_id', 'val_id', 'sessionkey', 'refund_ref_id'),
+ );
+ }
+
+ public static function refundSchemaDefinition()
+ {
+ return array(
+ 'columns' => array(
+ 'id'=>'increments','payment_tran_id'=>'string:30','invoice_id'=>'integer',
+ 'refund_trans_id'=>'string:30','request_key'=>'string:64','source_currency'=>'string:8',
+ 'source_amount'=>'decimal:16,2','base_refunded_bdt'=>'decimal:16,2','amount_bdt'=>'decimal:16,2',
+ 'refund_ref_id'=>'string:50?','status'=>'string:20','raw_response'=>'mediumText?',
+ 'created_at'=>'timestamp?','updated_at'=>'timestamp?',
+ ),
+ 'unique' => array('refund_trans_id', 'request_key'),
+ 'indexes' => array('payment_tran_id', 'invoice_id', 'refund_ref_id', 'status'),
+ );
+ }
+
+ public function ensureSchema()
+ {
+ if ($this->schemaReady) {
+ return;
+ }
+ if ($this->adapter) {
+ $this->adapter->ensureSchema(self::schemaDefinition());
+ if (method_exists($this->adapter, 'ensureRefundSchema')) {
+ $this->adapter->ensureRefundSchema(self::refundSchemaDefinition());
+ }
+ $this->schemaReady = true;
+ return;
+ }
+
+ $capsule = '\\WHMCS\\Database\\Capsule';
+ if (!class_exists($capsule)) {
+ throw new RuntimeException('WHMCS Capsule is not available.');
+ }
+ if (!$capsule::schema()->hasTable(self::TABLE)) {
+ try {
+ $capsule::schema()->create(self::TABLE, function ($table) {
+ $table->increments('id');
+ $table->integer('invoice_id')->unsigned()->index();
+ $table->string('tran_id', 30)->unique();
+ $table->string('val_id', 100)->nullable()->index();
+ $table->string('bank_tran_id', 100)->nullable()->index();
+ $table->string('sessionkey', 128)->nullable()->index();
+ $table->string('status', 32)->default('initiated')->index();
+ $table->string('currency', 8);
+ $table->decimal('invoice_amount', 16, 2)->default(0);
+ $table->decimal('bdt_amount', 16, 2)->default(0);
+ $table->decimal('currency_rate_bdt', 18, 8)->default(0);
+ $table->decimal('refunded_bdt', 16, 2)->default(0);
+ $table->string('refund_ref_id', 100)->nullable()->index();
+ $table->string('refund_trans_id', 30)->nullable();
+ $table->string('card_no', 80)->nullable();
+ $table->string('card_type', 100)->nullable();
+ $table->string('card_brand', 50)->nullable();
+ $table->string('card_issuer', 150)->nullable();
+ $table->smallInteger('risk_level')->default(0);
+ $table->string('risk_title', 80)->nullable();
+ $table->mediumText('raw_response')->nullable();
+ $table->timestamp('settlement_claimed_at')->nullable();
+ $table->timestamp('paid_at')->nullable();
+ $table->timestamp('created_at')->nullable();
+ $table->timestamp('updated_at')->nullable();
+ });
+ } catch (Throwable $error) {
+ if (!$capsule::schema()->hasTable(self::TABLE)) { throw $error; }
+ }
+ } else {
+ $this->migrateExistingTable($capsule);
+ }
+ $this->ensureRefundTable($capsule);
+ $this->schemaReady = true;
+ }
+
+ public function begin(array $attempt)
+ {
+ $this->ensureSchema();
+ $now = date('Y-m-d H:i:s');
+ $row = array_merge(array(
+ 'status' => 'initiated', 'bdt_amount' => 0, 'currency_rate_bdt' => 0,
+ 'refunded_bdt' => 0, 'created_at' => $now, 'updated_at' => $now,
+ ), $this->filter($attempt));
+ if ($this->adapter) {
+ return $this->adapter->insert($row);
+ }
+ return \WHMCS\Database\Capsule::table(self::TABLE)->insertGetId($row);
+ }
+
+ public function update($tranId, array $fields)
+ {
+ $this->ensureSchema();
+ $fields = $this->filter($fields);
+ $fields['updated_at'] = date('Y-m-d H:i:s');
+ if ($this->adapter) {
+ return $this->adapter->update((string) $tranId, $fields);
+ }
+ return \WHMCS\Database\Capsule::table(self::TABLE)->where('tran_id', (string) $tranId)->update($fields);
+ }
+
+ public function find($id)
+ {
+ $this->ensureSchema();
+ if ($this->adapter) {
+ return $this->adapter->find((string) $id);
+ }
+ return \WHMCS\Database\Capsule::table(self::TABLE)
+ ->where('tran_id', (string) $id)->orWhere('bank_tran_id', (string) $id)->first();
+ }
+
+ public function findById($id)
+ {
+ $this->ensureSchema();
+ if ($this->adapter) {
+ return $this->adapter->findById((int) $id);
+ }
+ return \WHMCS\Database\Capsule::table(self::TABLE)->where('id', (int) $id)->first();
+ }
+
+ public function recent($limit = 20)
+ {
+ $this->ensureSchema();
+ $limit = max(1, min(5000, (int) $limit));
+ if ($this->adapter) {
+ return $this->adapter->recent($limit);
+ }
+ return \WHMCS\Database\Capsule::table(self::TABLE)->orderBy('id', 'desc')->limit($limit)->get()->all();
+ }
+
+ public function upsertFromGateway(array $transaction, $sessionKey = null)
+ {
+ if (empty($transaction['tran_id'])) { return false; }
+ $tranId = (string)$transaction['tran_id'];
+ $currency = strtoupper(isset($transaction['currency_type']) ? (string)$transaction['currency_type'] : (isset($transaction['currency']) ? (string)$transaction['currency'] : ''));
+ $invoiceAmount = isset($transaction['currency_amount']) && (float)$transaction['currency_amount'] > 0
+ ? (float)$transaction['currency_amount'] : (isset($transaction['amount']) ? (float)$transaction['amount'] : 0);
+ $safeTransaction = class_exists('SslCommerzSupport') ? SslCommerzSupport::redact($transaction) : $transaction;
+ $fields = array(
+ 'invoice_id'=>isset($transaction['value_a'])?(int)$transaction['value_a']:0,
+ 'val_id'=>isset($transaction['val_id'])?$transaction['val_id']:null,
+ 'bank_tran_id'=>isset($transaction['bank_tran_id'])?$transaction['bank_tran_id']:null,
+ 'sessionkey'=>$sessionKey ?: (isset($transaction['sessionkey'])?$transaction['sessionkey']:null),
+ 'status'=>strtolower(isset($transaction['status'])?$transaction['status']:'unknown'),
+ 'currency'=>$currency,'invoice_amount'=>$invoiceAmount,
+ 'bdt_amount'=>isset($transaction['amount'])?(float)$transaction['amount']:0,
+ 'currency_rate_bdt'=>$invoiceAmount > 0 && isset($transaction['amount']) ? round((float)$transaction['amount']/$invoiceAmount,8) : 0,
+ 'card_no'=>isset($transaction['card_no'])?$transaction['card_no']:null,
+ 'card_type'=>isset($transaction['card_type'])?$transaction['card_type']:null,
+ 'card_brand'=>isset($transaction['card_brand'])?$transaction['card_brand']:null,
+ 'card_issuer'=>isset($transaction['card_issuer'])?$transaction['card_issuer']:null,
+ 'risk_level'=>isset($transaction['risk_level'])?(int)$transaction['risk_level']:0,
+ 'risk_title'=>isset($transaction['risk_title'])?$transaction['risk_title']:null,
+ 'raw_response'=>json_encode($safeTransaction),
+ );
+ $existing = $this->find($tranId);
+ if ($existing) { return $this->update($tranId, $fields); }
+ if ($fields['invoice_id'] <= 0 || $fields['invoice_amount'] <= 0 || $currency === '') { return false; }
+ $fields['tran_id'] = $tranId;
+ return $this->begin($fields);
+ }
+
+ public function search($field, $value, $limit = 50)
+ {
+ $this->ensureSchema();
+ $allowed = array('invoice_id', 'tran_id', 'bank_tran_id', 'val_id', 'sessionkey', 'refund_ref_id', 'card_last4');
+ if (!in_array($field, $allowed, true)) {
+ throw new InvalidArgumentException('Unsupported ledger search field.');
+ }
+ $limit = max(1, min(5000, (int) $limit));
+ if ($this->adapter) {
+ return $this->adapter->search($field, (string) $value, $limit);
+ }
+ $query = \WHMCS\Database\Capsule::table(self::TABLE);
+ if ($field === 'card_last4') {
+ $query->where('card_no', 'like', '%' . preg_replace('/\D/', '', (string) $value));
+ } else {
+ $query->where($field, $value);
+ }
+ return $query->orderBy('id', 'desc')->limit($limit)->get()->all();
+ }
+
+ public function claim($tranId, $staleSeconds = 300)
+ {
+ try {
+ $this->ensureSchema();
+ $now = date('Y-m-d H:i:s');
+ $staleBefore = date('Y-m-d H:i:s', time() - max(30, (int) $staleSeconds));
+ if ($this->adapter) {
+ return $this->adapter->claim((string) $tranId, $now, $staleBefore) ? 'acquired' : 'held';
+ }
+ $updated = \WHMCS\Database\Capsule::table(self::TABLE)
+ ->where('tran_id', (string) $tranId)
+ ->where(function ($query) use ($staleBefore) {
+ $query->whereNull('settlement_claimed_at')->orWhere('settlement_claimed_at', '<', $staleBefore);
+ })
+ ->update(array('settlement_claimed_at' => $now, 'updated_at' => $now));
+ return $updated > 0 ? 'acquired' : 'held';
+ } catch (Throwable $error) {
+ return 'unavailable';
+ }
+ }
+
+ public function release($tranId)
+ {
+ return $this->update($tranId, array('settlement_claimed_at' => null));
+ }
+
+ public function markPaid($tranId)
+ {
+ return $this->update($tranId, array('status' => 'paid', 'paid_at' => date('Y-m-d H:i:s')));
+ }
+
+ public function recordRefund($tranId, array $refund)
+ {
+ $row = $this->find($tranId);
+ if (!$row) {
+ throw new RuntimeException('Payment ledger row was not found.');
+ }
+ $fields = array(
+ 'refunded_bdt' => (float) (isset($row->refunded_bdt) ? $row->refunded_bdt : 0) + (float) $refund['refund_bdt'],
+ 'refund_ref_id' => isset($refund['refund_ref_id']) ? $refund['refund_ref_id'] : null,
+ 'refund_trans_id' => isset($refund['refund_trans_id']) ? $refund['refund_trans_id'] : null,
+ 'status' => isset($refund['status']) ? $refund['status'] : 'refund_processing',
+ );
+ return $this->update($row->tran_id, $fields);
+ }
+
+ public function reserveRefund(array $request)
+ {
+ $this->ensureSchema();
+ if ($this->adapter) {
+ return $this->adapter->reserveRefund($request);
+ }
+ return \WHMCS\Database\Capsule::connection()->transaction(function () use ($request) {
+ $payment = \WHMCS\Database\Capsule::table(self::TABLE)
+ ->where(function ($query) use ($request) {
+ $query->where('tran_id', (string)$request['payment_identifier'])
+ ->orWhere('bank_tran_id', (string)$request['payment_identifier']);
+ })->lockForUpdate()->first();
+ if (!$payment) { throw new RuntimeException('Payment ledger row was not found.'); }
+
+ $currency = strtoupper((string)$request['source_currency']);
+ $sourceAmount = round((float)$request['source_amount'], 2);
+ $baseRefunded = round((float)$payment->refunded_bdt, 2);
+ $recentSuccess = \WHMCS\Database\Capsule::table(self::REFUND_TABLE)
+ ->where('payment_tran_id', $payment->tran_id)->where('source_currency', $currency)
+ ->where('source_amount', $sourceAmount)->whereIn('status', array('success','processing'))
+ ->where('updated_at', '>=', date('Y-m-d H:i:s', time() - 300))->orderBy('id', 'desc')->first();
+ if ($recentSuccess) { $recentSuccess->replay = true; return $recentSuccess; }
+
+ $requestKey = hash('sha256', $payment->tran_id . '|' . $currency . '|' . number_format($sourceAmount,2,'.','') . '|' . number_format($baseRefunded,2,'.',''));
+ $existing = \WHMCS\Database\Capsule::table(self::REFUND_TABLE)->where('request_key', $requestKey)->lockForUpdate()->first();
+ if ($existing) {
+ $existing->replay = true;
+ return $existing;
+ }
+ $reserved = (float) \WHMCS\Database\Capsule::table(self::REFUND_TABLE)
+ ->where('payment_tran_id', $payment->tran_id)->where('status', 'reserved')->sum('amount_bdt');
+ $remaining = round(max(0, (float)$payment->bdt_amount - $baseRefunded - $reserved), 2);
+ $desiredBdt = round((float)$request['desired_bdt'], 2);
+ if ($desiredBdt > $remaining + 0.009) { throw new RuntimeException('Refund amount exceeds the remaining captured balance.'); }
+ $amountBdt = $desiredBdt;
+ if ($amountBdt <= 0) { throw new RuntimeException('No refundable balance remains on this payment.'); }
+ $now = date('Y-m-d H:i:s');
+ $id = \WHMCS\Database\Capsule::table(self::REFUND_TABLE)->insertGetId(array(
+ 'payment_tran_id'=>$payment->tran_id,'invoice_id'=>(int)$request['invoice_id'],
+ 'refund_trans_id'=>(string)$request['refund_trans_id'],'request_key'=>$requestKey,
+ 'source_currency'=>$currency,'source_amount'=>$sourceAmount,'base_refunded_bdt'=>$baseRefunded,
+ 'amount_bdt'=>$amountBdt,'status'=>'reserved','created_at'=>$now,'updated_at'=>$now,
+ ));
+ $row = \WHMCS\Database\Capsule::table(self::REFUND_TABLE)->where('id', $id)->first();
+ $row->replay = false;
+ return $row;
+ });
+ }
+
+ public function finalizeRefund($refundTransId, array $result)
+ {
+ $this->ensureSchema();
+ if ($this->adapter) { return $this->adapter->finalizeRefund($refundTransId, $result); }
+ return \WHMCS\Database\Capsule::connection()->transaction(function () use ($refundTransId, $result) {
+ $refund = \WHMCS\Database\Capsule::table(self::REFUND_TABLE)->where('refund_trans_id', (string)$refundTransId)->lockForUpdate()->first();
+ if (!$refund) { throw new RuntimeException('Refund reservation was not found.'); }
+ if (in_array($refund->status, array('success','processing'), true)) { return $refund; }
+ $status = isset($result['status']) ? (string)$result['status'] : 'failed';
+ $fields = array(
+ 'status'=>$status,'refund_ref_id'=>isset($result['refund_ref_id'])?$result['refund_ref_id']:null,
+ 'raw_response'=>isset($result['raw_response'])?$result['raw_response']:null,'updated_at'=>date('Y-m-d H:i:s'),
+ );
+ \WHMCS\Database\Capsule::table(self::REFUND_TABLE)->where('id', $refund->id)->update($fields);
+ if (in_array($status, array('success','processing'), true)) {
+ $payment = \WHMCS\Database\Capsule::table(self::TABLE)->where('tran_id', $refund->payment_tran_id)->lockForUpdate()->first();
+ if (!$payment) { throw new RuntimeException('Payment ledger row was not found.'); }
+ $newTotal = min((float)$payment->bdt_amount, (float)$payment->refunded_bdt + (float)$refund->amount_bdt);
+ \WHMCS\Database\Capsule::table(self::TABLE)->where('id', $payment->id)->update(array(
+ 'refunded_bdt'=>$newTotal,'refund_ref_id'=>$fields['refund_ref_id'],'refund_trans_id'=>$refundTransId,
+ 'status'=>$newTotal + 0.009 >= (float)$payment->bdt_amount ? 'refunded' : 'partially_refunded',
+ 'updated_at'=>date('Y-m-d H:i:s'),
+ ));
+ }
+ return \WHMCS\Database\Capsule::table(self::REFUND_TABLE)->where('id', $refund->id)->first();
+ });
+ }
+
+ private function filter(array $fields)
+ {
+ $allowed = array_keys(self::schemaDefinition()['columns']);
+ return array_intersect_key($fields, array_flip($allowed));
+ }
+
+ private function migrateExistingTable($capsule)
+ {
+ $definitions = array(
+ 'currency_rate_bdt' => function ($t) { $t->decimal('currency_rate_bdt', 18, 8)->default(0); },
+ 'refunded_bdt' => function ($t) { $t->decimal('refunded_bdt', 16, 2)->default(0); },
+ 'refund_trans_id' => function ($t) { $t->string('refund_trans_id', 30)->nullable(); },
+ 'raw_response' => function ($t) { $t->mediumText('raw_response')->nullable(); },
+ 'settlement_claimed_at' => function ($t) { $t->timestamp('settlement_claimed_at')->nullable(); },
+ 'paid_at' => function ($t) { $t->timestamp('paid_at')->nullable(); },
+ );
+ foreach ($definitions as $column => $definition) {
+ if (!$capsule::schema()->hasColumn(self::TABLE, $column)) {
+ $capsule::schema()->table(self::TABLE, $definition);
+ }
+ }
+ try {
+ $columns = $capsule::select("SHOW COLUMNS FROM `" . self::TABLE . "`");
+ $names = array();
+ foreach ($columns as $column) { $names[] = $column->Field; }
+ $capsule::statement("ALTER TABLE `" . self::TABLE . "` MODIFY `card_no` VARCHAR(80) NULL");
+ $capsule::statement("ALTER TABLE `" . self::TABLE . "` MODIFY `bank_tran_id` VARCHAR(100) NULL");
+ $capsule::statement("ALTER TABLE `" . self::TABLE . "` MODIFY `val_id` VARCHAR(100) NULL");
+ if (in_array('invoice_amount', $names, true) && in_array('bdt_amount', $names, true)) {
+ $capsule::statement("UPDATE `" . self::TABLE . "` SET `currency_rate_bdt` = `bdt_amount` / `invoice_amount` WHERE `currency_rate_bdt` = 0 AND `invoice_amount` > 0 AND `bdt_amount` > 0");
+ }
+ if (in_array('validation_raw', $names, true)) {
+ $capsule::statement("UPDATE `" . self::TABLE . "` SET `raw_response` = `validation_raw` WHERE `raw_response` IS NULL AND `validation_raw` IS NOT NULL");
+ }
+ } catch (Throwable $ignored) {
+ // Best-effort widening/backfill is repeatable and should not block payments.
+ }
+ try {
+ $indexes = $capsule::select("SHOW INDEX FROM `" . self::TABLE . "` WHERE `Key_name` = 'sslcommerz_tran_id_unique'");
+ if (!$indexes) {
+ $capsule::statement("ALTER TABLE `" . self::TABLE . "` ADD UNIQUE INDEX `sslcommerz_tran_id_unique` (`tran_id`)");
+ }
+ } catch (Throwable $ignored) {
+ // Existing duplicate legacy rows should not make the whole gateway unavailable.
+ }
+ }
+
+ private function ensureRefundTable($capsule)
+ {
+ if ($capsule::schema()->hasTable(self::REFUND_TABLE)) { return; }
+ try {
+ $capsule::schema()->create(self::REFUND_TABLE, function ($table) {
+ $table->increments('id');
+ $table->string('payment_tran_id',30)->index();
+ $table->integer('invoice_id')->unsigned()->index();
+ $table->string('refund_trans_id',30)->unique();
+ $table->string('request_key',64)->unique();
+ $table->string('source_currency',8);
+ $table->decimal('source_amount',16,2);
+ $table->decimal('base_refunded_bdt',16,2)->default(0);
+ $table->decimal('amount_bdt',16,2);
+ $table->string('refund_ref_id',50)->nullable()->index();
+ $table->string('status',20)->default('reserved')->index();
+ $table->mediumText('raw_response')->nullable();
+ $table->timestamp('created_at')->nullable();
+ $table->timestamp('updated_at')->nullable();
+ });
+ } catch (Throwable $error) {
+ if (!$capsule::schema()->hasTable(self::REFUND_TABLE)) { throw $error; }
+ }
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/PaymentProcessor.php b/modules/gateways/sslcommerz/lib/PaymentProcessor.php
new file mode 100644
index 0000000..3286352
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/PaymentProcessor.php
@@ -0,0 +1,151 @@
+api = $api;
+ $this->ledger = $ledger;
+ $this->callbacks = $callbacks;
+ $this->gateway = $gateway;
+ }
+
+ public function process(array $notification, $source)
+ {
+ $source = $source === 'ipn' ? 'ipn' : 'browser';
+ $status = strtoupper(isset($notification['status']) ? (string) $notification['status'] : '');
+ $tranId = isset($notification['tran_id']) ? (string) $notification['tran_id'] : '';
+ $valId = isset($notification['val_id']) ? (string) $notification['val_id'] : '';
+
+ if ($source === 'ipn' && SslCommerzSupport::signatureMatches($notification, isset($this->gateway['store_password']) ? $this->gateway['store_password'] : '') === false) {
+ return $this->finish('rejected', 0, 'IPN Signature Rejected', $notification);
+ }
+
+ $attempt = null;
+ if ($tranId !== '') {
+ try {
+ $attempt = $this->ledger->find($tranId);
+ } catch (Throwable $error) {
+ if (in_array($status, array('VALID', 'VALIDATED'), true)) {
+ return $this->finish('retry', 0, 'Ledger Lookup Failed', array('error' => $error->getMessage(), 'notification' => $notification));
+ }
+ }
+ }
+ $knownInvoiceId = $attempt && isset($attempt->invoice_id) ? (int) $attempt->invoice_id : 0;
+ if (in_array($status, array('FAILED', 'CANCELLED', 'EXPIRED', 'UNATTEMPTED'), true)) {
+ if ($tranId !== '') { $this->safeUpdate($tranId, array('status' => strtolower($status))); }
+ return $this->finish('ignored', $knownInvoiceId, $source . ' ' . $status, $notification);
+ }
+ if (!in_array($status, array('VALID', 'VALIDATED'), true) || $tranId === '' || $valId === '') {
+ return $this->finish('rejected', 0, 'Notification Missing Valid Identity', $notification);
+ }
+
+ if (!$attempt) {
+ return $this->finish('rejected', 0, 'Unknown Merchant Transaction', $notification);
+ }
+ $attemptArray = (array) $attempt;
+ $invoiceId = (int) $attemptArray['invoice_id'];
+
+ try {
+ $validation = $this->api->validate($valId);
+ } catch (Throwable $error) {
+ return $this->finish('retry', $invoiceId, 'Validation API Failed', array('error' => $error->getMessage(), 'notification' => $notification));
+ }
+ $decision = SslCommerzPaymentRules::validationDecision($attemptArray, $validation);
+ if (!$decision['accepted']) {
+ $this->safeUpdate($tranId, array('status' => $decision['code'], 'val_id' => $valId, 'raw_response' => json_encode(SslCommerzSupport::redact($validation))));
+ return $this->finish('rejected', $invoiceId, 'Validation ' . $decision['code'], array('notification' => $notification, 'validation' => $validation));
+ }
+
+ $bankTranId = isset($validation['bank_tran_id']) ? (string) $validation['bank_tran_id'] : '';
+ if ($bankTranId === '') {
+ return $this->finish('rejected', $invoiceId, 'Validation Missing Bank Transaction ID', $validation);
+ }
+ $this->safeUpdate($tranId, array(
+ 'val_id' => $valId,
+ 'bank_tran_id' => $bankTranId,
+ 'status' => 'validated',
+ 'bdt_amount' => $decision['bdt_amount'],
+ 'currency_rate_bdt' => $decision['currency_rate_bdt'],
+ 'card_no' => isset($validation['card_no']) ? $validation['card_no'] : null,
+ 'card_type' => isset($validation['card_type']) ? $validation['card_type'] : null,
+ 'card_brand' => isset($validation['card_brand']) ? $validation['card_brand'] : null,
+ 'card_issuer' => isset($validation['card_issuer']) ? $validation['card_issuer'] : null,
+ 'risk_level' => isset($validation['risk_level']) ? (int) $validation['risk_level'] : 0,
+ 'risk_title' => isset($validation['risk_title']) ? $validation['risk_title'] : null,
+ 'raw_response' => json_encode(SslCommerzSupport::redact($validation)),
+ ));
+
+ foreach (array($tranId, $bankTranId) as $candidate) {
+ $existingInvoice = call_user_func($this->callbacks['find_transaction'], $candidate);
+ if ($existingInvoice !== null) {
+ if ((int) $existingInvoice === $invoiceId) {
+ $this->safeMarkPaid($tranId);
+ return $this->finish('duplicate', $invoiceId, 'Already Processed', array('transaction_id' => $candidate));
+ }
+ return $this->finish('rejected', $invoiceId, 'Transaction Used By Another Invoice', array('transaction_id' => $candidate, 'existing_invoice' => $existingInvoice));
+ }
+ }
+
+ $claim = $this->ledger->claim($tranId);
+ if ($claim === 'held') {
+ return $this->finish('retry', $invoiceId, 'Settlement Is Being Processed', array('tran_id' => $tranId));
+ }
+ if ($claim === 'unavailable') {
+ $this->log('Ledger Unavailable - WHMCS Guards Active', array('tran_id' => $tranId, 'invoice_id' => $invoiceId));
+ }
+
+ try {
+ $checkedInvoiceId = call_user_func($this->callbacks['check_invoice'], $invoiceId);
+ if ($checkedInvoiceId !== null) {
+ $invoiceId = (int) $checkedInvoiceId;
+ }
+ $recordedId = isset($this->gateway['transid_source']) && $this->gateway['transid_source'] === 'bank_tran_id' ? $bankTranId : $tranId;
+ call_user_func($this->callbacks['add_payment'], $invoiceId, $recordedId, (float) $decision['invoice_amount']);
+ } catch (Throwable $error) {
+ if ($claim === 'acquired') {
+ try { $this->ledger->release($tranId); } catch (Throwable $ignored) {}
+ }
+ return $this->finish('retry', $invoiceId, 'WHMCS Settlement Failed', array('error' => $error->getMessage(), 'tran_id' => $tranId));
+ }
+
+ $this->safeMarkPaid($tranId);
+ return $this->finish('paid', $invoiceId, ucfirst($source) . ' Payment Successful', array(
+ 'tran_id' => $tranId, 'bank_tran_id' => $bankTranId,
+ 'invoice_amount' => $decision['invoice_amount'], 'bdt_amount' => $decision['bdt_amount'],
+ ));
+ }
+
+ private function safeUpdate($tranId, array $fields)
+ {
+ try { $this->ledger->update($tranId, $fields); } catch (Throwable $error) {
+ $this->log('Ledger Update Failed', array('tran_id' => $tranId, 'error' => $error->getMessage()));
+ }
+ }
+
+ private function safeMarkPaid($tranId)
+ {
+ try { $this->ledger->markPaid($tranId); } catch (Throwable $error) {
+ $this->log('Ledger Paid Mark Failed', array('tran_id' => $tranId, 'error' => $error->getMessage()));
+ }
+ }
+
+ private function finish($code, $invoiceId, $status, array $data)
+ {
+ $this->log($status, $data);
+ return array('code' => $code, 'invoice_id' => (int) $invoiceId, 'message' => $status);
+ }
+
+ private function log($status, array $data)
+ {
+ call_user_func($this->callbacks['log'], $status, SslCommerzSupport::redact($data));
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/PaymentRules.php b/modules/gateways/sslcommerz/lib/PaymentRules.php
new file mode 100644
index 0000000..fcf57fb
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/PaymentRules.php
@@ -0,0 +1,141 @@
+ 500000)) {
+ throw new InvalidArgumentException('SSLCommerz accepts direct BDT payments from 10.00 to 500000.00 BDT.');
+ }
+ $customerName = trim(
+ (isset($invoice['firstname']) ? (string)$invoice['firstname'] : '') . ' '
+ . (isset($invoice['lastname']) ? (string)$invoice['lastname'] : '')
+ );
+ if ($customerName === '') {
+ throw new InvalidArgumentException('Customer name is required for SSLCommerz.');
+ }
+ if (!isset($invoice['email']) || trim((string)$invoice['email']) === '') {
+ throw new InvalidArgumentException('Customer email is required for SSLCommerz.');
+ }
+
+ $payload = array(
+ 'store_id' => trim((string) $gateway['store_id']),
+ 'store_passwd' => trim((string) $gateway['store_password']),
+ 'total_amount' => $amount,
+ 'currency' => $currency,
+ 'tran_id' => (string) $tranId,
+ 'success_url' => (string) $urls['success_url'],
+ 'fail_url' => (string) $urls['fail_url'],
+ 'cancel_url' => (string) $urls['cancel_url'],
+ 'ipn_url' => (string) $urls['ipn_url'],
+ 'cus_name' => $customerName,
+ 'cus_email' => (string) $invoice['email'],
+ 'cus_add1' => isset($invoice['address1']) ? (string)$invoice['address1'] : '',
+ 'cus_city' => isset($invoice['city']) ? (string)$invoice['city'] : '',
+ 'cus_state' => isset($invoice['state']) ? (string)$invoice['state'] : '',
+ 'cus_postcode' => isset($invoice['postcode']) ? (string)$invoice['postcode'] : '',
+ 'cus_country' => isset($invoice['country']) ? (string)$invoice['country'] : '',
+ 'cus_phone' => isset($invoice['phone']) ? (string)$invoice['phone'] : '',
+ 'shipping_method' => 'NO',
+ 'num_of_item' => 1,
+ 'product_name' => (string) $invoice['description'],
+ 'product_category' => 'Domain-Hosting',
+ 'product_profile' => 'general',
+ 'value_a' => (string) $invoice['invoiceid'],
+ );
+
+ if (!empty($invoice['address2'])) {
+ $payload['cus_add2'] = (string) $invoice['address2'];
+ }
+ if (!empty($urls['return_url'])) {
+ $payload['value_b'] = (string) $urls['return_url'];
+ }
+
+ return $payload;
+ }
+
+ public static function validationDecision(array $attempt, array $validation)
+ {
+ $status = strtoupper(isset($validation['status']) ? (string) $validation['status'] : '');
+ if (!in_array($status, array('VALID', 'VALIDATED'), true)) {
+ return self::reject('status_invalid');
+ }
+ if (!isset($validation['tran_id'], $attempt['tran_id']) || (string) $validation['tran_id'] !== (string) $attempt['tran_id']) {
+ return self::reject('transaction_mismatch');
+ }
+ if (!isset($validation['value_a'], $attempt['invoice_id']) || (int) $validation['value_a'] !== (int) $attempt['invoice_id']) {
+ return self::reject('invoice_mismatch');
+ }
+ if ((int) (isset($validation['risk_level']) ? $validation['risk_level'] : -1) !== 0) {
+ return self::reject('risk_flagged');
+ }
+
+ $currency = strtoupper(isset($attempt['currency']) ? (string) $attempt['currency'] : '');
+ $validatedCurrency = strtoupper(isset($validation['currency_type']) ? (string) $validation['currency_type'] : (isset($validation['currency']) ? (string) $validation['currency'] : ''));
+ if ($validatedCurrency !== $currency) {
+ return self::reject('currency_mismatch');
+ }
+
+ $invoiceAmount = (float) (isset($attempt['invoice_amount']) ? $attempt['invoice_amount'] : 0);
+ $validatedInvoiceAmount = $currency === 'BDT'
+ ? (float) (isset($validation['currency_amount']) && $validation['currency_amount'] !== '' ? $validation['currency_amount'] : (isset($validation['amount']) ? $validation['amount'] : 0))
+ : (float) (isset($validation['currency_amount']) ? $validation['currency_amount'] : 0);
+ if ($invoiceAmount <= 0 || abs($invoiceAmount - $validatedInvoiceAmount) > 0.01) {
+ return self::reject('amount_mismatch');
+ }
+
+ $bdtAmount = (float) (isset($validation['amount']) ? $validation['amount'] : 0);
+ if ($bdtAmount <= 0) {
+ return self::reject('amount_mismatch');
+ }
+
+ return array(
+ 'accepted' => true,
+ 'code' => 'accepted',
+ 'invoice_amount' => $invoiceAmount,
+ 'bdt_amount' => $bdtAmount,
+ 'currency_rate_bdt' => round($bdtAmount / $invoiceAmount, 8),
+ );
+ }
+
+ public static function refundAmountBdt($requested, $currency, $capturedInvoice, $capturedBdt, $alreadyRefundedBdt)
+ {
+ $requested = (float) $requested;
+ $currency = strtoupper((string) $currency);
+ $capturedInvoice = (float) $capturedInvoice;
+ $capturedBdt = (float) $capturedBdt;
+ $remainingBdt = max(0.0, $capturedBdt - (float) $alreadyRefundedBdt);
+
+ if ($requested <= 0) {
+ throw new InvalidArgumentException('Refund amount must be greater than zero.');
+ }
+ if ($currency === 'BDT') {
+ if ($capturedBdt > 0 && $requested > $remainingBdt + 0.009) {
+ throw new InvalidArgumentException('Refund amount exceeds the remaining captured balance.');
+ }
+ return round($requested, 2);
+ }
+ if ($capturedInvoice <= 0 || $capturedBdt <= 0) {
+ throw new InvalidArgumentException('The capture-time BDT conversion rate is unavailable.');
+ }
+
+ $converted = round($requested * ($capturedBdt / $capturedInvoice), 2);
+ if ($converted > $remainingBdt + 0.009) {
+ throw new InvalidArgumentException('Refund amount exceeds the remaining captured balance.');
+ }
+ return $converted;
+ }
+
+ private static function reject($code)
+ {
+ return array(
+ 'accepted' => false,
+ 'code' => $code,
+ 'invoice_amount' => 0.0,
+ 'bdt_amount' => 0.0,
+ 'currency_rate_bdt' => 0.0,
+ );
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/RefundService.php b/modules/gateways/sslcommerz/lib/RefundService.php
new file mode 100644
index 0000000..e0fb033
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/RefundService.php
@@ -0,0 +1,159 @@
+api = $api;
+ $this->ledger = $ledger;
+ $this->logger = $logger;
+ }
+
+ public static function fromWhmcs(array $params)
+ {
+ $api = new SslCommerzApiClient(array(
+ 'store_id' => isset($params['store_id']) ? $params['store_id'] : '',
+ 'store_password' => isset($params['store_password']) ? $params['store_password'] : '',
+ 'testmode' => isset($params['testmode']) && $params['testmode'] === 'on',
+ ));
+ $logger = function ($status, array $data) use ($params) {
+ if (function_exists('logTransaction')) {
+ logTransaction(isset($params['name']) ? $params['name'] : 'SSLCommerz', SslCommerzSupport::redact($data), $status);
+ }
+ };
+ return new self($api, new SslCommerzLedger(), $logger);
+ }
+
+ public function refund(array $params)
+ {
+ try {
+ $invoiceId = isset($params['invoiceid']) ? (int) $params['invoiceid'] : 0;
+ $transId = isset($params['transid']) ? trim((string) $params['transid']) : '';
+ $currency = strtoupper(isset($params['currency']) ? (string) $params['currency'] : 'BDT');
+ if ($invoiceId <= 0 || $transId === '') {
+ throw new InvalidArgumentException('A valid invoice and payment transaction are required.');
+ }
+
+ $row = $this->ledger->find($transId);
+ if (!$row) {
+ $row = $this->importLegacyBdtPayment($invoiceId, $transId, $currency);
+ }
+ $capture = (array) $row;
+ if (!empty($capture['currency']) && strtoupper((string)$capture['currency']) !== $currency) {
+ throw new InvalidArgumentException('Refund currency does not match the captured payment currency.');
+ }
+ $bankTranId = isset($capture['bank_tran_id']) ? trim((string) $capture['bank_tran_id']) : '';
+ if ($bankTranId === '') {
+ throw new RuntimeException('The captured bank transaction ID is unavailable.');
+ }
+
+ $refundBdt = SslCommerzPaymentRules::refundAmountBdt(
+ isset($params['amount']) ? $params['amount'] : 0,
+ isset($capture['currency']) ? $capture['currency'] : $currency,
+ isset($capture['invoice_amount']) ? $capture['invoice_amount'] : 0,
+ isset($capture['bdt_amount']) ? $capture['bdt_amount'] : 0,
+ isset($capture['refunded_bdt']) ? $capture['refunded_bdt'] : 0
+ );
+ if ($refundBdt <= 0) {
+ throw new InvalidArgumentException('No refundable balance remains on this payment.');
+ }
+
+ $refundTransId = SslCommerzSupport::refundTransactionId($invoiceId);
+ $reservation = $this->ledger->reserveRefund(array(
+ 'payment_identifier'=>$transId,'invoice_id'=>$invoiceId,
+ 'source_amount'=>isset($params['amount'])?$params['amount']:0,'source_currency'=>$currency,
+ 'desired_bdt'=>$refundBdt,'refund_trans_id'=>$refundTransId,
+ ));
+ $refundTransId = (string)$reservation->refund_trans_id;
+ $refundBdt = (float)$reservation->amount_bdt;
+ if (!empty($reservation->replay) && in_array($reservation->status, array('success','processing'), true)
+ && !empty($reservation->refund_ref_id)) {
+ return array('status'=>'success','transid'=>(string)$reservation->refund_ref_id,'rawdata'=>array('status'=>'idempotent_replay'));
+ }
+ $response = $this->api->refund(array(
+ 'bank_tran_id' => $bankTranId,
+ 'refund_trans_id' => $refundTransId,
+ 'refund_amount' => number_format($refundBdt, 2, '.', ''),
+ 'refund_remarks' => 'Refund for WHMCS invoice #' . $invoiceId,
+ 'refe_id' => 'INV' . $invoiceId,
+ ));
+ $status = strtolower(isset($response['status']) ? (string) $response['status'] : 'failed');
+ $apiConnect = strtoupper(isset($response['APIConnect']) ? (string) $response['APIConnect'] : 'DONE');
+ $refundRefId = isset($response['refund_ref_id']) ? trim((string) $response['refund_ref_id']) : '';
+
+ if ($apiConnect !== 'DONE' || !in_array($status, array('success', 'processing'), true) || $refundRefId === '') {
+ $this->ledger->finalizeRefund($refundTransId, array(
+ 'status'=>'failed','refund_ref_id'=>$refundRefId,
+ 'raw_response'=>json_encode(SslCommerzSupport::redact($response)),
+ ));
+ $this->log('Refund Declined', array('request' => $params, 'response' => $response));
+ return array(
+ 'status' => 'declined',
+ 'rawdata' => SslCommerzSupport::redact($response),
+ );
+ }
+
+ $this->ledger->finalizeRefund($refundTransId, array(
+ 'refund_ref_id' => $refundRefId,
+ 'status' => $status,
+ 'raw_response'=>json_encode(SslCommerzSupport::redact($response)),
+ ));
+ $this->log('Refund Accepted', array('request' => $params, 'response' => $response, 'refund_bdt' => $refundBdt));
+
+ return array(
+ 'status' => 'success',
+ 'transid' => $refundRefId,
+ 'rawdata' => SslCommerzSupport::redact($response),
+ );
+ } catch (Throwable $error) {
+ $this->log('Refund Error', array('error' => $error->getMessage(), 'request' => $params));
+ return array('status' => 'error', 'rawdata' => array('message' => $error->getMessage()));
+ }
+ }
+
+ public function queryStatus($refundRefId)
+ {
+ return $this->api->queryRefund($refundRefId);
+ }
+
+ private function importLegacyBdtPayment($invoiceId, $transId, $currency)
+ {
+ if ($currency !== 'BDT') {
+ throw new RuntimeException('A historical non-BDT payment cannot be refunded without its capture-time conversion rate.');
+ }
+ $response = $this->api->query(array('tran_id' => $transId));
+ $rows = isset($response['element']) && is_array($response['element']) ? $response['element'] : array($response);
+ foreach ($rows as $candidate) {
+ if (!is_array($candidate)) { continue; }
+ $status = strtoupper(isset($candidate['status']) ? (string) $candidate['status'] : '');
+ if (!in_array($status, array('VALID', 'VALIDATED'), true)) { continue; }
+ if (!empty($candidate['tran_id']) && (string) $candidate['tran_id'] !== $transId) { continue; }
+ $bankTranId = isset($candidate['bank_tran_id']) ? trim((string) $candidate['bank_tran_id']) : '';
+ $bdtAmount = isset($candidate['amount']) ? (float) $candidate['amount'] : 0;
+ if ($bankTranId === '' || $bdtAmount <= 0) { continue; }
+ $this->ledger->begin(array(
+ 'invoice_id' => $invoiceId, 'tran_id' => $transId, 'currency' => 'BDT',
+ 'invoice_amount' => $bdtAmount, 'bdt_amount' => $bdtAmount,
+ ));
+ $this->ledger->update($transId, array('bank_tran_id' => $bankTranId, 'status' => 'paid'));
+ return $this->ledger->find($transId);
+ }
+ throw new RuntimeException('The original SSLCommerz payment could not be resolved.');
+ }
+
+ private function log($status, array $data)
+ {
+ if ($this->logger) {
+ call_user_func($this->logger, $status, SslCommerzSupport::redact($data));
+ }
+ }
+}
diff --git a/modules/gateways/sslcommerz/lib/Support.php b/modules/gateways/sslcommerz/lib/Support.php
new file mode 100644
index 0000000..728141b
--- /dev/null
+++ b/modules/gateways/sslcommerz/lib/Support.php
@@ -0,0 +1,163 @@
+ 'legacy_popup',
+ 'legacy easycheckout popup' => 'legacy_popup',
+ 'easycheckout popup' => 'legacy_popup',
+ 'legacy_hosted' => 'legacy_hosted',
+ 'legacy hosted redirect' => 'legacy_hosted',
+ 'legacy (hosted redirect)' => 'legacy_hosted',
+ 'new_hosted' => 'new_hosted',
+ 'new hosted checkout' => 'new_hosted',
+ 'new checkout popup' => 'new_hosted',
+ );
+ return isset($map[$normalized]) ? $map[$normalized] : 'legacy_popup';
+ }
+
+ public static function transactionId($invoiceId, $randomHex = null)
+ {
+ $invoice = preg_replace('/[^0-9]/', '', (string) $invoiceId);
+ if ($invoice === '') {
+ throw new InvalidArgumentException('A numeric invoice ID is required.');
+ }
+
+ $random = $randomHex === null ? bin2hex(random_bytes(6)) : strtolower((string) $randomHex);
+ $random = preg_replace('/[^a-f0-9]/', '', $random);
+ if ($random === '') {
+ throw new InvalidArgumentException('Transaction entropy is required.');
+ }
+
+ $prefix = 'INV' . $invoice . '-';
+ return $prefix . substr($random, 0, max(1, 30 - strlen($prefix)));
+ }
+
+ public static function refundTransactionId($invoiceId, $randomHex = null)
+ {
+ $invoice = preg_replace('/[^0-9]/', '', (string) $invoiceId);
+ $random = $randomHex === null ? bin2hex(random_bytes(6)) : preg_replace('/[^a-f0-9]/', '', strtolower((string) $randomHex));
+ $prefix = 'REF' . $invoice . '-';
+ return $prefix . substr($random, 0, max(1, 30 - strlen($prefix)));
+ }
+
+ public static function checkoutToken($invoiceId, $expires, $storePassword)
+ {
+ return hash_hmac('sha256', (int) $invoiceId . '|' . (int) $expires, (string) $storePassword);
+ }
+
+ public static function checkoutTokenMatches($invoiceId, $expires, $token, $storePassword, $now = null)
+ {
+ $now = $now === null ? time() : (int) $now;
+ $expires = (int) $expires;
+ if ($expires < $now || $expires > $now + 3600) {
+ return false;
+ }
+ return hash_equals(self::checkoutToken($invoiceId, $expires, $storePassword), (string) $token);
+ }
+
+ public static function redact(array $data)
+ {
+ $redacted = array();
+ foreach ($data as $key => $value) {
+ $normalized = strtolower((string) $key);
+ if (preg_match('/pass|password|secret|authorization|api[_-]?key/', $normalized)
+ || $normalized === 'token' || substr($normalized, -6) === '_token') {
+ $redacted[$key] = '[REDACTED]';
+ } elseif ($normalized === 'card_no' && is_scalar($value)) {
+ $digits = preg_replace('/\D/', '', (string) $value);
+ $redacted[$key] = strlen($digits) >= 4 ? '****' . substr($digits, -4) : '[REDACTED]';
+ } elseif (is_array($value)) {
+ $redacted[$key] = self::redact($value);
+ } else {
+ $redacted[$key] = $value;
+ }
+ }
+ return $redacted;
+ }
+
+ public static function signatureMatches(array $payload, $storePassword)
+ {
+ if (empty($payload['verify_sign']) || empty($payload['verify_key'])) {
+ return null;
+ }
+
+ $fields = array();
+ foreach (explode(',', (string) $payload['verify_key']) as $field) {
+ $field = trim($field);
+ if ($field !== '' && array_key_exists($field, $payload)) {
+ $fields[$field] = (string) $payload[$field];
+ }
+ }
+ $fields['store_passwd'] = md5((string) $storePassword);
+ ksort($fields);
+
+ $parts = array();
+ foreach ($fields as $field => $value) {
+ $parts[] = $field . '=' . $value;
+ }
+
+ return hash_equals(strtolower((string) $payload['verify_sign']), md5(implode('&', $parts)));
+ }
+
+ public static function safeGatewayUrl($url)
+ {
+ $parts = parse_url((string) $url);
+ if (!is_array($parts) || strtolower(isset($parts['scheme']) ? $parts['scheme'] : '') !== 'https') {
+ return false;
+ }
+ if (!empty($parts['user']) || !empty($parts['pass'])) {
+ return false;
+ }
+ if (isset($parts['port']) && (int) $parts['port'] !== 443) {
+ return false;
+ }
+ $host = strtolower(isset($parts['host']) ? rtrim($parts['host'], '.') : '');
+ return in_array($host, self::$allowedGatewayHosts, true);
+ }
+
+ public static function newCheckoutUrl($url, $testMode)
+ {
+ if (!self::safeGatewayUrl($url)) {
+ throw new InvalidArgumentException('SSLCommerz returned an unsafe gateway URL.');
+ }
+ if ($testMode) {
+ return $url;
+ }
+
+ $parts = parse_url($url);
+ $host = strtolower($parts['host']);
+ if (in_array($host, array('securepay.sslcommerz.com', 'seamless-epay.sslcommerz.com', 'epay-gw.sslcommerz.com'), true)) {
+ $parts['host'] = 'pay.sslcommerz.com';
+ }
+ return self::buildUrl($parts);
+ }
+
+ private static function buildUrl(array $parts)
+ {
+ $url = $parts['scheme'] . '://' . $parts['host'];
+ if (isset($parts['port']) && (int) $parts['port'] !== 443) {
+ $url .= ':' . (int) $parts['port'];
+ }
+ $url .= isset($parts['path']) ? $parts['path'] : '';
+ if (isset($parts['query']) && $parts['query'] !== '') {
+ $url .= '?' . $parts['query'];
+ }
+ if (isset($parts['fragment']) && $parts['fragment'] !== '') {
+ $url .= '#' . $parts['fragment'];
+ }
+ return $url;
+ }
+}
diff --git a/modules/gateways/sslcommerz/logo.png b/modules/gateways/sslcommerz/logo.png
new file mode 100644
index 0000000..2e7da45
Binary files /dev/null and b/modules/gateways/sslcommerz/logo.png differ
diff --git a/modules/gateways/sslcommerz/whmcs.json b/modules/gateways/sslcommerz/whmcs.json
new file mode 100644
index 0000000..5b4ece6
--- /dev/null
+++ b/modules/gateways/sslcommerz/whmcs.json
@@ -0,0 +1,33 @@
+{
+ "schema": "1.0",
+ "type": "whmcs-gateways",
+ "name": "sslcommerz",
+ "version": "1.0.0",
+ "license": "MIT",
+ "category": "payments",
+ "description": {
+ "name": "SSLCommerz Payment Gateway",
+ "tagline": "Bangladesh's first online payment gateway integration for WHMCS with full v4 API support.",
+ "long": "SSLCommerz Payment Gateway module for WHMCS. Implements v4 session creation, order validation, IPN, refunds, idempotent settlement, capture-time currency conversion, and transaction reconciliation. Supports EasyCheckout popup, hosted redirect, and the production new hosted checkout experience.",
+ "features": [
+ "Checkout with SSLCommerz for a faster checkout & payment experience",
+ "EasyCheckout Popup and hosted checkout modes",
+ "Capture-time BDT currency reconciliation",
+ "Transaction ledger with an audit trail",
+ "Full and partial refund support"
+ ]
+ },
+ "logo": {
+ "filename": "logo.png"
+ },
+ "support": {
+ "homepage": "https://sslcommerz.com",
+ "docs_url": "https://developer.sslcommerz.com/doc/v4/"
+ },
+ "authors": [
+ {
+ "name": "Extent Technologies Limited",
+ "homepage": "https://extentit.com"
+ }
+ ]
+}