Paytm Payment Gateway Integration In Android

0Shares

Paytm Payment Gateway Integration In Android

Today in this article you learn Paytm payment gateway integration in android. today everyone knows about what is Paytm? currently in India paytm is the best payment gateway. Paytm have 350 million active users in India. Paytm have too many options for payment methods like debit cards, credit card, UPI, Paytm wallet, Paytm payment bank. You can create a paytm merchant account or Paytm for a business account to get pay on paytm.paytm has more than payment options compare to PayUMoney.

how paytm merchant account work? All the payment is done through paytm is receive on the paytm server and transfer into the merchant account.

Paytm payment gateway is divide into three pricing categories,

  1. individual.
  2. small business.
  3. big business.

Paytm Money transfer limit is based on the above-given categories. You can check complete Paytm Pricing here.

Life Cycle of paytmFor Paytm payment integration first, you need a paytm merchant account.

How to make a paytm merchant account?

  • first, go to the official site of Paytm. create an account using a mobile number. for testing purposes, you do not need to active account but for production, you need an active account.
  • after creating a merchant account it time for integrating with the android platform.so let’s get started.

For testing, we use the testing API details. for testing API details you need to login and there you got your test API details like test merchant key, test merchant ID, Transaction URL, Transaction Status URL, etc.

testing key

Paytm Payment Gateway Integration In Android

1) Add dependence

  • starting days in paytm give jar file but after 2 years paytm introduces dependence for android and Ios.but now jar file is no longer available. You must add below a given line of code into the android project Gradle file(module:app).
  • Paytm official has introduced some new parameters for integration so if you want to check click here.
  • Note: paytm official docs have some incorrect information like mobile no, email, etc.
implementation 'com.paytm:pgplussdk:1.1.2' // add this dependance in to gradle file(module:app) 
implementation("com.squareup.okhttp3:okhttp:4.1.0") //okhttp for api

2)Add run time permission and PaytmActivity

  • you need two permission READ SMS and RECEIVE SMS. API level 25  after you need run time permission from java file.
  • why READ SMS and RECEIVE SMS permission needed? when your application in the production stage, the bank sends OTP  and for auto-read OTP in payment activity required this two permission.
  • Paytm is provide paytm UI for start transaction using  com.paytm.pgsdk.PaytmPGActivity.  so we add in an android manifest file in this code snippets.
  • Paytm SDK already has paytm activity class file, Just add below given line in a manifest file inside application tag.
//permission add in android manifes file 
<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"/> 
//add this activity under application tag in manifest file
 <activity android:name="com.paytm.pgsdk.PaytmPGActivity" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation|keyboard"/>

3) Upload file on the server 

  • In the early section when we create an account that time we got it over TEST merchant key and  TEST merchant ID  and other details
  • now you need to upload some files on the server to generate the checksum. As paytm official website says “Checksumhash is a signature used by Paytm to ensure that request has not tampered”. download that file Click here.
  • download file after you see the lib folder, in this folder two files. you need to change in config_paytm.php, put your merchant Key, and upload all 3 files on the server. This is the file you need to call from android to generate the checksum. so your checksum URL will look like – http://www.your-domain/foldername/generateChecksum.php
  • If you don’t want to buy any paid hosting server so you may go with a free server like 000webhost.com.

4)Generate Checksum

  • if you read paytm official docs file you see some important point.
  1. ORDER_ID is every time unique generate
  2. Required parameters ORDER_ID , CUST_ID, MID, TXN_AMOUNT, CHANNEL_ID, WEBSITE.

5)Android Code

  • we take transaction amount from XML file and ORDER_ID is generating using Random() function.

