ibnnajjaar/mib-global-pay
Composer 安装命令:
composer require ibnnajjaar/mib-global-pay
包简介
Framework-agnostic MIB Global integration in PHP
README 文档
README
A Framework-agnostic PHP SDK for integrating with MIB Global Pay – enabling merchants to initiate payments and retrieve payment statuses using a clean, developer-friendly interface.
This SDK targets the Hosted Checkout integration of the Mastercard Payment Gateway (MPGS).
What is Hosted Checkout? Hosted Checkout is a gateway-managed, PCI-compliant checkout page that you redirect shoppers to for entering payment details. The gateway collects and processes sensitive card data on its own secure pages, then redirects the shopper back to your site with the payment result. This reduces your PCI scope and simplifies compliance while keeping your app focused on order creation and result handling.
Further reading: See the official MPGS Hosted Checkout documentation: https://test-mib.mtf.gateway.mastercard.com/api/documentation/integrationGuidelines/hostedCheckout/integrationModelHostedCheckout.html?locale=en_US
Table of Contents
- Requirements
- Installation
- Setup & Configuration
- Implementation Guide
- Error Handling
- API Response Structures
- Security Considerations
- Testing
- Contributing
- Contributors
- License
Requirements
- PHP 7.2 or higher
- Composer
Installation
Install the package using Composer:
composer require ibnnajjaar/mib-global-pay
Setup & Configuration
Environment Setup
Before using the SDK, obtain your Merchant ID and API Key from the MIB Merchant Portal.
Environment (Sandbox or Production):
$merchant_portal_url = 'sandbox.gateway.mastercard.com'; $merchant_id = 'YOUR_SANDBOX_MERCHANT_ID'; $api_password = 'your-sandbox-api-password';
Client Initialization
Initialize the client:
use IbnNajjaar\MIBGlobalPay\MIBGlobalPayConnector; $connector = new MIBGlobalPayConnector($merchant_portal_url, $merchant_id, $api_password);
Environment Variables (Recommended)
Store credentials securely using environment variables:
// .env file MIB_MERCHANT_URL=sandbox.gateway.mastercard.com MIB_MERCHANT_ID=your_merchant_id MIB_API_PASSWORD=your_api_password // In your code $connector = new MIBGlobalPayConnector( $_ENV['MIB_MERCHANT_URL'], $_ENV['MIB_MERCHANT_ID'], $_ENV['MIB_API_PASSWORD'] );
Note: NEVER commit your env file to the repository.
Implementation Guide
Create Payment
To initiate a payment, first prepare the order data:
// Minimum required data $order_id = 'order123'; $amount = 100.00; $payment_details = OrderData::make($order_id, $amount); // You can chain methods to set other information. All available methods are as follows: $payment_details->setOrderCurrency('MVR') ->setOrderDescription('Test Order') ->setMerchantAddressLine1('Sample, Majeedhee Magu') ->setMerchantEmail('merchant@example.mv') ->setMerchantLogo('https://example.mv/logo.svg') ->setMerchantName('Merchant Name') ->setMerchantPhone('1234567890') ->setMerchantUrl('https://example.mv') // Return URL is important though not required // This is the URL the gateway will redirect the user to after payment ->setReturnUrl('https://example.mv/order123/process') // NOTE: Although not documented, the redirect page throws errors if the cancel URL is missing. // It’s recommended to set a cancel URL (usually same as the return URL) to avoid this issue. ->setCancelUrl('https://example.mv/order123/process') ->setRedirectMerchantUrl('https://example.mv/order123/process') ->setWebHookUrl('https://example.mv/webhook') ->setRetryAttemptCount(3);
Send the request with the data:
use IbnNajjaar\MIBGlobalPay\Requests\DataObjects\OrderData; try { $response = $connector->createTransaction($payment_details); $response_data = $response->toDto(); $session_id = $response_data->getSessionId(); $success_indicator = $response_data->getSuccessIndicator(); // Store success indicator for later verification // You may store it in your transaction or order record. // This will be used later to verify payment } catch (Exception $e) { // Handle error appropriately echo $e->getMessage(); }
For further information, see the API documentation: Initiate Checkout.
Important: Save the successIndicator in your database for later verification after redirection.
Redirect to MIB Checkout
Once you have the session ID, redirect the user to the page below. You will need to update the sandbox.gateway.mastercard.com to the appropriate URL and also send the session ID to the view. This view will automatically redirect the user to the MIB Global Pay payment page.
<!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Payment Checkout</title> <script src="https://sandbox.gateway.mastercard.com/static/checkout/checkout.min.js" data-error="errorCallback" data-cancel="cancelCallback"></script> </head> <body> <div id="loading">Processing payment...</div> <script> Checkout.configure({ session: { id: '<?php echo htmlspecialchars($session_id); ?>' } }); // Redirect user to the payment page Checkout.showPaymentPage(); </script> </body> </html>
For further information, see the Documentation: Implementing the Hosted Payment Page.
Handle Payment Completion
After the payment process, MIB will redirect the user to the return_url you provided earlier. On that page, verify the payment result:
// Get the result indicator from the redirect $return_data = HostedCheckoutReturnData::fromArray($_GET); $result_indicator = $return_data->getResultIndicator(); // Retrieve the stored success indicator // Verify payment result if ($result_indicator && $result_indicator == $success_indicator) { // Payment was successful // Normally you should make a GET request to get order details // to confirm the payment before marking the order as paid echo "Payment was successful!"; } else { // Payment failed or was cancelled echo "Payment was not successful."; }
For further information, see the Documentation: Interpreting the Response.
Retrieve Payment Status
To double-check the status of a payment via API:
$order_reference = 'order_12345'; // Use the order ID you saved earlier try { $response = $connector->getOrderDetails($order_reference); $response_data = $response->toDto(); // Available methods on dto $response_data->getOrderStatus(); $response_data->getTotalCapturedAmount(); $response_data->getTransactions(); $response_data->getRawResponse(); $response_data->paymentSuccessfullyCaptured(); // To mark the order as paid if ($response_data->paymentSuccessfullyCaptured()) { // Mark order as paid } } catch (Exception $e) { error_log('Failed to retrieve payment status: ' . $e->getMessage()); echo "Could not retrieve payment status."; }
For further information, see the API documentation: Retrieve Order. Best Practice: Always verify payment status with the get order API for critical orders.
Handling Webhook Data
A webhook notifies you of successful transactions at predefined intervals, which is very useful for marking orders as paid. Sometimes, users may close their browser or interrupt the session before the payment gateway returns the transaction information. In such cases, your order might remain marked as unpaid in your database, even though the payment was completed in the merchant portal.
The webhook sends the successful transaction data to a predefined URL. You can use this data to update and mark the order as paid. Additionally, you can set a secret token in the merchant portal that will be included in the webhook request headers. This token can be used to verify the authenticity of the data.
Since webhook notifications are sent as POST requests, your application must be able to accept POST requests at the specified endpoint.
You can convert the webhook data into a response data object as shown below:
$webhook_data = WebhookResponseData::fromArray($_POST, getallheaders()); // Available methods: returns all strings or null $webhook_data->getOrderReference(); $webhook_data->getOrderAmount(); // returns float|null $webhook_data->getOrderCurrency(); $webhook_data->getOrderStatus(); $webhook_data->getNotificationSecret(); $webhook_data->getResult(); $webhook_data->getGatewayCode(); $webhook_data->getRawResponse(); $webhook_data->paymentIsSuccessful(); // returns a boolean
For further information, see the Documentation: Webhook Notifications.
Error Handling
The SDK may encounter various errors during API calls. Always implement proper error handling:
try { $response = $client->transactions->create($payment_details->toArray()); $response_data = json_decode($response->getBody()->getContents(), true); } catch (Exception $e) { // Log the error error_log('MIB Payment Error: ' . $e->getMessage()); }
API Response Structures
Create Payment Response
This is a typical response you will receive when you send a create transaction request:
[
'checkoutMode' => 'WEBSITE',
'merchant' => 'YOURMERCHANTID',
'result' => 'SUCCESS',
'session' => [
'id' => 'SESSION_abc123', // session id
'updateStatus' => 'SUCCESS',
'version' => 'fasdf3452'
],
'successIndicator' => 'abc123def456'
]
Payment Status Response
This is a typical response you will receive to your return URL:
[
'order' => 'ORD-9010047',
'resultIndicator' => '50addc325519453c',
'sessionVersion' => '1fasdf23f',
'checkoutVersion' => '1.0.0',
]
Note: The order ID is present because it was included in the return URL. If you did not include the order ID in the return URL, the order key will not be present.
Response Methods
All responses have the following methods available:
- getStatusCode(): returns int
- getHeaders(): returns an array
- getBody(): returns json string
- toArray(): returns an array
- toDto(): returns a data transfer object defined in the request
- isSuccessful(): returns a boolean
- isFailed(): returns a boolean
- throw(): throws an exception on failed response
Security Considerations
Credential Management
- Store API credentials in environment variables
- Never commit credentials to version control
- Use different credentials for sandbox and production
HTTPS Requirements
- Always use HTTPS for return URLs
- Ensure your checkout page is served over HTTPS
- Verify SSL certificates in production
Test Card Numbers
Use test card numbers provided by the bank. Test cards will be listed in the documentation. Test Cards
Testing
composer test
Run tests in Docker
If you prefer to run the test suite in Docker (no local PHP or Composer required):
# Build the image docker compose build # Install dependencies inside the container (if vendor is not present or is outdated) docker compose run --rm php composer install # Run PHPUnit # Option A: Use the dedicated 'test' service docker compose run --rm test # Option B: Run via the php service (overriding the command) docker compose run --rm php vendor/bin/phpunit -c phpunit.xml --colors=always
Changelog
See CHANGELOG.md for release notes: CHANGELOG.md
Contributing
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Contributors
License
MIT License.
For additional support, please raise an issue.
ibnnajjaar/mib-global-pay 适用场景与选型建议
ibnnajjaar/mib-global-pay 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 201 次下载、GitHub Stars 达 7, 最近一次更新时间为 2025 年 07 月 13 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「Bank」 「maldives」 「ibnnajjaar」 「mib-global-pay」 「maldives islamic bank」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 ibnnajjaar/mib-global-pay 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 ibnnajjaar/mib-global-pay 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 ibnnajjaar/mib-global-pay 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Symfony integration for Czech bank account library
PHP Bindings for the BML Connect API
Check for holidays - localeaware
PHP SDK for Dhiraagu Bulk SMS Gateway
Laravel wrapper for BML Connect PHP SDK
Laravel notification channel for Dhiraagu Bulk SMS Gateway
统计信息
- 总下载量: 201
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 7
- 点击次数: 16
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-13