Paytm Payment Gateway in Android

Image source: https://unsplash.com/photos/E2HgkL3LaFE

 

Paytm is that the most well liked mobile wallet and payment method utilized in India. So I assumed to publish a Paytm Integration in Android Example.

In this post, we’ll determine 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’s very confusing, and if you are a newbie then you’ll face troubles. Here I’ll show you each step in a very detailed explanation so you will be able to easily integrate Paytm payments in your application.

How to get Credentials from Paytm:

The first step is getting a credential from Paytm. Paytm provides it to any or all the merchants. So you would like to signup as a merchant in Paytm. But the matter is it takes time, and you would like to submit some docs like GST, bank account details.

Go to this link and sign up along with your Paytm account. you’ll be able to also create an account from the dashboard also if you don’t have any.
Go to the Analytics menu on the left side of the screen, then click on the Get Test Key button.

 

  • it will give you Test API Details for your demo.
  • We can use merchant id and merchant key in the future.

 

How to Integrate Paytm Payment into Android Application?

Let’s first understand how we add Paytm Payment in our Application. we want to perform these two steps.

 

  1. Generate CHECKSUM on the server.
  2. Accept Payment with Paytm SDK.

We need to come up with the Checksum on the server, that the process requires some server-side implementation likewise. And here on the server-side, you can get serverside checksum from here.

Download this kit and set your Paytm Test Merchant Key in config_paytm.php. Here is the path paytm>lib>config_paytm.php, (remember to set your Merchant key, not Merchant  Id. do not confuse in both secrets)

We have completed Server-side Integration, Now it’s time to integrate SDK Client-side in Android.

Paytm Integration in Android Example:

  • Configuring the Paytm Checksum Kit
    • You can download Paytm Checksum Kit from here.
    • Remember using localhost won’t work you wish to search out the IP. you’ll be able to see it using the ipconfig command, and if you’re employing a live server, then you’ll use the URL along with your domain.
    • Now, let’s move ahead by creating an Android Studio Project.
  • Integrating Paytm Payment in Android Project:

    • First, we are going to create a brand new Android Studio Project. I’ve got create a project named PaytmPayment with an Empty Activity.
  • Adding Paytm SDK:

    • Add this to your App-level build. Gradle file dependency section, That’s it the Paytm SDK is added.
dependencies {
   //...

    // paytm dependency
    implementation('com.paytm:pgplussdk:1.2.3') {
        transitive = true;
    }
}
  • Adding Permissions and Paytm Activity

    • We need to feature INTERNET, READ or WRITE SMS and ACCESS_NETWORK_STATE permission, and PaytmPGActivity (The activity comes with the Paytm SDK that we already added).
    • So my AndroidManifest.xml looks as below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kartik.work.paytmpayment">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <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>

        <activity android:name="com.paytm.pgsdk.PaytmPGActivity"
            android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation|keyboard"/>

        <activity android:name=".checksum" />

    </application>

</manifest>

 

  • Creating User Interface
    • Now we’ll create an awfully Simple interface. So come inside activity_main.xml and write the subsequent code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:weightSum="1">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Paytm Integrations"
                android:textStyle="bold"
                android:textSize="24dip"
                android:layout_marginTop="20dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="10dip"/>



        </LinearLayout>


        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:id="@+id/orderid"
            android:hint="Order ID" />


        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:id="@+id/custid"
            android:hint="Customer ID"/>

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:id="@+id/pay_amt"
            android:hint="pay amount"/>


        <Button
            android:layout_width="217dp"
            android:layout_height="wrap_content"
            android:id="@+id/start_transaction"
            android:text="Start Payment"
            android:onClick="onStartTransaction"
            android:layout_gravity="center"
            android:textStyle="bold"
            android:textSize="16dip"
            android:layout_marginTop="30dip"
            android:layout_weight="2.05" />

    </LinearLayout>

</RelativeLayout>
  • Creating Models

    • We need two classes one is for CHECKSUM and the other is for storing Paytm payment details.
    • First, create a class named Checksum.java and write the code that is given below.
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;

import com.paytm.pgsdk.PaytmOrder;
import com.paytm.pgsdk.PaytmPGService;
import com.paytm.pgsdk.PaytmPaymentTransactionCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by kartik-vaghani on 24-07-2021.
 */

public class checksum extends AppCompatActivity implements PaytmPaymentTransactionCallback {

    String custid="",pay_amt="", orderId="", mid="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        Intent intent = getIntent();
        orderId = intent.getExtras().getString("orderid");
        custid = intent.getExtras().getString("custid");
        pay_amt = intent.getExtras().getString("pay_amt_");

