├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── examples └── .gitkeep ├── src └── Paymentsds │ └── MPesa │ ├── Client.php │ ├── Configuration.php │ ├── Constants.php │ ├── Environment.php │ ├── ErrorType.php │ ├── Exception │ ├── AuthenticationException.php │ ├── InvalidHostException.php │ ├── InvalidReceiverException.php │ ├── MissingPropertiesException.php │ ├── TimeoutException.php │ └── ValidationException.php │ ├── Operation.php │ ├── Response.php │ └── Service.php └── tests ├── .env.example └── ClientTest.php /.gitignore: -------------------------------------------------------------------------------- 1 | /tmp 2 | /vendor 3 | /composer.lock 4 | *.env -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PHP M-Pesa SDK 2 | 3 | 4 |

5 | Total Downloads 6 | Latest Stable Version 7 | License 8 |

9 | 10 | This is a library willing to help you to integrate the [Vodacom M-Pesa](https://developer.mpesa.vm.co.mz) operations to your application. 11 | 12 |
13 | 14 | ### Features 15 | 16 | Using this library, you can implement the following operations: 17 | 18 | - Receive money from a mobile account to a business account (C2B) 19 | - Send money from a business account to a mobile account (B2C) 20 | - Send money from a business account to another business account (B2B) 21 | - Revert any of the transactions above mentioned 22 | - Query the status of a transaction 23 | 24 |

25 | 26 | ## Requirements 27 | 28 | - [PHP 7.2+](https://php.net/downloads) 29 | - [Composer](https://getcomposer.org) 30 | - Valid credentials obtained from the [Mpesa Developer](https://developer.mpesa.vm.co.mz) portal 31 | - Port 18352 open on your server (usually open on local env) 32 | 33 | 34 |

35 | 36 | 37 | ## Installation 38 | 39 |
40 | 41 | ### Using Composer 42 | 43 | ```bash 44 | composer require paymentsds/mpesa 45 | ``` 46 | 47 |
48 | 49 | ### Manual Installation 50 | ```bash 51 | git clone https://github.com/paymentsds/mpesa-php-sdk mpesa-php-sdk 52 | cd mpesa-php-sdk 53 | composer install 54 | ``` 55 | 56 |

57 | 58 | 59 | ## Usage 60 | 61 | Using this SDK is very simple and fast, let us see some examples: 62 | 63 |
64 | 65 | #### C2B Transaction (Receive money from mobile account) 66 | 67 | ```php 68 | use Paymentsds\MPesa\Client; 69 | use Paymentsds\MPesa\Environment; 70 | 71 | $client = new Client([ 72 | 'apiKey' => '', // API Key 73 | 'publicKey' => '', // Public Key 74 | 'serviceProviderCode' => '' // Service Provider Code 75 | 'environment' => Environment::SANDBOX // Environment. Use Environment::PRODUCTION for production 76 | ]); 77 | 78 | $paymentData = [ 79 | 'from' => '841234567', // Customer MSISDN 80 | 'reference' => '11114', // Third Party Reference 81 | 'transaction' => 'T12344CC', // Transaction Reference 82 | 'amount' => '10' // Amount 83 | ]; 84 | 85 | $result = $client->receive($paymentData); 86 | 87 | if ($result->success) { 88 | // Handle success 89 | } else { 90 | // Handle failure 91 | } 92 | ``` 93 | 94 |
95 | 96 | #### B2C Transaction (Sending money to mobile account) 97 | 98 | ```php 99 | use Paymentsds\MPesa\Client; 100 | 101 | $client = new Client([ 102 | 'apiKey' => '', // API Key 103 | 'publicKey' => '', // Public Key 104 | 'serviceProviderCode' => '' // Service Provider Code 105 | ]); 106 | 107 | $paymentData = [ 108 | 'to' => '841234567', // Customer MSISDN 109 | 'reference' => '11114', // Third Party Reference 110 | 'transaction' => 'T12344CC', // Transaction Reference 111 | 'amount' => '10' // Amount 112 | ]; 113 | 114 | $result = $client->send($paymentData); 115 | 116 | if ($result->success) { 117 | // Handle success scenario 118 | } else { 119 | // Handle failure scenario 120 | } 121 | ``` 122 | 123 |
124 | 125 | #### B2B Transaction (Sending money to business account) 126 | 127 | ```php 128 | $client = new Client([ 129 | 'apiKey' => '', // API Key 130 | 'publicKey' => '', // Public Key 131 | 'serviceProviderCode' => '' // Service Provider Code 132 | ]); 133 | 134 | $paymentData = [ 135 | 'from' => '979797', // Receiver Party Code 136 | 'reference' => '11114', // Third Party Reference 137 | 'transaction' => 'T12344CC', // Transaction Reference 138 | 'amount' => '10' // Amount 139 | ]; 140 | 141 | $result = $client->send($paymentData) 142 | 143 | if ($result->success) { 144 | // Handle success scenario 145 | } else { 146 | // Handle failure scenario 147 | } 148 | ``` 149 | 150 |
151 | 152 | 153 | #### Transaction Reversal 154 | 155 | ```php 156 | use Paymentsds\MPesa\Client; 157 | 158 | $client = new Client([ 159 | 'apiKey' => '', // API Key 160 | 'publicKey' => '', // Public Key 161 | 'serviceProviderCode' => '', // Service Provider Code 162 | 'initiatorIdentifier' => '', // Initiator Identifier 163 | 'securityIdentifier' => '' // Security Credential 164 | ]); 165 | 166 | $paymentData = [ 167 | 'reference' => '11114', // Third Party Reference 168 | 'transaction' => 'T12344CC', // Transaction Reference 169 | 'amount' => '10' // Amount 170 | ]; 171 | 172 | $result = $client->revert($paymentData); 173 | 174 | if ($result->success) { 175 | // Handle success scenario 176 | } else { 177 | // Handle failure scenario 178 | } 179 | ``` 180 | 181 |
182 | 183 | #### Query the transaction status 184 | 185 | ```php 186 | use Paymentsds\MPesa\Client; 187 | 188 | $client = new Client([ 189 | 'apiKey' => '', // API Key 190 | 'publicKey' => '', // Public Key 191 | 'serviceProviderCode' => '' // Service Provider Code 192 | ]); 193 | 194 | $paymentData = [ 195 | 'subject' => '11114', // Query Reference 196 | 'transaction' => 'T12344CC', // Transaction Reference 197 | ]; 198 | 199 | $result = $client->query($paymentData); 200 | 201 | if ($result->success) { 202 | // Handle success scenario 203 | } else { 204 | // Handle failure scenario 205 | } 206 | ``` 207 | 208 |

209 | 210 | ## Friends 211 | 212 | - [M-Pesa SDK for Javascript](https://github.com/paymentsds/mpesa-js-sdk) 213 | - [M-Pesa SDK for Python](https://github.com/paymentsds/mpesa-python-sdk) 214 | - [M-Pesa SDK for Java](https://github.com/paymentsds/mpesa-java-sdk) 215 | - [M-Pesa SDK for Ruby](https://github.com/paymentsds/mpesa-ruby-sdk) 216 | 217 | 218 |

219 | 220 | ## Authors 221 | 222 | - [Anísio Mandlate](https://github.com/AnisioMandlate) 223 | - [Edson Michaque](https://github.com/edsonmichaque) 224 | - [Elton Laice](https://github.com/eltonlaice) 225 | - [Nélio Macombo](https://github.com/neliomacombo) 226 | 227 | 228 |

229 | 230 | ## Contributing 231 | 232 | Thank you for considering contributing to this package. If you wish to do it, email us at [developers@paymentsds.org](mailto:developers@paymentsds.org) and we will get back to you as soon as possible. 233 | 234 | 235 |

236 | 237 | ## Security Vulnerabilities 238 | 239 | If you discover a security vulnerability, please email us at [developers@paymentsds.org](mailto:developers@paymentsds.org) and we will address the issue with the needed urgency. 240 | 241 |

242 | 243 | ## License 244 | 245 | Copyright 2020 © The PaymentsDS Team 246 | 247 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 248 | 249 | http://www.apache.org/licenses/LICENSE-2.0 250 | 251 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 252 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "paymentsds/mpesa", 3 | "description": "PHP client library for MPesa API", 4 | "type": "library", 5 | "license": "Apache-2.0", 6 | "authors": [ 7 | { 8 | "name": "Edson Michaque", 9 | "email": "edson@michaque.com" 10 | }, 11 | { 12 | "name": "Elton Laice", 13 | "email": "me@eltonlaice.com" 14 | }, 15 | { 16 | "name": "Karson Adam", 17 | "email": "karson@turbohost.co.mz" 18 | } 19 | ], 20 | "minimum-stability": "dev", 21 | "prefer-stable": true, 22 | "require": { 23 | "php": ">=7.2", 24 | "guzzlehttp/guzzle": "7.*", 25 | "ext-curl": "*", 26 | "ext-json": "*" 27 | }, 28 | "require-dev": { 29 | "phpunit/phpunit": "^9.5", 30 | "vlucas/phpdotenv": "^5.4" 31 | }, 32 | "autoload": { 33 | "psr-4": { 34 | "Paysuite\\MPesa\\": "src" 35 | }, 36 | "files": [ 37 | "src/Paymentsds/MPesa/Environment.php", 38 | "src/Paymentsds/MPesa/Operation.php", 39 | "src/Paymentsds/MPesa/Constants.php", 40 | "src/Paymentsds/MPesa/Configuration.php", 41 | "src/Paymentsds/MPesa/Service.php", 42 | "src/Paymentsds/MPesa/Client.php", 43 | "src/Paymentsds/MPesa/ErrorType.php", 44 | "src/Paymentsds/MPesa/Response.php", 45 | "src/Paymentsds/MPesa/Exception/AuthenticationException.php", 46 | "src/Paymentsds/MPesa/Exception/InvalidHostException.php", 47 | "src/Paymentsds/MPesa/Exception/InvalidReceiverException.php", 48 | "src/Paymentsds/MPesa/Exception/TimeoutException.php", 49 | "src/Paymentsds/MPesa/Exception/ValidationException.php" 50 | ] 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /examples/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paymentsds/mpesa-php-sdk/bac22b90d4acf498ce09d5131707ba1b370272f0/examples/.gitkeep -------------------------------------------------------------------------------- /src/Paymentsds/MPesa/Client.php: -------------------------------------------------------------------------------- 1 | service = new Service($args); 11 | } 12 | 13 | public function send($intent) 14 | { 15 | return $this->service->handleSend($intent); 16 | } 17 | 18 | public function receive($intent) 19 | { 20 | return $this->service->handleReceive($intent); 21 | } 22 | 23 | public function revert($intent) 24 | { 25 | return $this->service->handleRevert($intent); 26 | } 27 | 28 | public function query($intent) 29 | { 30 | return $this->service->handleQuery($intent); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Paymentsds/MPesa/Configuration.php: -------------------------------------------------------------------------------- 1 | environment = Environment::fromURL(Environment::SANDBOX); 26 | $this->debugging = false; 27 | $this->verifySSL = false; 28 | $this->origin = '*'; 29 | $this->userAgent = 'MPesa-PHP'; 30 | $this->timeout = 0; 31 | 32 | foreach (self::PARAMS as $param) { 33 | if (!empty($args[$param])) { 34 | switch ($param) { 35 | case 'environment': 36 | if ($args['environment'] == Environment::PRODUCTION) { 37 | $this->environment = Environment::fromURL(Environment::PRODUCTION); 38 | } 39 | 40 | break; 41 | case 'host': 42 | $this->environment = Environment::fromURL($args[$param]); 43 | break; 44 | default: 45 | $this->{$param} = $args[$param]; 46 | } 47 | } 48 | } 49 | } 50 | 51 | public function __set($property, $value) 52 | { 53 | if (in_array($property, self::PARAMS)) { 54 | $this->{$property} = $value; 55 | } 56 | } 57 | 58 | public function __get($property) 59 | { 60 | return $this->{$property}; 61 | } 62 | 63 | public function generateAccessToken() 64 | { 65 | $hasKeys = isset($this->apiKey) && isset($this->publicKey); 66 | $hasAccessToken = isset($this->accessToken); 67 | 68 | if ($hasKeys) { 69 | $publicKey = openssl_get_publickey($this->formatPublicKey()); 70 | 71 | openssl_public_encrypt($this->apiKey, $accessToken, $publicKey, OPENSSL_PKCS1_PADDING); 72 | 73 | $this->auth = base64_encode($accessToken); 74 | } 75 | 76 | if ($hasAccessToken) { 77 | $this->auth = $this->accessToken; 78 | } 79 | } 80 | 81 | private function formatPublicKey() 82 | { 83 | $publicKeyHeader = "-----BEGIN PUBLIC KEY-----\n"; 84 | $publicKeyFooter = "\n-----END PUBLIC KEY-----"; 85 | 86 | return sprintf("%s%s%s", $publicKeyHeader, $this->publicKey, $publicKeyFooter); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/Paymentsds/MPesa/Constants.php: -------------------------------------------------------------------------------- 1 | [ 24 | 'method' => self::POST, 25 | 'port' => self::C2B_PAYMENT_PORT, 26 | 'path' => '/ipg/v1x/c2bPayment/singleStage/', 27 | 'mapping' => [ 28 | 'to' => 'input_ServiceProviderCode', 29 | 'from' => 'input_CustomerMSISDN', 30 | 'amount' => 'input_Amount', 31 | 'reference' => 'input_ThirdPartyReference', 32 | 'transaction' => 'input_TransactionReference', 33 | 34 | ], 35 | 'validation' => [ 36 | 'to' => self::PATTERNS['SERVICE_PROVIDER_CODE'], 37 | 'from' => self::PATTERNS['PHONE_NUMBER'], 38 | 'amount' => self::PATTERNS['MONEY_AMOUNT'], 39 | 'reference' => self::PATTERNS['WORD'], 40 | 'transaction' => self::PATTERNS['WORD'], 41 | ], 42 | 'required' => [ 43 | 'from', 44 | 'reference', 45 | 'transaction', 46 | 'amount' 47 | ], 48 | 'optional' => [ 49 | 'to' 50 | ] 51 | ], 52 | 53 | self::B2B_PAYMENT => [ 54 | 'method' => self::POST, 55 | 'port' => self::B2B_PAYMENT_PORT, 56 | 'path' => '/ipg/v1x/b2bPayment/', 57 | 'mapping' => [ 58 | 'to' => 'input_ReceiverPartyCode', 59 | 'from' => 'input_PrimaryPartyCode', 60 | 'amount' => 'input_Amount', 61 | 'reference' => 'input_ThirdPartyReference', 62 | 'transaction' => 'input_TransactionReference', 63 | ], 64 | 'validation' => [ 65 | 'to' => self::PATTERNS['SERVICE_PROVIDER_CODE'], 66 | 'from' => self::PATTERNS['SERVICE_PROVIDER_CODE'], 67 | 'amount' => self::PATTERNS['MONEY_AMOUNT'], 68 | 'reference' => self::PATTERNS['WORD'], 69 | 'transaction' => self::PATTERNS['WORD'], 70 | ], 71 | 'required' => [ 72 | 'to', 73 | 'amount', 74 | 'reference', 75 | 'transaction' 76 | ], 77 | 'optional' => [ 78 | 'from' 79 | ] 80 | 81 | ], 82 | 83 | self::B2C_PAYMENT => [ 84 | 'method' => self::POST, 85 | 'port' => self::B2C_PAYMENT_PORT, 86 | 'path' => '/ipg/v1x/b2cPayment/', 87 | 'mapping' => [ 88 | 'to' => 'input_CustomerMSISDN', 89 | 'from' => 'input_ServiceProviderCode', 90 | 'amount' => 'input_Amount', 91 | 'reference' => 'input_ThirdPartyReference', 92 | 'transaction' => 'input_TransactionReference', 93 | ], 94 | 'validation' => [ 95 | 'to' => self::PATTERNS['PHONE_NUMBER'], 96 | 'from' => self::PATTERNS['SERVICE_PROVIDER_CODE'], 97 | 'amount' => self::PATTERNS['MONEY_AMOUNT'], 98 | 'reference' => self::PATTERNS['WORD'], 99 | 'transaction' => self::PATTERNS['WORD'], 100 | ], 101 | 'required' => [ 102 | 'to', 103 | 'from', 104 | 'amount', 105 | 'reference', 106 | 'transaction' 107 | ], 108 | 'optional' => [ 109 | 'from' 110 | ] 111 | ], 112 | 113 | self::REVERSAL => [ 114 | 'method' => self::PUT, 115 | 'port' => self::REVERSAL_PORT, 116 | 'path' => '/ipg/v1x/reversal/', 117 | 'mapping' => [ 118 | 'to' => 'input_ServiceProviderCode', 119 | 'amount' => 'input_ReversalAmount', 120 | 'reference' => 'input_ThirdPartyReference', 121 | 'transaction' => 'input_TransactionID', 122 | 'securityCredential' => 'input_SecurityCredential', 123 | 'initiatorIdentifier' => 'input_InitiatorIdentifier' 124 | ], 125 | 'validation' => [ 126 | 'to' => self::PATTERNS['SERVICE_PROVIDER_CODE'], 127 | 'amount' => self::PATTERNS['MONEY_AMOUNT'], 128 | 'reference' => self::PATTERNS['WORD'], 129 | 'transaction' => self::PATTERNS['WORD'], 130 | 'securityCredential' => self::PATTERNS['WORD'], 131 | 'initiatorIdentifier' => self::PATTERNS['WORD'] 132 | ], 133 | 'required' => [ 134 | 'to', 135 | 'amount', 136 | 'reference', 137 | 'transaction', 138 | 'securityCredential', 139 | 'initiatorIdentifier' 140 | ], 141 | 'optional' => [ 142 | 'to', 143 | 'securityCredential', 144 | 'initiatorIdentifier' 145 | ] 146 | ], 147 | 148 | self::QUERY_TRANSACTION_STATUS => [ 149 | 'method' => self::GET, 150 | 'port' => self::QUERY_TRANSACTION_STATUS_PORT, 151 | 'path' => '/ipg/v1x/queryTransactionStatus/', 152 | 'mapping' => [ 153 | 'from' => 'input_ServiceProviderCode', 154 | 'subject' => 'input_QueryReference', 155 | 'reference' => 'input_ThirdPartyReference' 156 | ], 157 | 'validation' => [ 158 | 'from' => self::PATTERNS['SERVICE_PROVIDER_CODE'], 159 | 'subject' => self::PATTERNS['WORD'], 160 | 'reference' => self::PATTERNS['WORD'], 161 | ], 162 | 'required' => [ 163 | 'from', 164 | 'subject', 165 | 'reference' 166 | ], 167 | 'optional' => [ 168 | 'from' 169 | ] 170 | ] 171 | ]; 172 | 173 | const PATTERNS = [ 174 | 'PHONE_NUMBER' => '/^((00|\+)?258)?8[45][0-9]{7}$/', 175 | 'WORD' => '/^\w+$/', 176 | 'MONEY_AMOUNT' => '/^[1-9][0-9]*(\.[0-9]+)?$/', 177 | 'SERVICE_PROVIDER_CODE' => '/^[0-9]{5,6}$/' 178 | ]; 179 | } 180 | -------------------------------------------------------------------------------- /src/Paymentsds/MPesa/Environment.php: -------------------------------------------------------------------------------- 1 | scheme = $scheme; 20 | $this->domain = $domain; 21 | } 22 | 23 | public function __get($property) 24 | { 25 | if (in_array($property, self::PARAMS)) { 26 | return $this->{$property}; 27 | } 28 | 29 | return null; 30 | } 31 | 32 | public static function fromURL($url) 33 | { 34 | $parts = explode("://", $url); 35 | return new Environment($parts[0], $parts[1]); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Paymentsds/MPesa/ErrorType.php: -------------------------------------------------------------------------------- 1 | {$param} = $args[$param]; 21 | } 22 | } 23 | } 24 | 25 | public function __get($property) 26 | { 27 | if (in_array($property, self::PARAMS)) { 28 | return $this->{$property}; 29 | } 30 | 31 | return null; 32 | } 33 | 34 | public function __set($property, $value) 35 | { 36 | if (in_array($property, self::PARAMS)) { 37 | $this->{$property} = $value; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Paymentsds/MPesa/Response.php: -------------------------------------------------------------------------------- 1 | success = $success; 20 | $this->error= $error; 21 | $this->data = $data; 22 | } 23 | 24 | public function __get($property) 25 | { 26 | if (in_array($property, self::PARAMS)) { 27 | return $this->{$property}; 28 | } 29 | 30 | return null; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Paymentsds/MPesa/Service.php: -------------------------------------------------------------------------------- 1 | config = new Configuration($args); 26 | } 27 | 28 | public function handleSend($intent) 29 | { 30 | try { 31 | $opcode = $this->detectOperation($intent); 32 | 33 | return $this->handleRequest($opcode, $intent); 34 | } catch (InvalidReceiverException $e) { 35 | return new Response(false, ErrorType::INVALID_RECEIVER); 36 | } 37 | } 38 | 39 | public function handleReceive($intent) 40 | { 41 | return $this->handleRequest(Constants::C2B_PAYMENT, $intent); 42 | } 43 | 44 | public function handleQuery($intent) 45 | { 46 | return $this->handleRequest(Constants::QUERY_TRANSACTION_STATUS, $intent); 47 | } 48 | 49 | public function handleRevert($intent) 50 | { 51 | return $this->handleRequest(Constants::REVERSAL, $intent); 52 | } 53 | 54 | public function handleRequest($opcode, $intent) 55 | { 56 | $data = $this->fillOptionalProperties($opcode, $intent); 57 | 58 | $missingProperties = $this->detectMissingProperties($opcode, $data); 59 | if (count($missingProperties) > 0) { 60 | throw new MissingPropertiesException('Missing properties'); 61 | } 62 | 63 | $validationErrors = $this->detectErrors($opcode, $data); 64 | if (count($validationErrors) > 0) { 65 | throw new ValidationException('Validation errors'); 66 | } 67 | 68 | return $this->performRequest($opcode, $data); 69 | } 70 | 71 | private function detectOperation($intent) 72 | { 73 | if (isset($intent['to'])) { 74 | if (preg_match(Constants::PATTERNS['PHONE_NUMBER'], $intent['to'])) { 75 | return Constants::B2C_PAYMENT; 76 | } 77 | 78 | if (preg_match(Constants::PATTERNS['SERVICE_PROVIDER_CODE'], $intent['to'])) { 79 | return Constants::B2B_PAYMENT; 80 | } 81 | } 82 | 83 | throw new InvalidReceiverException('Invalid operation'); 84 | } 85 | 86 | private function detectMissingProperties($opcode, $intent) 87 | { 88 | $operation = Constants::OPERATIONS[$opcode]; 89 | 90 | $requires = $operation['required']; 91 | $missing = array_filter($requires, function ($v, $k) use ($intent) { 92 | return !(isset($intent[$v])); 93 | }, ARRAY_FILTER_USE_BOTH); 94 | 95 | return $missing; 96 | } 97 | 98 | private function detectErrors($opcode, $intent) 99 | { 100 | $operation = Constants::OPERATIONS[$opcode]; 101 | 102 | $requires = $operation['required']; 103 | $errors = array_filter($requires, function ($v, $k) use ($intent, $operation) { 104 | return !preg_match($operation['validation'][$v], $intent[$v]); 105 | }, ARRAY_FILTER_USE_BOTH); 106 | 107 | return $errors; 108 | } 109 | 110 | private function fillOptionalProperties($opcode, $intent) 111 | { 112 | switch ($opcode) { 113 | case Constants::C2B_PAYMENT: 114 | foreach (['to' => 'serviceProviderCode'] as $k => $v) { 115 | if (!isset($intent[$k]) && isset($this->config->{$v})) { 116 | $intent[$k] = $this->config->{$v}; 117 | } 118 | } 119 | break; 120 | 121 | case Constants::B2C_PAYMENT: 122 | case Constants::B2B_PAYMENT: 123 | foreach (['from' => 'serviceProviderCode'] as $k => $v) { 124 | if (!isset($intent[$k]) && isset($this->config->{$v})) { 125 | $intent[$k] = $this->config->{$v}; 126 | } 127 | } 128 | break; 129 | 130 | case Constants::REVERSAL: 131 | foreach ([ 132 | 'to' => 'serviceProviderCode', 133 | 'initiatorIdentifier' => 'initiatorIdentifier', 134 | 'securityCredential' => 'securityCredential' 135 | ] as $k => $v) { 136 | if (!isset($intent[$k]) && isset($this->config->{$v})) { 137 | $intent[$k] = $this->config->{$v}; 138 | } 139 | } 140 | break; 141 | 142 | case Constants::QUERY_TRANSACTION_STATUS: 143 | foreach (['from' => 'serviceProviderCode'] as $k => $v) { 144 | if (!isset($intent[$k]) && isset($this->config->{$v})) { 145 | $intent[$k] = $this->config->{$v}; 146 | } 147 | } 148 | break; 149 | } 150 | 151 | return $intent; 152 | } 153 | 154 | private function buildRequestBody($opcode, $intent) 155 | { 156 | $operation = Constants::OPERATIONS[$opcode]; 157 | $body = []; 158 | 159 | foreach ($intent as $oldKey => $value) { 160 | $newKey = $operation['mapping'][$oldKey]; 161 | $body[$newKey] = $value; 162 | } 163 | 164 | return $body; 165 | } 166 | 167 | private function buildRequestHeaders($opcode, $indent) 168 | { 169 | $headers = [ 170 | 'User-Agent' => $this->config->userAgent, 171 | 'Origin' => $this->config->origin, 172 | 'Content-Type' => "application/json", 173 | 'Authorization' => sprintf("Bearer %s", $this->config->auth) 174 | ]; 175 | 176 | return $headers; 177 | } 178 | 179 | private function performRequest($opcode, $intent) 180 | { 181 | $this->generateAccessToken(); 182 | 183 | if (isset($this->config->environment)) { 184 | if (isset($this->config->auth)) { 185 | $operation = Constants::OPERATIONS[$opcode]; 186 | $headers = $this->buildRequestHeaders($opcode, $intent); 187 | $body = $this->buildRequestBody($opcode, $intent); 188 | 189 | $baseURL = sprintf("%s://%s:%s", $this->config->environment->scheme, $this->config->environment->domain, $operation['port']); 190 | 191 | $data = [ 192 | 'headers' => $headers, 193 | 'debug' => $this->config->debugging, 194 | 'verify' => $this->config->verifySSL 195 | ]; 196 | 197 | if ($operation['method'] == 'get') { 198 | $data['query'] = $body; 199 | } else { 200 | $data['json'] = $body; 201 | } 202 | 203 | $httpClient = new Client([ 204 | 'base_uri' => $baseURL, 205 | 'timeout' => $this->config->timeout, 206 | ]); 207 | 208 | 209 | try { 210 | $response = $httpClient->request(strtoupper($operation['method']), $operation['path'], $data); 211 | $body = json_decode($response->getBody()->getContents(), true); 212 | return new Response(true, null, $this->buildResponse($body)); 213 | } catch (ConnectionException $e) { 214 | } catch (ClientException | ServerException $e) { 215 | $response = $e->getResponse(); 216 | $body = json_decode($response->getBody()->getContents(), true); 217 | if (isset($body['output_error'])) { 218 | $errorType = ErrorType::UNAUTHORIZED_API_OR_SESSION; 219 | } elseif (isset($body['output_ResponseCode'])) { 220 | $errorType = $this->detectErrorType($body['output_ResponseCode']); 221 | } else { 222 | $errorType = ErrorType::UNKNOWN; 223 | } 224 | 225 | return new Response(false, $errorType, $this->buildResponse($body)); 226 | } catch (\Exception $e) { 227 | return new Response(false, null, null); 228 | } 229 | } else { 230 | throw new AuthenticationException('No auth data'); 231 | } 232 | } else { 233 | throw new InvalidHostException('Invalid connection settings'); 234 | } 235 | } 236 | 237 | private function generateAccessToken() 238 | { 239 | $this->config->generateAccessToken(); 240 | } 241 | 242 | private function buildResponse($body) 243 | { 244 | $mapping = [ 245 | 'output_ConversationID' => 'conversation', 246 | 'output_ResponseCode' => 'code', 247 | 'output_ResponseDesc' => 'description', 248 | 'output_ThirdPartyReference' => 'reference', 249 | 'output_ResponseTransactionStatus' => 'status', 250 | 'output_TransactionID' => 'transaction' 251 | ]; 252 | 253 | $output = []; 254 | foreach ($mapping as $k => $v) { 255 | if (in_array($k, array_keys($body))) { 256 | $output[$v] = $body[$k]; 257 | } 258 | } 259 | 260 | return $output; 261 | } 262 | 263 | private function detectErrorType($code) 264 | { 265 | $mapping = [ 266 | 'INS-0' => ErrorType::SUCCESS, 267 | 'INS-1' => ErrorType::INTERNAL_ERROR, 268 | 'INS-5' => ErrorType::TRANSACTION_CANCELLED_BY_CUSTOMER, 269 | 'INS-6' => ErrorType::TRANSACTION_FAILED, 270 | 'INS-9' => ErrorType::REQUEST_TIMEOUT, 271 | 'INS-10' => ErrorType::DUPLICATE_TRANSACTION, 272 | 'INS-13' => ErrorType::INVALID_SHORT_CODE_USED, 273 | 'INS-14' => ErrorType::INVALID_REFERENCE_USED, 274 | 'INS-15' => ErrorType::INVALID_AMOUNT_USED, 275 | 'INS-16' => ErrorType::SERVER_UNDER_OVERLOAD, 276 | 'INS-17' => ErrorType::INVALID_TRANSACTION_REFERENCE, 277 | 'INS-18' => ErrorType::INVALID_TRANSACTION, 278 | 'INS-19' => ErrorType::INVALID_REFERENCE, 279 | 'INS-20' => ErrorType::MISSING_PROPERTIES, 280 | 'INS-21' => ErrorType::INVALID_PARAMETERS, 281 | 'INS-22' => ErrorType::INVALID_OPERATION_TYPE, 282 | 'INS-23' => ErrorType::UNKOWN_STATUS, 283 | 'INS-24' => ErrorType::INVALID_INITIATOR_IDENTIFIER, 284 | 'INS-25' => ErrorType::INVALID_SECURITY_CREDENTIAL, 285 | 'INS-993' => ErrorType::DIRECT_DEBIT_MISSING, 286 | 'INS-994' => ErrorType::DIRECT_DEBIT_ALREAD_EXISTS, 287 | 'INS-995' => ErrorType::CUSTOMER_HAS_PROBLEMS, 288 | 'INS-996' => ErrorType::CUSTOMER_ACCOUNT_NOT_ACTIVE, 289 | 'INS-997' => ErrorType::UNKNOWN, 290 | 'INS-998' => ErrorType::INVALID_MARKET, 291 | 'INS-2001' => ErrorType::INITIATOR_AUTH_ERROR, 292 | 'INS-2002' => ErrorType::RECEIVER_INVALID, 293 | 'INS-2006' => ErrorType::INSUFICIENT_BALANCE, 294 | 'INS-2051' => ErrorType::INVALID_MSISDN, 295 | 'INS-2057' => ErrorType::LANGUAGE_CODE_INVALID, 296 | ]; 297 | 298 | return $mapping[$code]; 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /tests/.env.example: -------------------------------------------------------------------------------- 1 | API_KEY=null 2 | PUBLIC_KEY=null 3 | SERVICE_PROVIDER_CODE=null 4 | PHONE_NUMBER=null 5 | SECURITY_CREDENTIAL=null 6 | INITIATOR_IDENTIFIER=null -------------------------------------------------------------------------------- /tests/ClientTest.php: -------------------------------------------------------------------------------- 1 | load(); 14 | 15 | $this->client = new Client([ 16 | 'apiKey' => $_ENV['API_KEY'], // API Key 17 | 'publicKey' => $_ENV['PUBLIC_KEY'], // Public Key 18 | 'serviceProviderCode' => $_ENV['SERVICE_PROVIDER_CODE'] // input_ServiceProviderCode 19 | ]); 20 | 21 | $this->clientRevert = new Client([ 22 | 'apiKey' => $_ENV['API_KEY'], // API Key 23 | 'publicKey' => $_ENV['PUBLIC_KEY'], // Public Key 24 | 'serviceProviderCode' => $_ENV['SERVICE_PROVIDER_CODE'], // input_ServiceProviderCode 25 | 'initiatorIdentifier' => $_ENV['INITIATOR_IDENTIFIER'], // input_InitiatorIdentifier, 26 | 'securityCredential' => $_ENV['SECURITY_CREDENTIAL'] // input_SecurityCredential 27 | ]); 28 | 29 | $this->paymentDataSend = [ 30 | 'to' => $_ENV['PHONE_NUMBER'], // input_CustomerMSISDN 31 | 'reference' => '11115' . rand(1, 99), // input_ThirdPartyReference 32 | 'transaction' => 'T12344CC', // input_TransactionReference 33 | 'amount' => '10' // input_Amount 34 | ]; 35 | 36 | $this->paymentDataReceive = [ 37 | 'from' => $_ENV['PHONE_NUMBER'], // input_CustomerMSISDN 38 | 'reference' => '11114' . rand(1, 99), // input_ThirdPartyReference 39 | 'transaction' => 'T12344CC', // input_TransactionReference 40 | 'amount' => '10' // input_Amount 41 | ]; 42 | 43 | $this->paymentDataBusiness = [ 44 | 'to' => '979797', // input_ReceiverPartyCode 45 | 'reference' => '11114' . rand(1, 99), // input_ThirdPartyReference 46 | 'transaction' => 'T12344CC', // input_TransactionReference 47 | 'amount' => '10' // input_Amount 48 | ]; 49 | 50 | $this->paymentDataRevert = [ 51 | 'reference' => '11114' . rand(1, 99), // input_ThirdPartyReference 52 | 'transaction' => 'T12344CC', // input_TransactionReference 53 | 'amount' => '10' // input_Amount 54 | ]; 55 | } 56 | public function testSend() 57 | { 58 | $result = $this->client->send($this->paymentDataSend); 59 | $this->assertTrue($result->success); 60 | } 61 | 62 | public function testSendBusiness() 63 | { 64 | $result = $this->client->send($this->paymentDataBusiness); 65 | $this->assertTrue($result->success); 66 | } 67 | 68 | public function testReceive() 69 | { 70 | $result = $this->client->receive($this->paymentDataReceive); 71 | $this->assertTrue($result->success); 72 | } 73 | 74 | public function testRevert() 75 | { 76 | $result = $this->clientRevert->revert($this->paymentDataRevert); 77 | $this->assertTrue($result->success); 78 | } 79 | } 80 | --------------------------------------------------------------------------------