├── .github └── FUNDING.yml ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json └── src ├── Mpesa.php ├── Providers └── ServiceProvider.php └── config └── mpesa.php /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github:[karson] 4 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `mpesa-php-sdk` will be documented in this file 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | ## [1.4.0] - 2020-11-06 10 | ### Added 11 | - laravel compatibility 12 | - ServiceProviderCode Parameter initialization 13 | ### Changed 14 | - ServiceProvider Optional on transactions methods 15 | ## [1.3.0] - 2020-11-06 16 | - Update dependencies 17 | ## [1.2.2] - 2020-05-22 18 | ### Changed 19 | - Disable SSL Verification behavior of request 20 | 21 | ## [1.0] - 2020-01-14 22 | ### Added 23 | - Readme 24 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Karson Adam 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mpesa Mozambique PHP SDK 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/karson/mpesa-php-sdk.svg?style=flat-square)](https://packagist.org/packages/karson/mpesa-php-sdk) 4 | [![Build Status](https://img.shields.io/travis/karson/mpesa-php-sdk/master.svg?style=flat-square)](https://travis-ci.org/karson/mpesa-php-sdk) 5 | [![Quality Score](https://img.shields.io/scrutinizer/g/karson/mpesa-php-sdk.svg?style=flat-square)](https://scrutinizer-ci.com/g/karson/mpesa-php-sdk) 6 | [![Total Downloads](https://img.shields.io/packagist/dt/karson/mpesa-php-sdk.svg?style=flat-square)](https://packagist.org/packages/karson/mpesa-php-sdk) 7 | 8 | This package seeks to help php developers implement the various Mpesa APIs without much hustle. It is based on the REST API whose documentation is available on https://developer.mpesa.vm.co.mz/. 9 | 10 | ## Installation 11 | 12 | You can install the package via composer: 13 | 14 | ```bash 15 | composer require karson/mpesa-php-sdk 16 | ``` 17 | 18 | ## Usage 19 | 20 | ``` php 21 | // Set the api and public key as follows . Copy it from Mpesa Developer Console (https://developer.mpesa.vm.co.mz/) . 22 | $mpesa = new \Karson\MpesaPhpSdk\Mpesa(); 23 | $mpesa->setApiKey('your api key'); 24 | $mpesa->setPublicKey('your public key'); 25 | $mpesa->setServiceProviderCode('your public key'); 26 | $mpesa->setEnv('test');// 'live' production environment 27 | 28 | //This creates transaction between an M-Pesa service provider code to a phone number registered on M-Pesa. 29 | $invoice_id = "FT0001"; // Eg: Invoice number 30 | $phone_number = "258841234567"; // Prefixed with country code (258) 31 | $amount = "10"; // Payment amount 32 | $reference_id = "XBRAND001"; // Should be unique for each transaction 33 | 34 | $result = $mpesa->c2b($invoice_id, $phone_number, $amount, $reference_id); 35 | 36 | var_dump($result); 37 | ``` 38 | ### Instalation in Laravel 39 | 40 | ``` php 41 | // Set the api, public key, provider and environment secret as follows in your .env file 42 | 43 | MPESA_API_KEY ="Your API Key"; 44 | MPESA_PUBLIC_KEY='You Public Key' 45 | MPESA_ENV='test' // 'live' production environment 46 | MPESA_SERVICE_PROVIDER_CODE=171717 47 | ``` 48 | 49 | ### Testing 50 | 51 | ``` bash 52 | composer test 53 | ``` 54 | 55 | ### Changelog 56 | 57 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 58 | 59 | ## Contributing 60 | 61 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 62 | 63 | ### Security 64 | 65 | If you discover any security related issues, please email karson@turbohost.co instead of using the issue tracker. 66 | 67 | ## Credits 68 | 69 | - [Karson Adam](https://github.com/karson) 70 | - [All Contributors](../../contributors) 71 | 72 | ## License 73 | 74 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 75 | 76 | ## PHP Package Boilerplate 77 | 78 | This package was generated using the [PHP Package Boilerplate](https://laravelpackageboilerplate.com). 79 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "karson/mpesa-php-sdk", 3 | "description": "", 4 | "keywords": [ 5 | "karson", 6 | "mpesa-sdk", 7 | "mpesa-api", 8 | "mpesa", 9 | "payment-gateway", 10 | "vodacom-mozambique", 11 | "payment-gateway" 12 | ], 13 | "homepage": "https://github.com/karson/mpesa-php-sdk", 14 | "license": "MIT", 15 | "type": "library", 16 | "minimum-stability": "dev", 17 | "prefer-stable": true, 18 | "authors": [ 19 | { 20 | "name": "Karson Adam", 21 | "email": "karson@turbohost.co.mz", 22 | "role": "Developer" 23 | } 24 | ], 25 | "require": { 26 | "php": ">=7.3", 27 | "guzzlehttp/guzzle": "^7.0", 28 | "ext-curl": "*", 29 | "ext-json": "*" 30 | }, 31 | "require-dev": { 32 | "phpunit/phpunit": "^9.3.3" 33 | }, 34 | "autoload": { 35 | "psr-4": { 36 | "Karson\\MpesaPhpSdk\\": "src" 37 | }, 38 | "files": [ 39 | "src/Mpesa.php" 40 | ] 41 | }, 42 | "autoload-dev": { 43 | "psr-4": { 44 | "Karson\\MpesaPhpSdk\\Tests\\": "tests" 45 | } 46 | }, 47 | "scripts": { 48 | "test": "vendor/bin/phpunit", 49 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 50 | 51 | }, 52 | "config": { 53 | "sort-packages": true 54 | }, 55 | "extra": { 56 | "laravel": { 57 | "providers": [ 58 | "Karson\\MpesaPhpSdk\\Providers\\ServiceProvider" 59 | ], 60 | "aliases": { 61 | "Mpesa": "Karson\\MpesaPhpSdk\\Facade" 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Mpesa.php: -------------------------------------------------------------------------------- 1 | setPublicKey($config['public_key']); 18 | $this->setApiKey($config['api_key']); 19 | $this->setEnv($config['env']); 20 | $this->setServiceProviderCode($config['service_provider_code']); 21 | } 22 | } 23 | 24 | public function setPublicKey($public_key) 25 | { 26 | $this->public_key = trim($public_key); 27 | } 28 | 29 | public function setApiKey($api_key) 30 | { 31 | $this->api_key = $api_key; 32 | } 33 | 34 | public function setServiceProviderCode($service_provider_code) 35 | { 36 | $this->service_provider_code = $service_provider_code; 37 | } 38 | 39 | public function setEnv($env) 40 | { 41 | if ($env == 'live') { 42 | $this->base_uri = 'https://api.vm.co.mz'; 43 | } 44 | } 45 | 46 | 47 | /** 48 | * Standard customer-to-business transaction 49 | * 50 | * @param $transactionReference 51 | * @param $customerMSISDN 52 | * @param $amount 53 | * @param $thirdPartReferece 54 | * @param $serviceProviderCode 55 | * @return \stdClass 56 | */ 57 | public function c2b($transactionReference, $customerMSISDN, $amount, $thirdPartReferece, $serviceProviderCode = null) 58 | { 59 | $serviceProviderCode = $serviceProviderCode ?: $this->service_provider_code; 60 | $fields = [ 61 | "input_TransactionReference" => $transactionReference, 62 | "input_CustomerMSISDN" => $customerMSISDN, 63 | "input_Amount" => $amount, 64 | "input_ThirdPartyReference" => $thirdPartReferece, 65 | "input_ServiceProviderCode" => $serviceProviderCode 66 | ]; 67 | 68 | return $this->makeRequest('/ipg/v1x/c2bPayment/singleStage/', 18352, 'POST', $fields); 69 | } 70 | 71 | /** 72 | * Business to customer transaction 73 | * 74 | * @param [type] $transactionReference 75 | * @param [type] $customerMSISDN 76 | * @param [type] $amount 77 | * @param [type] $thirdPartReferece 78 | * @param [type] $serviceProviderCode 79 | * @return stdClass 80 | */ 81 | public function b2c($transactionReference, $customerMSISDN, $amount, $thirdPartReferece, $serviceProviderCode = null) 82 | { 83 | $serviceProviderCode = $serviceProviderCode ?: $this->service_provider_code; 84 | $fields = [ 85 | "input_TransactionReference" => $transactionReference, 86 | "input_CustomerMSISDN" => $customerMSISDN, 87 | "input_Amount" => $amount, 88 | "input_ThirdPartyReference" => $thirdPartReferece, 89 | "input_ServiceProviderCode" => $serviceProviderCode 90 | ]; 91 | 92 | return $this->makeRequest('/ipg/v1x/b2cPayment/', 18345, 'POST', $fields); 93 | } 94 | 95 | /** 96 | * @param $transactionID 97 | * @param $securityCredential 98 | * @param $initiatorIdentifier 99 | * @param $thirdPartyReference 100 | * @param $serviceProviderCode 101 | * @param $reversalAmount 102 | * @return \stdClass 103 | */ 104 | public function transactionReversal($transactionID, $securityCredential, $initiatorIdentifier, $thirdPartyReference, $serviceProviderCode = null, $reversalAmount = null) 105 | { 106 | $serviceProviderCode = $serviceProviderCode ?: $this->service_provider_code; 107 | $fields = [ 108 | "input_TransactionID" => $transactionID, 109 | "input_SecurityCredential" => $securityCredential, 110 | "input_InitiatorIdentifier" => $initiatorIdentifier, 111 | "input_ThirdPartyReference" => $thirdPartyReference, 112 | "input_ServiceProviderCode" => $serviceProviderCode, 113 | ]; 114 | if (isset($reversalAmount)) { 115 | $fields['input_ReversalAmount'] = $reversalAmount; 116 | } 117 | return $this->makeRequest('/ipg/v1x/reversal/', 18354, 'PUT', $fields); 118 | } 119 | 120 | /** 121 | * @param $thirdPartyReference 122 | * @param $queryReference 123 | * @param $serviceProviderCode 124 | * @return \stdClass 125 | */ 126 | public function status($thirdPartyReference, $queryReference, $serviceProviderCode = null) 127 | { 128 | $serviceProviderCode = $serviceProviderCode ?: $this->service_provider_code; 129 | $fields = [ 130 | 'input_ThirdPartyReference' => $thirdPartyReference, 131 | 'input_QueryReference' => $queryReference, 132 | 'input_ServiceProviderCode' => $serviceProviderCode 133 | ]; 134 | 135 | 136 | 137 | return $this->makeRequest('/ipg/v1x/queryTransactionStatus/', 18353, 'GET', $fields); 138 | } 139 | 140 | /** 141 | * The Query Customer Name API is used to provide the customer’s name associated to the mobile money wallet on Business to Wallet transfers, for confirmation purposes. This API will provide the First and Second name from the customer but obfuscated. 142 | * @param $thirdPartyReference 143 | * @param $queryReference 144 | * @param $serviceProviderCode 145 | * @return \stdClass 146 | */ 147 | public function queryCustomerName($customerMSISDN, $thirdPartReferece, $serviceProviderCode = null) 148 | { 149 | $serviceProviderCode = $serviceProviderCode ?: $this->service_provider_code; 150 | $fields = [ 151 | "input_CustomerMSISDN" => $customerMSISDN, 152 | "input_ThirdPartyReference" => $thirdPartReferece, 153 | "input_ServiceProviderCode" => $serviceProviderCode 154 | ]; 155 | 156 | return $this->makeRequest('/ipg/v1x/queryCustomerName/', 19323, 'GET', $fields); 157 | } 158 | 159 | /** 160 | * Generates a base64 encoded token 161 | */ 162 | public function getToken() 163 | { 164 | if (!empty($this->public_key) && !empty($this->api_key)) { 165 | $key = "-----BEGIN PUBLIC KEY-----\n"; 166 | $key .= wordwrap($this->public_key, 60, "\n", true); 167 | $key .= "\n-----END PUBLIC KEY-----"; 168 | $pk = openssl_get_publickey($key); 169 | openssl_public_encrypt($this->api_key, $token, $pk, OPENSSL_PKCS1_PADDING); 170 | 171 | return base64_encode($token); 172 | } 173 | return 'error'; 174 | } 175 | 176 | /** 177 | * @param string $url 178 | * @param string $method 179 | * @param array $fields 180 | * @return \stdClass 181 | */ 182 | private function makeRequest(string $url, int $port, string $method, array $fields = []) 183 | { 184 | $client = new Client([ 185 | 'base_uri' => $this->base_uri . ':' . $port, 186 | 'timeout' => 90, 187 | ]); 188 | 189 | $options = [ 190 | 'http_errors' => false, 191 | 'headers' => $this->getHeaders(), 192 | 'verify' => false 193 | ]; 194 | 195 | if ($method == 'POST' || $method == 'PUT') { 196 | $options += ['json' => $fields]; 197 | } else { 198 | $options += ['query' => $fields]; 199 | } 200 | 201 | $response = $client->request($method, $url, $options); 202 | 203 | $return = new \stdClass(); 204 | $return->response = json_decode($response->getBody()); 205 | 206 | if ($return->response == false) { 207 | $return->response = $response->getBody(); 208 | } 209 | 210 | 211 | $return->status = $response->getStatusCode(); 212 | return $return; 213 | } 214 | 215 | /** 216 | * @return array 217 | */ 218 | private function getHeaders() 219 | { 220 | $headers = [ 221 | 'Content-Type' => 'application/json', 222 | 'Authorization' => 'Bearer ' . $this->getToken(), 223 | 'origin' => 'developer.mpesa.vm.co.mz', 224 | 'Connection' => 'keep-alive' 225 | ]; 226 | return $headers; 227 | } 228 | } 229 | -------------------------------------------------------------------------------- /src/Providers/ServiceProvider.php: -------------------------------------------------------------------------------- 1 | publishes([ 21 | __DIR__.'/../config/mpesa.php'=> config_path('mpesa.php'), 22 | ]); 23 | } 24 | 25 | /** 26 | * Register the application services. 27 | * 28 | * @return void 29 | */ 30 | public function register() 31 | { 32 | $this->mergeConfigFrom( 33 | __DIR__.'/../config/mpesa.php', 34 | 'mpesa' 35 | ); 36 | 37 | $this->app->bind(Mpesa::class, function ($app) { 38 | $mpesa = new \Karson\MpesaPhpSdk\Mpesa(); 39 | 40 | $mpesa->setPublicKey(config('mpesa.public_key')); 41 | $mpesa->setApiKey(config('mpesa.api_key'));//test 42 | $mpesa->setEnv(config('mpesa.env')); 43 | $mpesa->setServiceProviderCode(config('mpesa.service_provider_code')); 44 | 45 | return $mpesa; 46 | }); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/config/mpesa.php: -------------------------------------------------------------------------------- 1 | env('MPESA_API_KEY'), 7 | 8 | 'public_key' => env('MPESA_PUBLIC_KEY'), 9 | 10 | 'env' => env('MPESA_ENV'), 11 | 'service_provider_code' => env('MPESA_SERVICE_PROVIDER_CODE'), 12 | 13 | ]; 14 | --------------------------------------------------------------------------------