        mid = "[your_marchant_id]";
        sendUserDetailTOServerdd dl = new sendUserDetailTOServerdd();
        dl.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    }

    public class sendUserDetailTOServer extends AsyncTask<ArrayList<String>, Void, String> {

        private ProgressDialog dialog = new ProgressDialog(checksum.this);

        //private String orderId , mid, custid, amt;
        String url ="your_php_checksum_kit_server_url"; 
        String varifyurl = "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp";
        String CHECKSUMHASH ="";

                @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Please wait");
            this.dialog.show();
        }

        protected String doInBackground(ArrayList<String>... alldata) {
            JSONParser jsonParser = new JSONParser(checksum.this);
            String param=
                    "MID="+mid+
                    "&ORDER_ID=" + orderId+
                    "&CUST_ID="+custid+
                    "&CHANNEL_ID=WAP"+
                            "&TXN_AMOUNT="+pay_amt+
                            "&WEBSITE=WEBSTAGING"+
                            "&CALLBACK_URL="+ varifyurl+"&INDUSTRY_TYPE_ID=Retail";

            JSONObject jsonObject = jsonParser.makeHttpRequest(url,"POST",param);
            if(jsonObject != null){
                Log.e("CheckSum result >>",jsonObject.toString());
                try {

                    CHECKSUMHASH=jsonObject.has("CHECKSUMHASH")?jsonObject.getString("CHECKSUMHASH"):"";
                    Log.e("CheckSum result >>",CHECKSUMHASH);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return CHECKSUMHASH;
        }

        @Override
        protected void onPostExecute(String result) {
            Log.e(" setup acc ","  signup result  " + result);
            if (dialog.isShowing()) {
                dialog.dismiss();
            }

            PaytmPGService Service = PaytmPGService.getStagingService();
           // when app is ready to publish use production service
            // PaytmPGService  Service = PaytmPGService.getProductionService();

            // now call paytm service here
            //below parameter map is required to construct PaytmOrder object, Merchant should replace below map values with his own values
            HashMap<String, String> paramMap = new HashMap<String, String>();
            //these are mandatory parameters
            paramMap.put("MID", mid); //MID provided by paytm
            paramMap.put("ORDER_ID", orderId);
            paramMap.put("CUST_ID", custid);
            paramMap.put("CHANNEL_ID", "WAP");
            paramMap.put("TXN_AMOUNT",pay_amt);
            paramMap.put("WEBSITE", "WEBSTAGING");
            paramMap.put("CALLBACK_URL" ,varifyurl);

            paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
            //paramMap.put("PAYMENT_TYPE_ID" ,"CC");    // no need
            paramMap.put("INDUSTRY_TYPE_ID", "Retail");

            PaytmOrder Order = new PaytmOrder(paramMap);
            Log.e("checksum ", "param "+ paramMap.toString());
            Service.initialize(Order,null);
            // start payment service call here
            Service.startPaymentTransaction(checksum.this, true, true,
                    checksum.this  );


        }

    }


    @Override
    public void onTransactionResponse(Bundle bundle) {
        Log.e("checksum ", " respon true " + bundle.toString());
    }

    @Override
    public void networkNotAvailable() {

    }

    @Override
    public void clientAuthenticationFailed(String s) {

    }

    @Override
    public void someUIErrorOccurred(String s) {
        Log.e("checksum ", " ui fail respon  "+ s );
    }

    @Override
    public void onErrorLoadingWebPage(int i, String s, String s1) {
        Log.e("checksum ", " error loading pagerespon true "+ s + "  s1 " + s1);
    }

    @Override
    public void onBackPressedCancelTransaction() {
        Log.e("checksum ", " cancel call back respon  " );
    }

    @Override
    public void onTransactionCancel(String s, Bundle bundle) {
        Log.e("checksum ", "  transaction cancel " );
    }


}
    • In the onCreate method of checksum class I can use String type variable “mid” to pass your Test Merchant ID  (remember to set your Merchant id, not Merchant  key. do not confuse in both secrets.)
    • In  sendUserDetailTOServer class, set your PaytmChecksum kit(php) url.
    • Set verify URL as it is.
    • Now, create a class named JsonParser.java and write the code that is given below.
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by kartik-vaghani on 24-07-2021.
 */
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    HttpURLConnection urlConnection = null;
    // variable to hold context
    private Context context;
    // constructor
    public JSONParser(Context context){
        this.context=context;
    }


    public JSONObject makeHttpRequest(String url, String method, String params) {

        // boolean isReachable =Config.isURLReachable(context);
        // Making HTTP request
        try {
            String retSrc="";
            char current = '0';

            URL url1 = new URL(url);
            // check for request method
            HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
            if (method == "POST") {
                // request method is POST
                urlConnection.setDoOutput(true);
                urlConnection.setRequestMethod("POST");
                urlConnection.setFixedLengthStreamingMode(params.getBytes().length);
                urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
                out.print(params);
                out.close();
            }
            InputStream in = urlConnection.getInputStream();

            InputStreamReader isw = new InputStreamReader(in);

            byte[] bytes = new byte[10000];
            StringBuilder x = new StringBuilder();
            int numRead = 0;
            while ((numRead = in.read(bytes)) >= 0) {
                x.append(new String(bytes, 0, numRead));
            }
            retSrc=x.toString();

           // Log.e("json parse ", " the value is "+ retSrc);

            jObj = new JSONObject(retSrc);
        } catch (Exception e) {
            e.printStackTrace();
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "Connectivity issue. Please try again later.", Toast.LENGTH_LONG).show();
                }
            });
            return null;
        }finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
       // Log.e("jsonpardse ", "respone is "+ jObj.toString() );
        return jObj;
    }
}
    • With the use of the above, both model classes generate checksum tokens for make payments.
  • Now Write code in MainActivity.java:

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText orderid, custid , payamt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //initOrderId();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        Button btn = (Button) findViewById(R.id.start_transaction);
        orderid = (EditText) findViewById(R.id.orderid);
        custid = (EditText) findViewById(R.id.custid);
        payamt = (EditText) findViewById(R.id.pay_amt);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, checksum.class);
                intent.putExtra("orderid", orderid.getText().toString());
                intent.putExtra("custid", custid.getText().toString());
                intent.putExtra("pay_amt_", payamt.getText().toString());
                startActivity(intent);
            }
        });

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 101);
        }

    }
}
    • Set order id, customer id, payment amount from your side, click on the start payment button and it will be done.

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories