Compare commits

...

27 Commits

Author SHA1 Message Date
587fb27f8a Delete langs/en_US 2025-04-09 15:16:18 +02:00
96a2d6531b Add langs/en_US
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-04-09 15:15:03 +02:00
98a022e670 Delete langs/en_US/en_US 2025-04-09 15:14:27 +02:00
b023662290 Add langs/en_US/en_US
Modified langs directory

Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-04-09 15:13:56 +02:00
34a58cede2 Delete langs
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-04-09 15:11:43 +02:00
9d922601a0 Add langs 2025-04-09 15:10:58 +02:00
dadc9092d1 Delete langs/en_US/dolipesa.lang
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-04-09 15:10:01 +02:00
77690ea3a4 Add modDolipesah1.class.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 14:43:28 +02:00
e11e6e063b Delete langs/nestict log banner.png
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:58:10 +02:00
ebdef49b2d Delete langs/en_US/nestict log banner.png
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:57:58 +02:00
4f506935d0 Add langs/en_US/dolipesa.lang
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:57:38 +02:00
8ce2b3f32d Upload files to "langs/en_US"
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:56:46 +02:00
a29aa917cb Upload files to "langs"
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:55:44 +02:00
532677c02d Update hooks/dolipesa_hook.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:53:49 +02:00
d72b25dc43 Update core/dolipesa_setup.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:53:05 +02:00
6f1805038b Update modDolipesa.class.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:50:56 +02:00
785648ebf9 Update modMpesapay.class.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:50:07 +02:00
05f948294d Update modMpesapay.class.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:44:44 +02:00
8cc6a82807 Update pages/payment.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:40:13 +02:00
e0b07cbfd7 Update pages/callback.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:38:19 +02:00
818a1957be Update pages/callback.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:36:57 +02:00
0901fc1015 Update hooks/mpesapay_hook.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:33:43 +02:00
325d011128 Update core/mpesapay_setup.php
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:30:56 +02:00
3a06133a8c Update README.md
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:26:31 +02:00
dba8026684 Update README.md
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:24:43 +02:00
437311194c Update README.md
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:24:16 +02:00
e18a23a492 Update README.md
Signed-off-by: kevinowino869 <kevinowino869@www.codelab.nestict.africa>
2025-03-30 13:23:45 +02:00
10 changed files with 1207 additions and 257 deletions

114
README.md
View File