paytm_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:viewBindingIgnore="true"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:src="@drawable/paytm" />
    <TextView
        android:id="@+id/txt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:gravity="center"
        android:layout_margin="10dp"
        android:textColor="@color/colorPrimaryDark"
        android:text="Paytm payment gateway intigration in android"/>
    <TextView
        android:id="@+id/txt2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:gravity="center"
        android:textColor="@color/colorPrimaryDark"
        android:text="androidcrown.com"/>
    <EditText
        android:id="@+id/txtamont"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginTop="25dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:hint="Enter amount"
        android:inputType="number"/>
    <Button
        android:id="@+id/pay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:layout_marginLeft="15dp"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        android:textAllCaps="false"
        android:textSize="18sp"
        android:layout_marginRight="15dp"
        android:text="Paynow with paytm"/>

    <TextView
        android:id="@+id/payment_response"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimaryDark"
        android:layout_marginTop="25dp"
        android:textSize="14sp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"/>

</LinearLayout>

 MainActivity.java

  • MainActivity.java file in we add runtime permission for READ SMS and RECEIVE SMS.
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); }
  • after add permission we initialization view by creating init() method.in this, we get edit text, button widget view, and progress dialog.
  • Onclick of paynow button we call GenerateCheck() method in this method first we generate random ORDER_ID using Random class and get transaction amount from edit text and store in TXNAMOUNT variable.
  • now you need to call generateChecksum.php file by POST parameters. You may use Volley, Okhttp, Retrofit. I use okhttp method by calling OkHttpHandler_Paytm, this calls is generated in inner class in MainActivity.java
  • their parameters are –MID(Merchant ID), Order Id, Customer ID, Website, Amount, Channel ID, Callback URL, and Industry type.
  • Callback URL mention on paytm official doc is not working. Please use the given URL as a callback.
  • once you get checksum from server its time verify with Paytm server.
  • by calling onStartTransaction() method we call paytm_Service.startPaymentTransaction(). this service class has seven method.

Full Source Code

