├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── myduka │ │ └── app │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── ic_launcher-web.png │ ├── java │ │ └── com │ │ │ └── myduka │ │ │ └── app │ │ │ ├── MyDuka.java │ │ │ ├── api │ │ │ ├── ApiClient.java │ │ │ ├── interceptor │ │ │ │ ├── AccessTokenInterceptor.java │ │ │ │ └── AuthInterceptor.java │ │ │ ├── model │ │ │ │ ├── AccessToken.java │ │ │ │ └── STKPush.java │ │ │ └── services │ │ │ │ └── STKPushService.java │ │ │ ├── service │ │ │ ├── MyFirebaseInstanceIDService.java │ │ │ └── MyFirebaseMessagingService.java │ │ │ ├── ui │ │ │ ├── RecyclerviewListDecorator.java │ │ │ ├── activity │ │ │ │ ├── MainActivity.java │ │ │ │ └── NotificationActivity.java │ │ │ ├── adapter │ │ │ │ └── CartListAdapter.java │ │ │ └── callback │ │ │ │ └── PriceTransfer.java │ │ │ └── util │ │ │ ├── AppConstants.java │ │ │ ├── NotificationUtils.java │ │ │ ├── SharedPrefsUtil.java │ │ │ └── Utils.java │ └── res │ │ ├── color │ │ ├── gray_highlight.xml │ │ ├── list_number_highlight.xml │ │ └── white_highlight_text.xml │ │ ├── drawable │ │ ├── apples.jpg │ │ ├── bananas.jpg │ │ ├── calc_btn_bg.xml │ │ ├── calc_btn_bg_square.xml │ │ ├── fruits_a.jpg │ │ ├── fruits_b.jpg │ │ ├── fruits_c.jpg │ │ └── tomatoes.JPG │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── activity_notification.xml │ │ ├── category_list_item.xml │ │ ├── content_main.xml │ │ └── slideshow_item.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── raw │ │ └── notification.mp3 │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── myduka │ └── app │ └── ExampleUnitTest.java ├── art ├── a.jpg ├── b.jpg ├── c.jpg ├── d.jpg └── e.jpg ├── build.gradle ├── deps.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample-google-services.json ├── sample.gradle.properties └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | /app/app-release.apk 11 | /app/google-services.json 12 | /.idea/ 13 | !/app/src/androidTest/ 14 | app/app-release.apk 15 | app/libs/ 16 | /gradle.properties 17 | -------------------------------------------------------------------------------- /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 | Lipa Na Mpesa Android Sample 2 | ------------------------------ 3 | This app demonstrates how to impeliment Lipa Na MPESA Online. 4 | Documentation on the API can be found on [Safaricom Developer Portal] (https://developer.safaricom.co.ke/docs) 5 | 6 | ### Requirements 7 | 8 | * JDK Version 1.7 & above 9 | * Android Studio 10 | 11 | ### Getting Safaricom Credentials 12 | 1. Create an account on the [Safaricom Developer Portal] (https://developer.safaricom.co.ke/) 13 | 2. Create a Lipa na MPESA Online App 14 | 15 | ### Project Setup 16 | 1. Rename `sample.gradle.properties` file to `gradle.properties` then add you `Consumer key` and `Consumer secret`. 17 | 2. Copy `sample-google-services.json` inside `app` directory and rename it to `google-services.json`. This will ensure your project build without an error. 18 | 19 | #### NB 20 | `sample-google-services.json` is just a sample file to help you bypass build error due to a `google-services.json` missing. 21 | 22 | #### Firebase Setup 23 | In order to send push notifications to the user, you will need to setup [FCM - Firebase Cloud Messaging Service] (https://firebase.google.com/docs/cloud-messaging/android/client). AndroidHive has an awesome [tutorial](https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm) on this. 24 | 25 | ### Screenshots 26 | 27 | ##### Add an item to the cart: 28 | ![alt text](https://github.com/safaricom/LNMOnlineAndroidSample/blob/master/art/a.jpg "Screen A") 29 | 30 | ##### Add a customers phone number: 31 | ![alt text](https://github.com/safaricom/LNMOnlineAndroidSample/blob/master/art/b.jpg "Screen B") 32 | 33 | ##### The STK push payment popup is sent to the customer phone: 34 | ![alt text](https://github.com/safaricom/LNMOnlineAndroidSample/blob/master/art/c.jpg "Screen C") 35 | 36 | ##### MPESA confirmation message: 37 | ![alt text](https://github.com/Jaymo/LNMOnlineAndroidSample/blob/master/art/d.jpg "Screen D") 38 | 39 | ##### Payment confirmation from the API callback: 40 | ![alt text](https://github.com/safaricom/LNMOnlineAndroidSample/blob/master/art/e.jpg "Screen E") 41 | 42 | ### Libraries Used 43 | 1. [Sweet alerts] (https://github.com/pedant/sweet-alert-dialog) 44 | 2. [Butterknife] (https://github.com/JakeWharton/butterknife) 45 | 3. [Retrofit] (http://square.github.io/retrofit/) 46 | 4. [GSON] (https://github.com/google/gson) 47 | 5. [FireBase] (https://firebase.google.com/docs/android/setup) 48 | 6. [Okhttp] (http://square.github.io/okhttp/) 49 | 7. [okio] (https://github.com/square/okio) 50 | 8. [OkHttp Interceptors](https://github.com/square/okhttp/wiki/Interceptors) 51 | 9. [Timber] (https://github.com/JakeWharton/timber) 52 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | apply plugin: 'com.android.application' 20 | 21 | android { 22 | compileSdkVersion 27 23 | 24 | defaultConfig { 25 | applicationId "com.myduka.app" 26 | minSdkVersion 16 27 | targetSdkVersion 27 28 | versionCode 1 29 | versionName "1.0" 30 | multiDexEnabled true 31 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 32 | } 33 | buildTypes { 34 | release { 35 | minifyEnabled false 36 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 37 | } 38 | } 39 | 40 | compileOptions { 41 | sourceCompatibility JavaVersion.VERSION_1_8 42 | targetCompatibility JavaVersion.VERSION_1_8 43 | } 44 | 45 | dataBinding { 46 | enabled = true 47 | } 48 | 49 | buildTypes.each { 50 | 51 | // CONSUMER_KEY & CONSUMER_SECRET Build Variables are referenced from gradle.properties file 52 | it.buildConfigField 'String', 'CONSUMER_KEY', DARAJA_CONSUMER_KEY 53 | it.buildConfigField 'String', 'CONSUMER_SECRET', DARAJA_CONSUMER_SECRET 54 | } 55 | 56 | } 57 | 58 | dependencies { 59 | implementation fileTree(dir: 'libs', include: ['*.jar']) 60 | implementation deps.support.appcompat 61 | implementation deps.support.design 62 | implementation deps.support.support 63 | implementation deps.support.multidex 64 | implementation deps.support.cardview 65 | implementation deps.support.recyclerview 66 | implementation deps.support.constraintLayout 67 | //Butterknife - Bind Views 68 | implementation deps.butterknife.core 69 | annotationProcessor deps.butterknife.compiler 70 | //Log - Replace the Android Log Class 71 | implementation deps.timber 72 | //Firebase 73 | implementation deps.firebase 74 | //My Lib -> Monitor Internet Connectivity 75 | implementation deps.networkmanager 76 | //Glide - Handle Images 77 | implementation deps.glide.core 78 | annotationProcessor deps.glide.compiler 79 | //Sweet Alert Replacement 80 | implementation deps.sweetalert 81 | //Retrofit - Network Client 82 | implementation deps.retrofit.core 83 | implementation deps.retrofit.gsonConverter 84 | //OKHTTP3 85 | implementation deps.okhttp3.core 86 | implementation deps.okhttp3.interceptor 87 | //GSON 88 | implementation deps.gson 89 | //OKIO 90 | implementation deps.okio 91 | 92 | //Testing !!! 93 | testImplementation 'junit:junit:4.12' 94 | androidTestImplementation 'com.android.support.test:runner:1.0.1' 95 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' 96 | androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:2.2.2', { 97 | exclude group: 'com.android.support', module: 'support-annotations' 98 | exclude group: 'com.android.support', module: 'support-v4' 99 | exclude group: 'com.android.support', module: 'design' 100 | exclude group: 'com.android.support', module: 'recyclerview-v7' 101 | } 102 | 103 | } 104 | apply plugin: 'com.google.gms.google-services' 105 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Users\USER\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | # Uncomment this to preserve the line number information for 20 | # debugging stack traces. 21 | #-keepattributes SourceFile,LineNumberTable 22 | 23 | # If you keep the line number information, uncomment this to 24 | # hide the original source file name. 25 | #-renamesourcefileattribute SourceFile 26 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/myduka/app/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app; 20 | 21 | import android.content.Context; 22 | import android.support.test.InstrumentationRegistry; 23 | import android.support.test.runner.AndroidJUnit4; 24 | 25 | import org.junit.Test; 26 | import org.junit.runner.RunWith; 27 | 28 | import static org.junit.Assert.*; 29 | 30 | /** 31 | * Instrumentation test, which will execute on an Android device. 32 | * 33 | * @see Testing documentation 34 | */ 35 | @RunWith(AndroidJUnit4.class) 36 | public class ExampleInstrumentedTest { 37 | @Test 38 | public void useAppContext() throws Exception { 39 | // Context of the app under test. 40 | Context appContext = InstrumentationRegistry.getTargetContext(); 41 | 42 | assertEquals("com.myduka.app", appContext.getPackageName()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 18 | 19 | 22 | 23 | 24 | 25 | 26 | 35 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /app/src/main/ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/safaricom/LNMOnlineAndroidSample/74eced63f0cd5fd2f9869f9fcaf9b14823dcadb8/app/src/main/ic_launcher-web.png -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/MyDuka.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app; 20 | 21 | import android.content.Context; 22 | import android.support.multidex.MultiDex; 23 | import android.support.multidex.MultiDexApplication; 24 | 25 | import timber.log.Timber; 26 | 27 | /** 28 | * Created on 8/2/2017. 29 | */ 30 | 31 | public class MyDuka extends MultiDexApplication { 32 | protected void attachBaseContext(Context base) { 33 | super.attachBaseContext(base); 34 | MultiDex.install(this); 35 | 36 | if (BuildConfig.DEBUG) { 37 | Timber.plant(new Timber.DebugTree()); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/api/ApiClient.java: -------------------------------------------------------------------------------- 1 | package com.myduka.app.api; 2 | 3 | import com.myduka.app.api.interceptor.AccessTokenInterceptor; 4 | import com.myduka.app.api.interceptor.AuthInterceptor; 5 | import com.myduka.app.api.services.STKPushService; 6 | 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import okhttp3.OkHttpClient; 10 | import okhttp3.logging.HttpLoggingInterceptor; 11 | import retrofit2.Retrofit; 12 | import retrofit2.converter.gson.GsonConverterFactory; 13 | 14 | import static com.myduka.app.util.AppConstants.BASE_URL; 15 | import static com.myduka.app.util.AppConstants.CONNECT_TIMEOUT; 16 | import static com.myduka.app.util.AppConstants.READ_TIMEOUT; 17 | import static com.myduka.app.util.AppConstants.WRITE_TIMEOUT; 18 | 19 | /** 20 | * API Client helper class used to configure Retrofit object. 21 | * 22 | * @author Thomas Kioko 23 | */ 24 | 25 | public class ApiClient { 26 | 27 | private Retrofit retrofit; 28 | private boolean isDebug; 29 | private boolean isGetAccessToken; 30 | private String mAuthToken; 31 | private HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); 32 | 33 | /** 34 | * Set the {@link Retrofit} log level. This allows one to view network traffic. 35 | * 36 | * @param isDebug If true, the log level is set to 37 | * {@link HttpLoggingInterceptor.Level#BODY}. Otherwise 38 | * {@link HttpLoggingInterceptor.Level#NONE}. 39 | */ 40 | public ApiClient setIsDebug(boolean isDebug) { 41 | this.isDebug = isDebug; 42 | return this; 43 | } 44 | 45 | /** 46 | * Helper method used to set the authenication Token 47 | * 48 | * @param authToken token from api 49 | */ 50 | public ApiClient setAuthToken(String authToken) { 51 | mAuthToken = authToken; 52 | return this; 53 | } 54 | 55 | /** 56 | * Helper method used to determine if get token enpoint has been invoked. This should be called 57 | * only when requesting of an accessToken 58 | * 59 | * @param getAccessToken {@link Boolean} 60 | */ 61 | public ApiClient setGetAccessToken(boolean getAccessToken) { 62 | isGetAccessToken = getAccessToken; 63 | return this; 64 | } 65 | 66 | /** 67 | * Configure OkHttpClient 68 | * 69 | * @return OkHttpClient 70 | */ 71 | private OkHttpClient.Builder okHttpClient() { 72 | OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder(); 73 | okHttpClient 74 | .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) 75 | .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) 76 | .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) 77 | .addInterceptor(httpLoggingInterceptor); 78 | 79 | return okHttpClient; 80 | } 81 | 82 | /** 83 | * Return the current {@link Retrofit} instance. If none exists (first call, API key changed), 84 | * builds a new one. 85 | *

86 | * When building, sets the endpoint and a {@link HttpLoggingInterceptor} which adds the API key as query param. 87 | */ 88 | private Retrofit getRestAdapter() { 89 | 90 | Retrofit.Builder builder = new Retrofit.Builder(); 91 | builder.baseUrl(BASE_URL); 92 | builder.addConverterFactory(GsonConverterFactory.create()); 93 | 94 | if (isDebug) { 95 | httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); 96 | } 97 | 98 | OkHttpClient.Builder okhttpBuilder = okHttpClient(); 99 | 100 | if (isGetAccessToken) { 101 | okhttpBuilder.addInterceptor(new AccessTokenInterceptor()); 102 | } 103 | 104 | if (mAuthToken != null && !mAuthToken.isEmpty()) { 105 | okhttpBuilder.addInterceptor(new AuthInterceptor(mAuthToken)); 106 | } 107 | 108 | builder.client(okhttpBuilder.build()); 109 | 110 | retrofit = builder.build(); 111 | 112 | return retrofit; 113 | } 114 | 115 | /** 116 | * Create service instance. 117 | * 118 | * @return STKPushService Service. 119 | */ 120 | public STKPushService mpesaService() { 121 | return getRestAdapter().create(STKPushService.class); 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/api/interceptor/AccessTokenInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.myduka.app.api.interceptor; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.util.Base64; 5 | 6 | import com.myduka.app.BuildConfig; 7 | import com.myduka.app.api.ApiClient; 8 | 9 | import java.io.IOException; 10 | 11 | import okhttp3.Interceptor; 12 | import okhttp3.Request; 13 | import okhttp3.Response; 14 | 15 | public class AccessTokenInterceptor implements Interceptor { 16 | 17 | public AccessTokenInterceptor() { 18 | 19 | } 20 | 21 | @Override 22 | public Response intercept(@NonNull Chain chain) throws IOException { 23 | 24 | String keys = BuildConfig.CONSUMER_KEY + ":" + BuildConfig.CONSUMER_SECRET; 25 | 26 | Request request = chain.request().newBuilder() 27 | .addHeader("Authorization", "Basic " + Base64.encodeToString(keys.getBytes(), Base64.NO_WRAP)) 28 | .build(); 29 | return chain.proceed(request); 30 | } 31 | } -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/api/interceptor/AuthInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.myduka.app.api.interceptor; 2 | 3 | 4 | 5 | import android.support.annotation.NonNull; 6 | 7 | 8 | import java.io.IOException; 9 | 10 | import okhttp3.Interceptor; 11 | import okhttp3.Request; 12 | import okhttp3.Response; 13 | 14 | /** 15 | * This class add information an authorization key to {@link okhttp3.OkHttpClient} which is passed in 16 | * {ApiClient#getRestAdapter} which is required when making a request. 17 | * 18 | * @author Thomas Kioko 19 | */ 20 | public class AuthInterceptor implements Interceptor { 21 | 22 | private String mAuthToken; 23 | 24 | public AuthInterceptor(String authToken) { 25 | mAuthToken = authToken; 26 | } 27 | 28 | @Override 29 | public Response intercept(@NonNull Chain chain) throws IOException { 30 | Request request = chain.request().newBuilder() 31 | .addHeader("Authorization", "Bearer " + mAuthToken) 32 | .build(); 33 | return chain.proceed(request); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/api/model/AccessToken.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.api.model; 20 | 21 | import com.google.gson.annotations.Expose; 22 | import com.google.gson.annotations.SerializedName; 23 | 24 | /** 25 | * Created on 7/13/2017. 26 | */ 27 | 28 | public class AccessToken { 29 | @SerializedName("access_token") 30 | @Expose 31 | public String accessToken; 32 | @SerializedName("expires_in") 33 | @Expose 34 | private String expiresIn; 35 | 36 | public AccessToken(String accessToken, String expiresIn) { 37 | this.accessToken = accessToken; 38 | this.expiresIn = expiresIn; 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/api/model/STKPush.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.api.model; 20 | 21 | import com.google.gson.annotations.SerializedName; 22 | 23 | /** 24 | * Created on 5/28/2017. 25 | */ 26 | 27 | public class STKPush { 28 | 29 | @SerializedName("BusinessShortCode") 30 | private String businessShortCode; 31 | @SerializedName("Password") 32 | private String password; 33 | @SerializedName("Timestamp") 34 | private String timestamp; 35 | @SerializedName("TransactionType") 36 | private String transactionType; 37 | @SerializedName("Amount") 38 | private String amount; 39 | @SerializedName("PartyA") 40 | private String partyA; 41 | @SerializedName("PartyB") 42 | private String partyB; 43 | @SerializedName("PhoneNumber") 44 | private String phoneNumber; 45 | @SerializedName("CallBackURL") 46 | private String callBackURL; 47 | @SerializedName("AccountReference") 48 | private String accountReference; 49 | @SerializedName("TransactionDesc") 50 | private String transactionDesc; 51 | 52 | public STKPush(String businessShortCode, String password, String timestamp, String transactionType, 53 | String amount, String partyA, String partyB, String phoneNumber, String callBackURL, 54 | String accountReference, String transactionDesc) { 55 | this.businessShortCode = businessShortCode; 56 | this.password = password; 57 | this.timestamp = timestamp; 58 | this.transactionType = transactionType; 59 | this.amount = amount; 60 | this.partyA = partyA; 61 | this.partyB = partyB; 62 | this.phoneNumber = phoneNumber; 63 | this.callBackURL = callBackURL; 64 | this.accountReference = accountReference; 65 | this.transactionDesc = transactionDesc; 66 | } 67 | } -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/api/services/STKPushService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.api.services; 20 | 21 | import com.myduka.app.api.model.AccessToken; 22 | import com.myduka.app.api.model.STKPush; 23 | 24 | import retrofit2.Call; 25 | import retrofit2.http.Body; 26 | import retrofit2.http.GET; 27 | import retrofit2.http.POST; 28 | 29 | /** 30 | * Created on 5/28/2017. 31 | */ 32 | 33 | public interface STKPushService { 34 | @POST("mpesa/stkpush/v1/processrequest") 35 | Call sendPush(@Body STKPush stkPush); 36 | 37 | @GET("jobs/pending") 38 | Call getTasks(); 39 | 40 | @GET("oauth/v1/generate?grant_type=client_credentials") 41 | Call getAccessToken(); 42 | } 43 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/service/MyFirebaseInstanceIDService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.service; 20 | 21 | import android.content.Intent; 22 | import android.content.SharedPreferences; 23 | import android.support.v4.content.LocalBroadcastManager; 24 | 25 | import com.google.firebase.iid.FirebaseInstanceId; 26 | import com.google.firebase.iid.FirebaseInstanceIdService; 27 | 28 | import static com.myduka.app.util.AppConstants.REGISTRATION_COMPLETE; 29 | import static com.myduka.app.util.AppConstants.SHARED_PREF; 30 | 31 | /** 32 | * Created on 6/30/2017. 33 | */ 34 | 35 | public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { 36 | private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName(); 37 | 38 | @Override 39 | public void onTokenRefresh() { 40 | super.onTokenRefresh(); 41 | String refreshedToken = FirebaseInstanceId.getInstance().getToken(); 42 | 43 | // Saving reg id to shared preferences 44 | storeRegIdInPref(refreshedToken); 45 | 46 | // sending reg id to your server 47 | sendRegistrationToServer(refreshedToken); 48 | 49 | // Notify UI that registration has completed, so the progress indicator can be hidden. 50 | Intent registrationComplete = new Intent(REGISTRATION_COMPLETE); 51 | registrationComplete.putExtra("token", refreshedToken); 52 | LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); 53 | } 54 | 55 | private void sendRegistrationToServer(final String token) { 56 | // sending gcm token to server 57 | //Log.e(TAG, "sendRegistrationToServer: " + token); 58 | } 59 | 60 | /** 61 | * Setting values in Preference: 62 | */ 63 | 64 | private void storeRegIdInPref(String token) { 65 | SharedPreferences pref = getApplicationContext().getSharedPreferences(SHARED_PREF, 0); 66 | SharedPreferences.Editor editor = pref.edit(); 67 | editor.putString("regId", token); 68 | editor.apply(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/service/MyFirebaseMessagingService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.service; 20 | 21 | import android.content.Context; 22 | import android.content.Intent; 23 | import android.support.v4.content.LocalBroadcastManager; 24 | import android.text.TextUtils; 25 | 26 | import com.google.firebase.messaging.FirebaseMessagingService; 27 | import com.google.firebase.messaging.RemoteMessage; 28 | import com.myduka.app.ui.activity.MainActivity; 29 | import com.myduka.app.util.NotificationUtils; 30 | 31 | import org.json.JSONException; 32 | import org.json.JSONObject; 33 | 34 | import static com.myduka.app.util.AppConstants.PUSH_NOTIFICATION; 35 | 36 | /** 37 | * Created on 6/30/2017. 38 | */ 39 | 40 | public class MyFirebaseMessagingService extends FirebaseMessagingService { 41 | 42 | private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); 43 | 44 | private NotificationUtils notificationUtils; 45 | 46 | @Override 47 | public void onMessageReceived(RemoteMessage remoteMessage) { 48 | //Log.e(TAG, "From: " + remoteMessage.getFrom()); 49 | 50 | if (remoteMessage == null) 51 | return; 52 | 53 | // Check if message contains a notification payload. 54 | if (remoteMessage.getNotification() != null) { 55 | //Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody()); 56 | handleNotification(remoteMessage.getNotification().getBody()); 57 | } 58 | 59 | // Check if message contains a data payload. 60 | if (remoteMessage.getData().size() > 0) { 61 | //Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString()); 62 | 63 | try { 64 | JSONObject json = new JSONObject(remoteMessage.getData().toString()); 65 | handleDataMessage(json); 66 | } catch (Exception e) { 67 | //Log.e(TAG, "Exception: " + e.getMessage()); 68 | } 69 | } 70 | } 71 | 72 | private void handleNotification(String message) { 73 | if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { 74 | // app is in foreground, broadcast the push message 75 | Intent pushNotification = new Intent(PUSH_NOTIFICATION); 76 | pushNotification.putExtra("message", message); 77 | LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); 78 | 79 | // play notification sound 80 | NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); 81 | notificationUtils.playNotificationSound(); 82 | } else { 83 | // If the app is in background, firebase itself handles the notification 84 | } 85 | } 86 | 87 | private void handleDataMessage(JSONObject json) { 88 | //Log.e(TAG, "push json: " + json.toString()); 89 | 90 | try { 91 | JSONObject data = json.getJSONObject("data"); 92 | 93 | String title = data.getString("title"); 94 | String message = data.getString("message"); 95 | boolean isBackground = data.getBoolean("is_background"); 96 | String imageUrl = data.getString("image"); 97 | String timestamp = data.getString("timestamp"); 98 | JSONObject payload = data.getJSONObject("payload"); 99 | 100 | //Log.e(TAG, "title: " + title); 101 | //Log.e(TAG, "message: " + message); 102 | //Log.e(TAG, "isBackground: " + isBackground); 103 | //Log.e(TAG, "payload: " + payload.toString()); 104 | //Log.e(TAG, "imageUrl: " + imageUrl); 105 | //Log.e(TAG, "timestamp: " + timestamp); 106 | 107 | 108 | if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) { 109 | // app is in foreground, broadcast the push message 110 | Intent pushNotification = new Intent(PUSH_NOTIFICATION); 111 | pushNotification.putExtra("message", message); 112 | LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification); 113 | 114 | // play notification sound 115 | NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext()); 116 | notificationUtils.playNotificationSound(); 117 | } else { 118 | // app is in background, show the notification in notification tray 119 | Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class); 120 | resultIntent.putExtra("message", message); 121 | 122 | // check for image attachment 123 | if (TextUtils.isEmpty(imageUrl)) { 124 | showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent); 125 | } else { 126 | // image is present, show notification with image 127 | showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl); 128 | } 129 | } 130 | } catch (JSONException e) { 131 | //Log.e(TAG, "Json Exception: " + e.getMessage()); 132 | } catch (Exception e) { 133 | //Log.e(TAG, "Exception: " + e.getMessage()); 134 | } 135 | } 136 | 137 | /** 138 | * Showing notification with text only 139 | */ 140 | private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) { 141 | notificationUtils = new NotificationUtils(context); 142 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 143 | notificationUtils.showNotificationMessage(title, message, timeStamp, intent); 144 | } 145 | 146 | /** 147 | * Showing notification with text and image 148 | */ 149 | private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) { 150 | notificationUtils = new NotificationUtils(context); 151 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 152 | notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl); 153 | } 154 | } -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/ui/RecyclerviewListDecorator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.ui; 20 | 21 | import android.content.Context; 22 | import android.content.res.TypedArray; 23 | import android.graphics.Canvas; 24 | import android.graphics.Rect; 25 | import android.graphics.drawable.Drawable; 26 | import android.support.v7.widget.LinearLayoutManager; 27 | import android.support.v7.widget.RecyclerView; 28 | import android.view.View; 29 | 30 | /** 31 | * Created by Brayo on 8/28/2016. 32 | */ 33 | public class RecyclerviewListDecorator extends RecyclerView.ItemDecoration { 34 | 35 | private static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; 36 | private static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; 37 | private static final int[] ATTRS = new int[]{ 38 | android.R.attr.listDivider 39 | }; 40 | private Drawable mDivider; 41 | 42 | private int mOrientation; 43 | 44 | public RecyclerviewListDecorator(Context context, int orientation) { 45 | final TypedArray a = context.obtainStyledAttributes(ATTRS); 46 | mDivider = a.getDrawable(0); 47 | a.recycle(); 48 | setOrientation(orientation); 49 | } 50 | 51 | /** 52 | * Setting orientation 53 | */ 54 | private void setOrientation(int orientation) { 55 | if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { 56 | throw new IllegalArgumentException("invalid orientation"); 57 | } 58 | mOrientation = orientation; 59 | } 60 | 61 | @Override 62 | public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { 63 | if (mOrientation == VERTICAL_LIST) { 64 | drawVertical(c, parent); 65 | } else { 66 | drawHorizontal(c, parent); 67 | } 68 | } 69 | 70 | /** 71 | * Drawing only virtical lines in Android 72 | */ 73 | private void drawVertical(Canvas c, RecyclerView parent) { 74 | final int left = parent.getPaddingLeft(); 75 | final int right = parent.getWidth() - parent.getPaddingRight(); 76 | 77 | final int childCount = parent.getChildCount(); 78 | for (int i = 0; i < childCount; i++) { 79 | final View child = parent.getChildAt(i); 80 | final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child 81 | .getLayoutParams(); 82 | final int top = child.getBottom() + params.bottomMargin; 83 | final int bottom = top + mDivider.getIntrinsicHeight(); 84 | mDivider.setBounds(left, top, right, bottom); 85 | mDivider.draw(c); 86 | } 87 | } 88 | 89 | /** 90 | * Drawing only horizontal lines in Android 91 | */ 92 | private void drawHorizontal(Canvas c, RecyclerView parent) { 93 | final int top = parent.getPaddingTop(); 94 | final int bottom = parent.getHeight() - parent.getPaddingBottom(); 95 | 96 | final int childCount = parent.getChildCount(); 97 | for (int i = 0; i < childCount; i++) { 98 | final View child = parent.getChildAt(i); 99 | final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child 100 | .getLayoutParams(); 101 | final int left = child.getRight() + params.rightMargin; 102 | final int right = left + mDivider.getIntrinsicHeight(); 103 | mDivider.setBounds(left, top, right, bottom); 104 | mDivider.draw(c); 105 | } 106 | } 107 | 108 | @Override 109 | public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { 110 | if (mOrientation == VERTICAL_LIST) { 111 | outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); 112 | } else { 113 | outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); 114 | } 115 | } 116 | } -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/ui/activity/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.ui.activity; 20 | 21 | import android.app.ProgressDialog; 22 | import android.content.BroadcastReceiver; 23 | import android.content.Context; 24 | import android.content.Intent; 25 | import android.content.IntentFilter; 26 | import android.graphics.Color; 27 | import android.os.Bundle; 28 | import android.support.annotation.NonNull; 29 | import android.support.design.widget.Snackbar; 30 | import android.support.v4.content.LocalBroadcastManager; 31 | import android.support.v7.app.AlertDialog; 32 | import android.support.v7.app.AppCompatActivity; 33 | import android.support.v7.widget.LinearLayoutManager; 34 | import android.support.v7.widget.RecyclerView; 35 | import android.text.InputType; 36 | import android.text.TextUtils; 37 | import android.view.Menu; 38 | import android.view.MenuItem; 39 | import android.view.View; 40 | import android.widget.Button; 41 | import android.widget.EditText; 42 | import android.widget.TextView; 43 | import android.widget.Toast; 44 | 45 | import com.google.firebase.messaging.FirebaseMessaging; 46 | import com.myduka.app.R; 47 | import com.myduka.app.api.ApiClient; 48 | import com.myduka.app.api.model.AccessToken; 49 | import com.myduka.app.api.model.STKPush; 50 | import com.myduka.app.ui.RecyclerviewListDecorator; 51 | import com.myduka.app.ui.adapter.CartListAdapter; 52 | import com.myduka.app.ui.callback.PriceTransfer; 53 | import com.myduka.app.util.NotificationUtils; 54 | import com.myduka.app.util.SharedPrefsUtil; 55 | import com.myduka.app.util.Utils; 56 | import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog; 57 | 58 | import java.util.ArrayList; 59 | 60 | import butterknife.BindView; 61 | import butterknife.ButterKnife; 62 | import butterknife.OnClick; 63 | import retrofit2.Call; 64 | import retrofit2.Callback; 65 | import retrofit2.Response; 66 | import timber.log.Timber; 67 | 68 | import static com.myduka.app.util.AppConstants.BUSINESS_SHORT_CODE; 69 | import static com.myduka.app.util.AppConstants.CALLBACKURL; 70 | import static com.myduka.app.util.AppConstants.PARTYB; 71 | import static com.myduka.app.util.AppConstants.PASSKEY; 72 | import static com.myduka.app.util.AppConstants.PUSH_NOTIFICATION; 73 | import static com.myduka.app.util.AppConstants.REGISTRATION_COMPLETE; 74 | import static com.myduka.app.util.AppConstants.TOPIC_GLOBAL; 75 | import static com.myduka.app.util.AppConstants.TRANSACTION_TYPE; 76 | 77 | public class MainActivity extends AppCompatActivity implements PriceTransfer { 78 | 79 | @BindView(R.id.cart_list) 80 | RecyclerView mRecyclerViewCartList; 81 | @BindView(R.id.txt_response) 82 | TextView mTVResponse; 83 | @BindView(R.id.buttonCheckout) 84 | Button mButtonCheckout; 85 | 86 | private String mFireBaseRegId; 87 | private BroadcastReceiver mRegistrationBroadcastReceiver; 88 | private ProgressDialog mProgressDialog; 89 | private SharedPrefsUtil mSharedPrefsUtil; 90 | private ApiClient mApiClient; 91 | private ArrayList mPriceArrayList = new ArrayList<>(); 92 | 93 | @Override 94 | protected void onCreate(Bundle savedInstanceState) { 95 | super.onCreate(savedInstanceState); 96 | setContentView(R.layout.activity_main); 97 | ButterKnife.bind(this); 98 | 99 | mProgressDialog = new ProgressDialog(this); 100 | mSharedPrefsUtil = new SharedPrefsUtil(this); 101 | mApiClient = new ApiClient(); 102 | mApiClient.setIsDebug(true); //Set True to enable logging, false to disable. 103 | 104 | getAccessToken(); 105 | 106 | LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false); 107 | 108 | mRecyclerViewCartList.setLayoutManager(layoutManager); 109 | mRecyclerViewCartList.addItemDecoration(new RecyclerviewListDecorator(MainActivity.this, 110 | LinearLayoutManager.HORIZONTAL)); 111 | 112 | ArrayList cartItems = new ArrayList<>(); 113 | cartItems.add("Tomatoes"); 114 | cartItems.add("Apples"); 115 | cartItems.add("Bananas"); 116 | 117 | ArrayList cartPrices = new ArrayList<>(); 118 | cartPrices.add("1"); 119 | cartPrices.add("200"); 120 | cartPrices.add("120"); 121 | 122 | mRecyclerViewCartList.setAdapter(new CartListAdapter(this, cartItems, cartPrices, MainActivity.this)); 123 | 124 | mRegistrationBroadcastReceiver = new BroadcastReceiver() { 125 | @Override 126 | public void onReceive(Context context, Intent intent) { 127 | 128 | // checking for type intent filter 129 | if (intent.getAction().equals(REGISTRATION_COMPLETE)) { 130 | // gcm successfully registered 131 | // now subscribe to `global` topic to receive app wide notifications 132 | FirebaseMessaging.getInstance().subscribeToTopic(TOPIC_GLOBAL); 133 | getFirebaseRegId(); 134 | 135 | } else if (intent.getAction().equals(PUSH_NOTIFICATION)) { 136 | String message = intent.getStringExtra("message"); 137 | NotificationUtils.createNotification(getApplicationContext(), message); 138 | showResultDialog(message); 139 | } 140 | } 141 | }; 142 | 143 | getFirebaseRegId(); 144 | } 145 | 146 | @OnClick({R.id.buttonCheckout}) 147 | public void onClickViews(View view) { 148 | switch (view.getId()) { 149 | case R.id.buttonCheckout: 150 | if (mPriceArrayList.size() > 0) 151 | //Calling getPhoneNumber method. 152 | showCheckoutDialog(); 153 | break; 154 | } 155 | } 156 | 157 | @Override 158 | public boolean onCreateOptionsMenu(Menu menu) { 159 | // Inflate the menu; this adds items to the action bar if it is present. 160 | getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu 161 | return true; 162 | } 163 | 164 | @Override 165 | protected void onDestroy() { 166 | super.onDestroy(); 167 | 168 | unregisterReceiver(mRegistrationBroadcastReceiver); 169 | } 170 | 171 | @Override 172 | public boolean onOptionsItemSelected(MenuItem item) { 173 | switch (item.getItemId()) { 174 | case R.id.action_checkout: 175 | Snackbar.make(findViewById(R.id.pay_layout), "Item 1 Selected", Snackbar.LENGTH_LONG) 176 | .setActionTextColor(Color.RED) 177 | .show(); 178 | return true; 179 | default: 180 | return super.onOptionsItemSelected(item); 181 | } 182 | } 183 | 184 | public void getAccessToken() { 185 | mApiClient.setGetAccessToken(true); 186 | mApiClient.mpesaService().getAccessToken().enqueue(new Callback() { 187 | @Override 188 | public void onResponse(@NonNull Call call, @NonNull Response response) { 189 | 190 | if (response.isSuccessful()) { 191 | mApiClient.setAuthToken(response.body().accessToken); 192 | } 193 | } 194 | 195 | @Override 196 | public void onFailure(@NonNull Call call, @NonNull Throwable t) { 197 | 198 | } 199 | }); 200 | } 201 | 202 | public void showCheckoutDialog() { 203 | AlertDialog.Builder builder = new AlertDialog.Builder(this); 204 | builder.setTitle(getString(R.string.checkout_dialog_title, getTotal(mPriceArrayList))); 205 | 206 | final EditText input = new EditText(this); 207 | input.setInputType(InputType.TYPE_CLASS_PHONE); 208 | input.setHint(getString(R.string.hint_phone_number)); 209 | builder.setView(input); 210 | 211 | builder.setPositiveButton(android.R.string.ok, (dialog, which) -> { 212 | String phone_number = input.getText().toString(); 213 | performSTKPush(phone_number); 214 | }); 215 | builder.setNegativeButton(getString(R.string.clear_cart), (dialog, which) -> { 216 | mPriceArrayList.clear(); 217 | mButtonCheckout.setText(getString(R.string.checkout)); 218 | dialog.cancel(); 219 | }); 220 | 221 | builder.show(); 222 | } 223 | 224 | public void performSTKPush(String phone_number) { 225 | mProgressDialog.setMessage(getString(R.string.dialog_message_processing)); 226 | mProgressDialog.setTitle(getString(R.string.title_wait)); 227 | mProgressDialog.setIndeterminate(true); 228 | mProgressDialog.show(); 229 | String timestamp = Utils.getTimestamp(); 230 | STKPush stkPush = new STKPush( 231 | BUSINESS_SHORT_CODE, 232 | Utils.getPassword(BUSINESS_SHORT_CODE, PASSKEY, timestamp), 233 | timestamp, 234 | TRANSACTION_TYPE, 235 | String.valueOf(getTotal(mPriceArrayList)), 236 | Utils.sanitizePhoneNumber(phone_number), 237 | PARTYB, 238 | Utils.sanitizePhoneNumber(phone_number), 239 | CALLBACKURL + mFireBaseRegId, 240 | "test", //The account reference 241 | "test" //The transaction description 242 | ); 243 | 244 | mApiClient.setGetAccessToken(false); 245 | 246 | mApiClient.mpesaService().sendPush(stkPush).enqueue(new Callback() { 247 | @Override 248 | public void onResponse(@NonNull Call call, @NonNull Response response) { 249 | mProgressDialog.dismiss(); 250 | try { 251 | if (response.isSuccessful()) { 252 | Timber.d("post submitted to API. %s", response.body()); 253 | } else { 254 | Timber.e("Response %s", response.errorBody().string()); 255 | } 256 | } catch (Exception e) { 257 | e.printStackTrace(); 258 | } 259 | } 260 | 261 | @Override 262 | public void onFailure(@NonNull Call call, @NonNull Throwable t) { 263 | mProgressDialog.dismiss(); 264 | Timber.e(t); 265 | } 266 | }); 267 | } 268 | 269 | private void getFirebaseRegId() { 270 | mFireBaseRegId = mSharedPrefsUtil.getFirebaseRegistrationID(); 271 | 272 | if (!TextUtils.isEmpty(mFireBaseRegId)) { 273 | mSharedPrefsUtil.saveFirebaseRegistrationID(mFireBaseRegId); 274 | } 275 | } 276 | 277 | @Override 278 | protected void onResume() { 279 | super.onResume(); 280 | 281 | // register GCM registration complete receiver 282 | LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, 283 | new IntentFilter(REGISTRATION_COMPLETE)); 284 | 285 | // register new push message receiver 286 | // by doing this, the activity will be notified each time a new message arrives 287 | LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, 288 | new IntentFilter(PUSH_NOTIFICATION)); 289 | 290 | // clear the notification area when the app is opened 291 | NotificationUtils.clearNotifications(getApplicationContext()); 292 | } 293 | 294 | @Override 295 | protected void onPause() { 296 | LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); 297 | super.onPause(); 298 | } 299 | 300 | @Override 301 | public void setPrices(ArrayList prices) { 302 | this.mPriceArrayList = prices; 303 | mButtonCheckout.setText(getString(R.string.checkout_value, getTotal(prices))); 304 | } 305 | 306 | public int getTotal(ArrayList prices) { 307 | int sum = 0; 308 | for (int i = 0; i < prices.size(); i++) { 309 | sum = sum + prices.get(i); 310 | } 311 | 312 | if (prices.size() == 0) { 313 | Toast.makeText(MainActivity.this, String.valueOf("Total: " + sum), Toast.LENGTH_SHORT).show(); 314 | return 0; 315 | } else 316 | return sum; 317 | } 318 | 319 | 320 | public void showResultDialog(String result) { 321 | Timber.d(result); 322 | if (!mSharedPrefsUtil.getIsFirstTime()) { 323 | // run your one time code 324 | mSharedPrefsUtil.saveIsFirstTime(true); 325 | 326 | new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE) 327 | .setTitleText(getString(R.string.title_success)) 328 | .setContentText(getString(R.string.dialog_message_success)) 329 | .setConfirmClickListener(sDialog -> { 330 | sDialog.dismissWithAnimation(); 331 | mSharedPrefsUtil.saveIsFirstTime(false); 332 | }) 333 | .show(); 334 | } 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/ui/activity/NotificationActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.ui.activity; 20 | 21 | import android.content.BroadcastReceiver; 22 | import android.content.Context; 23 | import android.content.Intent; 24 | import android.content.IntentFilter; 25 | import android.os.Bundle; 26 | import android.support.v4.content.LocalBroadcastManager; 27 | import android.support.v7.app.AppCompatActivity; 28 | import android.text.TextUtils; 29 | import android.widget.EditText; 30 | import android.widget.TextView; 31 | import android.widget.Toast; 32 | 33 | import com.google.firebase.messaging.FirebaseMessaging; 34 | import com.myduka.app.R; 35 | import com.myduka.app.util.NotificationUtils; 36 | import com.myduka.app.util.SharedPrefsUtil; 37 | 38 | import static com.myduka.app.util.AppConstants.PUSH_NOTIFICATION; 39 | import static com.myduka.app.util.AppConstants.REGISTRATION_COMPLETE; 40 | import static com.myduka.app.util.AppConstants.TOPIC_GLOBAL; 41 | 42 | public class NotificationActivity extends AppCompatActivity { 43 | 44 | private static final String TAG = MainActivity.class.getSimpleName(); 45 | private BroadcastReceiver mRegistrationBroadcastReceiver; 46 | private TextView txtMessage; 47 | private EditText txtRegId; 48 | 49 | @Override 50 | protected void onCreate(Bundle savedInstanceState) { 51 | super.onCreate(savedInstanceState); 52 | setContentView(R.layout.activity_notification); 53 | 54 | txtRegId = findViewById(R.id.txt_reg_id); 55 | txtMessage = findViewById(R.id.txt_push_message); 56 | 57 | mRegistrationBroadcastReceiver = new BroadcastReceiver() { 58 | @Override 59 | public void onReceive(Context context, Intent intent) { 60 | 61 | // checking for type intent filter 62 | if (intent.getAction().equals(REGISTRATION_COMPLETE)) { 63 | // gcm successfully registered 64 | // now subscribe to `global` topic to receive app wide notifications 65 | FirebaseMessaging.getInstance().subscribeToTopic(TOPIC_GLOBAL); 66 | 67 | displayFirebaseRegId(); 68 | 69 | } else if (intent.getAction().equals(PUSH_NOTIFICATION)) { 70 | // new push notification is received 71 | String message = intent.getStringExtra("message"); 72 | Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show(); 73 | txtMessage.setText(message); 74 | } 75 | } 76 | }; 77 | 78 | displayFirebaseRegId(); 79 | } 80 | 81 | // Fetches reg id from shared preferences 82 | // and displays on the screen 83 | private void displayFirebaseRegId() { 84 | SharedPrefsUtil sharedPrefsUtil = new SharedPrefsUtil(this); 85 | String regId = sharedPrefsUtil.getFirebaseRegistrationID(); 86 | 87 | if (!TextUtils.isEmpty(regId)) 88 | txtRegId.setText("Firebase Reg Id: " + regId); 89 | else 90 | txtRegId.setText("Firebase Reg Id is not received yet!"); 91 | } 92 | 93 | @Override 94 | protected void onResume() { 95 | super.onResume(); 96 | 97 | // register GCM registration complete receiver. 98 | LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, 99 | new IntentFilter(REGISTRATION_COMPLETE)); 100 | 101 | // register new push message receiver. 102 | // by doing this, the activity will be notified each time a new message arrives 103 | LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, 104 | new IntentFilter(PUSH_NOTIFICATION)); 105 | 106 | // clear the notification area when the app is opened. 107 | NotificationUtils.clearNotifications(getApplicationContext()); 108 | } 109 | 110 | @Override 111 | protected void onPause() { 112 | LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); 113 | super.onPause(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/ui/adapter/CartListAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.ui.adapter; 20 | 21 | import android.app.Dialog; 22 | import android.content.Context; 23 | import android.support.v7.widget.RecyclerView; 24 | import android.view.LayoutInflater; 25 | import android.view.View; 26 | import android.view.ViewGroup; 27 | import android.widget.Button; 28 | import android.widget.ImageView; 29 | import android.widget.TextView; 30 | import android.widget.Toast; 31 | 32 | import com.bumptech.glide.Glide; 33 | import com.myduka.app.R; 34 | import com.myduka.app.ui.callback.PriceTransfer; 35 | 36 | import java.util.ArrayList; 37 | import java.util.List; 38 | 39 | /** 40 | * Created on 8/1/2017. 41 | */ 42 | 43 | public class CartListAdapter extends RecyclerView.Adapter { 44 | 45 | private final LayoutInflater inflater; 46 | private PriceTransfer priceTransfer; 47 | private List items; 48 | private Context context; 49 | private Dialog myDialog; 50 | private List item_prices; 51 | private ArrayList prices = new ArrayList<>(); 52 | 53 | public CartListAdapter(Context context, List items, List item_prices, PriceTransfer priceTransfer) { 54 | this.items = items; 55 | this.context = context; 56 | this.item_prices = item_prices; 57 | this.priceTransfer = priceTransfer; 58 | inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 59 | } 60 | 61 | @Override 62 | public CartListAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { 63 | View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_list_item, viewGroup, false); 64 | return new ViewHolder(view); 65 | } 66 | 67 | @Override 68 | public void onBindViewHolder(CartListAdapter.ViewHolder viewHolder, int i) { 69 | viewHolder.item_name.setText(items.get(i)); 70 | viewHolder.btn_add_to_cart.setText("Add Kshs " + item_prices.get(i)); 71 | viewHolder.item_description.setText(items.get(i) + " fresh and healthy now available."); 72 | 73 | if (items.get(i).equals("Tomatoes")) 74 | Glide.with(context) 75 | .load(R.drawable.tomatoes) 76 | .into(viewHolder.item_image); 77 | else if (items.get(i).equals("Apples")) 78 | Glide.with(context) 79 | .load(R.drawable.apples) 80 | .into(viewHolder.item_image); 81 | else if (items.get(i).equals("Bananas")) 82 | Glide.with(context) 83 | .load(R.drawable.bananas) 84 | .into(viewHolder.item_image); 85 | } 86 | 87 | @Override 88 | /** 89 | * tells the Adapter that how many rows are there to display 90 | */ 91 | public int getItemCount() { 92 | return items.size(); 93 | } 94 | 95 | public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { 96 | ImageView item_image; 97 | TextView item_name, item_description; 98 | Button btn_add_to_cart; 99 | 100 | ViewHolder(View view) { 101 | super(view); 102 | 103 | item_image = view.findViewById(R.id.item_image); 104 | item_name = view.findViewById(R.id.item_name); 105 | item_description = view.findViewById(R.id.item_description); 106 | btn_add_to_cart = view.findViewById(R.id.btn_add_to_cart); 107 | 108 | btn_add_to_cart.setOnClickListener(this); 109 | } 110 | 111 | @Override 112 | public void onClick(View view) { 113 | int position = getAdapterPosition(); 114 | if (view.getId() == R.id.btn_add_to_cart) { 115 | prices.add(Integer.valueOf(btn_add_to_cart.getText().toString().replace("Add Kshs ", ""))); 116 | Toast.makeText(context, String.valueOf("Added: " + items.get(position)), Toast.LENGTH_SHORT).show(); 117 | 118 | priceTransfer.setPrices(prices); 119 | } 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/ui/callback/PriceTransfer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.ui.callback; 20 | 21 | import java.util.ArrayList; 22 | 23 | /** 24 | * Created on 8/1/2017. 25 | */ 26 | 27 | public interface PriceTransfer { 28 | public void setPrices(ArrayList prices); 29 | } 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/util/AppConstants.java: -------------------------------------------------------------------------------- 1 | package com.myduka.app.util; 2 | 3 | /** 4 | * 5 | */ 6 | 7 | public class AppConstants { 8 | 9 | /** 10 | * Connection timeout duration 11 | */ 12 | public static final int CONNECT_TIMEOUT = 60 * 1000; 13 | /** 14 | * Connection Read timeout duration 15 | */ 16 | public static final int READ_TIMEOUT = 60 * 1000; 17 | /** 18 | * Connection write timeout duration 19 | */ 20 | public static final int WRITE_TIMEOUT = 60 * 1000; 21 | /** 22 | * Base URL 23 | */ 24 | public static final String BASE_URL = "https://sandbox.safaricom.co.ke/"; 25 | /** 26 | * global topic to receive app wide push notifications 27 | */ 28 | public static final String TOPIC_GLOBAL = "global"; 29 | 30 | // broadcast receiver intent filters 31 | public static final String REGISTRATION_COMPLETE = "registrationComplete"; 32 | public static final String PUSH_NOTIFICATION = "pushNotification"; 33 | 34 | // id to handle the notification in the notification tray 35 | public static final int NOTIFICATION_ID = 100; 36 | public static final int NOTIFICATION_ID_BIG_IMAGE = 101; 37 | public static final String SHARED_PREF = "ah_firebase"; 38 | 39 | //STKPush Properties 40 | public static final String BUSINESS_SHORT_CODE = "174379"; 41 | public static final String PASSKEY = "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919"; 42 | public static final String TRANSACTION_TYPE = "CustomerPayBillOnline"; 43 | public static final String PARTYB = "174379"; 44 | public static final String CALLBACKURL = "https://spurquoteapp.ga/pusher/pusher.php?title=stk_push&message=result&push_type=individual®Id="; 45 | 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/util/NotificationUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.util; 20 | 21 | import android.app.ActivityManager; 22 | import android.app.Notification; 23 | import android.app.NotificationManager; 24 | import android.app.PendingIntent; 25 | import android.content.ComponentName; 26 | import android.content.ContentResolver; 27 | import android.content.Context; 28 | import android.content.Intent; 29 | import android.graphics.Bitmap; 30 | import android.graphics.BitmapFactory; 31 | import android.media.Ringtone; 32 | import android.media.RingtoneManager; 33 | import android.net.ParseException; 34 | import android.net.Uri; 35 | import android.os.Build; 36 | import android.support.v4.app.NotificationCompat; 37 | import android.text.Html; 38 | import android.text.TextUtils; 39 | import android.util.Patterns; 40 | 41 | import com.myduka.app.R; 42 | 43 | import java.io.IOException; 44 | import java.io.InputStream; 45 | import java.net.HttpURLConnection; 46 | import java.net.URL; 47 | import java.text.SimpleDateFormat; 48 | import java.util.Date; 49 | import java.util.List; 50 | 51 | import static android.content.Context.NOTIFICATION_SERVICE; 52 | import static com.myduka.app.util.AppConstants.NOTIFICATION_ID; 53 | import static com.myduka.app.util.AppConstants.NOTIFICATION_ID_BIG_IMAGE; 54 | 55 | /** 56 | * Created on 6/30/2017. 57 | */ 58 | 59 | public class NotificationUtils { 60 | private static String TAG = NotificationUtils.class.getSimpleName(); 61 | 62 | private Context mContext; 63 | 64 | public NotificationUtils(Context mContext) { 65 | this.mContext = mContext; 66 | } 67 | 68 | public static void createNotification(Context context, String content) { 69 | Notification noti = new Notification.Builder(context) 70 | .setContentTitle(content) 71 | .setContentText("Subject").setSmallIcon(R.mipmap.ic_launcher).build(); 72 | NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); 73 | // hide the notification after its selected 74 | noti.flags |= Notification.FLAG_AUTO_CANCEL; 75 | 76 | notificationManager.notify(1, noti); 77 | 78 | } 79 | 80 | /** 81 | * Method checks if the app is in background or not 82 | */ 83 | public static boolean isAppIsInBackground(Context context) { 84 | boolean isInBackground = true; 85 | ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 86 | if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { 87 | List runningProcesses = am.getRunningAppProcesses(); 88 | for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) { 89 | if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { 90 | for (String activeProcess : processInfo.pkgList) { 91 | if (activeProcess.equals(context.getPackageName())) { 92 | isInBackground = false; 93 | } 94 | } 95 | } 96 | } 97 | } else { 98 | List taskInfo = am.getRunningTasks(1); 99 | ComponentName componentInfo = taskInfo.get(0).topActivity; 100 | if (componentInfo.getPackageName().equals(context.getPackageName())) { 101 | isInBackground = false; 102 | } 103 | } 104 | 105 | return isInBackground; 106 | } 107 | 108 | // Clears notification tray messages 109 | public static void clearNotifications(Context context) { 110 | NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); 111 | notificationManager.cancelAll(); 112 | } 113 | 114 | public static long getTimeMilliSec(String timeStamp) { 115 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 116 | try { 117 | Date date = format.parse(timeStamp); 118 | return date.getTime(); 119 | } catch (ParseException e) { 120 | e.printStackTrace(); 121 | } catch (java.text.ParseException e) { 122 | e.printStackTrace(); 123 | } 124 | return 0; 125 | } 126 | 127 | public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) { 128 | showNotificationMessage(title, message, timeStamp, intent, null); 129 | } 130 | 131 | public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) { 132 | // Check for empty push message 133 | if (TextUtils.isEmpty(message)) 134 | return; 135 | 136 | // notification icon 137 | final int icon = R.mipmap.ic_launcher; 138 | 139 | intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 140 | final PendingIntent resultPendingIntent = 141 | PendingIntent.getActivity( 142 | mContext, 143 | 0, 144 | intent, 145 | PendingIntent.FLAG_CANCEL_CURRENT 146 | ); 147 | 148 | final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( 149 | mContext); 150 | 151 | final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE 152 | + "://" + mContext.getPackageName() + "/raw/notification"); 153 | 154 | if (!TextUtils.isEmpty(imageUrl)) { 155 | 156 | if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) { 157 | 158 | Bitmap bitmap = getBitmapFromURL(imageUrl); 159 | 160 | if (bitmap != null) { 161 | showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound); 162 | } else { 163 | showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound); 164 | } 165 | } 166 | } else { 167 | showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound); 168 | playNotificationSound(); 169 | } 170 | } 171 | 172 | private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) { 173 | 174 | NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); 175 | 176 | inboxStyle.addLine(message); 177 | 178 | Notification notification; 179 | notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0) 180 | .setAutoCancel(true) 181 | .setContentTitle(title) 182 | .setContentIntent(resultPendingIntent) 183 | .setSound(alarmSound) 184 | .setStyle(inboxStyle) 185 | .setWhen(getTimeMilliSec(timeStamp)) 186 | .setSmallIcon(R.mipmap.ic_launcher) 187 | .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon)) 188 | .setContentText(message) 189 | .build(); 190 | 191 | NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE); 192 | notificationManager.notify(NOTIFICATION_ID, notification); 193 | } 194 | 195 | private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) { 196 | NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(); 197 | bigPictureStyle.setBigContentTitle(title); 198 | bigPictureStyle.setSummaryText(Html.fromHtml(message).toString()); 199 | bigPictureStyle.bigPicture(bitmap); 200 | Notification notification; 201 | notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0) 202 | .setAutoCancel(true) 203 | .setContentTitle(title) 204 | .setContentIntent(resultPendingIntent) 205 | .setSound(alarmSound) 206 | .setStyle(bigPictureStyle) 207 | .setWhen(getTimeMilliSec(timeStamp)) 208 | .setSmallIcon(R.mipmap.ic_launcher) 209 | .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon)) 210 | .setContentText(message) 211 | .build(); 212 | 213 | NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE); 214 | notificationManager.notify(NOTIFICATION_ID_BIG_IMAGE, notification); 215 | } 216 | 217 | /** 218 | * Downloading push notification image before displaying it in 219 | * the notification tray 220 | */ 221 | public Bitmap getBitmapFromURL(String strURL) { 222 | try { 223 | URL url = new URL(strURL); 224 | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 225 | connection.setDoInput(true); 226 | connection.connect(); 227 | InputStream input = connection.getInputStream(); 228 | Bitmap myBitmap = BitmapFactory.decodeStream(input); 229 | return myBitmap; 230 | } catch (IOException e) { 231 | e.printStackTrace(); 232 | return null; 233 | } 234 | } 235 | 236 | // Playing notification sound 237 | public void playNotificationSound() { 238 | try { 239 | Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE 240 | + "://" + mContext.getPackageName() + "/raw/notification"); 241 | Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound); 242 | r.play(); 243 | } catch (Exception e) { 244 | e.printStackTrace(); 245 | } 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/util/SharedPrefsUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright (C) 2017 Safaricom, Ltd. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * * you may not use this file except in compliance with the License. 7 | * * You may obtain a copy of the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, 13 | * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * * See the License for the specific language governing permissions and 15 | * * limitations under the License. 16 | * 17 | */ 18 | 19 | package com.myduka.app.util; 20 | 21 | import android.content.Context; 22 | import android.content.SharedPreferences; 23 | 24 | /** 25 | * Created on 7/4/2017. 26 | */ 27 | 28 | public class SharedPrefsUtil { 29 | private static final String SHARED_PREFER_FILE_NAME = "keys"; 30 | private SharedPreferences pref; 31 | private SharedPreferences.Editor editor; 32 | 33 | /** 34 | * Retrieve data from preference: 35 | */ 36 | 37 | public SharedPrefsUtil(Context context) { 38 | int PRIVATE_MODE = 0; 39 | pref = context.getSharedPreferences(SHARED_PREFER_FILE_NAME, PRIVATE_MODE); 40 | editor = pref.edit(); 41 | editor.apply(); 42 | } 43 | 44 | public void saveFirebaseRegistrationID(String firebaseRegId) { 45 | editor.putString("regId", firebaseRegId); 46 | editor.commit(); 47 | } 48 | 49 | public String getFirebaseRegistrationID() { 50 | return pref.getString("regId", null); 51 | } 52 | 53 | public void saveIsFirstTime(boolean isFirstTime) { 54 | editor.putBoolean("firstTime", isFirstTime); 55 | editor.commit(); 56 | } 57 | 58 | public boolean getIsFirstTime() { 59 | return pref.getBoolean("firstTime", false); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /app/src/main/java/com/myduka/app/util/Utils.java: -------------------------------------------------------------------------------- 1 | package com.myduka.app.util; 2 | 3 | import android.util.Base64; 4 | 5 | import java.text.SimpleDateFormat; 6 | import java.util.Date; 7 | import java.util.Locale; 8 | 9 | /** 10 | * Created by miles on 23/11/2017. 11 | * Taken from https://github.com/bdhobare/mpesa-android-sdk 12 | */ 13 | 14 | public class Utils { 15 | 16 | public static String getTimestamp() { 17 | return new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date()); 18 | } 19 | 20 | public static String sanitizePhoneNumber(String phone) { 21 | 22 | if (phone.equals("")) { 23 | return ""; 24 | } 25 | 26 | if (phone.length() < 11 & phone.startsWith("0")) { 27 | String p = phone.replaceFirst("^0", "254"); 28 | return p; 29 | } 30 | if (phone.length() == 13 && phone.startsWith("+")) { 31 | String p = phone.replaceFirst("^+", ""); 32 | return p; 33 | } 34 | return phone; 35 | } 36 | 37 | public static String getPassword(String businessShortCode, String passkey, String timestamp) { 38 | String str = businessShortCode + passkey + timestamp; 39 | //encode the password to Base64 40 | return Base64.encodeToString(str.getBytes(), Base64.NO_WRAP); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /app/src/main/res/color/gray_highlight.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/color/list_number_highlight.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/color/white_highlight_text.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/apples.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/safaricom/LNMOnlineAndroidSample/74eced63f0cd5fd2f9869f9fcaf9b14823dcadb8/app/src/main/res/drawable/apples.jpg -------------------------------------------------------------------------------- /app/src/main/res/drawable/bananas.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/safaricom/LNMOnlineAndroidSample/74eced63f0cd5fd2f9869f9fcaf9b14823dcadb8/app/src/main/res/drawable/bananas.jpg -------------------------------------------------------------------------------- /app/src/main/res/drawable/calc_btn_bg.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | 23 | 25 | 29 | 31 | 32 | 33 | 34 | 35 | 36 | 38 | 42 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/calc_btn_bg_square.xml: -------------------------------------------------------------------------------- 1 | 2 | 19 | 20 | 21 | 22 | 23 | 25 | 29 | 31 | 32 | 33 | 34 | 35 | 36 | 38 | 42 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/fruits_a.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/safaricom/LNMOnlineAndroidSample/74eced63f0cd5fd2f9869f9fcaf9b14823dcadb8/app/src/main/res/drawable/fruits_a.jpg -------------------------------------------------------------------------------- /app/src/main/res/drawable/fruits_b.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/safaricom/LNMOnlineAndroidSample/74eced63f0cd5fd2f9869f9fcaf9b14823dcadb8/app/src/main/res/drawable/fruits_b.jpg -------------------------------------------------------------------------------- /app/src/main/res/drawable/fruits_c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/safaricom/LNMOnlineAndroidSample/74eced63f0cd5fd2f9869f9fcaf9b14823dcadb8/app/src/main/res/drawable/fruits_c.jpg -------------------------------------------------------------------------------- /app/src/main/res/drawable/tomatoes.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/safaricom/LNMOnlineAndroidSample/74eced63f0cd5fd2f9869f9fcaf9b14823dcadb8/app/src/main/res/drawable/tomatoes.JPG -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 18 | 19 | 25 | 26 | 30 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_notification.xml: -------------------------------------------------------------------------------- 1 | 18 | 19 | 27 | 28 | 38 | 39 | 45 | 46 | -------------------------------------------------------------------------------- /app/src/main/res/layout/category_list_item.xml: -------------------------------------------------------------------------------- 1 | 18 | 19 | 28 | 29 | 34 | 35 | 40 | 41 | 48 | 49 | 58 | 59 |