@ -1,30 +1,100 @@
# Dolibarr M-Pesa Payment Module
## Overview
The M-Pesa Payment Module for Dolibarr enables seamless integration with M-Pesa, allowing businesses to accept payments directly from customers.
## Features
- Generate payment URLs for invoices.
- Real-time payment processing via M-Pesa.
- Automatic payment confirmation and transaction recording.
---
## Installation
1. Download the module ZIP package.
2. Extract and upload the contents to Dolibarr's custom modules directory (e.g., /htdocs/custom/mpesapay).
3. Go to **Home > Setup > Modules** and activate the "M-Pesa Payment Module".
**License:** GNU General Public License v3.0 (consistent with Dolibarrs open-source framework)
## Configuration
1. Navigate to **M-Pesa Module Configuration** in Dolibarr.
2. Enter your M-Pesa Paybill Number and Passkey.
#### Overview
Dolipesa 1.0.1 is a tailored payment module that seamlessly integrates M-Pesa, a widely used mobile payment platform in East Africa, with Dolibarr ERP/CRM. This first release empowers businesses to accept M-Pesa payments for invoices, orders, and other transactions directly within Dolibarr, utilizing its native payment infrastructure and M-Pesas API for a streamlined experience.
## Usage
1. Generate an invoice in Dolibarr.
2. Click on "Pay with M-Pesa" to initiate payment.
3. Customers complete payment via M-Pesa and the module confirms the transaction.
#### Features
1. **M-Pesa Payment Gateway Integration**
- Employs M-Pesas STK Push API to prompt customers for PIN entry on their mobile devices.
- Facilitates payments for invoices and sales orders within Dolibarr.
- Supports Kenyan Shilling (KES), with plans for broader currency compatibility in future updates.
## Support
For inquiries, contact [NESTICT INFOTECH](https://www.nestict.com).
2. **Payment Confirmation**
- Verifies transactions in real-time via M-Pesas callback/result URL.
- Automatically updates Dolibarr invoice/order statuses (e.g., "Draft" to "Paid") upon payment success.
## License
This module is licensed under GPLv3.
3. **Basic Configuration**
- Offers an admin panel to input M-Pesa API credentials (Consumer Key, Consumer Secret, Shortcode, Passkey).
- Allows customization of the payment description shown to customers during STK Push.
4. **Transaction Logging**
- Logs M-Pesa transaction IDs and statuses in Dolibarr for easy reconciliation and tracking.
5. **Public Payment Page**
- Enhances Dolibarrs `/public/payment/newpayment.php` endpoint to include M-Pesa as a payment option.
#### Requirements
- **Dolibarr Version:** 19.0.* or higher (tested up to 20.0.0 as of March 30, 2025).
- **PHP Version:** 7.4 or later (aligned with Dolibarrs specifications).
- **M-Pesa API Access:**
- Safaricom Daraja API credentials (Consumer Key, Consumer Secret, Shortcode, Passkey).
- A registered callback URL hosted on your Dolibarr server.
- **Server:** HTTPS-enabled (mandatory for secure API communication).
- **Dependencies:** PHP cURL extension for API interactions.
#### Installation Instructions
1. **Download the Module**
- Get the `dolipesa-1.0.1.zip` file from [Your Repository/Dolistore Link].
2. **Install the Module**
- Log into Dolibarr as an administrator.
- Go to **Home > Setup > Modules > Deploy/Install External App/Module**.
- Upload `dolipesa-1.0.1.zip` and click **Install**.
- If upload issues occur, manually unzip the file into `/custom` (e.g., `/var/www/dolibarr/custom/dolipesa`).
3. **Activate the Module**
- Navigate to **Home > Setup > Modules**.
- Find "Dolipesa - M-Pesa Payment," click **Activate**, and adjust settings as needed.
#### Configuration
1. **Obtain M-Pesa API Credentials**
- Sign up at [developer.safaricom.co.ke](https://developer.safaricom.co.ke).
- Acquire a Consumer Key, Consumer Secret, and Passkey.
- Set a callback URL (e.g., `https://your-dolibarr-domain.com/custom/dolipesa/callback.php`).
2. **Set Up in Dolibarr**
- Go to **Home > Setup > Modules > Dolipesa - M-Pesa Payment > Configure**.
- Input your Shortcode, Consumer Key, Consumer Secret, Passkey, and Callback URL.
- Save your settings.
3. **Test the Integration**
- Generate a test invoice in Dolibarr.
- Visit the public payment page (e.g., `https://your-dolibarr-domain.com/public/payment/newpayment.php?source=invoice&ref=INVREF`).
- Choose "M-Pesa," enter a test phone number, and confirm the STK Push in a test M-Pesa account.
#### Usage
- **For Customers:**
- Select "M-Pesa" on the payment page, input your phone number, and approve the STK Push notification.
- **For Admins:**
- Track transactions via **Bank & Cash > M-Pesa Transactions** (a new module-added tab).
#### Technical Notes
- **Hook Implementation:** Integrates with Dolibarrs "newpayment" hooks at `/public/payment/newpayment.php`, setting session variables (`TRANSACTIONID`, `FinalPaymentAmt`, `currencyCodeType`) per Dolibarrs payment documentation.
- **API Calls:** Leverages M-Pesas OAuth token and STK Push endpoints (e.g., `https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest` for testing).
- **Security:** Enforces HTTPS for API calls; encrypts API credentials in Dolibarrs database.
#### Known Limitations (1.0.1)
- Limited to KES transactions.
- Basic error handling without retry for failed STK Push attempts.
- Sandbox mode only (production requires Safaricom approval).
#### Changelog
- **1.0.1 (March 30, 2025):**
- Resolved callback URL validation issue.
- Marked as the initial stable release post-1.0.0 beta.
#### Future Enhancements (Planned for 1.1.0)
- Multi-currency support with conversion.
- Retry mechanism for failed transactions.
- Payment success email notifications for customers.
#### Support
- Submit issues or feature requests to [support@nestict.com](mailto:support@nestict.com).
- Access documentation at [https://www.community.nestict.com/dashboard](https://www.community.nestict.com/dashboard).
---

97
core/dolipesa_setup.php Normal file
View File

@ -0,0 +1,97 @@
<?php
/**
* Dolipesa - M-Pesa Payment Module Setup Page
* Author: NESTICT INFOTECH
* Version: 1.0.1
* License: GNU General Public License v3.0
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
$langs->load('adminross('admin');
$langs->load('dolipesa@dolipesa');
if (!$user->admin) accessforbidden();
$action = GETPOST('action', 'alpha');
// Save settings
if ($action === 'save') {
$consumer_key = GETPOST('MPESAPAY_CONSUMER_KEY', 'alpha');
$consumer_secret = GETPOST('MPESAPAY_CONSUMER_SECRET', 'alpha');
$shortcode = GETPOST('MPESAPAY_SHORTCODE', 'alpha');
$passkey = GETPOST('MPESAPAY_PASSKEY', 'alpha');
$callback_url = GETPOST('MPESAPAY_CALLBACK_URL', 'alpha');
// Validate required fields
if (empty($shortcode) || empty($passkey) || empty($consumer_key) || empty($consumer_secret)) {
setEventMessages($langs->trans('ErrorFieldRequired'), null, 'errors');
} else {
// Store settings in Dolibarr configuration (encrypted for sensitive data)
dolibarr_set_const($db, 'MPESAPAY_CONSUMER_KEY', $consumer_key, 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'MPESAPAY_CONSUMER_SECRET', dol_encrypt($consumer_secret), 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'MPESAPAY_SHORTCODE', $shortcode, 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'MPESAPAY_PASSKEY', dol_encrypt($passkey), 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'MPESAPAY_CALLBACK_URL', $callback_url, 'chaine', 0, '', $conf->entity);
setEventMessages($langs->trans('SettingsSaved'), null, 'mesgs');
}
}
// Page title
print load_fiche_titre($langs->trans('MpesaPaymentModuleConfig'));
// Configuration form
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
print '<input type="hidden" name="action" value="save">';
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<th>' . $langs->trans('Parameter') . '</th>';
print '<th>' . $langs->trans('Value') . '</th>';
print '</tr>';
// Consumer Key
print '<tr class="oddeven">';
print '<td><label for="consumer_key">' . $langs->trans('MpesaConsumerKey') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_CONSUMER_KEY" id="consumer_key" value="' . dolibarr_get_const($db, 'MPESAPAY_CONSUMER_KEY') . '" size="40"></td>';
print '</tr>';
// Consumer Secret (decrypted for display)
print '<tr class="oddeven">';
print '<td><label for="consumer_secret">' . $langs->trans('MpesaConsumerSecret') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_CONSUMER_SECRET" id="consumer_secret" value="' . dol_decrypt(dolibarr_get_const($db, 'MPESAPAY_CONSUMER_SECRET')) . '" size="40"></td>';
print '</tr>';
// Shortcode (Business Till/Paybill Number)
print '<tr class="oddeven">';
print '<td><label for="shortcode">' . $langs->trans('MpesaShortcode') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_SHORTCODE" id="shortcode" value="' . dolibarr_get_const($db, 'MPESAPAY_SHORTCODE') . '" size="20"></td>';
print '</tr>';
// Passkey (decrypted for display)
print '<tr class="oddeven">';
print '<td><label for="passkey">' . $langs->trans('MpesaPasskey') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_PASSKEY" id="passkey" value="' . dol_decrypt(dolibarr_get_const($db, 'MPESAPAY_PASSKEY')) . '" size="40"></td>';
print '</tr>';
// Callback URL
print '<tr class="oddeven">';
print '<td><label for="callback_url">' . $langs->trans('MpesaCallbackURL') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_CALLBACK_URL" id="callback_url" value="' . dolibarr_get_const($db, 'MPESAPAY_CALLBACK_URL') . '" size="60"></td>';
print '</tr>';
print '</table>';
print '<div class="center" style="margin-top: 20px;">';
print '<input type="submit" class="button" value="' . $langs->trans('Save') . '">';
print '</div>';
print '</form>';
// Footer
llxFooter();
$db->close();
?>

View File

@ -1,47 +0,0 @@
<?php
/**
* M-Pesa Payment Module - Setup Page
* Author: NESTICT INFOTECH
* Version: 1.0.0
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php";
$langs->load("admin");
$langs->load("mpesapay");
if (!$user->admin) accessforbidden();
$action = GETPOST('action', 'alpha');
if ($action == 'save') {
$paybill = GETPOST('MPESAPAY_PAYBILL', 'alpha');
$passkey = GETPOST('MPESAPAY_PASSKEY', 'alpha');
dolibarr_set_const($db, "MPESAPAY_PAYBILL", $paybill, 'chaine', 0, '', 1);
dolibarr_set_const($db, "MPESAPAY_PASSKEY", $passkey, 'chaine', 0, '', 1);
setEventMessages("Settings saved", null, 'mesgs');
}
print load_fiche_titre("M-Pesa Payment Module Configuration");
print '<form method="POST">';
print '<input type="hidden" name="action" value="save">';
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre"><th>Setting</th><th>Value</th></tr>';
print '<tr><td>M-Pesa Paybill Number</td>';
print '<td><input type="text" name="MPESAPAY_PAYBILL" value="' . dolibarr_get_const($db, "MPESAPAY_PAYBILL") . '"></td></tr>';
print '<tr><td>M-Pesa Passkey</td>';
print '<td><input type="text" name="MPESAPAY_PASSKEY" value="' . dolibarr_get_const($db, "MPESAPAY_PASSKEY") . '"></td></tr>';
print '</table>';
print '<div class="center">';
print '<button type="submit" class="button">Save</button>';
print '</div>';
print '</form>';
llxFooter();
$db->close();
?>

131
hooks/dolipesa_hook.php Normal file
View File

@ -0,0 +1,131 @@
<?php
/**
* Dolipesa - M-Pesa Payment Module Hook Handling
* Author: NESTICT INFOTECH
* Version: 1.0.1
* License: GNU General Public License v3.0
*/
class ActionsDolipesa
{
/**
* Hook manager instance
*
* @var DoliHookManager
*/
protected $hookmanager;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
$this->db = $db;
}
/**
* Add M-Pesa payment option to invoice card
*
* @param array $parameters Hook parameters
* @param CommonObject $object Current object (e.g., Facture)
* @param string $action Current action
* @param HookManager $hookmanager Hook manager instance
* @return int 0 on success, < 0 on error
*/
public function formObjectOptions($parameters, &$object, &$action, $hookmanager)
{
global $langs, $conf;
$this->hookmanager = $hookmanager;
// Check if we're on the invoice card and the invoice is validated (statut = 1)
if (in_array('invoicecard', explode(':', $parameters['currentcontext'])) && $object->statut == 1) {
// Load module configuration
$shortcode = $conf->global->MPESAPAY_SHORTCODE;
if (empty($shortcode)) {
return 0; // Do nothing if module not configured
}
// Generate payment URL for the public payment page
$paymentUrl = DOL_MAIN_URL_ROOT . '/public/payment/newpayment.php?source=invoice&ref=' . urlencode($object->ref);
// Output M-Pesa payment button
print '<tr class="oddeven"><td colspan="2">';
print '<div class="dolipesa-payment" style="margin-top: 10px;">';
print '<a href="' . $paymentUrl . '" class="butAction" target="_blank">' . $langs->trans('PayWithMpesa') . '</a>';
print '</div>';
print '</td></tr>';
}
return 0;
}
/**
* Add M-Pesa transaction input to payment card
*
* @param array $parameters Hook parameters
* @param CommonObject $object Current object (e.g., Payment)
* @param string $action Current action
* @param HookManager $hookmanager Hook manager instance
* @return int 0 on success, < 0 on error
*/
public function formAddObjectLine($parameters, &$object, &$action, $hookmanager)
{
global $langs, $conf;
$this->hookmanager = $hookmanager;
// Check if we're on the payment card and payment is draft (statut = 0)
if (in_array('paymentcard', explode(':', $parameters['currentcontext'])) && $object->statut == 0) {
// Load module configuration
$shortcode = $conf->global->MPESAPAY_SHORTCODE;
if (empty($shortcode)) {
return 0; // Do nothing if module not configured
}
// Output M-Pesa transaction ID input field
print '<tr class="oddeven"><td colspan="2">';
print '<div class="dolipesa-payment" style="margin-top: 10px;">';
print '<label for="mpesapay_transaction_id">' . $langs->trans('MpesaTransactionID') . ':</label> ';
print '<input type="text" name="mpesapay_transaction_id" id="mpesapay_transaction_id" placeholder="' . $langs->trans('EnterTransactionID') . '" size="30">';
print '</div>';
print '</td></tr>';
}
return 0;
}
/**
* Handle actions after payment creation (e.g., process M-Pesa transaction ID)
*
* @param array $parameters Hook parameters
* @param CommonObject $object Current object (e.g., Payment)
* @param string $action Current action
* @param HookManager $hookmanager Hook manager instance
* @return int 0 on success, < 0 on error
*/
public function createPayment($parameters, &$object, &$action, $hookmanager)
{
global $langs, $db;
if ($action === 'addpayment' && !empty(GETPOST('mpesapay_transaction_id', 'alpha'))) {
$transactionId = GETPOST('mpesapay_transaction_id', 'alpha');
// Here you could add logic to verify the transaction ID with M-Pesa API
// For now, we'll just log it (assuming a transaction log table exists)
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "dolipesa_transactions (transaction_id, fk_payment, datec) ";
$sql .= "VALUES ('" . $db->escape($transactionId) . "', " . $object->id . ", NOW())";
$resql = $db->query($sql);
if (!$resql) {
setEventMessages($langs->trans('ErrorSavingTransaction'), null, 'errors');
return -1;
}
}
return 0;
}
}
?>

View File

@ -1,58 +0,0 @@
<?php
/**
* M-Pesa Payment Module - Hook Handling
* Author: NESTICT INFOTECH
* Version: 1.0.0
*/
class ActionsMpesapay
{
/**
* Execute hooks for payment and invoice card
*
* @param array $parameters Hook parameters
* @param object $object Current object (invoice or payment)
* @param string $action Current action
* @param object $hookmanager Hook manager
* @return int
*/
function formObjectOptions($parameters, $object, $action, $hookmanager)
{
global $langs, $db;
if ($parameters['currentcontext'] === 'invoicecard' && $object->statut == 1) {
$module = new modMpesapay($db);
$paymentUrl = $module->generatePaymentUrl($object->id);
echo '<div class="mpesapay-payment">';
echo '<a href="' . $paymentUrl . '" class="button">Pay with M-Pesa</a>';
echo '</div>';
}
return 0;
}
/**
* Add a payment button on payment card
*
* @param array $parameters Hook parameters
* @param object $object Current object (invoice or payment)
* @param string $action Current action
* @param object $hookmanager Hook manager
* @return int
*/
function formAddObjectLine($parameters, $object, $action, $hookmanager)
{
global $langs, $db;
if ($parameters['currentcontext'] === 'payment' && $object->statut == 0) {
echo '<div class="mpesapay-payment">';
echo '<label>M-Pesa Payment:</label>';
echo '<input type="text" name="mpesapay_transaction_id" placeholder="Transaction ID">';
echo '</div>';
}
return 0;
}
}
?>

86
modDolipesa.class.php Normal file
View File

@ -0,0 +1,86 @@
<?php
/**
* Dolipesa - M-Pesa Payment Module Setup Page
* Author: NESTICT INFOTECH
* Version: 1.0.1
* License: GNU General Public License v3.0
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
$langs->load('admin');
$langs->load('dolipesa@dolipesa');
if (!$user->admin) accessforbidden();
$action = GETPOST('action', 'alpha');
if ($action === 'save') {
$consumer_key = GETPOST('MPESAPAY_CONSUMER_KEY', 'alpha');
$consumer_secret = GETPOST('MPESAPAY_CONSUMER_SECRET', 'alpha');
$shortcode = GETPOST('MPESAPAY_SHORTCODE', 'alpha');
$passkey = GETPOST('MPESAPAY_PASSKEY', 'alpha');
$callback_url = GETPOST('MPESAPAY_CALLBACK_URL', 'alpha');
if (empty($shortcode) || empty($passkey) || empty($consumer_key) || empty($consumer_secret)) {
setEventMessages($langs->trans('ErrorFieldRequired'), null, 'errors');
} else {
dolibarr_set_const($db, 'MPESAPAY_CONSUMER_KEY', $consumer_key, 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'MPESAPAY_CONSUMER_SECRET', dol_encrypt($consumer_secret), 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'MPESAPAY_SHORTCODE', $shortcode, 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'MPESAPAY_PASSKEY', dol_encrypt($passkey), 'chaine', 0, '', $conf->entity);
dolibarr_set_const($db, 'MPESAPAY_CALLBACK_URL', $callback_url, 'chaine', 0, '', $conf->entity);
setEventMessages($langs->trans('SettingsSaved'), null, 'mesgs');
}
}
print load_fiche_titre($langs->trans('MpesaPaymentModuleConfig'));
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">';
print '<input type="hidden" name="action" value="save">';
print '<table class="noborder centpercent">';
print '<tr class="liste_titre">';
print '<th>' . $langs->trans('Parameter') . '</th>';
print '<th>' . $langs->trans('Value') . '</th>';
print '</tr>';
print '<tr class="oddeven">';
print '<td><label for="consumer_key">' . $langs->trans('MpesaConsumerKey') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_CONSUMER_KEY" id="consumer_key" value="' . dolibarr_get_const($db, 'MPESAPAY_CONSUMER_KEY') . '" size="40"></td>';
print '</tr>';
print '<tr class="oddeven">';
print '<td><label for="consumer_secret">' . $langs->trans('MpesaConsumerSecret') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_CONSUMER_SECRET" id="consumer_secret" value="' . dol_decrypt(dolibarr_get_const($db, 'MPESAPAY_CONSUMER_SECRET')) . '" size="40"></td>';
print '</tr>';
print '<tr class="oddeven">';
print '<td><label for="shortcode">' . $langs->trans('MpesaShortcode') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_SHORTCODE" id="shortcode" value="' . dolibarr_get_const($db, 'MPESAPAY_SHORTCODE') . '" size="20"></td>';
print '</tr>';
print '<tr class="oddeven">';
print '<td><label for="passkey">' . $langs->trans('MpesaPasskey') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_PASSKEY" id="passkey" value="' . dol_decrypt(dolibarr_get_const($db, 'MPESAPAY_PASSKEY')) . '" size="40"></td>';
print '</tr>';
print '<tr class="oddeven">';
print '<td><label for="callback_url">' . $langs->trans('MpesaCallbackURL') . '</label></td>';
print '<td><input type="text" name="MPESAPAY_CALLBACK_URL" id="callback_url" value="' . dolibarr_get_const($db, 'MPESAPAY_CALLBACK_URL') . '" size="60"></td>';
print '</tr>';
print '</table>';
print '<div class="center" style="margin-top: 20px;">';
print '<input type="submit" class="button" value="' . $langs->trans('Save') . '">';
print '</div>';
print '</form>';
llxFooter();
$db->close();
?>

539
modDolipesah1.class.php Normal file
View File

@ -0,0 +1,539 @@
<?php
/* Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2018-2019 Nicolas ZABOURI <info@inovea-conseil.com>
* Copyright (C) 2019-2024 Frédéric France <frederic.france@free.fr>
* Copyright (C) 2025 System MANAGER <icttechnest@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \defgroup dolipesa Module Dolipesa
* \brief Dolipesa module descriptor.
*
* \file htdocs/dolipesa/core/modules/modDolipesa.class.php
* \ingroup dolipesa
* \brief Description and activation file for module Dolipesa
*/
include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
/**
* Description and activation class for module Dolipesa
*/
class modDolipesa extends DolibarrModules
{
/**
* Constructor. Define names, constants, directories, boxes, permissions
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
global $conf, $langs;
$this->db = $db;
// Id for module (must be unique).
// Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id).
$this->numero = 50201; // TODO Go on page https://wiki.dolibarr.org/index.php/List_of_modules_id to reserve an id number for your module
// Key text used to identify module (for permissions, menus, etc...)
$this->rights_class = 'dolipesa';
// Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...'
// It is used to group modules by family in module setup page
$this->family = 'interface';
// Module position in the family on 2 digits ('01', '10', '20', ...)
$this->module_position = '90';
// Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this)
//$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily")));
// Module label (no space allowed), used if translation string 'ModuleDolipesaName' not found (Dolipesa is name of module).
$this->name = preg_replace('/^mod/i', '', get_class($this));
// DESCRIPTION_FLAG
// Module description, used if translation string 'ModuleDolipesaDesc' not found (Dolipesa is name of module).
$this->description = 'M-Pesa Payment Gateway Integration';
// Used only if file README.md and README-LL.md not found.
$this->descriptionlong = "DolipesaDescription";
// Author
$this->editor_name = 'Nestict Infotech';
$this->editor_url = 'www.nestict.africa'; // Must be an external online web site
$this->editor_squarred_logo = ''; // Must be image filename into the module/img directory followed with @modulename. Example: 'myimage.png@dolipesa'
// Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated', 'experimental_deprecated' or a version string like 'x.y.z'
$this->version = '1.0';
// Url to the file with your last numberversion of this module
//$this->url_last_version = 'http://www.example.com/versionmodule.txt';
// Key used in llx_const table to save module status enabled/disabled (where DOLIPESA is value of property name of module in uppercase)
$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
// Name of image file used for this module.
// If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue'
// If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module'
// To use a supported fa-xxx css style of font awesome, use this->picto='xxx'
$this->picto = 'fa-file';
// Define some features supported by module (triggers, login, substitutions, menus, css, etc...)
$this->module_parts = array(
// Set this to 1 if module has its own trigger directory (core/triggers)
'triggers' => 0,
// Set this to 1 if module has its own login method file (core/login)
'login' => 0,
// Set this to 1 if module has its own substitution function file (core/substitutions)
'substitutions' => 0,
// Set this to 1 if module has its own menus handler directory (core/menus)
'menus' => 0,
// Set this to 1 if module overwrite template dir (core/tpl)
'tpl' => 0,
// Set this to 1 if module has its own barcode directory (core/modules/barcode)
'barcode' => 0,
// Set this to 1 if module has its own models directory (core/modules/xxx)
'models' => 0,
// Set this to 1 if module has its own printing directory (core/modules/printing)
'printing' => 0,
// Set this to 1 if module has its own theme directory (theme)
'theme' => 0,
// Set this to relative path of css file if module has its own css file
'css' => array(
// '/dolipesa/css/dolipesa.css.php',
),
// Set this to relative path of js file if module must load a js on all pages
'js' => array(
// '/dolipesa/js/dolipesa.js.php',
),
// Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context to 'all'
/* BEGIN MODULEBUILDER HOOKSCONTEXTS */
'hooks' => array(
// 'data' => array(
// 'hookcontext1',
// 'hookcontext2',
// ),
// 'entity' => '0',
),
/* END MODULEBUILDER HOOKSCONTEXTS */
// Set this to 1 if features of module are opened to external users
'moduleforexternal' => 0,
// Set this to 1 if the module provides a website template into doctemplates/websites/website_template-mytemplate
'websitetemplates' => 0,
// Set this to 1 if the module provides a captcha driver
'captcha' => 0
);
// Data directories to create when module is enabled.
// Example: this->dirs = array("/dolipesa/temp","/dolipesa/subdir");
$this->dirs = array("/dolipesa/temp");
// Config pages. Put here list of php page, stored into dolipesa/admin directory, to use to setup module.
$this->config_page_url = array("setup.php@dolipesa");
// Dependencies
// A condition to hide module
$this->hidden = getDolGlobalInt('MODULE_DOLIPESA_DISABLED'); // A condition to disable module;
// List of module class names that must be enabled if this module is enabled. Example: array('always'=>array('modModuleToEnable1','modModuleToEnable2'), 'FR'=>array('modModuleToEnableFR')...)
$this->depends = array();
// List of module class names to disable if this one is disabled. Example: array('modModuleToDisable1', ...)
$this->requiredby = array();
// List of module class names this module is in conflict with. Example: array('modModuleToDisable1', ...)
$this->conflictwith = array();
// The language file dedicated to your module
$this->langfiles = array("dolipesa@dolipesa");
// Prerequisites
$this->phpmin = array(7, 1); // Minimum version of PHP required by module
$this->need_dolibarr_version = array(19, -3); // Minimum version of Dolibarr required by module
$this->need_javascript_ajax = 0;
// Messages at activation
$this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','MX'='textmx'...)
$this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','MX'='textmx'...)
//$this->automatic_activation = array('FR'=>'DolipesaWasAutomaticallyActivatedBecauseOfYourCountryChoice');
//$this->always_enabled = true; // If true, can't be disabled
// Constants
// List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive)
// Example: $this->const=array(1 => array('DOLIPESA_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1),
// 2 => array('DOLIPESA_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1)
// );
$this->const = array();
// Some keys to add into the overwriting translation tables
/*$this->overwrite_translation = array(
'en_US:ParentCompany'=>'Parent company or reseller',
'fr_FR:ParentCompany'=>'Maison mère ou revendeur'
)*/
if (!isModEnabled("dolipesa")) {
$conf->dolipesa = new stdClass();
$conf->dolipesa->enabled = 0;
}
// Array to add new pages in new tabs
/* BEGIN MODULEBUILDER TABS */
$this->tabs = array();
/* END MODULEBUILDER TABS */
// Example:
// To add a new tab identified by code tabname1
// $this->tabs[] = array('data' => 'objecttype:+tabname1:Title1:mylangfile@dolipesa:$user->hasRight(\'dolipesa\', \'read\'):/dolipesa/mynewtab1.php?id=__ID__');
// To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key.
// $this->tabs[] = array('data' => 'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@dolipesa:$user->hasRight(\'othermodule\', \'read\'):/dolipesa/mynewtab2.php?id=__ID__',
// To remove an existing tab identified by code tabname
// $this->tabs[] = array('data' => 'objecttype:-tabname:NU:conditiontoremove');
//
// Where objecttype can be
// 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member)
// 'contact' to add a tab in contact view
// 'contract' to add a tab in contract view
// 'delivery' to add a tab in delivery view
// 'group' to add a tab in group view
// 'intervention' to add a tab in intervention view
// 'invoice' to add a tab in customer invoice view
// 'invoice_supplier' to add a tab in supplier invoice view
// 'member' to add a tab in foundation member view
// 'opensurveypoll' to add a tab in opensurvey poll view
// 'order' to add a tab in sale order view
// 'order_supplier' to add a tab in supplier order view
// 'payment' to add a tab in payment view
// 'payment_supplier' to add a tab in supplier payment view
// 'product' to add a tab in product view
// 'propal' to add a tab in propal view
// 'project' to add a tab in project view
// 'stock' to add a tab in stock view
// 'thirdparty' to add a tab in third party view
// 'user' to add a tab in user view
// Dictionaries
/* Example:
$this->dictionaries=array(
'langs' => 'dolipesa@dolipesa',
// List of tables we want to see into dictionary editor
'tabname' => array("table1", "table2", "table3"),
// Label of tables
'tablib' => array("Table1", "Table2", "Table3"),
// Request to select fields
'tabsql' => array('SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table1 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table2 as f', 'SELECT f.rowid as rowid, f.code, f.label, f.active FROM '.MAIN_DB_PREFIX.'table3 as f'),
// Sort order
'tabsqlsort' => array("label ASC", "label ASC", "label ASC"),
// List of fields (result of select to show dictionary)
'tabfield' => array("code,label", "code,label", "code,label"),
// List of fields (list of fields to edit a record)
'tabfieldvalue' => array("code,label", "code,label", "code,label"),
// List of fields (list of fields for insert)
'tabfieldinsert' => array("code,label", "code,label", "code,label"),
// Name of columns with primary key (try to always name it 'rowid')
'tabrowid' => array("rowid", "rowid", "rowid"),
// Condition to show each dictionary
'tabcond' => array(isModEnabled('dolipesa'), isModEnabled('dolipesa'), isModEnabled('dolipesa')),
// Tooltip for every fields of dictionaries: DO NOT PUT AN EMPTY ARRAY
'tabhelp' => array(array('code' => $langs->trans('CodeTooltipHelp'), 'field2' => 'field2tooltip'), array('code' => $langs->trans('CodeTooltipHelp'), 'field2' => 'field2tooltip'), ...),
);
*/
/* BEGIN MODULEBUILDER DICTIONARIES */
$this->dictionaries = array();
/* END MODULEBUILDER DICTIONARIES */
// Boxes/Widgets
// Add here list of php file(s) stored in dolipesa/core/boxes that contains a class to show a widget.
/* BEGIN MODULEBUILDER WIDGETS */
$this->boxes = array(
// 0 => array(
// 'file' => 'dolipesawidget1.php@dolipesa',
// 'note' => 'Widget provided by Dolipesa',
// 'enabledbydefaulton' => 'Home',
// ),
// ...
);
/* END MODULEBUILDER WIDGETS */
// Cronjobs (List of cron jobs entries to add when module is enabled)
// unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week
/* BEGIN MODULEBUILDER CRON */
$this->cronjobs = array(
// 0 => array(
// 'label' => 'MyJob label',
// 'jobtype' => 'method',
// 'class' => '/dolipesa/class/myobject.class.php',
// 'objectname' => 'MyObject',
// 'method' => 'doScheduledJob',
// 'parameters' => '',
// 'comment' => 'Comment',
// 'frequency' => 2,
// 'unitfrequency' => 3600,
// 'status' => 0,
// 'test' => 'isModEnabled("dolipesa")',
// 'priority' => 50,
// ),
);
/* END MODULEBUILDER CRON */
// Example: $this->cronjobs=array(
// 0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'isModEnabled("dolipesa")', 'priority'=>50),
// 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'isModEnabled("dolipesa")', 'priority'=>50)
// );
// Permissions provided by this module
$this->rights = array();
$r = 0;
// Add here entries to declare new permissions
/* BEGIN MODULEBUILDER PERMISSIONS */
/*
$o = 1;
$this->rights[$r][0] = $this->numero . sprintf("%02d", ($o * 10) + 1); // Permission id (must not be already used)
$this->rights[$r][1] = 'Read objects of Dolipesa'; // Permission label
$this->rights[$r][4] = 'myobject';
$this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->hasRight('dolipesa', 'myobject', 'read'))
$r++;
$this->rights[$r][0] = $this->numero . sprintf("%02d", ($o * 10) + 2); // Permission id (must not be already used)
$this->rights[$r][1] = 'Create/Update objects of Dolipesa'; // Permission label
$this->rights[$r][4] = 'myobject';
$this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->hasRight('dolipesa', 'myobject', 'write'))
$r++;
$this->rights[$r][0] = $this->numero . sprintf("%02d", ($o * 10) + 3); // Permission id (must not be already used)
$this->rights[$r][1] = 'Delete objects of Dolipesa'; // Permission label
$this->rights[$r][4] = 'myobject';
$this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->hasRight('dolipesa', 'myobject', 'delete'))
$r++;
*/
/* END MODULEBUILDER PERMISSIONS */
// Main menu entries to add
$this->menu = array();
$r = 0;
// Add here entries to declare new menus
/* BEGIN MODULEBUILDER TOPMENU */
$this->menu[$r++] = array(
'fk_menu' => '', // Will be stored into mainmenu + leftmenu. Use '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
'type' => 'top', // This is a Top menu entry
'titre' => 'ModuleDolipesaName',
'prefix' => img_picto('', $this->picto, 'class="pictofixedwidth valignmiddle"'),
'mainmenu' => 'dolipesa',
'leftmenu' => '',
'url' => '/dolipesa/dolipesaindex.php',
'langs' => 'dolipesa@dolipesa', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
'position' => 1000 + $r,
'enabled' => 'isModEnabled("dolipesa")', // Define condition to show or hide menu entry. Use 'isModEnabled("dolipesa")' if entry must be visible if module is enabled.
'perms' => '1', // Use 'perms'=>'$user->hasRight("dolipesa", "myobject", "read")' if you want your menu with a permission rules
'target' => '',
'user' => 2, // 0=Menu for internal users, 1=external users, 2=both
);
/* END MODULEBUILDER TOPMENU */
/* BEGIN MODULEBUILDER LEFTMENU MYOBJECT */
/*
$this->menu[$r++]=array(
'fk_menu' => 'fk_mainmenu=dolipesa', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
'type' => 'left', // This is a Left menu entry
'titre' => 'MyObject',
'prefix' => img_picto('', $this->picto, 'class="pictofixedwidth valignmiddle paddingright"'),
'mainmenu' => 'dolipesa',
'leftmenu' => 'myobject',
'url' => '/dolipesa/dolipesaindex.php',
'langs' => 'dolipesa@dolipesa', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
'position' => 1000 + $r,
'enabled' => 'isModEnabled("dolipesa")', // Define condition to show or hide menu entry. Use 'isModEnabled("dolipesa")' if entry must be visible if module is enabled.
'perms' => '$user->hasRight("dolipesa", "myobject", "read")',
'target' => '',
'user' => 2, // 0=Menu for internal users, 1=external users, 2=both
'object' => 'MyObject'
);
$this->menu[$r++]=array(
'fk_menu' => 'fk_mainmenu=dolipesa,fk_leftmenu=myobject', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
'type' => 'left', // This is a Left menu entry
'titre' => 'New_MyObject',
'mainmenu' => 'dolipesa',
'leftmenu' => 'dolipesa_myobject_new',
'url' => '/dolipesa/myobject_card.php?action=create',
'langs' => 'dolipesa@dolipesa', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
'position' => 1000 + $r,
'enabled' => 'isModEnabled("dolipesa")', // Define condition to show or hide menu entry. Use 'isModEnabled("dolipesa")' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected.
'perms' => '$user->hasRight("dolipesa", "myobject", "write")'
'target' => '',
'user' => 2, // 0=Menu for internal users, 1=external users, 2=both
'object' => 'MyObject'
);
$this->menu[$r++]=array(
'fk_menu' => 'fk_mainmenu=dolipesa,fk_leftmenu=myobject', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode
'type' => 'left', // This is a Left menu entry
'titre' => 'List_MyObject',
'mainmenu' => 'dolipesa',
'leftmenu' => 'dolipesa_myobject_list',
'url' => '/dolipesa/myobject_list.php',
'langs' => 'dolipesa@dolipesa', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory.
'position' => 1000 + $r,
'enabled' => 'isModEnabled("dolipesa")', // Define condition to show or hide menu entry. Use 'isModEnabled("dolipesa")' if entry must be visible if module is enabled.
'perms' => '$user->hasRight("dolipesa", "myobject", "read")'
'target' => '',
'user' => 2, // 0=Menu for internal users, 1=external users, 2=both
'object' => 'MyObject'
);
*/
/* END MODULEBUILDER LEFTMENU MYOBJECT */
// Exports profiles provided by this module
$r = 1;
/* BEGIN MODULEBUILDER EXPORT MYOBJECT */
/*
$langs->load("dolipesa@dolipesa");
$this->export_code[$r] = $this->rights_class.'_'.$r;
$this->export_label[$r] = 'MyObjectLines'; // Translation key (used only if key ExportDataset_xxx_z not found)
$this->export_icon[$r] = $this->picto;
// Define $this->export_fields_array, $this->export_TypeFields_array and $this->export_entities_array
$keyforclass = 'MyObject'; $keyforclassfile='/dolipesa/class/myobject.class.php'; $keyforelement='myobject@dolipesa';
include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php';
//$this->export_fields_array[$r]['t.fieldtoadd']='FieldToAdd'; $this->export_TypeFields_array[$r]['t.fieldtoadd']='Text';
//unset($this->export_fields_array[$r]['t.fieldtoremove']);
//$keyforclass = 'MyObjectLine'; $keyforclassfile='/dolipesa/class/myobject.class.php'; $keyforelement='myobjectline@dolipesa'; $keyforalias='tl';
//include DOL_DOCUMENT_ROOT.'/core/commonfieldsinexport.inc.php';
$keyforselect='myobject'; $keyforaliasextra='extra'; $keyforelement='myobject@dolipesa';
include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
//$keyforselect='myobjectline'; $keyforaliasextra='extraline'; $keyforelement='myobjectline@dolipesa';
//include DOL_DOCUMENT_ROOT.'/core/extrafieldsinexport.inc.php';
//$this->export_dependencies_array[$r] = array('myobjectline' => array('tl.rowid','tl.ref')); // To force to activate one or several fields if we select some fields that need same (like to select a unique key if we ask a field of a child to avoid the DISTINCT to discard them, or for computed field than need several other fields)
//$this->export_special_array[$r] = array('t.field' => '...');
//$this->export_examplevalues_array[$r] = array('t.field' => 'Example');
//$this->export_help_array[$r] = array('t.field' => 'FieldDescHelp');
$this->export_sql_start[$r]='SELECT DISTINCT ';
$this->export_sql_end[$r] =' FROM '.MAIN_DB_PREFIX.'dolipesa_myobject as t';
//$this->export_sql_end[$r] .=' LEFT JOIN '.MAIN_DB_PREFIX.'dolipesa_myobject_line as tl ON tl.fk_myobject = t.rowid';
$this->export_sql_end[$r] .=' WHERE 1 = 1';
$this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('myobject').')';
$r++; */
/* END MODULEBUILDER EXPORT MYOBJECT */
// Imports profiles provided by this module
$r = 1;
/* BEGIN MODULEBUILDER IMPORT MYOBJECT */
/*
$langs->load("dolipesa@dolipesa");
$this->import_code[$r] = $this->rights_class.'_'.$r;
$this->import_label[$r] = 'MyObjectLines'; // Translation key (used only if key ExportDataset_xxx_z not found)
$this->import_icon[$r] = $this->picto;
$this->import_tables_array[$r] = array('t' => MAIN_DB_PREFIX.'dolipesa_myobject', 'extra' => MAIN_DB_PREFIX.'dolipesa_myobject_extrafields');
$this->import_tables_creator_array[$r] = array('t' => 'fk_user_author'); // Fields to store import user id
$import_sample = array();
$keyforclass = 'MyObject'; $keyforclassfile='/dolipesa/class/myobject.class.php'; $keyforelement='myobject@dolipesa';
include DOL_DOCUMENT_ROOT.'/core/commonfieldsinimport.inc.php';
$import_extrafield_sample = array();
$keyforselect='myobject'; $keyforaliasextra='extra'; $keyforelement='myobject@dolipesa';
include DOL_DOCUMENT_ROOT.'/core/extrafieldsinimport.inc.php';
$this->import_fieldshidden_array[$r] = array('extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'dolipesa_myobject');
$this->import_regex_array[$r] = array();
$this->import_examplevalues_array[$r] = array_merge($import_sample, $import_extrafield_sample);
$this->import_updatekeys_array[$r] = array('t.ref' => 'Ref');
$this->import_convertvalue_array[$r] = array(
't.ref' => array(
'rule'=>'getrefifauto',
'class'=>(!getDolGlobalString('DOLIPESA_MYOBJECT_ADDON') ? 'mod_myobject_standard' : getDolGlobalString('DOLIPESA_MYOBJECT_ADDON')),
'path'=>"/core/modules/dolipesa/".(!getDolGlobalString('DOLIPESA_MYOBJECT_ADDON') ? 'mod_myobject_standard' : getDolGlobalString('DOLIPESA_MYOBJECT_ADDON')).'.php',
'classobject'=>'MyObject',
'pathobject'=>'/dolipesa/class/myobject.class.php',
),
't.fk_soc' => array('rule' => 'fetchidfromref', 'file' => '/societe/class/societe.class.php', 'class' => 'Societe', 'method' => 'fetch', 'element' => 'ThirdParty'),
't.fk_user_valid' => array('rule' => 'fetchidfromref', 'file' => '/user/class/user.class.php', 'class' => 'User', 'method' => 'fetch', 'element' => 'user'),
't.fk_mode_reglement' => array('rule' => 'fetchidfromcodeorlabel', 'file' => '/compta/paiement/class/cpaiement.class.php', 'class' => 'Cpaiement', 'method' => 'fetch', 'element' => 'cpayment'),
);
$this->import_run_sql_after_array[$r] = array();
$r++; */
/* END MODULEBUILDER IMPORT MYOBJECT */
}
/**
* Function called when module is enabled.
* The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
* It also creates data directories
*
* @param string $options Options when enabling module ('', 'noboxes')
* @return int<-1,1> 1 if OK, <=0 if KO
*/
public function init($options = '')
{
global $conf, $langs;
// Create tables of module at module activation
//$result = $this->_load_tables('/install/mysql/', 'dolipesa');
$result = $this->_load_tables('/dolipesa/sql/');
if ($result < 0) {
return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default')
}
// Create extrafields during init
//include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
//$extrafields = new ExtraFields($this->db);
//$result0=$extrafields->addExtraField('dolipesa_separator1', "Separator 1", 'separator', 1, 0, 'thirdparty', 0, 0, '', array('options'=>array(1=>1)), 1, '', 1, 0, '', '', 'dolipesa@dolipesa', 'isModEnabled("dolipesa")');
//$result1=$extrafields->addExtraField('dolipesa_myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty', 0, 0, '', '', 1, '', -1, 0, '', '', 'dolipesa@dolipesa', 'isModEnabled("dolipesa")');
//$result2=$extrafields->addExtraField('dolipesa_myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project', 0, 0, '', '', 1, '', -1, 0, '', '', 'dolipesa@dolipesa', 'isModEnabled("dolipesa")');
//$result3=$extrafields->addExtraField('dolipesa_myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', -1, 0, '', '', 'dolipesa@dolipesa', 'isModEnabled("dolipesa")');
//$result4=$extrafields->addExtraField('dolipesa_myattr4', "New Attr 4 label", 'select', 1, 3, 'thirdparty', 0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', -1, 0, '', '', 'dolipesa@dolipesa', 'isModEnabled("dolipesa")');
//$result5=$extrafields->addExtraField('dolipesa_myattr5', "New Attr 5 label", 'text', 1, 10, 'user', 0, 0, '', '', 1, '', -1, 0, '', '', 'dolipesa@dolipesa', 'isModEnabled("dolipesa")');
// Permissions
$this->remove($options);
$sql = array();
// Document templates
$moduledir = dol_sanitizeFileName('dolipesa');
$myTmpObjects = array();
$myTmpObjects['MyObject'] = array('includerefgeneration' => 0, 'includedocgeneration' => 0);
foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) {
if ($myTmpObjectArray['includerefgeneration']) {
$src = DOL_DOCUMENT_ROOT.'/install/doctemplates/'.$moduledir.'/template_myobjects.odt';
$dirodt = DOL_DATA_ROOT.($conf->entity > 1 ? '/'.$conf->entity : '').'/doctemplates/'.$moduledir;
$dest = $dirodt.'/template_myobjects.odt';
if (file_exists($src) && !file_exists($dest)) {
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
dol_mkdir($dirodt);
$result = dol_copy($src, $dest, '0', 0);
if ($result < 0) {
$langs->load("errors");
$this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest);
return 0;
}
}
$sql = array_merge($sql, array(
"DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = 'standard_".strtolower($myTmpObjectKey)."' AND type = '".$this->db->escape(strtolower($myTmpObjectKey))."' AND entity = ".((int) $conf->entity),
"INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('standard_".strtolower($myTmpObjectKey)."', '".$this->db->escape(strtolower($myTmpObjectKey))."', ".((int) $conf->entity).")",
"DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = 'generic_".strtolower($myTmpObjectKey)."_odt' AND type = '".$this->db->escape(strtolower($myTmpObjectKey))."' AND entity = ".((int) $conf->entity),
"INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('generic_".strtolower($myTmpObjectKey)."_odt', '".$this->db->escape(strtolower($myTmpObjectKey))."', ".((int) $conf->entity).")"
));
}
}
return $this->_init($sql, $options);
}
/**
* Function called when module is disabled.
* Remove from database constants, boxes and permissions from Dolibarr database.
* Data directories are not deleted
*
* @param string $options Options when enabling module ('', 'noboxes')
* @return int<-1,1> 1 if OK, <=0 if KO
*/
public function remove($options = '')
{
$sql = array();
return $this->_remove($sql, $options);
}
}