package com.androidcrown.paytm;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.snackbar.Snackbar;
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.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    // Key in your staging and production MID available in your dashboard
    String MID = "put your merchant ID here";//put your Merchant ID here
    String checksum;
    String orderId;
    String cusID = "78945678787";//random customer id
    // This is the staging value. Production value is available in your dashboard
    String channelId = "WAP";
    String txnAmount;
    String industryTypeId = "Retail";
    String website = "WEBSTAGING";
    EditText amount;
    Button paynow;
    TextView response_payment;
    private ProgressDialog pDialog;

    @Override
    protected void onStart() {
        super.onStart();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.paytm_activity);
        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);
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        init();
        paynow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNetworkConnected()) {
                    if (amount.getText().length() > 0) {
                        GenerateCheck();
                    }
                    else {
                        Snackbar.make(findViewById(android.R.id.content), "Enter vaild Amount", Snackbar.LENGTH_LONG).show();
                    }
                } else {
                    Snackbar.make(findViewById(android.R.id.content), "Check Your Internet Connection", Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }

    private void GenerateCheck() {
        initorderID();
        txnAmount = amount.getText().toString();
        OkHttpHandler_Paytm okHttpHandler_forgot = new OkHttpHandler_Paytm();
        okHttpHandler_forgot.execute(AppConstants.url);
    }

    private void initorderID() {
        Random r = new Random(System.currentTimeMillis());
        orderId = "ORDER" + (1 + r.nextInt(3)) * 10000 + r.nextInt(10000);
    }

    private void init() {
        amount = findViewById(R.id.txtamont);
        paynow = findViewById(R.id.pay);
        response_payment = findViewById(R.id.payment_response);
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
    }

    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }


    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

    private class OkHttpHandler_Paytm extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showpDialog();
        }

        @Override
        protected String doInBackground(String... url) {
            OkHttpClient httpClient = new OkHttpClient();

            RequestBody formBody = new FormBody.Builder()
                    .add("MID", MID)
                    .add("ORDER_ID", orderId)
                    .add("CUST_ID", cusID)
                    .add("INDUSTRY_TYPE_ID", industryTypeId)
                    .add("CHANNEL_ID", channelId)
                    .add("TXN_AMOUNT", txnAmount)
                    .add("WEBSITE", website)
                    .add("CALLBACK_URL", "https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=" + orderId)
                    .build();
            Request request = new Request.Builder()
                    .url(url[0])
                    .post(formBody)
                    .build();
            Response response = null;
            try {
                response = httpClient.newCall(request).execute();
                String checksum_response = response.body().string();
                JSONObject ChecksumResponse = new JSONObject(checksum_response);

                if (ChecksumResponse.has("CHECKSUMHASH")) {
                    checksum = ChecksumResponse.getString("CHECKSUMHASH");
                    Log.e("getrespone", String.valueOf(response));
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            hidepDialog();
            if (checksum.trim().length() != 0) {
                onStartTransaction();
            }
        }
    }

    private void onStartTransaction() {
        PaytmPGService Service = PaytmPGService.getStagingService();
        Map<String, String> paramMap = new HashMap<String, String>();

        // these are mandatory parameters

        paramMap.put("CALLBACK_URL", "https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=" + orderId);
        paramMap.put("CHANNEL_ID", channelId);
        paramMap.put("CHECKSUMHASH", checksum);
        paramMap.put("CUST_ID", cusID);
        paramMap.put("INDUSTRY_TYPE_ID", industryTypeId);
        paramMap.put("MID", MID);
        paramMap.put("ORDER_ID", orderId);
        paramMap.put("TXN_AMOUNT", txnAmount);
        paramMap.put("WEBSITE", website);

        PaytmOrder Order = new PaytmOrder(paramMap);
        Service.initialize(Order, null);

        Service.startPaymentTransaction(this, true, true,
                new PaytmPaymentTransactionCallback() {
                    @Override
                    public void onTransactionResponse(Bundle inResponse) {
                        Log.d("LOG", "Payment Transaction is successful " + inResponse);
                        response_payment.setText(inResponse.toString());
                    }

                    @Override
                    public void networkNotAvailable() {
                        // If network is not
                        // available, then this
                        // method gets called.
                    }

                    @Override
                    public void clientAuthenticationFailed(String inErrorMessage) {
                        // This method gets called if client authentication
                        // failed.
                        // Failure may be due to following reasons //
                        // 1. Server error or downtime. // 2. Server unable to
                        // generate checksum or checksum response is not in
                        // proper format. // 3. Server failed to authenticate
                        // that client. That is value of payt_STATUS is 2. //
                        // Error Message describes the reason for failure.
                    }

                    @Override
                    public void someUIErrorOccurred(String inErrorMessage) {
                        // Some UI Error Occurred in Payment Gateway Activity.
                        // // This may be due to initialization of views in
                        // Payment Gateway Activity or may be due to //
                        // initialization of webview.
                        // Error Message details
                        // the error occurred.
                    }

                    @Override
                    public void onErrorLoadingWebPage(int iniErrorCode, String inErrorMessage, String inFailingUrl) {

                    }

                    @Override
                    public void onBackPressedCancelTransaction() {
                        Toast.makeText(MainActivity.this, "Back pressed. Transaction cancelled", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
                        Log.d("LOG", "Payment Transaction Failed " + inErrorMessage);
                        Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show();
                    }
                });
    }
}

AppConstants.java

package com.androidcrown.paytm;

public class AppConstants {
    public  static final String  url = "";//put your checksum generation file url
}

That’s it your application is ready…

You can download the full source code from here…

6)Testing Mobile Number and card details

  • Once you have completed the Paytm integration, you can test your app (or the app provided in this article), using the test mode credentials provided.
Mobile / username 7777777777
OTP 489871

References

Below are useful links you can keep handy while working on this project.
1. PayTM Android SDK documentation
2. PayTM REST API documentation
3. PayTM test mode credentials

Conclusion:

I hope guys you enjoy and learn easily Paytm Payment Gateway Integration In Android for more such examples visit androidcrown.com
if you any query do comment in the below section.

0Shares

Leave a Comment