Paytm is the most popular mobile wallet and payment method used in India. So I thought to publish a Paytm Integration in Android Example.
In this post, we will learn how can we add a Pay with Paytm method in our android application.
There is the official documentation about integrating Paytm at PayWithPaytm/Developer but that is very confusing, and if you are a newbie then you can face troubles. Here I will show you every step in detailed explanation so you can easily integrate Paytm payments in your application.
Table of Contents
Getting Credentials from Paytm
The first step is getting credential from Paytm. Paytm provides it to all the merchants. So you need to signup as a merchant in Paytm. But the problem is it takes time, and you need to submit some docs like GST, Bank Account details.
But you do not need to worry as the developer can get sandbox access for development purposes.
- Go to this link and sign in with your Paytm account.
- You do not need to submit any details after Signup just click on Sandbox Access link as shown in the below image.
- Now you will see your Sandbox Credential.
- You are going to use the above credentials. Now lets integrate the Paytm Payment.
How to Integrate Paytm Payment into Android Application?
Let’s first understand how we add Paytm Payment in our Application. We need to perform these two steps.
- Generate CHECKSUM on our server.
- Accept Payment with Paytm SDK.
We need to generate the Checksum on our server, so the process requires some server-side implementation as well. And here on the server side, I am going to use PHP with Xampp Server.
And for sending Request from android side I will be using Retrofit.
Paytm Integration in Android Example
Configuring the Paytm Checksum Kit
Now let’s start the real process. We will start with the server-side implementation.
- Open XAMPP Server and Start the Server. (Skip this step if you are using a live server).
- Then download the Paytm App Checksum Kit. And paste it to your server’s root directory. (For XAMPP it is c:/xampp/htdocs by default)
- I have renamed the folder to only paytm to make it short and simple.
- Inside the folder we have a file named generateChecksum.php and we need to use it for generating checksum.
- But first we need to put our Paytm Merchant Key in the configuration.
- Go to config_paytm.php (it is inside the lib folder paytm/lib/config_paytm.php), and put your Paytm Merchant Key.
1 2 3 4 5 6 7 8 |
<?php //Change the value of PAYTM_MERCHANT_KEY constant with details received from Paytm. define('PAYTM_MERCHANT_KEY', 'YOUR_MERCHANT_KEY_HERE'); ?> |
- That’s it for the server side implementation, we just need to route to generateChecksum.php file. So it is localhost/paytm/generateChecksum.php.
But remember using localhost will not work you need to find the IP. You can see it using the ipconfig command, and if you are using a live server, then you can use the URL with your domain.Â
Now, let’s move ahead by creating an Android Studio Project.
Integrating Paytm Payment in Android Project
Creating a New Project
- First, we will create a new Android Studio Project. I have create a project named PaytmPaymentSample with an Empty Activity.
Adding Paytm SDK
- Now download the Paytm SDK. Inside the SDK you will find a file named PGSDK_V2.1.jar. We need to add this file in our project dependencies.
- So first on the project explorer select Project.
- Then inside app/lib paste the PGSDK_V2.1.jar that we downloaded.
- Now click on File->Project Structure.
- Now from the top tabs go to dependency, and from the right green plus icon select jar dependency.
- Now select the jar from the lib folder that you added, and hit ok.
- That’s it the Paytm SDK is added.
Adding Permissions and Paytm Activity
- We need to add INTERNET and ACCESS_NETWORK_STATE permission, and PaytmPGActivity (The activity comes with the Paytm SDK that we already added).
- So open AndroidManifest.xml and modify it as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="simplifiedcoding.net.paytmpaymentsample"> <!-- the following two permissions are needed --> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- Add this activity to your manifest it comes with the Paytm SDK --> <activity android:name="com.paytm.pgsdk.PaytmPGActivity" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation|keyboard"/> </application> </manifest> |
Adding Retrofit and Gson
- As I told you above that, we are going to use the Retrofit Library for sending network request. So for this, we need to Add Retrofit and Gson.
- Come inside your app level build.gradle file and add both libraries.
1 2 3 4 |
compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.retrofit2:converter-gson:2.2.0' |
Defining Constants
- Now, we will define all the required constants in a separate class. For this create a new class named Constants.java and define the following inside.
- Remember you need to change the first 3 values according to the Paytm Credentials you got.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package simplifiedcoding.net.paytmpaymentsample; /** * Created by Belal on 1/10/2018. */ public class Constants { public static final String M_ID = "xxxxxxxx"; //Paytm Merchand Id we got it in paytm credentials public static final String CHANNEL_ID = "WEB"; //Paytm Channel Id, got it in paytm credentials public static final String INDUSTRY_TYPE_ID = "Retail"; //Paytm industry type got it in paytm credential public static final String WEBSITE = "APP_STAGING"; public static final String CALLBACK_URL = "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp"; } |
Creating User Interface
- Now we will create a very Simple User Interface. So come inside activity_main.xml and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context="simplifiedcoding.net.paytmpaymentsample.MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="120dp" android:layout_height="90dp" android:background="@drawable/macbook_air" android:padding="4dp" /> <TextView android:id="@+id/textViewTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_toRightOf="@id/imageView" android:text="Apple MacBook Air Core i5 5th Gen - (8 GB/128 GB SSD/Mac OS Sierra)" android:textAppearance="@style/Base.TextAppearance.AppCompat.Small" android:textColor="#000000" /> <TextView android:id="@+id/textViewShortDesc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textViewTitle" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:layout_toRightOf="@id/imageView" android:text="13.3 Inch, 256 GB" android:textAppearance="@style/Base.TextAppearance.AppCompat.Small" /> <TextView android:id="@+id/textViewRating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textViewShortDesc" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:layout_toRightOf="@id/imageView" android:background="@color/colorPrimary" android:paddingLeft="15dp" android:paddingRight="15dp" android:text="4.7" android:textAppearance="@style/Base.TextAppearance.AppCompat.Small.Inverse" android:textStyle="bold" /> <TextView android:id="@+id/textViewPrice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textViewRating" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:layout_toRightOf="@id/imageView" android:text="10.00" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" android:textStyle="bold" /> <Button android:id="@+id/buttonBuy" android:layout_toRightOf="@id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textViewPrice" android:text="Buy" /> </RelativeLayout> |
- The above code will generate the following layout.
- Make sure you add an image named macbook_air in the drawable folder. Or if the name of your image is different, then change it in the ImageView of your layout.
Creating Retrofit Models and Interface
Creating Models
We need two classes one is for CHECKSUM and other is for storing Paytm payment details.
- First create a class named Checksum.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package simplifiedcoding.net.paytmpaymentsample; import com.google.gson.annotations.SerializedName; /** * Created by Belal on 1/10/2018. */ public class Checksum { @SerializedName("CHECKSUMHASH") private String checksumHash; @SerializedName("ORDER_ID") private String orderId; @SerializedName("payt_STATUS") private String paytStatus; public Checksum(String checksumHash, String orderId, String paytStatus) { this.checksumHash = checksumHash; this.orderId = orderId; this.paytStatus = paytStatus; } public String getChecksumHash() { return checksumHash; } public String getOrderId() { return orderId; } public String getPaytStatus() { return paytStatus; } } |
- Now create Paytm.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
package simplifiedcoding.net.paytmpaymentsample; import android.util.Log; import com.google.gson.annotations.SerializedName; import java.util.UUID; /** * Created by Belal on 1/10/2018. */ public class Paytm { @SerializedName("MID") String mId; @SerializedName("ORDER_ID") String orderId; @SerializedName("CUST_ID") String custId; @SerializedName("CHANNEL_ID") String channelId; @SerializedName("TXN_AMOUNT") String txnAmount; @SerializedName("WEBSITE") String website; @SerializedName("CALLBACK_URL") String callBackUrl; @SerializedName("INDUSTRY_TYPE_ID") String industryTypeId; public Paytm(String mId, String channelId, String txnAmount, String website, String callBackUrl, String industryTypeId) { this.mId = mId; this.orderId = generateString(); this.custId = generateString(); this.channelId = channelId; this.txnAmount = txnAmount; this.website = website; this.callBackUrl = callBackUrl; this.industryTypeId = industryTypeId; Log.d("orderId", orderId); Log.d("customerId", custId); } public String getmId() { return mId; } public String getOrderId() { return orderId; } public String getCustId() { return custId; } public String getChannelId() { return channelId; } public String getTxnAmount() { return txnAmount; } public String getWebsite() { return website; } public String getCallBackUrl() { return callBackUrl; } public String getIndustryTypeId() { return industryTypeId; } /* * The following method we are using to generate a random string everytime * As we need a unique customer id and order id everytime * For real scenario you can implement it with your own application logic * */ private String generateString() { String uuid = UUID.randomUUID().toString(); return uuid.replaceAll("-", ""); } } |
Creating Retrofit API Interface
- Create a new interface named Api.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package simplifiedcoding.net.paytmpaymentsample; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * Created by Belal on 1/10/2018. */ public interface Api { //this is the URL of the paytm folder that we added in the server //make sure you are using your ip else it will not work String BASE_URL = "http://192.168.101.1/paytm/"; @FormUrlEncoded @POST("generateChecksum.php") Call<Checksum> getChecksum( @Field("MID") String mId, @Field("ORDER_ID") String orderId, @Field("CUST_ID") String custId, @Field("CHANNEL_ID") String channelId, @Field("TXN_AMOUNT") String txnAmount, @Field("WEBSITE") String website, @Field("CALLBACK_URL") String callbackUrl, @Field("INDUSTRY_TYPE_ID") String industryTypeId ); } |
- If you don’t know anything about using Retrofit you better go through the Retrofit Tutorial first.
- Now come to MainActivity.java and write the following code to complete our project.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
package simplifiedcoding.net.paytmpaymentsample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.paytm.pgsdk.PaytmOrder; import com.paytm.pgsdk.PaytmPGService; import com.paytm.pgsdk.PaytmPaymentTransactionCallback; import java.util.HashMap; import java.util.Map; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; //implementing PaytmPaymentTransactionCallback to track the payment result. public class MainActivity extends AppCompatActivity implements PaytmPaymentTransactionCallback { //the textview in the interface where we have the price TextView textViewPrice; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting the textview textViewPrice = findViewById(R.id.textViewPrice); //attaching a click listener to the button buy findViewById(R.id.buttonBuy).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //calling the method generateCheckSum() which will generate the paytm checksum for payment generateCheckSum(); } }); } private void generateCheckSum() { //getting the tax amount first. String txnAmount = textViewPrice.getText().toString().trim(); //creating a retrofit object. Retrofit retrofit = new Retrofit.Builder() .baseUrl(Api.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); //creating the retrofit api service Api apiService = retrofit.create(Api.class); //creating paytm object //containing all the values required final Paytm paytm = new Paytm( Constants.M_ID, Constants.CHANNEL_ID, txnAmount, Constants.WEBSITE, Constants.CALLBACK_URL, Constants.INDUSTRY_TYPE_ID ); //creating a call object from the apiService Call<Checksum> call = apiService.getChecksum( paytm.getmId(), paytm.getOrderId(), paytm.getCustId(), paytm.getChannelId(), paytm.getTxnAmount(), paytm.getWebsite(), paytm.getCallBackUrl(), paytm.getIndustryTypeId() ); //making the call to generate checksum call.enqueue(new Callback<Checksum>() { @Override public void onResponse(Call<Checksum> call, Response<Checksum> response) { //once we get the checksum we will initiailize the payment. //the method is taking the checksum we got and the paytm object as the parameter initializePaytmPayment(response.body().getChecksumHash(), paytm); } @Override public void onFailure(Call<Checksum> call, Throwable t) { } }); } private void initializePaytmPayment(String checksumHash, Paytm paytm) { //getting paytm service PaytmPGService Service = PaytmPGService.getStagingService(); //use this when using for production //PaytmPGService Service = PaytmPGService.getProductionService(); //creating a hashmap and adding all the values required Map<String, String> paramMap = new HashMap<>(); paramMap.put("MID", Constants.M_ID); paramMap.put("ORDER_ID", paytm.getOrderId()); paramMap.put("CUST_ID", paytm.getCustId()); paramMap.put("CHANNEL_ID", paytm.getChannelId()); paramMap.put("TXN_AMOUNT", paytm.getTxnAmount()); paramMap.put("WEBSITE", paytm.getWebsite()); paramMap.put("CALLBACK_URL", paytm.getCallBackUrl()); paramMap.put("CHECKSUMHASH", checksumHash); paramMap.put("INDUSTRY_TYPE_ID", paytm.getIndustryTypeId()); //creating a paytm order object using the hashmap PaytmOrder order = new PaytmOrder(paramMap); //intializing the paytm service Service.initialize(order, null); //finally starting the payment transaction Service.startPaymentTransaction(this, true, true, this); } //all these overriden method is to detect the payment result accordingly @Override public void onTransactionResponse(Bundle bundle) { Toast.makeText(this, bundle.toString(), Toast.LENGTH_LONG).show(); } @Override public void networkNotAvailable() { Toast.makeText(this, "Network error", Toast.LENGTH_LONG).show(); } @Override public void clientAuthenticationFailed(String s) { Toast.makeText(this, s, Toast.LENGTH_LONG).show(); } @Override public void someUIErrorOccurred(String s) { Toast.makeText(this, s, Toast.LENGTH_LONG).show(); } @Override public void onErrorLoadingWebPage(int i, String s, String s1) { Toast.makeText(this, s, Toast.LENGTH_LONG).show(); } @Override public void onBackPressedCancelTransaction() { Toast.makeText(this, "Back Pressed", Toast.LENGTH_LONG).show(); } @Override public void onTransactionCancel(String s, Bundle bundle) { Toast.makeText(this, s + bundle.toString(), Toast.LENGTH_LONG).show(); } } |
- Now you can try running your application.
- Bingo! it is working fine.
Paytm Integration in Android Example – Source Code
- If you are having some problem following this example, then you get my source code from my GitHub Repository. The link is given below.
[sociallocker id=5688] Paytm Integration in Android Example [/sociallocker]
So that’s all for this Paytm Integration in Android Example friends. I hope you found it useful if you did, please SHARE it with your friends.
And if you are having any query regarding this Paytm Integration in Android Example then don’t hesitate in commenting. Thank You 🙂