View File

@ -1,43 +0,0 @@
<?php
/**
* Dolibarr Module Descriptor for M-Pesa Payment
* Author: NESTICT INFOTECH
* Version: 1.0.0
*/
include_once DOL_DOCUMENT_ROOT . "/core/modules/DolibarrModules.class.php";
class modMpesapay extends DolibarrModules
{
function __construct($db)
{
global $langs, $conf;
$this->db = $db;
$this->numero = 104900;
$this->rights_class = 'mpesapay';
$this->family = 'payment';
$this->name = "M-Pesa Payment Module";
$this->description = "Accept M-Pesa payments in Dolibarr.";
$this->version = '1.0.0';
$this->const = array(
array('MPESAPAY_PAYBILL', 'chaine', '', 'M-Pesa Paybill Number', 0, 'current', 1),
array('MPESAPAY_PASSKEY', 'chaine', '', 'M-Pesa Passkey', 0, 'current', 1)
);
$this->module_parts = array('hooks' => array('invoicecard', 'payment'));
$this->config_page_url = "mpesapay_setup.php";
$this->dirs = array('/mpesapay');
$this->picto = 'payment';
}
// Generate Payment URL
function generatePaymentUrl($invoiceId)
{
$token = base64_encode(hash('sha256', $invoiceId . time()));
return DOL_URL_ROOT . "/custom/mpesapay/payment.php?invoice_id={$invoiceId}&token={$token}";
}
}
?>

