Subiendo proyecto completo sin restricciones de git ignore

This commit is contained in:
Jose Sanchez
2023-08-17 11:44:02 -04:00
parent a0d4f5ba3b
commit 20f1c60600
19921 changed files with 2509159 additions and 45 deletions

65
vendor/osenco/mpesa/B2C.md vendored Normal file
View File

@@ -0,0 +1,65 @@
# The B2C (Business To Customer) API
### Instantiating The Class
Remember to add the Mpesa web portal username and password for a user with `B2C ORG API Initiator` role when setting up the class.
````php
B2C::init(
array(
'env' => 'sandbox',
'type' => 4,
'shortcode' => '174379',
'key' => 'Your Consumer Key',
'secret' => 'Your Consumer Secret',
'username' => '',
'password' => '',
'passkey' => 'Your Online Passkey',
'results_url' => url('mpesa/results'),
'timeout_url' => url('mpesa/timeout'),
)
);
````
## Make payment
```php
B2C::send($phone, $amount, $command, $remarks, $occassion, function($response)
{
$ConversationID = $response["ConversationID"];
$OriginatorConversationID = $response["OriginatorConversationID"];
$ResponseCode = $response["ResponseCode"];
$ResponseDescription = $response["ResponseDescription"];
// TIP: Save $OriginatorConversationID in the database, and use it as a key for update
});
```
## Process the Payment
```php
B2C::reconcile(function($response)
{
$Result = $response["Result"];
$ResultType = $Result["ResultType"];
$ResultCode = $Result["ResultCode"];
$ResultDesc = $Result["ResultDesc"];
$OriginatorConversationID = $Result["OriginatorConversationID"];
$ConversationID = $Result["ConversationID"];
$TransactionID = $Result["TransactionID"];
$ResultParameters = $Result["ResultParameters"];
$ResultParameter = $Result["ResultParameters"]["ResultParameter"];
$TransactionReceipt = $ResultParameter[0]["Value"];
$TransactionAmount = $ResultParameter[1]["Value"];
$B2CWorkingAccountAvailableFunds = $ResultParameter[2]["Value"];
$B2CUtilityAccountAvailableFunds = $ResultParameter[3]["Value"];
$TransactionCompletedDateTime = $ResultParameter[4]["Value"];
$ReceiverPartyPublicName = $ResultParameter[5]["Value"];
$B2CChargesPaidAccountAvailableFunds = $ResultParameter[6]["Value"];
$B2CRecipientIsRegisteredCustomer = $ResultParameter[7]["Value"];
$ReferenceData = $Result["ReferenceData"];
$ReferenceItem = $ReferenceData["ReferenceItem"];
$QueueTimeoutURL = $ReferenceItem[0]["Value"];
// Update Database record with $TransactionID as the MPESA receipt number where $OriginatorConversationID
});
```
See [the README](README.md) for making and processing payment requests.

113
vendor/osenco/mpesa/C2B.md vendored Normal file
View File

