├── .classpath
├── .gitignore
├── .project
├── .settings
├── org.eclipse.core.resources.prefs
├── org.eclipse.jdt.apt.core.prefs
├── org.eclipse.jdt.core.prefs
└── org.eclipse.m2e.core.prefs
├── AUTHORS
├── LICENSE
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── pom.xml
├── settings.gradle
└── src
└── main
└── java
└── org
└── paymentsds
└── mpesa
├── Callback.java
├── Client.java
├── Environment.java
├── Request.java
├── Response.java
└── internal
├── Client.java
├── MpesaRequest.java
├── MpesaResponse.java
└── MpesaService.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.toptal.com/developers/gitignore/api/gradle,maven
3 | # Edit at https://www.toptal.com/developers/gitignore?templates=gradle,maven
4 |
5 | ### Maven ###
6 | target/
7 | pom.xml.tag
8 | pom.xml.releaseBackup
9 | pom.xml.versionsBackup
10 | pom.xml.next
11 | release.properties
12 | dependency-reduced-pom.xml
13 | buildNumber.properties
14 | .mvn/timing.properties
15 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar
16 | .mvn/wrapper/maven-wrapper.jar
17 |
18 | ### Gradle ###
19 | .gradle
20 | build/
21 |
22 | # Ignore Gradle GUI config
23 | gradle-app.setting
24 |
25 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
26 | !gradle-wrapper.jar
27 |
28 | # Cache of project
29 | .gradletasknamecache
30 |
31 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
32 | # gradle/wrapper/gradle-wrapper.properties
33 |
34 | ### Gradle Patch ###
35 | **/build/
36 |
37 | # End of https://www.toptal.com/developers/gitignore/api/gradle,maven
38 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | mpesa-java-sdk
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.m2e.core.maven2Builder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.eclipse.m2e.core.maven2Nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//src/main/java=UTF-8
3 | encoding//src/test/java=UTF-8
4 | encoding/=UTF-8
5 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.apt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.apt.aptEnabled=false
3 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
3 | org.eclipse.jdt.core.compiler.compliance=1.7
4 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
5 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
6 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
7 | org.eclipse.jdt.core.compiler.processAnnotations=disabled
8 | org.eclipse.jdt.core.compiler.release=disabled
9 | org.eclipse.jdt.core.compiler.source=1.7
10 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.m2e.core.prefs:
--------------------------------------------------------------------------------
1 | activeProfiles=
2 | eclipse.preferences.version=1
3 | resolveWorkspaceProjects=true
4 | version=1
5 |
--------------------------------------------------------------------------------
/AUTHORS:
--------------------------------------------------------------------------------
1 | Anísio Mandlate
2 | Edson Michaque
3 | Elton Laice
4 | Nélio Macombo
5 | Rosário P. Fernandes
6 |
--------------------------------------------------------------------------------
/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 2020 The PaymentsDS Authors
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 | # JAVA M-Pesa SDK
2 |
3 |
4 |