View File

@ -1,73 +1,182 @@
<?php
/**
* M-Pesa Payment Module - Payment Processing
* Dolipesa - M-Pesa Payment Module Callback Handler
* Author: NESTICT INFOTECH
* Version: 1.0.0
* Version: 1.0.1
* License: GNU General Public License v3.0
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php";
require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
// Load translations
$langs->load('dolipesa@dolipesa');
// Check if this is a callback from M-Pesa (no GET params, JSON input expected)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_GET)) {
// Handle M-Pesa callback
$callbackData = json_decode(file_get_contents('php://input'), true);
if (!isset($callbackData['Body']['stkCallback'])) {
http_response_code(400);
exit('Invalid callback data');
}
$stkCallback = $callbackData['Body']['stkCallback'];
$resultCode = $stkCallback['ResultCode'];
$resultDesc = $stkCallback['ResultDesc'];
$checkoutRequestID = $stkCallback['CheckoutRequestID'];
// Log the callback response (assumes llx_dolipesa_transactions table exists)
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "dolipesa_transactions (checkout_request_id, result_code, result_desc, datec) ";
$sql .= "VALUES ('" . $db->escape($checkoutRequestID) . "', '" . $db->escape($resultCode) . "', ";
$sql .= "'" . $db->escape($resultDesc) . "', NOW())";
$db->query($sql);
// Process successful payment (ResultCode 0 = success)
if ($resultCode == 0) {
$callbackMetadata = $stkCallback['CallbackMetadata']['Item'];
$transactionId = null;
$amount = null;
$phoneNumber = null;
foreach ($callbackMetadata as $item) {
switch ($item['Name']) {
case 'MpesaReceiptNumber':
$transactionId = $item['Value'];
break;
case 'Amount':
$amount = $item['Value'];
break;
case 'PhoneNumber':
$phoneNumber = $item['Value'];
break;
}
}
// Find invoice linked to this CheckoutRequestID (you will need to store this mapping)
$sql = "SELECT fk_invoice FROM " . MAIN_DB_PREFIX . "dolipesa_transactions ";
$sql .= "WHERE checkout_request_id = '" . $db->escape($checkoutRequestID) . "'";
$resql = $db->query($sql);
if ($resql && $obj = $db->fetch_object($resql)) {
$invoice = new Facture($db);
$invoice->fetch($obj->fk_invoice);
if ($invoice->id && $invoice->statut == 1) { // Validated invoice
// Mark invoice as paid
$invoice->setPaid($user, '', $transactionId);
// Log transaction with invoice link
$sql = "UPDATE " . MAIN_DB_PREFIX . "dolipesa_transactions ";
$sql .= "SET fk_invoice = " . $invoice->id . ", transaction_id = '" . $db->escape($transactionId) . "' ";
$sql .= "WHERE checkout_request_id = '" . $db->escape($checkoutRequestID) . "'";
$db->query($sql);
}
}
}
http_response_code(200);
exit('Callback processed');
}
// Payment initiation (assumes this is accessed via GET with invoice_id and token)
$invoiceId = GETPOST('invoice_id', 'int');
$token = GETPOST('token', 'alpha');
if (!$invoiceId || !$token) {
accessforbidden();
accessforbidden($langs->trans('MissingParameters'));
}
// Validate token
$expectedToken = base64_encode(hash('sha256', $invoiceId . time()));
// Validate token (simple example; improve as needed)
$expectedToken = md5($invoiceId . $conf->global->MAIN_SECURITY_SALT); // Use a more secure method in production
if ($token !== $expectedToken) {
accessforbidden();
accessforbidden($langs->trans('InvalidToken'));
}
// Load invoice
$invoice = new Facture($db);
if ($invoice->fetch($invoiceId) <= 0 || $invoice->statut != 1) {
accessforbidden($langs->trans('InvoiceNotFoundOrNotValidated'));
}
// Process payment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$phoneNumber = GETPOST('phone_number', 'alpha');
$amount = GETPOST('amount', 'int');
$amount = floatval($invoice->total_ttc); // Use invoice total
$paybill = dolibarr_get_const($db, "MPESAPAY_PAYBILL");
$passkey = dolibarr_get_const($db, "MPESAPAY_PASSKEY");
$payload = array(
"BusinessShortCode" => $paybill,
"Password" => base64_encode($paybill . $passkey . time()),
"Timestamp" => date('YmdHis'),
"TransactionType" => "CustomerPayBillOnline",
"Amount" => $amount,
"PartyA" => $phoneNumber,
"PartyB" => $paybill,
"PhoneNumber" => $phoneNumber,
"CallBackURL" => DOL_URL_ROOT . "/custom/mpesapay/callback.php",
"AccountReference" => $invoiceId,
"TransactionDesc" => "Payment for Invoice #$invoiceId"
);
$module = new modMpesapay($db);
$response = $module->sendMpesaRequest($payload);
if ($response && $response['ResponseCode'] == "0") {
echo "<p>Payment initiated. Check your phone to complete.</p>";
// Validate phone number (Kenyan format: 2547XXXXXXXX)
if (!preg_match('/^254[0-9]{9}$/', $phoneNumber)) {
setEventMessages($langs->trans('InvalidPhoneNumber'), null, 'errors');
} else {
echo "<p>Failed to initiate payment. Please try again.</p>";
// Load M-Pesa credentials
$consumerKey = $conf->global->MPESAPAY_CONSUMER_KEY;
$consumerSecret = dol_decrypt($conf->global->MPESAPAY_CONSUMER_SECRET);
$shortcode = $conf->global->MPESAPAY_SHORTCODE;
$passkey = dol_decrypt($conf->global->MPESAPAY_PASSKEY);
$callbackUrl = $conf->global->MPESAPAY_CALLBACK_URL ?: DOL_MAIN_URL_ROOT . '/custom/dolipesa/callback.php';
// Generate OAuth token
$credentials = base64_encode($consumerKey . ':' . $consumerSecret);
$tokenResponse = dol_http_get('https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials', [
'Authorization: Basic ' . $credentials
]);
$tokenData = json_decode($tokenResponse, true);
$accessToken = $tokenData['access_token'] ?? null;
if (!$accessToken) {
setEventMessages($langs->trans('FailedToGetMpesaToken'), null, 'errors');
} else {
// Prepare STK Push payload
$timestamp = date('YmdHis');
$password = base64_encode($shortcode . $passkey . $timestamp);
$payload = [
'BusinessShortCode' => $shortcode,
'Password' => $password,
'Timestamp' => $timestamp,
'TransactionType' => 'CustomerPayBillOnline',
'Amount' => $amount,
'PartyA' => $phoneNumber,
'PartyB' => $shortcode,
'PhoneNumber' => $phoneNumber,
'CallBackURL' => $callbackUrl,
'AccountReference' => $invoice->ref,
'TransactionDesc' => 'Payment for Invoice #' . $invoice->ref
];
// Send STK Push request
$response = dol_http_post('https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest', json_encode($payload), [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
$responseData = json_decode($response, true);
if ($responseData && $responseData['ResponseCode'] == '0') {
// Store CheckoutRequestID for callback mapping
$checkoutRequestID = $responseData['CheckoutRequestID'];
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "dolipesa_transactions (checkout_request_id, fk_invoice, datec) ";
$sql .= "VALUES ('" . $db->escape($checkoutRequestID) . "', " . $invoice->id . ", NOW())";
$db->query($sql);
setEventMessages($langs->trans('PaymentInitiated'), null, 'mesgs');
} else {
setEventMessages($langs->trans('PaymentInitiationFailed') . ': ' . ($responseData['errorMessage'] ?? 'Unknown error'), null, 'errors');
}
}
} else {
// Display payment form
$sql = "SELECT ref, total FROM ".MAIN_DB_PREFIX."facture WHERE rowid = $invoiceId";
$result = $db->query($sql);
if ($result) {
$invoice = $db->fetch_object($result);
print load_fiche_titre("Pay Invoice #{$invoice->ref}");
echo '<form method="POST">';
echo '<label>Phone Number (254...): <input type="text" name="phone_number" pattern="^254[0-9]{9}$" required></label><br>';
echo '<label>Amount: <input type="number" name="amount" value="'.$invoice->total.'" readonly></label><br>';
echo '<button type="submit">Pay Now</button>';
echo '</form>';
} else {
echo "<p>Invoice not found.</p>";
}
}
// Display payment form
print load_fiche_titre($langs->trans('PayInvoice', $invoice->ref));
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?invoice_id=' . $invoiceId . '&token=' . $token . '">';
print '<table class="noborder">';
print '<tr><td><label for="phone_number">' . $langs->trans('PhoneNumber') . ' (254...):</label></td>';
print '<td><input type="text" name="phone_number" id="phone_number" pattern="^254[0-9]{9}$" value="254" required></td></tr>';
print '<tr><td><label for="amount">' . $langs->trans('Amount') . ':</label></td>';
print '<td><input type="number" name="amount" id="amount" value="' . price($invoice->total_ttc) . '" readonly></td></tr>';
print '</table>';
print '<div class="center"><input type="submit" class="button" value="' . $langs->trans('PayNow') . '"></div>';
print '</form>';
llxFooter();
$db->close();
?>

View File

@ -1,56 +1,122 @@
<?php
/**
* M-Pesa Payment Module - Callback Handler
* Dolipesa - M-Pesa Payment Module Payment Initiation
* Author: NESTICT INFOTECH
* Version: 1.0.0
* Version: 1.0.1
* License: GNU General Public License v3.0
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php";
require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
header('Content-Type: application/json');
// Load translations
$langs->load('dolipesa@dolipesa');
// Retrieve M-Pesa callback data
$callbackData = json_decode(file_get_contents('php://input'), true);
// Security check
$invoiceId = GETPOST('invoice_id', 'int');
$token = GETPOST('token', 'alpha');
if (!$callbackData) {
http_response_code(400);
echo json_encode(["error" => "Invalid callback data"]);
exit;
if (!$invoiceId || !$token) {
accessforbidden($langs->trans('MissingParameters'));
}
// Extract data from callback
$invoiceId = $callbackData['AccountReference'] ?? null;
$transactionId = $callbackData['MpesaReceiptNumber'] ?? null;
$resultCode = $callbackData['ResultCode'] ?? 1;
$resultDesc = $callbackData['ResultDesc'] ?? "Unknown error";
if (!$invoiceId || !$transactionId) {
http_response_code(400);
echo json_encode(["error" => "Missing invoice or transaction ID"]);
exit;
// Validate token (simple example; enhance for production)
$expectedToken = md5($invoiceId . $conf->global->MAIN_SECURITY_SALT);
if ($token !== $expectedToken) {
accessforbidden($langs->trans('InvalidToken'));
}
// Handle successful transaction
if ($resultCode == 0) {
$sql = "UPDATE ".MAIN_DB_PREFIX."facture SET transaction_number = '$transactionId', paye = 1 WHERE rowid = $invoiceId";
// Load invoice
$invoice = new Facture($db);
if ($invoice->fetch($invoiceId) <= 0 || $invoice->statut != 1) { // Validated status
accessforbidden($langs->trans('InvoiceNotFoundOrNotValidated'));
}
// Process payment submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$phoneNumber = GETPOST('phone_number', 'alpha');
$amount = floatval($invoice->total_ttc); // Use invoice total including tax
// Validate phone number (Kenyan format: 2547XXXXXXXX)
if (!preg_match('/^254[0-9]{9}$/', $phoneNumber)) {
setEventMessages($langs->trans('InvalidPhoneNumber'), null, 'errors');
} else {
// Load M-Pesa credentials
$consumerKey = $conf->global->MPESAPAY_CONSUMER_KEY;
$consumerSecret = dol_decrypt($conf->global->MPESAPAY_CONSUMER_SECRET);
$shortcode = $conf->global->MPESAPAY_SHORTCODE;
$passkey = dol_decrypt($conf->global->MPESAPAY_PASSKEY);
$callbackUrl = $conf->global->MPESAPAY_CALLBACK_URL ?: DOL_MAIN_URL_ROOT . '/custom/dolipesa/callback.php';
if (empty($consumerKey) || empty($consumerSecret) || empty($shortcode) || empty($passkey)) {
setEventMessages($langs->trans('ModuleNotConfigured'), null, 'errors');
} else {
// Generate OAuth token
$credentials = base64_encode($consumerKey . ':' . $consumerSecret);
$tokenResponse = dol_http_get('https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials', [
'Authorization: Basic ' . $credentials
]);
$tokenData = json_decode($tokenResponse, true);
$accessToken = $tokenData['access_token'] ?? null;
if (!$accessToken) {
setEventMessages($langs->trans('FailedToGetMpesaToken'), null, 'errors');
} else {
// Prepare STK Push payload
$timestamp = date('YmdHis');
$password = base64_encode($shortcode . $passkey . $timestamp);
$payload = [
'BusinessShortCode' => $shortcode,
'Password' => $password,
'Timestamp' => $timestamp,
'TransactionType' => 'CustomerPayBillOnline',
'Amount' => $amount,
'PartyA' => $phoneNumber,
'PartyB' => $shortcode,
'PhoneNumber' => $phoneNumber,
'CallBackURL' => $callbackUrl,
'AccountReference' => $invoice->ref,
'TransactionDesc' => $langs->trans('PaymentForInvoice', $invoice->ref)
];
// Send STK Push request
$response = dol_http_post('https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest', json_encode($payload), [
'Authorization: Bearer ' . $accessToken,
'Content-Type: application/json'
]);
$responseData = json_decode($response, true);
if ($responseData && $responseData['ResponseCode'] == '0') {
// Store CheckoutRequestID for callback mapping
$checkoutRequestID = $responseData['CheckoutRequestID'];
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "dolipesa_transactions (checkout_request_id, fk_invoice, datec) ";
$sql .= "VALUES ('" . $db->escape($checkoutRequestID) . "', " . $invoice->id . ", NOW())";
$db->query($sql);
// Log payment in Dolibarr
$sqlPayment = "INSERT INTO ".MAIN_DB_PREFIX."paiement (facid, amount, datep, num_payment) VALUES ($invoiceId, (SELECT total FROM ".MAIN_DB_PREFIX."facture WHERE rowid = $invoiceId), NOW(), '$transactionId')";
$db->query($sqlPayment);
// Update invoice status
$sqlUpdateInvoice = "UPDATE ".MAIN_DB_PREFIX."facture SET statut = 2 WHERE rowid = $invoiceId"; // Paid status
$db->query($sqlUpdateInvoice);
http_response_code(200);
echo json_encode(["success" => "Payment successful", "transaction_id" => $transactionId]);
} else {
// Handle failed transaction
http_response_code(400);
echo json_encode(["error" => $resultDesc]);
setEventMessages($langs->trans('PaymentInitiated'), null, 'mesgs');
} else {
setEventMessages($langs->trans('PaymentInitiationFailed') . ': ' . ($responseData['errorMessage'] ?? 'Unknown error'), null, 'errors');
}
}
}
}
}
// Display payment form
print load_fiche_titre($langs->trans('PayInvoice', $invoice->ref));
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?invoice_id=' . $invoiceId . '&token=' . $token . '">';
print '<table class="noborder centpercent">';
print '<tr class="oddeven"><td><label for="phone_number">' . $langs->trans('PhoneNumber') . ' (254...):</label></td>';
print '<td><input type="text" name="phone_number" id="phone_number" pattern="^254[0-9]{9}$" value="254" required></td></tr>';
print '<tr class="oddeven"><td><label for="amount">' . $langs->trans('Amount') . ' (KES):</label></td>';
print '<td><input type="number" name="amount" id="amount" value="' . price($invoice->total_ttc, 0, '', 1, -1, -1, 'KES') . '" readonly></td></tr>';
print '</table>';
print '<div class="center" style="margin-top: 20px;">';
print '<input type="submit" class="button" value="' . $langs->trans('PayNow') . '">';
print '</div>';
print '</form>';
llxFooter();
$db->close();
?>