@@ -0,0 +1,113 @@
# The C2B (Customer To Business) API
This API enables Paybill and Buy Goods merchants to integrate to M-Pesa and receive real time payments notifications. A user pays through the traditional payment process (i.e goes to M-Pesa menu on their phone and makes the payment to your shortcode). The transaction details are then sent to your app.
This could come in handy and work as a backup to STK push, should the prompt fail, either because the user has not enabled their SIM, or it timed out before they saw it. In this case you should display appropriate instructions for the user to make this payment, making sure to supply your shortcode, and account number (for Paybills).
## Import Class With Namespace
Import the class namespace into your class or app to make it available for use.
```php
use Osen\Mpesa\C2B;
```
## Instantiating The Class
Remember to add the Mpesa web portal username when setting up the class.
```php
C2B::init(
array(
'env' => 'sandbox',
'type' => 4,
'shortcode' => '174379',
'headoffice' => '174379',
'key' => 'Your Consumer Key',
'secret' => 'Your Consumer Secret',
'passkey' => 'Your Online Passkey',
'validation_url' => url('lipwa/validate'),
'confirmation_url' => url('lipwa/confirm'),
'callback_url' => url('lipwa/reconcile'),
'results_url' => url('lipwa/results'),
'timeout_url' => url('lipwa/timeout'),
)
);
```
## The Validation/Confirmation URLs
Whenever M-Pesa receives a transaction on your shortcode, a validation request is sent to the validation URL registered above. M-Pesa completes or cancels the transaction depending on the validation response it receives.
These URLs must be HTTPS in production. Validation is an optional feature that needs to be activated on M-Pesa, the owner of the shortcode needs to make this request for activation. This can be done by sending an email to [apisupport@safaricom.co.ke](mailto:apisupport@safaricom.co.ke), or through a chat on the [developer portal](https://developer.safaricom.co.ke).
### Register Validation/Confirmation URLs
Simply call the `register` method of the `C2B` class, optionally passing a callback function to process the response from M-PESA. If no callback URL is supplied, the method will return an array of the response from M-PESA.
```php
C2B::register();
```
or
```php
C2B::register(function ($response){
// Do something with $response, like echo $response['ResponseDescription']
});
```
## Validate the Payment Data
When a user pays via M-Pesa, and validation is enabled for your shortcode, M-Pesa sends a request to your validation endpoint. The transaction data is sent with this request, and you can use the `validate` method of the `C2B` class to check the validity of this information, then return true. The method allows you to pass a callback function to process the data received.
```php
C2B::validate();
```
or
```php
C2B::validate(function ($response){
// Process $response
$TransactionType = $response['TransactionType'];
$TransID = $response['TransID'];
$TransTime = $response['TransTime'];
$TransAmount = $response['TransAmount'];
$BusinessShortCode = $response['BusinessShortCode'];
$BillRefNumber = $response['BillRefNumber'];
$InvoiceNumber = $response['InvoiceNumber'];
$OrgAccountBalance = $response['OrgAccountBalance'];
$ThirdPartyTransID = $response['ThirdPartyTransID'];
$MSISDN = $response['MSISDN'];
$FirstName = $response['FirstName'];
$MiddleName = $response['MiddleName'];
$LastName = $response['LastName'];
return true;
});
```
## Process the Payment (Confirmation)
If you return a success response at the validation endpoint. a confirmation request of the transaction is sent by M-Pesa to the confirmation URL. The transaction data is sent with this request, and you can use the `confirm` method of the `C2B` class to save this information, then return true. The method allows you to pass a callback function to process the data received.
```php
C2B::confirm();
```
or
```php
C2B::confirm(function ($response){
// Process $response
$TransactionType = $response['TransactionType'];
$TransID = $response['TransID'];
$TransTime = $response['TransTime'];
$TransAmount = $response['TransAmount'];
$BusinessShortCode = $response['BusinessShortCode'];
$BillRefNumber = $response['BillRefNumber'];
$InvoiceNumber = $response['InvoiceNumber'];
$OrgAccountBalance = $response['OrgAccountBalance'];
$ThirdPartyTransID = $response['ThirdPartyTransID'];
$MSISDN = $response['MSISDN'];
$FirstName = $response['FirstName'];
$MiddleName = $response['MiddleName'];
$LastName = $response['LastName'];
return true;
});
```
See [the README](README.md) for making and processing other payment requests.

61
vendor/osenco/mpesa/LARAVEL.md vendored Normal file
View File

@@ -0,0 +1,61 @@
# Sample Controller For Laravel
## The Mpesa Controller
We will need a controller to handle MPesa Transactions and save them to a database table of your choice. See [this example](examples/MpesaController.php) for sample code.
```bash
php artisan make:controller MpesaController
```
or create a file called `MpesaController.php` in the `app/Http/Controllers` and copy the contents of the [sample controller](examples/MpesaController.php) into the newl created file.
### Import Class With Namespace
Put this code at the top of the controller to make the M-PESA class available for use.
```php
use Osen\Mpesa\STK;
```
### Instantiating The Class
In your controller"s constructor, instantiate the Mpesa API class you want to use by passing configuration options like below:
```php
STK::init(
array(
"env" => "sandbox",
"type" => 4,
"shortcode" => "174379",
"headoffice" => "174379",
"key" => "Your Consumer Key",
"secret" => "Your Consumer Secret",
"passkey" => "Your Online Passkey",
"validation_url" => url("lipwa/validate"),
"confirmation_url" => url("lipwa/confirm"),
"callback_url" => url("lipwa/reconcile"),
"results_url" => url("lipwa/results"),
"timeout_url" => url("lipwa/timeout"),
)
);
```
## Routing and Endpoints
You can set your Laravel routes so as to create endpoints for interaction between Mpesa and your Laravel installation. Remember to call the respective actions (Mpesa methods) inside your controller methods.
```php
Route::prefix("lipwa")->group(function ()
{
Route::any("pay", "MpesaController@pay");
Route::any("validate", "MpesaController@validation");
Route::any("confirm", "MpesaController@confirmation");
Route::any("results", "MpesaController@results");
Route::any("register", "MpesaController@register");
Route::any("timeout", "MpesaController@timeout");
Route::any("reconcile", "MpesaController@reconcile");
Route::any("reverse", "MpesaController@reverse");
Route::any("status", "MpesaController@status");
});
```
### CSRF verification
Remember to add `lipwa/*` to the `$except` array in `app/Http/Middleware/VerifyCsrfToken.php` to whitelist your endpoints so they can receive data from Mpesa.
See [the README](README.md) for making and processing payment requests.

21
vendor/osenco/mpesa/LICENSE vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Osen Concepts Kenya
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.

414
vendor/osenco/mpesa/README.md vendored Normal file
View File

@@ -0,0 +1,414 @@
# Mpesa PHP SDK
Intuitive, Dynamic Mpesa PHP SDK
## Supported APIs
<table>
<thead>
<tr>
<th>API Type</th>
<th>Application Scenario</th>
</tr>
</thead>
<tbody>
<tr>
<td>STK - SIM Tool Kit Prompt</td>
<td>Customer Online Checkout</td>
</tr>
<tr>
<td>C2B - Customer To Business</td>
<td>Reconciling Manual Payments</td>
</tr>
<tr>
<td>B2C - Business To Customer</td>
<td>Salary Payments, Disbursals, Reversals</td>
</tr>
<!-- <tr>
<td>B2B - Business To Business</td>
<td>Payment For Supplies</td>
</tr> -->
<tr>
<td>Account Balance Check</td>
<td>Accounting Purposes</td>
</tr>
<tr>
<td>Transaction Status Check</td>
<td>Failed Transactions</td>
</tr>
<tr>
<td>Transaction Reversal</td>
<td>Wrongful Payment</td>
</tr>
</tbody>
</table>
## Installation
Install via composer by typing in your terminal
```bash
composer require osenco/mpesa
```
If you do not use composer you can just download this library from the releases, unzip it in your project and include the [autoload.php](autoload.php) file in your project.
```php
require_once("path/to/autoload.php");
```
For Laravel Users, there is a detailed guide [here](LARAVEL.md) as well as a sample [controller](examples/MpesaController.php)
## Usage
### Import Class With Namespace
Import the class namespace into your class or app to make it available for use. Replace STK with your API of choice. We will be using STK here. See how to set up [C2B here](C2B.md), [B2C here](B2C.md) and [B2B here](B2B.md).
```php
use Osen\Mpesa\STK;
```
### Instantiating The Class
The class uses static methods and does not need to be instantiated. This is to persist configuration in memory troughout execution of the script. To pass configuration options to the object, use the `init()` method at the top of your script. The `headoffice` key is only required for Till Numbers. Paybill users can ignore it.
```php
STK::init(
array(
"env" => "sandbox",
"type" => 4, // For Paybill, or, 2 for Till, 1 for MSISDN
"shortcode" => "174379",
"headoffice" => "174379", // Ignore if using Paybill
"key" => "Your Consumer Key",
"secret" => "Your Consumer Secret",
"username" => "", // Required for B2B and B2C APIs only
"password" => "", // Required for B2B and B2C APIs only
"passkey" => "Your Online Passkey",
"validation_url" => url("mpesa/validate"),
"confirmation_url" => url("mpesa/confirm"),
"callback_url" => url("mpesa/reconcile"),
"results_url" => url("mpesa/results"),
)
);
```
<b>TIP: You can just pass your URL endpoints for testing on sandbox, the system will use the test credentials provided from [Daraja](https://developer.safaricom.co.ke/test_credentials).</b>
### Making A Payment Request
Wrap your request in a try catch to ensure proper error handling
```php
try {
return $res = STK::send($phone, $amount, $reference);
// Do something with $res, like save to DB with the $res["MerchantRequestID"] as key.
} catch (\Throwable $th) {
return $th;
}
```
### Reconciling The Payment
The Mpesa transaction requests are asynchronous, and as such the payment details are not instantaneous. To get the transaction data and update the payment, use the `reconcile()` method. A callback function may be supplied to process the data. The callback function can either be a defined funtion or a closure(anonymous). If ommited, the method will return a successful response by default.
```php
STK::reconcile();
```
```php
STK::reconcile(function ($response){
$response = $response["Body"];
$resultCode = $response["stkCallback"]["ResultCode"];
$resultDesc = $response["stkCallback"]["ResultDesc"];
$merchantRequestID = $response["stkCallback"]["MerchantRequestID"];
if(isset($response["stkCallback"]["CallbackMetadata"])){
$CallbackMetadata = $response["stkCallback"]["CallbackMetadata"]["Item"];
$amount = $CallbackMetadata[0]["Value"];
$mpesaReceiptNumber = $CallbackMetadata[1]["Value"];
$balance = $CallbackMetadata[2]["Value"];
$transactionDate = $CallbackMetadata[3]["Value"];
$phone = $CallbackMetadata[4]["Value"];
$payment->status = "Paid";
$payment->amount = $amount;
$payment->receipt = $mpesaReceiptNumber;
}
return true;
});
```
### Processing Timeouts
When a valid M-Pesa API request is received by the API Gateway, it is sent to M-Pesa where it is added to a queue. M-Pesa then processes the requests in the queue and sends a response to the API Gateway which then forwards the response to the URL registered in the CallBackURL or ResultURL request parameter. Whenever M-Pesa receives more requests than the queue can handle, M-Pesa responds by rejecting any more requests and the API Gateway sends a queue timeout response to the URL registered in the QueueTimeOutURL request parameter. Use the `timeout()` method to process this response.
```php
STK::timeout();
```
This function takes the data sent by Safaricom, and returns a response. You can pass an optional argument to process the data and return true.
```php
STK::timeout(function ($response){
// Do something with $response
return true;
});
```
### Check Transaction Status
You can check for the status of a transaction by calling the `status" method at your endpoint.
```php
STK::status($transaction, $command = "TransactionStatusQuery", $remarks = "Transaction Status Query", $occassion = "Transaction Status Query");
```
You can pass an optional fifth argument that is a callback for processing the response from the request and returning true.
```php
STK::status($transaction, $command, $remarks, $occassion, function ($response){
// Do something with $response
return true;
});
```
### Reverse Transaction
To reverse a transaction, call the `reverse` method at your endpoint.
```php
STK::reverse($transaction, $amount, $receiver, $receiver_type = 3, $remarks = "Transaction Reversal", $occassion = "Transaction Reversal");
```
You can pass an optional seventh argument that is a callback for processing the response from the request and returning true.
```php
STK::reverse($transaction, $amount, $receiver, $receiver_type = 3, $remarks = "Transaction Reversal", $occassion = "", function ($response){
// Do something with $response
return true;
});
```
### Check Account Balance
To reverse a transaction, call the `reverse` method at your endpoint.
```php
STK::balance($command, $remarks = "Balance Query", $occassion = "");
```
You can pass an optional callback for processing the response from the request and returning true.
```php
STK::balance($command, $remarks = "Balance Query", function ($response){
// Do something with $response
return true;
});
```
### Processing Results
To process results from a transaction statuscheck, or a reversal, or an account balance check, call the `result` method at your endpoint.
```php
STK::result();
```
You can pass an optional callback for processing the response from the request and returning true.
```php
STK::result(function ($response){
// Process account balance check results
$result = $response["Result"];
$ResultType = $result["ResultType"];
$ResultCode = $result["ResultCode"];
$ResultDesc = $result["ResultDesc"];
$OriginatorConversationID = $result["OriginatorConversationID"];
$ConversationID = $result["ConversationID"];
$TransactionID = $result["TransactionID"];
$ResultParameters = $result["ResultParameters"];
$ResultParameter = $ResultParameters["ResultParameter"];
$ReceiptNo = $ResultParameter[0]["Value"];
$Conversation = $ResultParameter[1]["Value"];
$FinalisedTime = $ResultParameter[2]["Value"];
$Amount = $ResultParameter[3]["Value"];
$TransactionStatus = $ResultParameter[4]["Value"];
$ReasonType = $ResultParameter[5]["Value"];
$TransactionReason = $ResultParameter[6]["Value"];
$DebitPartyCharges = $ResultParameter[7]["Value"];
$DebitAccountType = $ResultParameter[8]["Value"];
$InitiatedTime = $ResultParameter[9]["Value"];
$OriginatorConversationID = $ResultParameter[10]["Value"];
$CreditPartyName = $ResultParameter[11]["Value"];
$DebitPartyName = $ResultParameter[12]["Value"];
$ReferenceData = $result["ReferenceData"];
$ReferenceItem = $ReferenceData["ReferenceItem"];
$Occasion = $ReferenceItem["Value"];
// Process transaction reversal results
$Result = $response["Result"];
$ResultType = $Result["ResultType"];
$ResultCode = $Result["ResultCode"];
$ResultDesc = $Result["ResultDesc"];
$OriginatorConversationID = $Result["OriginatorConversationID"];
$ConversationID = $Result["ConversationID"];
$TransactionID = $Result["TransactionID"];
$ReferenceData = $Result["ReferenceData"];
$ReferenceItem = $Result["ReferenceItem"];
$QueueTimeoutURL = $ReferenceItem["Value"];
// Process transaction status check results
$Result = $response["Result"];
$ResultType = $Result["ResultType"];
$ResultCode = $Result["ResultCode"];
$ResultDesc = $Result["ResultDesc"];
$OriginatorConversationID = $Result["OriginatorConversationID"];
$ConversationID = $Result["ConversationID"];
$TransactionID = $Result["TransactionID"];
$ResultParameters = $Result["ResultParameters"];
$ResultParameter = $ResultParameters["ResultParameter"];
$ReceiptNo = $ResultParameter[0]["Value"];
$ConversationID = $ResultParameter[1]["Value"];
$FinalisedTime = $ResultParameter[2]["Value"];
$Amount = $ResultParameter[3]["Value"];
$TransactionStatus = $ResultParameter[4]["Value"];
$ReasonType = $ResultParameter[5]["Value"];
$TransactionReason = $ResultParameter[6]["Value"];
$DebitPartyCharges = $ResultParameter[7]["Value"];
$DebitAccountType = $ResultParameter[8]["Value"];
$InitiatedTime = $ResultParameter[9]["Value"];
$OriginatorConversationID = $ResultParameter[10]["Value"];
$CreditPartyName = $ResultParameter[11]["Value"];
$DebitPartyName = $ResultParameter[12]["Value"];
$ReferenceData = $result["ReferenceData"];
$ReferenceItem = $ReferenceData["ReferenceItem"];
$Occasion = $ReferenceItem["Value"];
//TIP: You can differentiate between responses by checking value of $ResultType
return true;
});
```
## Available Command IDs
<table>
<thead>
<tr>
<th>Command ID</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>TransactionReversal</td>
<td>Reversal for an erroneous C2B transaction.</td>
</tr>
<tr>
<td>SalaryPayment</td>
<td>Used to send money from an employer to employees e.g. salaries</td>
</tr>
<tr>
<td>BusinessPayment</td>
<td>Used to send money from business to client e.g. refunds</td>
</tr>
<tr>
<td>PromotionPayment</td>
<td>Used to send money when promotions take place e.g. raffle winners</td>
</tr>
<tr>
<td>AccountBalance</td>
<td>Used to check the balance in a paybill/buy goods account (includes utility, MMF, Merchant, Charges paid account).</td>
</tr>
<tr>
<td>CustomerPayBillOnline</td>
<td>Used to simulate a transaction taking place in the case of C2B Simulate Transaction or to initiate a transaction on behalf of the client (STK Push).</td>
</tr>
<tr>
<td>TransactionStatusQuery</td>
<td>Used to query the details of a transaction.</td>
</tr>
<tr>
<td>CheckIdentity</td>
<td>Similar to STK push, uses M-Pesa PIN as a service.</td>
</tr>
<tr>
<td>BusinessPayBill</td>
<td>Sending funds from one paybill to another paybill</td>
</tr>
<tr>
<td>BusinessBuyGoods</td>
<td>sending funds from buy goods to another buy goods.</td>
</tr>
<tr>
<td>DisburseFundsToBusiness</td>
<td>Transfer of funds from utility to MMF account.</td>
</tr>
<tr>
<td>BusinessToBusinessTransfer</td>
<td>Transferring funds from one paybills MMF to another paybills MMF account.</td>
</tr>
<tr>
<td>BusinessTransferFromMMFToUtility</td>
<td>Transferring funds from paybills MMF to another paybills utility account.</td>
</tr>
</tbody>
</table>
## Helper Functions
You can use the helper function s for more concise code
To configure the class, use the `mpesa_setup_config` function , passing your configuration options as the first argument, and the API you wish to setup(STK, C2B, B2C, B2B) as the second argument. The API is set to STK by default.
```php
$config = array(
"env" => "sandbox",
"type" => 4, // For Paybill, or, 2 for Till, 1 for MSISDN
"shortcode" => "174379",
"headoffice" => "174379",
"key" => "Your Consumer Key",
"secret" => "Your Consumer Secret",
"username" => "",
"passkey" => "Your Online Passkey",
"validation_url" => url("mpesa/validate"),
"confirmation_url" => url("mpesa/confirm"),
"callback_url" => url("mpesa/reconcile"),
"results_url" => url("mpesa/results"),
);
mpesa_setup_config($config, "STK");
```
Optionally, you could configure with the `mpesa_setup_*` function s
```php
mpesa_setup_stk($config);
mpesa_setup_c2b($config);
mpesa_setup_b2c($config);
mpesa_setup_b2b($config);
```
To make a STK Prompt request, pass the user"s phone number, the amount due, and an optional reference(shows up on the user"s phone) respectively
```php
mpesa_stk_push($phone, $amount, $reference);
```
To simulate a c2b transaction, call the function as follows, passing the user"s phone number, the amount due, and an optional reference respectively
```php
mpesa_c2b_request($phone, $amount, $reference);
```
To send funds to a client
```php
mpesa_b2c_request();
```
Transfer funds between one business to another
```php
mpesa_b2b_request();
```
Validate Or Confirm Transaction Details. Call this function at your validation/confirmation endpoint.
```php
mpesa_validate();
mpesa_confirm()
```
## Credits & Acknowledgements
Mpesa is a service and registered trademark of [Safaricom PLC](https://safaricom.co.ke).
## Licensing
This software is released under [MIT License](LICENSE).
## Usage & Contribution
This library is free and open source software. You can copy, modify and distribute it as you so wish. If you have any ideas on how to improve it, shoot us an email at [hi@osen.co.ke](mailto:hi@osen.co.ke) or raise an issue here.

220
vendor/osenco/mpesa/RESPONSES.md vendored Normal file
View File

@@ -0,0 +1,220 @@
# MPESA API Responses
This file includes instructions and sample code for processing callback data sent from Safaricom. It includes sample responses from Safaricom and how to process them accordingly.
## STK Response Data
### Sample Response
```json
{
"Body":{
"stkCallback":{
"MerchantRequestID":"19465-780693-1",
"CheckoutRequestID":"ws_CO_27072017154747416",
"ResultCode":0,
"ResultDesc":"The service request is processed successfully.",
"CallbackMetadata":{
"Item":[
{
"Name":"Amount",
"Value":1
},
{
"Name":"MpesaReceiptNumber",
"Value":"LGR7OWQX0R"
},
{
"Name":"Balance"
},
{
"Name":"TransactionDate",
"Value":20170727154800
},
{
"Name":"PhoneNumber",
"Value":254721566839
}
]
}
}
}
}
```
### Sample Callback Function
```php
function mpesa_stk_callback($response)
{
$data = $response["Body"]["stkCallback"];
$MerchantRequestID = $data["MerchantRequestID"];
$CheckoutRequestID = $data["CheckoutRequestID"],
$ResultCode = $data["ResultCode"],
$ResultDesc = $data["ResultDesc"],
$CallbackMetadata = $data["CallbackMetadata"];
$Amount = $CallbackMetadata["Item"][0]["Value"];
$MpesaReceiptNumber = $CallbackMetadata["Item"][1]["Value"];
$Balance = $CallbackMetadata["Item"][2]["Value"];
$TransactionDate = $CallbackMetadata["Item"][3]["Value"];
$PhoneNumber = $CallbackMetadata["Item"][4]["Value"];
// Do something with the variables above then return true or false
return true
}
```
## C2B Response Data
### Sample Response
```json
{
"Body":
{
"stkCallback":
{
"MerchantRequestID":"19465-780693-1",
"CheckoutRequestID":"ws_CO_27072017154747416",
"ResultCode":0,
"ResultDesc":"The service request is processed successfully.",
"CallbackMetadata":
{
"Item":
[
{
"Name":"Amount",
"Value":1
},
{
"Name":"MpesaReceiptNumber",
"Value":"LGR7OWQX0R"
},
{
"Name":"Balance"
},
{
"Name":"TransactionDate",
"Value":20170727154800
},
{
"Name":"PhoneNumber",
"Value":254721566839
}
]
}
}
}
}
```
### Sample Callback Function
```php
function mpesa_c2b_callback($response)
{
$data = $response["Body"]["stkCallback"];
$MerchantRequestID = $data["MerchantRequestID"];
$CheckoutRequestID = $data["CheckoutRequestID"],
$ResultCode = $data["ResultCode"],
$ResultDesc = $data["ResultDesc"],
$CallbackMetadata = $data["CallbackMetadata"];
$Amount = $CallbackMetadata["Item"][0]["Value"];
$MpesaReceiptNumber = $CallbackMetadata["Item"][0]["Value"];
$Balance = $CallbackMetadata["Item"][0]["Value"];
$TransactionDate = $CallbackMetadata["Item"][0]["Value"];
$PhoneNumber = $CallbackMetadata["Item"][0]["Value"];
// Do something with the variables above then return true or false
return true
}
```
## B2C Response Data
### Sample Response
```json
{
"Result":
{
"ResultType":0,
"ResultCode":0,
"ResultDesc":"The service request has been accepted successfully.",
"OriginatorConversationID":"19455-424535-1",
"ConversationID":"AG_20170717_00006be9c8b5cc46abb6",
"TransactionID":"LGH3197RIB",
"ResultParameters":
{
"ResultParameter":
[
{
"Key":"TransactionReceipt",
"Value":"LGH3197RIB"
},
{
"Key":"TransactionAmount",
"Value":8000
},
{
"Key":"B2CWorkingAccountAvailableFunds",
"Value":150000
},
{
"Key":"B2CUtilityAccountAvailableFunds",
"Value":133568
},
{
"Key":"TransactionCompletedDateTime",
"Value":"17.07.2017 10:54:57"
},
{
"Key":"ReceiverPartyPublicName",
"Value":"254708374149 - John Doe"
},
{
"Key":"B2CChargesPaidAccountAvailableFunds",
"Value":0
},
{
"Key":"B2CRecipientIsRegisteredCustomer",
"Value":"Y"
}
]
},
"ReferenceData":{
"ReferenceItem":{
"Key":"QueueTimeoutURL",
"Value":"https://internalsandbox.safaricom.co.ke/mpesa/b2cresults/v1/submit"
}
}
}
}
```
### Sample Callback Function
```php
function mpesa_b2c_callback($response)
{
$data = $response["Result"];
$ResultType = $data["ResultType"];
$ResultCode = $data["ResultCode"];
$ResultDesc = $data["ResultDesc"];
$OriginatorConversationID = $data["OriginatorConversationID"];
$ConversationID = $data["ConversationID"];
$TransactionID = $data["TransactionID"];
$ResultParameters = $data["ResultParameters"]["ResultParameter"];
$QueueTimeoutURL = $data["ReferenceData"]["ReferenceItem"][0]["Value"];
$TransactionReceipt = $ResultParameters[0]["Value"];
$TransactionAmount = $ResultParameters[1]["Value"];
$B2CWorkingAccountAvailableFunds = $ResultParameters[2]["Value"];
$B2CUtilityAccountAvailableFunds = $ResultParameters[3]["Value"];
$TransactionCompletedDateTime = $ResultParameters[4]["Value"];
$ReceiverPartyPublicName = $ResultParameters[5]["Value"];
$B2CChargesPaidAccountAvailableFunds = $ResultParameters[6]["Value"];
$B2CRecipientIsRegisteredCustomer = $ResultParameters[7]["Value"];
// Do something with the variables above then return true or false
return true
}
```

21
vendor/osenco/mpesa/autoload.php vendored Normal file
View File

@@ -0,0 +1,21 @@
<?php
/**
* Register autoloader for classes under the Osen namespace
* @param class $class Full namespaced class e.g Osen\Mpesa\STK
*/
spl_autoload_register(
function ($class) {
if (strpos($class, "Osen\Mpesa")) {
$class = str_replace("Osen\Mpesa", "", $class);
$path = str_replace("\\", "/", $class);
require_once "src/{$path}.php";
}
}
);
/**
* Load helper functions for more concise functional code
*/
require_once "src/helpers.php";

22
vendor/osenco/mpesa/composer.json vendored Normal file
View File

@@ -0,0 +1,22 @@
{
"name": "osenco/mpesa",
"description": "Intuitive Mpesa SDK for PHP Apps. Just Plug 'N Play",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Osen Concepts",
"email": "hi@osen.co.ke"
}
],
"minimum-stability": "dev",
"require": {
"php": ">=7.0"
},
"autoload": {
"psr-4": {
"Osen\\Mpesa\\": "src/"
},
"files": ["src/helpers.php"]
}
}

View File

@@ -0,0 +1,102 @@
<?php
namespace App\Http\Controllers;
use App\Payment;
use Illuminate\Http\Request;
use Osen\Mpesa\B2C;
class MpesaController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
B2C::init(
array(
"env" => "sandbox",
"shortcode" => "173527",
"headoffice" => "173527",
"key" => "Your Consumer Key",
"secret" => "Your Consumer Secret",
"username" => "Your Org Username",
"password" => "Your Org Password",
"validation_url" => url("disburse/validate"),
"confirmation_url" => url("disburse/confirm"),
"callback_url" => url("disburse/reconcile"),
"results_url" => url("disburse/timeout"),
)
);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function pay(Request $request)
{
$data = $request->all();
try {
$request = B2C::send($request->phone, $request->amount, $request->command, $request->remarks, $request->occassion, function ($response) {
$ConversationID = $response["ConversationID"];
$OriginatorConversationID = $response["OriginatorConversationID"];
$ResponseCode = $response["ResponseCode"];
$ResponseDescription = $response["ResponseDescription"];
// TIP: Save $OriginatorConversationID in the database, and use it as a key for update
$data["request_id"] = $OriginatorConversationID;
$payment = Payment::create($data);
return true;
});
return back();
} catch (\Exception $e) {
return array("msg" => $e->getMessage);
}
}
public function confirmation()
{
return B2C::reconcile(function ($response) {
$Result = $response["Result"];
$ResultType = $Result["ResultType"];
$ResultCode = $Result["ResultCode"];
$ResultDesc = $Result["ResultDesc"];
$OriginatorConversationID = $Result["OriginatorConversationID"];
$ConversationID = $Result["ConversationID"];
$TransactionID = $Result["TransactionID"];
$ResultParameters = $Result["ResultParameters"];
$ResultParameter = $Result["ResultParameters"]["ResultParameter"];
$TransactionReceipt = $ResultParameter[0]["Value"];
$TransactionAmount = $ResultParameter[1]["Value"];
$B2CWorkingAccountAvailableFunds = $ResultParameter[2]["Value"];
$B2CUtilityAccountAvailableFunds = $ResultParameter[3]["Value"];
$TransactionCompletedDateTime = $ResultParameter[4]["Value"];
$ReceiverPartyPublicName = $ResultParameter[5]["Value"];
$B2CChargesPaidAccountAvailableFunds = $ResultParameter[6]["Value"];
$B2CRecipientIsRegisteredCustomer = $ResultParameter[7]["Value"];
$ReferenceData = $Result["ReferenceData"];
$ReferenceItem = $ReferenceData["ReferenceItem"];
$QueueTimeoutURL = $ReferenceItem[0]["Value"];
// Update Database record with $TransactionID as the MPESA receipt number where $OriginatorConversationID
$payment = Payment::where("request_id", $OriginatorConversationID)->first();
$payment->receipt = $TransactionID;
$payment->save();
return true;
});
}
public function results()
{
return B2C::results();
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace App\Http\Controllers;
use App\Payment;
use Illuminate\Http\Request;
use Osen\Mpesa\STK;
use Osen\Mpesa\C2B;
class MpesaController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
C2B::init(
array(
"env" => "sandbox",
"type" => 4,
"shortcode" => "174379",
"key" => "Your Consumer Key",
"secret" => "Your Consumer Secret",
"validation_url" => url("lipwa/validate"),
"confirmation_url" => url("lipwa/confirm"),
"timeout_url" => url("lipwa/timeout"),
)
);
STK::init(
array(
"env" => "sandbox",
"type" => 4,
"shortcode" => "173527",
"headoffice" => "173527",
"key" => "Your Consumer Key",
"secret" => "Your Consumer Secret",
"passkey" => "Your Online Passkey",
"validation_url" => url("lipwa/validate"),
"callback_url" => url("lipwa/reconcile"),
"timeout_url" => url("lipwa/timeout"),
)
);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function pay(Request $request)
{
$data = $request->all();
try {
$res = STK($request->phone, $request->amount, $request->reference);
if (!isset($res["errorCode"])) {
$data["ref"] = $res->MerchantRequestID;
$payment = Payment::create($data);
if ($payment) {
return array("msg" => "saved");
} else {
return array("msg" => "failed");
}
return back();
}
} catch (\Exception $e) {
return array("msg" => $e->getMessage());
return back();
}
}
public function reconcile(Request $request, $method = "mpesa")
{
if ($method == "mpesa") {
$response = STK::reconcile(function ($data) {
$payment = Payment::where("mpesa", $data["MerchantRequestID"])->first();
$payment->status = "Paid";
return $payment->save();
});
}
}
public function validation()
{
return STK::validate();
}
public function confirmation()
{
return C2B::confirm(function ($response) {
// Process $response
$TransactionType = $response["TransactionType"];
$TransID = $response["TransID"];
$TransTime = $response["TransTime"];
$TransAmount = $response["TransAmount"];
$BusinessShortCode = $response["BusinessShortCode"];
$BillRefNumber = $response["BillRefNumber"];
$InvoiceNumber = $response["InvoiceNumber"];
$OrgAccountBalance = $response["OrgAccountBalance"];
$ThirdPartyTransID = $response["ThirdPartyTransID"];
$MSISDN = $response["MSISDN"];
$FirstName = $response["FirstName"];
$MiddleName = $response["MiddleName"];
$LastName = $response["LastName"];
return true;
});
}
public function results()
{
return STK::results();
}
public function timeout()
{
return STK::timeout();
}
}

65
vendor/osenco/mpesa/src/B2B.php vendored Normal file
View File

@@ -0,0 +1,65 @@
<?php
namespace Osen\Mpesa;
use Osen\Mpesa\Service;
class B2B extends Service
{
/**
* Transfer funds between two paybills
* @param $receiver Receiving party paybill
* @param $receiver_type Receiver party type
* @param $amount Amount to transfer
* @param $command Command ID
* @param $reference Account Reference mandatory for “BusinessPaybill” CommandID.
* @param $remarks
*
* @return array
*/
public static function send(
$receiver,
$receiver_type,
$amount = 10,
$command = "",
$reference = "TRX",
$remarks = "",
$callback = null
)
{
$token = parent::token();
$env = parent::$config->env;
$endpoint = ($env == "live")
? "https://api.safaricom.co.ke/mpesa/b2b/v1/paymentrequest"
: "https://sandbox.safaricom.co.ke/mpesa/b2b/v1/paymentrequest";
$plaintext = parent::$config->password;
$publicKey = file_get_contents(__DIR__ . "/certs/{$env}/cert.cer");
openssl_public_encrypt($plaintext, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);
$password = base64_encode($encrypted);
$curl_post_data = array(
"Initiator" => parent::$config->username,
"SecurityCredential" => $password,
"CommandID" => $command,
"SenderIdentifierType" => parent::$config->type,
"RecieverIdentifierType" => $receiver_type,
"Amount" => $amount,
"PartyA" => parent::$config->shortcode,
"PartyB" => $receiver,
"AccountReference" => $reference,
"Remarks" => $remarks,
"QueueTimeOutURL" => parent::$config->timeout_url,
"ResultURL" => parent::$config->result_url,
);
$response = parent::remote_post($endpoint, $token, $curl_post_data);
$result = json_decode($response, true);
return is_null($callback)
? $result
: \call_user_func_array($callback, array($result));
}
}

60
vendor/osenco/mpesa/src/B2C.php vendored Normal file
View File

@@ -0,0 +1,60 @@
<?php
namespace Osen\Mpesa;
use Osen\Mpesa\Service;
class B2C extends Service
{
/**
* Transfer funds between two paybills
* @param $receiver Receiving party phone
* @param $amount Amount to transfer
* @param $command Command ID
* @param $occassion
* @param $remarks
*
* @return array
*/
public static function send($phone, $amount = 10, $command = "BusinessPayment", $remarks = "", $occassion = "", $callback = null)
{
$env = parent::$config->env;
$phone = (substr($phone, 0, 1) == "+") ? str_replace("+", "", $phone) : $phone;
$phone = (substr($phone, 0, 1) == "0") ? preg_replace("/^0/", "254", $phone) : $phone;
$phone = (substr($phone, 0, 1) == "7") ? "254{$phone}" : $phone;
$phone = ($env == "live") ? $phone : "254708374149";
$endpoint = ($env == "live")
? "https://api.safaricom.co.ke/mpesa/b2c/v1/paymentrequest"
: "https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest";
$timestamp = date("YmdHis");
$plaintext = parent::$config->password;
$publicKey = file_get_contents(__DIR__ . "/certs/{$env}/cert.cer");
openssl_public_encrypt($plaintext, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);
$password = base64_encode($encrypted);
$password = ($env == "live") ? $password : "Safaricom568!#";
$curl_post_data = array(
"InitiatorName" => parent::$config->username,
"SecurityCredential" => $password,
"CommandID" => $command,
"Amount" => round($amount),
"PartyA" => parent::$config->shortcode,
"PartyB" => $phone,
"Remarks" => $remarks,
"QueueTimeOutURL" => parent::$config->timeout_url,
"ResultURL" => parent::$config->results_url,
"Occasion" => $occassion,
);
$response = parent::remote_post($endpoint, $curl_post_data);
$result = json_decode($response, true);
return is_null($callback)
? $result
: \call_user_func_array($callback, array($result));
}
}

71
vendor/osenco/mpesa/src/C2B.php vendored Normal file
View File

@@ -0,0 +1,71 @@
<?php
namespace Osen\Mpesa;
use Osen\Mpesa\Service;
class C2B extends Service
{
/**
* Registers your confirmation and validation URLs to M-Pesa.
* Whenever M-Pesa receives a transaction on the shortcode, it triggers a validation request against the validation URL and the 3rd party system responds to M-Pesa with a validation response (either a success or an error code).
* M-Pesa completes or cancels the transaction depending on the validation response it receives from the 3rd party system. A confirmation request of the transaction is then sent by M-Pesa through the confirmation URL back to the 3rd party which then should respond with a success acknowledging the confirmation.
*/
public static function register($callback = null, $response_type = "Completed")
{
$endpoint = (parent::$config->env == "live")
? "https://api.safaricom.co.ke/mpesa/c2b/v1/registerurl"
: "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl";
$curl_post_data = array(
"ShortCode" => parent::$config->shortcode,
"ResponseType" => $response_type,
"ConfirmationURL" => parent::$config->confirmation_url,
"ValidationURL" => parent::$config->validation_url,
);
$response = parent::remote_post($endpoint, $curl_post_data);
$result = json_decode($response, true);
return is_null($callback)
? $result
: \call_user_func_array($callback, array($result));
}
/**
* Simulates a C2B request
*
* @param $phone Receiving party phone
* @param $amount Amount to transfer
* @param $command Command ID
* @param $reference
*
* @return array
*/
public static function send($phone = null, $amount = 10, $reference = "TRX", $command = "", $callback = null)
{
$phone = (substr($phone, 0, 1) == "+") ? str_replace("+", "", $phone) : $phone;
$phone = (substr($phone, 0, 1) == "0") ? preg_replace("/^0/", "254", $phone) : $phone;
$phone = (substr($phone, 0, 1) == "7") ? "254{$phone}" : $phone;
$endpoint = (parent::$config->env == "live")
? "https://api.safaricom.co.ke/mpesa/c2b/v1/simulate"
: "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate";
$curl_post_data = array(
"ShortCode" => parent::$config->shortcode,
"CommandID" => $command,
"Amount" => round($amount),
"Msisdn" => $phone,
"BillRefNumber" => $reference,
);
$response = parent::remote_post($endpoint, $curl_post_data);
$result = json_decode($response, true);
return is_null($callback)
? $result
: \call_user_func_array($callback, array($result));
}
}

53
vendor/osenco/mpesa/src/STK.php vendored Normal file
View File

@@ -0,0 +1,53 @@
<?php
namespace Osen\Mpesa;
use Osen\Mpesa\Service;
class STK extends Service
{
/**
* @param $phone The MSISDN sending the funds.
* @param $amount The amount to be transacted.
* @param $reference Used with M-Pesa PayBills.
* @param $description A description of the transaction.
* @param $remark Remarks
*
* @return array Response
*/
public static function send($phone, $amount, $reference = "ACCOUNT", $description = "Transaction Description", $remark = "Remark", $callback = null)
{
$phone = (substr($phone, 0, 1) == "+") ? str_replace("+", "", $phone) : $phone;
$phone = (substr($phone, 0, 1) == "0") ? preg_replace("/^0/", "254", $phone) : $phone;
$phone = (substr($phone, 0, 1) == "7") ? "254{$phone}" : $phone;
$timestamp = date("YmdHis");
$password = base64_encode(parent::$config->shortcode . parent::$config->passkey . $timestamp);
$endpoint = (parent::$config->env == "live")
? "https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
: "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest";
$curl_post_data = array(
"BusinessShortCode" => parent::$config->headoffice,
"Password" => $password,
"Timestamp" => $timestamp,
"TransactionType" => (parent::$config->type == 4) ? "CustomerPayBillOnline" : "CustomerBuyGoodsOnline",
"Amount" => round($amount),
"PartyA" => $phone,
"PartyB" => parent::$config->shortcode,
"PhoneNumber" => $phone,
"CallBackURL" => parent::$config->callback_url,
"AccountReference" => $reference,
"TransactionDesc" => $description,
"Remark" => $remark,
);
$response = parent::remote_post($endpoint, $curl_post_data);
$result = json_decode($response, true);
return is_null($callback)
? $result
: \call_user_func_array($callback, array($result));
}
}

309
vendor/osenco/mpesa/src/Service.php vendored Normal file
View File

@@ -0,0 +1,309 @@
<?php
namespace Osen\Mpesa;
class Service
{
/**
* @var object $config Configuration options
*/
public static $config;
public static function init($configs)
{
$base = (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . (isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : '');
$defaults = array(
"env" => "sandbox",
"type" => 4,
"shortcode" => "174379",
"headoffice" => "174379",
"key" => "Your Consumer Key",
"secret" => "Your Consumer Secret",
"username" => "apitest",
"password" => "",
"passkey" => "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919",
"validation_url" => $base . "/lipwa/validate",
"confirmation_url" => $base . "/lipwa/confirm",
"callback_url" => $base . "/lipwa/reconcile",
"timeout_url" => $base . "/lipwa/timeout",
"results_url" => $base . "/lipwa/results",
);
if (!empty($configs) && (!isset($configs["headoffice"]) || empty($configs["headoffice"]))) {
$defaults["headoffice"] = $configs["shortcode"];
}
foreach ($defaults as $key => $value) {
if (isset($configs[$key])) {
$defaults[$key] = $configs[$key];
}
}
self::$config = (object) $defaults;
}
public static function remote_get($endpoint, $credentials = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $endpoint);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Basic " . $credentials));
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
return curl_exec($curl);
}
public static function remote_post($endpoint, $data = array())
{
$token = self::token();
$curl = curl_init();
$data_string = json_encode($data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_URL, $endpoint);
curl_setopt(
$curl,
CURLOPT_HTTPHEADER,
array(
"Content-Type:application/json",
"Authorization:Bearer " . $token,
)
);
return curl_exec($curl);
}
/**
* @return string Access token
*/
public static function token()
{
$endpoint = (self::$config->env == "live")
? "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"
: "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";
$credentials = base64_encode(self::$config->key . ":" . self::$config->secret);
$response = self::remote_get($endpoint, $credentials);
$result = json_decode($response);
return isset($result->access_token) ? $result->access_token : "";
}
/**
* @param $transaction
* @param $command
* @param $remarks
* @param $occassion\
*
* @return array Result
*/
public static function status($transaction, $command = "TransactionStatusQuery", $remarks = "Transaction Status Query", $occasion = "Transaction Status Query", $callback = null)
{
$env = self::$config->env;
$plaintext = self::$config->password;
$publicKey = file_get_contents(__DIR__ . "/certs/{$env}/cert.cer");
openssl_public_encrypt($plaintext, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);
$password = base64_encode($encrypted);
$endpoint = ($env == "live")
? "https://api.safaricom.co.ke/lipwa/transactionstatus/v1/query"
: "https://sandbox.safaricom.co.ke/lipwa/transactionstatus/v1/query";
$curl_post_data = array(
"Initiator" => self::$config->username,
"SecurityCredential" => $password,
"CommandID" => $command,
"TransactionID" => $transaction,
"PartyA" => self::$config->shortcode,
"IdentifierType" => self::$config->type,
"ResultURL" => self::$config->results_url,
"QueueTimeOutURL" => self::$config->timeout_url,
"Remarks" => $remarks,
"Occasion" => $occasion,
);
$response = self::remote_post($endpoint, $curl_post_data);
$result = json_decode($response, true);
return is_null($callback)
? $result
: \call_user_func_array($callback, array($result));
}
/**
* @param $transaction
* @param $amount
* @param $receiver
* @param $receiver_type
* @param $remarks
* @param $occassion
*
* @return array Result
*/
public static function reverse($transaction, $amount, $receiver, $receiver_type = 3, $remarks = "Transaction Reversal", $occasion = "Transaction Reversal", $callback = null)
{
$env = self::$config->env;
$plaintext = self::$config->password;
$publicKey = file_get_contents(__DIR__ . "/certs/{$env}/cert.cer");
openssl_public_encrypt($plaintext, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);
$password = base64_encode($encrypted);
$endpoint = ($env == "live")
? "https://api.safaricom.co.ke/lipwa/reversal/v1/request"
: "https://sandbox.safaricom.co.ke/lipwa/reversal/v1/request";
$curl_post_data = array(
"CommandID" => "TransactionReversal",
"Initiator" => self::$config->business,
"SecurityCredential" => $password,
"TransactionID" => $transaction,
"Amount" => $amount,
"ReceiverParty" => $receiver,
"RecieverIdentifierType" => $receiver_type,
"ResultURL" => self::$config->results_url,
"QueueTimeOutURL" => self::$config->timeout_url,
"Remarks" => $remarks,
"Occasion" => $occasion,
);
$response = self::remote_post($endpoint, $curl_post_data);
$result = json_decode($response, true);
return is_null($callback)
? $result
: \call_user_func_array($callback, array($result));
}
/**
* @param $command
* @param $remarks
* @param $occassion
*
* @return array Result
*/
public static function balance($command, $remarks = "Balance Query", $callback = null)
{
$env = self::$config->env;
$plaintext = self::$config->password;
$publicKey = file_get_contents(__DIR__ . "/certs/{$env}/cert.cer");
openssl_public_encrypt($plaintext, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);
$password = base64_encode($encrypted);
$endpoint = ($env == "live")
? "https://api.safaricom.co.ke/lipwa/accountbalance/v1/query"
: "https://sandbox.safaricom.co.ke/lipwa/accountbalance/v1/query";
$curl_post_data = array(
"CommandID" => $command,
"Initiator" => self::$config->username,
"SecurityCredential" => $password,
"PartyA" => self::$config->shortcode,
"IdentifierType" => self::$config->type,
"Remarks" => $remarks,
"QueueTimeOutURL" => self::$config->timeout_url,
"ResultURL" => self::$config->results_url,
);
$response = self::remote_post($endpoint, $curl_post_data);
$result = json_decode($response, true);
return is_null($callback)
? $result
: \call_user_func_array($callback, array($result));
}
/**
* @param callable $callback Defined function or closure to process data and return true/false
*
* @return array
*/
public static function validate($callback = null)
{
$data = json_decode(file_get_contents("php://input"), true);
if (is_null($callback)) {
return array("ResultCode" => 0, "ResultDesc" => "Success");
} else {
return call_user_func_array($callback, array($data))
? array("ResultCode" => 0, "ResultDesc" => "Success")
: array("ResultCode" => 1, "ResultDesc" => "Failed");
}
}
/**
* @param callable $callback Defined function or closure to process data and return true/false
*
* @return array
*/
public static function confirm($callback = null)
{
$data = json_decode(file_get_contents("php://input"), true);
if (is_null($callback)) {
return array("ResultCode" => 0, "ResultDesc" => "Success");
} else {
return call_user_func_array($callback, array($data))
? array("ResultCode" => 0, "ResultDesc" => "Success")
: array("ResultCode" => 1, "ResultDesc" => "Failed");
}
}
/**
* @param callable $callback Defined function or closure to process data and return true/false
*
* @return array
*/
public static function reconcile(callable $callback = null)
{
$response = json_decode(file_get_contents("php://input"), true);
if (is_null($callback)) {
return array("ResultCode" => 0, "ResultDesc" => "Service request successful");
} else {
return call_user_func_array($callback, array($response))
? array("ResultCode" => 0, "ResultDesc" => "Service request successful")
: array("ResultCode" => 1, "ResultDesc" => "Service request failed");
}
}
/**
* @param callable $callback Defined function or closure to process data and return true/false
*
* @return array
*/
public static function results(callable $callback = null)
{
$response = json_decode(file_get_contents("php://input"), true);
if (is_null($callback)) {
return array("ResultCode" => 0, "ResultDesc" => "Service request successful");
} else {
return call_user_func_array($callback, array($response))
? array("ResultCode" => 0, "ResultDesc" => "Service request successful")
: array("ResultCode" => 1, "ResultDesc" => "Service request failed");
}
}
/**
* @param callable $callback Defined function or closure to process data and return true/false
*
* @return array
*/
public static function timeout(callable $callback = null)
{
$response = json_decode(file_get_contents("php://input"), true);
if (is_null($callback)) {
return array("ResultCode" => 0, "ResultDesc" => "Service request successful");
} else {
return call_user_func_array($callback, array($response))
? array("ResultCode" => 0, "ResultDesc" => "Service request successful")
: array("ResultCode" => 1, "ResultDesc" => "Service request failed");
}
}
}

View File

@@ -0,0 +1,38 @@
-----BEGIN CERTIFICATE-----
MIIGkzCCBXugAwIBAgIKXfBp5gAAAD+hNjANBgkqhkiG9w0BAQsFADBbMRMwEQYK
CZImiZPyLGQBGRYDbmV0MRkwFwYKCZImiZPyLGQBGRYJc2FmYXJpY29tMSkwJwYD
VQQDEyBTYWZhcmljb20gSW50ZXJuYWwgSXNzdWluZyBDQSAwMjAeFw0xNzA0MjUx
NjA3MjRaFw0xODAzMjExMzIwMTNaMIGNMQswCQYDVQQGEwJLRTEQMA4GA1UECBMH
TmFpcm9iaTEQMA4GA1UEBxMHTmFpcm9iaTEaMBgGA1UEChMRU2FmYXJpY29tIExp
bWl0ZWQxEzARBgNVBAsTClRlY2hub2xvZ3kxKTAnBgNVBAMTIGFwaWdlZS5hcGlj
YWxsZXIuc2FmYXJpY29tLmNvLmtlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEAoknIb5Tm1hxOVdFsOejAs6veAai32Zv442BLuOGkFKUeCUM2s0K8XEsU
t6BP25rQGNlTCTEqfdtRrym6bt5k0fTDscf0yMCoYzaxTh1mejg8rPO6bD8MJB0c
FWRUeLEyWjMeEPsYVSJFv7T58IdAn7/RhkrpBl1dT7SmIZfNVkIlD35+Cxgab+u7
+c7dHh6mWguEEoE3NbV7Xjl60zbD/Buvmu6i9EYz+27jNVPI6pRXHvp+ajIzTSsi
eD8Ztz1eoC9mphErasAGpMbR1sba9bM6hjw4tyTWn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Id1v+dZfPiMQ5lf
vfNu/1aNR1Y2/0q1YMG06v9eoIMPAAABZXs1F8IAAAQDAEgwRgIhAIRq2XFiC+RS
uDCYq8ICJg0QafSV+e9BLpJnElEdaSjiAiEAyiiW4vxwv4cWcAXE6FAipctyUBs6
bE5QyaCnmNpoDiQwDQYJKoZIhvcNAQELBQADggEBAB0YoWve9Sxhb0PBS3Hc46Rf
a7H1jhHuwE+UyscSQsdJdk8uPAgDuKRZMvJPGEaCkNHm36NfcaXXFjPOl7LI1d1a
9zqSP0xeZBI6cF0x96WuQGrI9/WR2tfxjmaUSp8a/aJ6n+tZA28eJZNPrIaMm+6j
gh7AkKnqcf+g8F/MvCCVdNAiVMdz6UpCscf6BRPHNZ5ifvChGh7aUKjrVLLuF4Ls
HE05qm6HNyV5eTa6wvcbc4ewguN1UDZvPWetSyfBk10Wbpor4znQ4TJ3Y9uCvsJH
41ldblDvZZ2z4kB2UYQ7iBkPlJSxSOaFgW/GGDXq49sz/995xzhVITHxh2SdLkI=
-----END CERTIFICATE-----

104
vendor/osenco/mpesa/src/helpers.php vendored Normal file
View File

@@ -0,0 +1,104 @@
<?php
/**
* These helper functions wrap around the various mpesa API classes for more concise code
*/
if (!function_exists("mpesa_setup_mpesa")) {
function mpesa_setup_config($config = [], $api = "STK")
{
$API = "Osen\\Mpesa\\{$api}";
return $API::init($config);
}
}
if (!function_exists("mpesa_setup_stk")) {
function mpesa_setup_stk($config = [])
{
return Osen\Mpesa\STK::init($config);
}
}
if (!function_exists("mpesa_setup_c2b")) {
function mpesa_setup_c2b($config = [])
{
return Osen\Mpesa\C2B::init($config);
}
}
if (!function_exists("mpesa_setup_b2c")) {
function mpesa_setup_b2c($config = [])
{
return Osen\Mpesa\B2C::init($config);
}
}
if (!function_exists("mpesa_setup_b2b")) {
function mpesa_setup_b2b($config = [])
{
return Osen\Mpesa\B2B::init($config);
}
}
if (!function_exists("mpesa_stk_push")) {
function mpesa_stk_push($phone, $amount, $reference)
{
return Osen\Mpesa\STK::send($phone, $amount, $reference);
}
}
if (!function_exists("mpesa_c2b_request")) {
function mpesa_c2b_request($phone, $amount, $reference)
{
return Osen\Mpesa\C2B::send($phone, $amount, $reference);
}
}
if (!function_exists("mpesa_b2c_request")) {
function mpesa_b2c_request($phone, $amount, $reference)
{
return Osen\Mpesa\B2C::send($phone, $amount, $reference);
}
}
if (!function_exists("mpesa_b2b_request")) {
function mpesa_b2b_request($phone, $amount, $reference)
{
return Osen\Mpesa\B2B::send($phone, $amount, $reference);
}
}
if (!function_exists("mpesa_validate")) {
function mpesa_validate(callable $callback = null)
{
return Osen\Mpesa\Service::validate($callback);
}
}
if (!function_exists("mpesa_confirm")) {
function mpesa_confirm(callable $callback = null)
{
return Osen\Mpesa\Service::confirm($callback);
}
}
if (!function_exists("mpesa_reconcile")) {
function mpesa_reconcile(callable $callback = null)
{
return Osen\Mpesa\Service::reconcile($callback);
}
}
if (!function_exists("mpesa_results")) {
function mpesa_results(callable $callback = null)
{
return Osen\Mpesa\Service::results($callback);
}
}
if (!function_exists("mpesa_timeout")) {
function mpesa_timeout(callable $callback = null)
{
return Osen\Mpesa\Service::timeout();
}
}