5 |
6 | This is a library willing to help you to integrate the [Vodacom M-Pesa](https://developer.mpesa.vm.co.mz) operations to your application.
7 |
8 |
9 |
10 | ### Features
11 |
12 | Using this library, you can implement the following operations:
13 |
14 | - Receive money from a mobile account to a business account (C2B)
15 | - Send money from a business account to a mobile account (B2C)
16 | - Send money from a business account to another business account (B2B)
17 | - Revert any of the transactions above mentioned
18 | - Query the status of a transaction
19 |
20 |
21 |
22 | ## Requirements
23 |
24 | - Valid credentials obtained from the [Mpesa Developer](https://developer.mpesa.vm.co.mz) portal
25 | - Port 18352 open on your server (usually open on local env)
26 |
27 |
28 |
29 |
30 |
31 | ## Installation
32 |
33 |
34 |
35 | ### Using Gradle
36 |
37 | 1. Add jitpack to your root `build.gradle` file, under `repositories`:
38 | ```groovy
39 | repositories {
40 | // ... other repositories here ...
41 | maven { url 'https://jitpack.io' }
42 | }
43 | ```
44 |
45 | 2. Add the dependency:
46 | ```groovy
47 | dependencies {
48 | implementation 'com.github.paymentsds:mpesa-java-sdk:0.1.0-alpha1'
49 | }
50 | ```
51 |
52 |
53 | ### Using Maven
54 |
55 | 1. Add jitpack to your `pom.xml` file, under `repositories`:
56 | ```xml
57 |
58 |
59 | jitpack.io
60 | https://jitpack.io
61 |
62 |
63 | ```
64 |
65 | 2. Add the dependency:
66 | ```xml
67 |
68 | com.github.paymentsds
69 | mpesa-java-sdk
70 | 0.1.0-alpha1
71 |
72 | ```
73 |
74 |
75 |
76 | ### Manual Installation
77 | ```bash
78 | git clone https://github.com/paymentsds/mpesa-sdk
79 | ```
80 |
81 |
82 |
83 |
84 | ## Usage
85 |
86 | Using this SDK is very simple and fast, let us see some examples:
87 |
88 |
89 |
90 | #### C2B Transaction (Receive money from mobile account)
91 |
92 | ```java
93 | import org.paymentsds.mpesa.Callback;
94 | import org.paymentsds.mpesa.Client;
95 | import org.paymentsds.mpesa.Environment;
96 | import org.paymentsds.mpesa.Request;
97 | import org.paymentsds.mpesa.Response;
98 |
99 | Client client = new Client.Builder()
100 | .apiKey("")
101 | .publicKey("")
102 | .serviceProviderCode("")
103 | .initiatorIdentifier("")
104 | .environment(Environment.DEVELOPMENT)
105 | .build();
106 |
107 | Request paymentRequest = new Request.Builder()
108 | .amount(10.0)
109 | .from("841234567")
110 | .reference("12345")
111 | .transaction("12345")
112 | .build();
113 |
114 | // Synchronous Call
115 | try {
116 | Response response = client.receive(paymentRequest);
117 | // Handle success scenario
118 | } catch (Exception e) {
119 | // Handle failure scenario
120 | }
121 |
122 | // Asynchronous Call
123 | client.receive(paymentRequest, new Callback() {
124 | @Override
125 | public void onResponse(Response response) {
126 | // Handle success scenario
127 | }
128 |
129 | @Override
130 | public void onError(Exception e) {
131 | // Handle failure scenario
132 | }
133 | });
134 |
135 | ```
136 |
137 |
138 |
139 | #### B2C Transaction (Sending money to mobile account)
140 |
141 | ```java
142 | import org.paymentsds.mpesa.Callback;
143 | import org.paymentsds.mpesa.Client;
144 | import org.paymentsds.mpesa.Environment;
145 | import org.paymentsds.mpesa.Request;
146 | import org.paymentsds.mpesa.Response;
147 |
148 | Client client = new Client.Builder()
149 | .apiKey("")
150 | .publicKey("")
151 | .serviceProviderCode("")
152 | .initiatorIdentifier("")
153 | .environment(Environment.PRODUCTION)
154 | .build();
155 |
156 | Request paymentRequest = new Request.Builder()
157 | .amount(10.0)
158 | .to("841234567")
159 | .reference("12345")
160 | .transaction("12345")
161 | .build();
162 |
163 | // Synchronous Call
164 | try {
165 | Response response = client.send(paymentRequest);
166 | // Handle success scenario
167 | } catch (Exception e) {
168 | // Handle failure scenario
169 | }
170 |
171 | // Asynchronous Call
172 | client.send(paymentRequest, new Callback() {
173 | @Override
174 | public void onResponse(Response response) {
175 | // Handle success scenario
176 | }
177 |
178 | @Override
179 | public void onError(Exception e) {
180 | // Handle failure scenario
181 | }
182 | });
183 |
184 | ```
185 |
186 |
187 |
188 | #### B2B Transaction (Sending money to business account)
189 |
190 | ```java
191 | import org.paymentsds.mpesa.Callback;
192 | import org.paymentsds.mpesa.Client;
193 | import org.paymentsds.mpesa.Environment;
194 | import org.paymentsds.mpesa.Request;
195 | import org.paymentsds.mpesa.Response;
196 |
197 | Client client = new Client.Builder()
198 | .apiKey("")
199 | .publicKey("")
200 | .serviceProviderCode("")
201 | .initiatorIdentifier("")
202 | .environment(Environment.PRODUCTION)
203 | .build();
204 |
205 | Request paymentRequest = new Request.Builder()
206 | .amount(10.0)
207 | .to("54321")
208 | .reference("12345")
209 | .transaction("12345")
210 | .build();
211 |
212 | // Synchronous Call
213 | try {
214 | Response response = client.send(paymentRequest);
215 | // Handle success scenario
216 | } catch (Exception e) {
217 | // Handle failure scenario
218 | }
219 |
220 | // Asynchronous Call
221 | client.send(paymentRequest, new Callback() {
222 | @Override
223 | public void onResponse(Response response) {
224 | // Handle success scenario
225 | }
226 |
227 | @Override
228 | public void onError(Exception e) {
229 | // Handle failure scenario
230 | }
231 | });
232 |
233 | ```
234 |
235 |
236 |
237 |
238 | #### Transaction Reversal
239 |
240 | ```java
241 | import org.paymentsds.mpesa.Callback;
242 | import org.paymentsds.mpesa.Client;
243 | import org.paymentsds.mpesa.Environment;
244 | import org.paymentsds.mpesa.Request;
245 | import org.paymentsds.mpesa.Response;
246 |
247 | Client client = new Client.Builder()
248 | .apiKey("")
249 | .publicKey("")
250 | .serviceProviderCode("")
251 | .initiatorIdentifier("")
252 | .environment(Environment.PRODUCTION)
253 | .securityCredential("")
254 | .build();
255 |
256 | Request reversalRequest = new Request.Builder()
257 | .amount(10.0)
258 | .reference("12345")
259 | .transaction("12345")
260 | .build();
261 |
262 | // Synchronous Call
263 | try {
264 | Response response = client.revert(reversalRequest);
265 | // Handle success scenario
266 | } catch (Exception e) {
267 | // Handle failure scenario
268 | }
269 |
270 | // Asynchronous Call
271 | client.revert(reversalRequest, new Callback() {
272 | @Override
273 | public void onResponse(Response response) {
274 | // Handle success scenario
275 | }
276 |
277 | @Override
278 | public void onError(Exception e) {
279 | // Handle failure scenario
280 | }
281 | });
282 |
283 | ```
284 |
285 |
286 |
287 | #### Query the transaction status
288 |
289 | ```java
290 | import org.paymentsds.mpesa.Callback;
291 | import org.paymentsds.mpesa.Client;
292 | import org.paymentsds.mpesa.Environment;
293 | import org.paymentsds.mpesa.Request;
294 | import org.paymentsds.mpesa.Response;
295 |
296 | Client client = new Client.Builder()
297 | .apiKey("")
298 | .publicKey("")
299 | .serviceProviderCode("")
300 | .build();
301 |
302 | Request queryRequest = new Request.Builder()
303 | .reference("12345") // input_ThirdPartyReference
304 | .subject("12345") // input_QueryReference
305 | .build();
306 |
307 | // Synchronous Call
308 | try {
309 | Response response = client.query(queryRequest);
310 | // Handle success scenario
311 | } catch (Exception e) {
312 | // Handle failure scenario
313 | }
314 |
315 | // Asynchronous Call
316 | client.query(queryRequest, new Callback() {
317 | @Override
318 | public void onResponse(Response response) {
319 | // Handle success scenario
320 | }
321 |
322 | @Override
323 | public void onError(Exception e) {
324 | // Handle failure scenario
325 | }
326 | });
327 |
328 | ```
329 |
330 |
331 |
332 | ## Friends
333 |
334 | - [M-Pesa SDK for Javascript](https://github.com/paymentsds/mpesa-js-sdk)
335 | - [M-Pesa SDK for Python](https://github.com/paymentsds/mpesa-python-sdk)
336 | - [M-Pesa SDK for PHP](https://github.com/paymentsds/mpesa-php-sdk)
337 | - [M-Pesa SDK for Ruby](https://github.com/paymentsds/mpesa-ruby-sdk)
338 |
339 |
340 |
341 |
342 | ## Authors
343 |
344 | - [Name](https://github.com/username)
345 |
346 |
347 |
348 |
349 | ## Contributing
350 |
351 | 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.
352 |
353 |
354 |
355 |
356 | ## Security Vulnerabilities
357 |
358 | 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.
359 |
360 |
361 |
362 | ## License
363 |
364 | Copyright 2022 © The PaymentsDS Team
365 |
366 | 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
367 |
368 | http://www.apache.org/licenses/LICENSE-2.0
369 |
370 | 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.
371 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | */
4 |
5 | plugins {
6 | id 'java'
7 | id 'maven-publish'
8 | }
9 |
10 | repositories {
11 | mavenLocal()
12 | mavenCentral()
13 | maven {
14 | url = uri('http://repo.maven.apache.org/maven2')
15 | }
16 | }
17 |
18 | dependencies {
19 | implementation 'com.squareup.retrofit2:retrofit:2.9.0'
20 | implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
21 |
22 | testImplementation 'junit:junit:4.11'
23 | }
24 |
25 | group = 'org.paymentsds.mpesa'
26 | version = '0.1.0-alpha1'
27 | description = 'mpesa-java-sdk'
28 | sourceCompatibility = '1.8'
29 |
30 | publishing {
31 | publications {
32 | maven(MavenPublication) {
33 | from(components.java)
34 | }
35 | }
36 | }
37 |
38 | tasks.withType(JavaCompile) {
39 | options.encoding = 'UTF-8'
40 | }
41 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paymentsds/mpesa-java-sdk/f64b1b1ee7c38276d9cd202905c9844dd7612649/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 | 4.0.0
6 |
7 | org.paymentsds.mpesa
8 | mpesa-java-sdk
9 | 0.1.0-alpha1
10 |
11 | mpesa-java-sdk
12 | A JAVA library aiming to helps developers integrating their products with M-Pesa Platform
13 | https://developers.paymentsds.org
14 | 2002
15 |
16 | PaymentsDS
17 | https://developers.paymentsds.org/
18 |
19 |
20 |
21 |
22 | eltonlaice
23 | Elton Tomas Laice
24 | me@eltonlaice.com
25 |
26 |
27 |
28 |
29 | UTF-8
30 | 1.8
31 | 1.8
32 |
33 |
34 |
35 |
36 | com.squareup.retrofit2
37 | retrofit
38 | 2.9.0
39 |
40 |
41 | com.squareup.retrofit2
42 | converter-gson
43 | 2.9.0
44 |
45 |
46 | junit
47 | junit
48 | 4.11
49 | test
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | maven-clean-plugin
59 | 3.1.0
60 |
61 |
62 |
63 | maven-resources-plugin
64 | 3.0.2
65 |
66 |
67 | maven-compiler-plugin
68 | 3.8.0
69 |
70 |
71 | maven-surefire-plugin
72 | 2.22.1
73 |
74 |
75 | maven-jar-plugin
76 | 3.0.2
77 |
78 |
79 | maven-install-plugin
80 | 2.5.2
81 |
82 |
83 | maven-deploy-plugin
84 | 2.8.2
85 |
86 |
87 |
88 | maven-site-plugin
89 | 3.7.1
90 |
91 |
92 | maven-project-info-reports-plugin
93 | 3.0.0
94 |
95 |
96 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This file was generated by the Gradle 'init' task.
3 | */
4 |
5 | rootProject.name = 'mpesa-java-sdk'
6 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/Callback.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa;
2 |
3 | public interface Callback {
4 | public void onResponse(Response response);
5 |
6 | public void onError(Exception exception);
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/Client.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa;
2 |
3 | import java.io.IOException;
4 |
5 | public class Client {
6 |
7 | private final org.paymentsds.mpesa.internal.Client client;
8 |
9 | private Client(
10 | String apiKey,
11 | String publicKey,
12 | String serviceProviderCode,
13 | String initiatorIdentifier,
14 | String host,
15 | String securityCredential) {
16 | client = new org.paymentsds.mpesa.internal.Client(apiKey, publicKey, serviceProviderCode,
17 | initiatorIdentifier, host, securityCredential);
18 | }
19 |
20 | public Response receive(Request request) throws IOException {
21 | return client.receive(request);
22 | }
23 |
24 | public void receive(Request request, Callback callback) {
25 | client.receive(request, callback);
26 | }
27 |
28 | public Response send(Request request) throws IOException {
29 | return client.send(request);
30 | }
31 |
32 | public void send(Request request, Callback callback) {
33 | client.send(request, callback);
34 | }
35 |
36 | public Response query(Request request) throws IOException {
37 | return client.query(request);
38 | }
39 |
40 | public void query(Request request, Callback callback) {
41 | client.query(request, callback);
42 | }
43 |
44 | public Response reversal(Request request) throws IOException {
45 | return client.reversal(request);
46 | }
47 |
48 | public void reversal(Request request, Callback callback) {
49 | client.reversal(request, callback);
50 | }
51 |
52 | public static class Builder {
53 | String apiKey;
54 | String publicKey;
55 | String serviceProviderCode;
56 | String initiatorIdentifier;
57 | String host;
58 | String securityCredential;
59 |
60 | public Builder apiKey(String apiKey) {
61 | this.apiKey = apiKey;
62 | return this;
63 | }
64 |
65 | public Builder publicKey(String publicKey) {
66 | this.publicKey = publicKey;
67 | return this;
68 | }
69 |
70 | public Builder serviceProviderCode(String serviceProviderCode) {
71 | this.serviceProviderCode = serviceProviderCode;
72 | return this;
73 | }
74 |
75 | public Builder initiatorIdentifier(String initiatorIdentifier) {
76 | this.initiatorIdentifier = initiatorIdentifier;
77 | return this;
78 | }
79 |
80 | public Builder environment(Environment environment) {
81 | if (environment == Environment.DEVELOPMENT) {
82 | host = "https://api.sandbox.vm.co.mz";
83 | } else {
84 | host = "https://api.vm.co.mz";
85 | }
86 | return this;
87 | }
88 |
89 | public Builder host(String host) {
90 | this.host = host;
91 | return this;
92 | }
93 |
94 | public Builder securityCredential(String securityCredential) {
95 | this.securityCredential = securityCredential;
96 | return this;
97 | }
98 |
99 | public Client build() {
100 | if (apiKey == null) {
101 | throw new IllegalArgumentException("Client must contain an apiKey");
102 | }
103 | if (publicKey == null) {
104 | throw new IllegalArgumentException("Client must contain a publicKey");
105 | }
106 | if (host == null) {
107 | throw new IllegalArgumentException("Client must contain either a host or an environment");
108 | }
109 | if (serviceProviderCode == null) {
110 | throw new IllegalArgumentException("Client must contain serviceProviderCode");
111 | }
112 | return new Client(apiKey, publicKey, serviceProviderCode, initiatorIdentifier, host, securityCredential);
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/Environment.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa;
2 |
3 | public enum Environment {
4 | PRODUCTION,
5 | DEVELOPMENT
6 | }
7 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/Request.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa;
2 |
3 | public class Request {
4 |
5 | // Receive Money
6 | private final double amount;
7 | private final String from;
8 | private final String reference;
9 | private final String transaction;
10 |
11 | // Send Money
12 | private final String to;
13 |
14 | // Query status
15 | private final String subject;
16 |
17 | private Request(
18 | double amount,
19 | String from,
20 | String reference,
21 | String transaction,
22 | String to,
23 | String subject) {
24 | this.amount = amount;
25 | this.from = from;
26 | this.reference = reference;
27 | this.transaction = transaction;
28 | this.to = to;
29 | this.subject = subject;
30 | }
31 |
32 | public double getAmount() {
33 | return amount;
34 | }
35 |
36 | public String getFrom() {
37 | return from;
38 | }
39 |
40 | public String getReference() {
41 | return reference;
42 | }
43 |
44 | public String getTransaction() {
45 | return transaction;
46 | }
47 |
48 | public String getTo() {
49 | return to;
50 | }
51 |
52 | public String getSubject() {
53 | return subject;
54 | }
55 |
56 | public static class Builder {
57 | // Receive Money
58 | double amount = 0.0;
59 | String from;
60 | String reference;
61 | String transaction;
62 |
63 | // Send Money
64 | String to;
65 |
66 | // Query status
67 | String subject;
68 |
69 | public Builder amount(double amount) {
70 | this.amount = amount;
71 | return this;
72 | }
73 |
74 | public Builder from(String from) {
75 | this.from = from;
76 | return this;
77 | }
78 |
79 | public Builder reference(String reference) {
80 | this.reference = reference;
81 | return this;
82 | }
83 |
84 | public Builder transaction(String transaction) {
85 | this.transaction = transaction;
86 | return this;
87 | }
88 |
89 | public Builder to(String to) {
90 | this.to = to;
91 | return this;
92 | }
93 |
94 | public Builder subject(String subject) {
95 | this.subject = subject;
96 | return this;
97 | }
98 |
99 | public Request build() {
100 | if (from != null && to != null) {
101 | throw new IllegalArgumentException("Request cannot contain both 'from' and 'to' arguments");
102 | }
103 |
104 | // This is required by all requests
105 | if (reference == null) {
106 | throw new IllegalArgumentException("Request must contain a reference");
107 | }
108 |
109 | // Handle C2B, B2C and B2B
110 | if (from != null || to != null) {
111 | if (amount == 0.0) {
112 | throw new IllegalArgumentException("Request must contain an amount greater than 0.0");
113 | }
114 | if (transaction == null) {
115 | throw new IllegalArgumentException("Request must contain a transaction reference");
116 | }
117 | }
118 |
119 | // Handle reversals
120 | if (to == null && from == null && subject == null) {
121 | if (transaction == null) {
122 | throw new IllegalArgumentException("Request must contain a transaction reference");
123 | }
124 | }
125 | return new Request(amount, from, reference, transaction, to, subject);
126 | }
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/Response.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa;
2 |
3 | import org.paymentsds.mpesa.internal.MpesaResponse;
4 |
5 | public class Response {
6 |
7 | private final String conversationId;
8 | private final String transactionId;
9 | private final String description;
10 | private final String code;
11 | private final String thirdPartyRef;
12 |
13 | // Query Transaction
14 | private final String transactionStatus;
15 |
16 | private Response(
17 | String conversationId,
18 | String transactionId,
19 | String description,
20 | String code,
21 | String thirdPartyRef,
22 | String transactionStatus) {
23 | this.conversationId = conversationId;
24 | this.transactionId = transactionId;
25 | this.description = description;
26 | this.code = code;
27 | this.thirdPartyRef = thirdPartyRef;
28 | this.transactionStatus = transactionStatus;
29 | }
30 |
31 | public static Response fromMpesaResponse(MpesaResponse mpesaResponse) {
32 | return new Response(mpesaResponse.getConversationId(),
33 | mpesaResponse.getTransactionId(), mpesaResponse.getResponseDesc(),
34 | mpesaResponse.getResponseCode(), mpesaResponse.getThirdPartyReference(),
35 | mpesaResponse.getResponseTransactionStatus());
36 | }
37 |
38 | public String getConversationId() { return conversationId; }
39 |
40 | public String getTransactionId() { return transactionId; }
41 |
42 | public String getDescription() { return description; }
43 |
44 | public String getCode() { return code; }
45 |
46 | public String getThirdPartyRef() { return thirdPartyRef; }
47 |
48 | public String getTransactionStatus() { return transactionStatus; }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/internal/Client.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa.internal;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.reflect.TypeToken;
5 | import org.paymentsds.mpesa.Callback;
6 | import org.paymentsds.mpesa.Request;
7 | import org.paymentsds.mpesa.Response;
8 | import retrofit2.Call;
9 | import retrofit2.Retrofit;
10 | import retrofit2.converter.gson.GsonConverterFactory;
11 |
12 | import javax.crypto.Cipher;
13 | import java.io.IOException;
14 | import java.nio.charset.StandardCharsets;
15 | import java.security.KeyFactory;
16 | import java.security.PublicKey;
17 | import java.security.spec.X509EncodedKeySpec;
18 | import java.util.Base64;
19 | import java.util.HashMap;
20 |
21 | public class Client implements retrofit2.Callback {
22 | private final String apiKey;
23 | private final String publicKey;
24 | private final String serviceProviderCode;
25 | private final String initiatorIdentifier;
26 | private final String host;
27 | private final String securityCredential;
28 |
29 | private final String authorizationToken;
30 | private Callback callback;
31 |
32 | // Constants
33 | private static final int PORT_C2B = 18352;
34 | private static final int PORT_B2B = 18349;
35 | private static final int PORT_B2C = 18345;
36 | private static final int PORT_QUERY = 18353;
37 | private static final int PORT_REVERSAL = 18354;
38 |
39 | private static final String PATH_C2B = "c2bPayment/singleStage/";
40 | private static final String PATH_B2B = "b2bPayment/";
41 | private static final String PATH_B2C = "b2cPayment/";
42 | private static final String PATH_QUERY = "queryTransactionStatus/";
43 | private static final String PATH_REVERSAL = "reversal/";
44 |
45 | public Client(
46 | String apiKey,
47 | String publicKey,
48 | String serviceProviderCode,
49 | String initiatorIdentifier,
50 | String host,
51 | String securityCredential) {
52 | this.apiKey = apiKey;
53 | this.publicKey = publicKey;
54 | this.serviceProviderCode = serviceProviderCode;
55 | this.initiatorIdentifier = initiatorIdentifier;
56 | this.host = host;
57 | this.securityCredential = securityCredential;
58 | this.authorizationToken = generateAuthorizationToken();
59 | }
60 |
61 | public Response receive(Request request) throws IOException {
62 | if (request.getFrom() == null) {
63 | throw new IllegalArgumentException("Request must contain a 'from' field to receive money.");
64 | }
65 | retrofit2.Response response = getHttpCall(request, PORT_C2B).execute();
66 | return parseHttpResponse(response);
67 | }
68 |
69 | public void receive(Request request, Callback callback) {
70 | if (request.getFrom() == null) {
71 | throw new IllegalArgumentException("Request must contain a 'from' field to receive money.");
72 | }
73 | this.callback = callback;
74 | getHttpCall(request, PORT_C2B).enqueue(this);
75 | }
76 |
77 | public Response send(Request request) throws IOException {
78 | if (request.getTo() == null) {
79 | throw new IllegalArgumentException("Request must contain a 'to' field to send money.");
80 | }
81 | retrofit2.Response response;
82 | // TODO(rosario): Improve this check once we implement regex to validate msisdn
83 | if (request.getTo().startsWith("258")) {
84 | response = getHttpCall(request, PORT_B2C).execute();
85 | } else {
86 | response = getHttpCall(request, PORT_B2B).execute();
87 | }
88 | return parseHttpResponse(response);
89 | }
90 |
91 | public void send(Request request, Callback callback) {
92 | if (request.getTo() == null) {
93 | throw new IllegalArgumentException("Request must contain a 'to' field to send money.");
94 | }
95 | this.callback = callback;
96 | // TODO(rosario): Improve this check once we implement regex to validate msisdn
97 | if (request.getTo().startsWith("258")) {
98 | getHttpCall(request, PORT_B2C).enqueue(this);
99 | } else {
100 | getHttpCall(request, PORT_B2B).enqueue(this);
101 | }
102 | }
103 |
104 | public Response query(Request request) throws IOException {
105 | retrofit2.Response response = getHttpCall(request, PORT_QUERY).execute();
106 | return parseHttpResponse(response);
107 | }
108 |
109 | public void query(Request request, Callback callback) {
110 | this.callback = callback;
111 | getHttpCall(request, PORT_QUERY).enqueue(this);
112 | }
113 |
114 | public Response reversal(Request request) throws IOException {
115 | if (securityCredential == null) {
116 | throw new IllegalArgumentException("Client must contain a securityCredential to revert a transaction");
117 | }
118 | if (initiatorIdentifier == null) {
119 | throw new IllegalArgumentException("Client must contain a initiatorIdentifier to revert a transaction");
120 | }
121 | retrofit2.Response response = getHttpCall(request, PORT_REVERSAL).execute();
122 | return parseHttpResponse(response);
123 | }
124 |
125 | public void reversal(Request request, Callback callback) {
126 | if (securityCredential == null) {
127 | throw new IllegalArgumentException("Client must contain a securityCredential to revert a transaction");
128 | }
129 | if (initiatorIdentifier == null) {
130 | throw new IllegalArgumentException("Client must contain a initiatorIdentifier to revert a transaction");
131 | }
132 | this.callback = callback;
133 | getHttpCall(request, PORT_REVERSAL).enqueue(this);
134 | }
135 |
136 | @Override
137 | public void onResponse(Call call, retrofit2.Response response) {
138 | try {
139 | Response res = parseHttpResponse(response);
140 | callback.onResponse(res);
141 | } catch (IOException e) {
142 | callback.onError(e);
143 | }
144 | }
145 |
146 | @Override
147 | public void onFailure(Call call, Throwable t) {
148 | callback.onError(new Exception(t));
149 | }
150 |
151 | private Call getHttpCall(Request request, int port) {
152 | Call responseCall;
153 | MpesaService service = getService(port);
154 | switch (port) {
155 | case PORT_C2B: {
156 | MpesaRequest mpesaRequest = MpesaRequest.fromC2BRequest(request, serviceProviderCode);
157 | responseCall = service.post(authorizationToken, PATH_C2B, mpesaRequest);
158 | break;
159 | }
160 | case PORT_B2B: {
161 | MpesaRequest mpesaRequest = MpesaRequest.fromB2BRequest(request, serviceProviderCode);
162 | responseCall = service.post(authorizationToken, PATH_B2B, mpesaRequest);
163 | break;
164 | }
165 | case PORT_B2C: {
166 | MpesaRequest mpesaRequest = MpesaRequest.fromB2CRequest(request, serviceProviderCode);
167 | responseCall = service.post(authorizationToken, PATH_B2C, mpesaRequest);
168 | break;
169 | }
170 | case PORT_QUERY: {
171 | HashMap params = new HashMap<>();
172 | params.put("input_QueryReference", request.getReference());
173 | params.put("input_ThirdPartyReference", request.getTransaction());
174 | params.put("input_ServiceProviderCode", serviceProviderCode);
175 | responseCall = service.get(authorizationToken, PATH_QUERY, params);
176 | break;
177 | }
178 | case PORT_REVERSAL: {
179 | MpesaRequest mpesaRequest = MpesaRequest.fromReversalRequest(request, serviceProviderCode,
180 | securityCredential, initiatorIdentifier);
181 | responseCall = service.put(authorizationToken, PATH_REVERSAL, mpesaRequest);
182 | break;
183 | }
184 | default:
185 | throw new IllegalStateException("Unexpected value: " + port);
186 | }
187 | return responseCall;
188 | }
189 |
190 | private MpesaService getService(int port) {
191 | Retrofit retrofit = new Retrofit.Builder()
192 | .baseUrl(host + ":" + port)
193 | .addConverterFactory(GsonConverterFactory.create())
194 | .build();
195 | return retrofit.create(MpesaService.class);
196 | }
197 |
198 | private Response parseHttpResponse(retrofit2.Response response) throws IOException {
199 | MpesaResponse mpesaResponse;
200 | if (response.isSuccessful()) {
201 | mpesaResponse = response.body();
202 | } else {
203 | Gson gson = new Gson();
204 | mpesaResponse = gson.fromJson(response.errorBody().string(), new TypeToken(){}.getType());
205 | }
206 | return Response.fromMpesaResponse(mpesaResponse);
207 | }
208 |
209 | private String generateAuthorizationToken(){
210 | try {
211 | KeyFactory keyFactory = KeyFactory.getInstance("RSA");
212 | Cipher cipher = Cipher.getInstance("RSA");
213 | byte[] x509PublicKey = Base64.getDecoder().decode(publicKey);
214 | X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(x509PublicKey);
215 | PublicKey pk = keyFactory.generatePublic(publicKeySpec);
216 | cipher.init(Cipher.ENCRYPT_MODE, pk);
217 | byte[] encryptedApiKey = Base64.getEncoder().encode(cipher.doFinal(
218 | apiKey.getBytes(StandardCharsets.UTF_8)));
219 | return "Bearer " + new String(encryptedApiKey, StandardCharsets.UTF_8);
220 | } catch (Exception e) {
221 | e.printStackTrace();
222 | return null;
223 | }
224 | }
225 | }
226 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/internal/MpesaRequest.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa.internal;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 | import org.paymentsds.mpesa.Request;
5 |
6 | public class MpesaRequest {
7 |
8 | @SerializedName("input_TransactionReference")
9 | private String transactionReference;
10 | @SerializedName("input_Amount")
11 | private String amount;
12 | @SerializedName("input_ThirdPartyReference")
13 | private String thirdPartyReference;
14 | @SerializedName("input_CustomerMSISDN")
15 | private String customerMsisdn;
16 | @SerializedName("input_ServiceProviderCode")
17 | private String serviceProviderCode;
18 |
19 | // B2B
20 | @SerializedName("input_PrimaryPartyCode")
21 | private String primaryPartyCode;
22 | @SerializedName("input_ReceiverPartyCode")
23 | private String receiverPartyCode;
24 |
25 | // Reversal
26 | @SerializedName("input_ReversalAmount")
27 | private String reversalAmount;
28 | @SerializedName("input_InitiatorIdentifier")
29 | private String initiatorIdentifier;
30 | @SerializedName("input_SecurityCredential")
31 | private String securityCredential;
32 | @SerializedName("input_TransactionID")
33 | private String transactionID;
34 |
35 | private MpesaRequest() { }
36 |
37 | public static MpesaRequest fromC2BRequest(Request request, String serviceProviderCode) {
38 | MpesaRequest mpesaRequest = new MpesaRequest();
39 | mpesaRequest.setAmount(request.getAmount() + "");
40 | mpesaRequest.setTransactionReference(request.getTransaction());
41 | mpesaRequest.setThirdPartyReference(request.getReference());
42 | mpesaRequest.setCustomerMsisdn(request.getFrom());
43 | mpesaRequest.setServiceProviderCode(serviceProviderCode);
44 | return mpesaRequest;
45 | }
46 |
47 | public static MpesaRequest fromB2CRequest(Request request, String serviceProviderCode) {
48 | MpesaRequest mpesaRequest = new MpesaRequest();
49 | mpesaRequest.setAmount(request.getAmount() + "");
50 | mpesaRequest.setTransactionReference(request.getTransaction());
51 | mpesaRequest.setThirdPartyReference(request.getReference());
52 | mpesaRequest.setCustomerMsisdn(request.getTo());
53 | mpesaRequest.setServiceProviderCode(serviceProviderCode);
54 | return mpesaRequest;
55 | }
56 |
57 | public static MpesaRequest fromB2BRequest(Request request, String primaryPartyCode) {
58 | MpesaRequest mpesaRequest = new MpesaRequest();
59 | mpesaRequest.setAmount(request.getAmount() + "");
60 | mpesaRequest.setTransactionReference(request.getTransaction());
61 | mpesaRequest.setThirdPartyReference(request.getReference());
62 | mpesaRequest.setPrimaryPartyCode(primaryPartyCode);
63 | mpesaRequest.setReceiverPartyCode(request.getTo());
64 | return mpesaRequest;
65 | }
66 |
67 | public static MpesaRequest fromReversalRequest(
68 | Request request,
69 | String serviceProviderCode,
70 | String securityCredential,
71 | String initiatorIdentifier) {
72 | MpesaRequest mpesaRequest = new MpesaRequest();
73 | mpesaRequest.setTransactionID(request.getTransaction());
74 | mpesaRequest.setSecurityCredential(securityCredential);
75 | mpesaRequest.setInitiatorIdentifier(initiatorIdentifier);
76 | mpesaRequest.setThirdPartyReference(request.getReference());
77 | mpesaRequest.setServiceProviderCode(serviceProviderCode);
78 | mpesaRequest.setReversalAmount(request.getAmount() + "");
79 | return mpesaRequest;
80 | }
81 |
82 | public String getTransactionReference() {
83 | return transactionReference;
84 | }
85 |
86 | public void setTransactionReference(String transactionReference) {
87 | this.transactionReference = transactionReference;
88 | }
89 |
90 | public String getCustomerMsisdn() {
91 | return customerMsisdn;
92 | }
93 |
94 | public void setCustomerMsisdn(String customerMsisdn) {
95 | this.customerMsisdn = customerMsisdn;
96 | }
97 |
98 | public String getAmount() {
99 | return amount;
100 | }
101 |
102 | public void setAmount(String amount) {
103 | this.amount = amount;
104 | }
105 |
106 | public String getThirdPartyReference() {
107 | return thirdPartyReference;
108 | }
109 |
110 | public void setThirdPartyReference(String thirdPartyReference) {
111 | this.thirdPartyReference = thirdPartyReference;
112 | }
113 |
114 | public String getServiceProviderCode() {
115 | return serviceProviderCode;
116 | }
117 |
118 | public void setServiceProviderCode(String serviceProviderCode) {
119 | this.serviceProviderCode = serviceProviderCode;
120 | }
121 |
122 | public String getPrimaryPartyCode() {
123 | return primaryPartyCode;
124 | }
125 |
126 | public void setPrimaryPartyCode(String primaryPartyCode) {
127 | this.primaryPartyCode = primaryPartyCode;
128 | }
129 |
130 | public String getReceiverPartyCode() {
131 | return receiverPartyCode;
132 | }
133 |
134 | public void setReceiverPartyCode(String receiverPartyCode) {
135 | this.receiverPartyCode = receiverPartyCode;
136 | }
137 |
138 | public String getReversalAmount() {
139 | return reversalAmount;
140 | }
141 |
142 | public void setReversalAmount(String reversalAmount) {
143 | this.reversalAmount = reversalAmount;
144 | }
145 |
146 | public String getInitiatorIdentifier() {
147 | return initiatorIdentifier;
148 | }
149 |
150 | public void setInitiatorIdentifier(String initiatorIdentifier) {
151 | this.initiatorIdentifier = initiatorIdentifier;
152 | }
153 |
154 | public String getSecurityCredential() {
155 | return securityCredential;
156 | }
157 |
158 | public void setSecurityCredential(String securityCredential) {
159 | this.securityCredential = securityCredential;
160 | }
161 |
162 | public String getTransactionID() {
163 | return transactionID;
164 | }
165 |
166 | public void setTransactionID(String transactionID) {
167 | this.transactionID = transactionID;
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/internal/MpesaResponse.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa.internal;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | public class MpesaResponse {
6 | @SerializedName("output_ConversationID")
7 | private String conversationId;
8 | @SerializedName("output_TransactionID")
9 | private String transactionId;
10 | @SerializedName("output_ResponseDesc")
11 | private String responseDesc;
12 | @SerializedName("output_ResponseCode")
13 | private String responseCode;
14 | @SerializedName("output_ThirdPartyReference")
15 | private String thirdPartyReference;
16 |
17 | // Query Transaction Status
18 | @SerializedName("output_ResponseTransactionStatus")
19 | private String responseTransactionStatus;
20 |
21 | public MpesaResponse() { }
22 |
23 | public String getConversationId() {
24 | return conversationId;
25 | }
26 |
27 | public void setConversationId(String conversationId) {
28 | this.conversationId = conversationId;
29 | }
30 |
31 | public String getTransactionId() {
32 | return transactionId;
33 | }
34 |
35 | public void setTransactionId(String transactionId) {
36 | this.transactionId = transactionId;
37 | }
38 |
39 | public String getResponseDesc() {
40 | return responseDesc;
41 | }
42 |
43 | public void setResponseDesc(String responseDesc) {
44 | this.responseDesc = responseDesc;
45 | }
46 |
47 | public String getResponseCode() {
48 | return responseCode;
49 | }
50 |
51 | public void setResponseCode(String responseCode) {
52 | this.responseCode = responseCode;
53 | }
54 |
55 | public String getThirdPartyReference() {
56 | return thirdPartyReference;
57 | }
58 |
59 | public void setThirdPartyReference(String thirdPartyReference) {
60 | this.thirdPartyReference = thirdPartyReference;
61 | }
62 |
63 | public String getResponseTransactionStatus() {
64 | return responseTransactionStatus;
65 | }
66 |
67 | public void setResponseTransactionStatus(String responseTransactionStatus) {
68 | this.responseTransactionStatus = responseTransactionStatus;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/org/paymentsds/mpesa/internal/MpesaService.java:
--------------------------------------------------------------------------------
1 | package org.paymentsds.mpesa.internal;
2 |
3 | import retrofit2.Call;
4 | import retrofit2.http.Body;
5 | import retrofit2.http.GET;
6 | import retrofit2.http.Header;
7 | import retrofit2.http.Headers;
8 | import retrofit2.http.Path;
9 | import retrofit2.http.POST;
10 | import retrofit2.http.PUT;
11 | import retrofit2.http.QueryMap;
12 |
13 | import java.util.Map;
14 |
15 | public interface MpesaService {
16 |
17 | @Headers({
18 | "Content-Type: application/json",
19 | "Origin: developer.mpesa.vm.co.mz"
20 | })
21 | @POST("/ipg/v1x/{operation}")
22 | Call post(
23 | @Header("Authorization") String authorization,
24 | @Path("operation") String operation,
25 | @Body MpesaRequest request);
26 |
27 | @Headers({
28 | "Content-Type: application/json",
29 | "Origin: developer.mpesa.vm.co.mz"
30 | })
31 | @GET("/ipg/v1x/{operation}")
32 | Call get(
33 | @Header("Authorization") String authorization,
34 | @Path("operation") String operation,
35 | @QueryMap Map params);
36 |
37 | @Headers({
38 | "Content-Type: application/json",
39 | "Origin: developer.mpesa.vm.co.mz"
40 | })
41 | @PUT("/ipg/v1x/{operation}")
42 | Call put(
43 | @Header("Authorization") String authorization,
44 | @Path("operation") String operation,
45 | @Body MpesaRequest request);
46 | }
--------------------------------------------------------------------------------