Integrate Paytm PGSDK_V2.0 Android

12,901

Solution 1

Paytm has change process to increase the security. now in PGSDK_V2.0 first you have to generate through calling the api Checksum Generation on your server side Like this:

 @Override
        protected String doInBackground(String... params) {
            url ="http://xxx.co.in/generateChecksum.php";
            JSONParser jsonParser = new JSONParser(MainActivity.this);

                param="ORDER_ID=" + orderId+
                        "&MID="+YourMID+
                        "&CUST_ID="+custId+
                        "&CHANNEL_ID=WAP&INDUSTRY_TYPE_ID=Retail110&WEBSITE=xxxwap&TXN_AMOUNT="+billAmt+"&CALLBACK_URL=http://xxx.co.in/verifyChecksum.php";

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

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

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

now after getting CHECKSUM string in your onPostExecute initialize paytm Service object and do further process Like This:

  @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressDialog.hide();
            Service = PaytmPGService.getProductionService();

    /*PaytmMerchant constructor takes two parameters
    1) Checksum generation url
    2) Checksum verification url
    Merchant should replace the below values with his values*/




            //below parameter map is required to construct PaytmOrder object, Merchant should replace below map values with his own values

            Map<String, String> paramMap = new HashMap<String, String>();

            //these are mandatory parameters


            paramMap.put("ORDER_ID", orderId);
            //MID provided by paytm

            paramMap.put("MID", yourMID);
            paramMap.put("CUST_ID", custId);
            paramMap.put("CHANNEL_ID", "WAP");
            paramMap.put("INDUSTRY_TYPE_ID", "Retail");
            paramMap.put("WEBSITE", "xxxwap");
            paramMap.put("TXN_AMOUNT",billAmt);
            // 
            paramMap.put("CALLBACK_URL" ,"http://xxx.co.in/verifyChecksum.php");
            paramMap.put("CHECKSUMHASH" ,CHECKSUMHASH);
            PaytmOrder Order = new PaytmOrder(paramMap);



            Service.initialize(Order,null);
            Service.startPaymentTransaction(ReviewBooking.this, true, true, new PaytmPaymentTransactionCallback() {
                @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 onTransactionResponse(Bundle inResponse) {
                    Log.d("LOG", "Payment Transaction : " + inResponse);
                    String response=inResponse.getString("RESPMSG");
                    if (response.equals("Txn Successful."))
                    {
                        new ConfirmMerchent().execute();
                    }else
                    {
                        Toast.makeText(getApplicationContext(),response,Toast.LENGTH_SHORT).show();
                    }
                    Toast.makeText(getApplicationContext(), "Payment Transaction response "+inResponse.toString(), Toast.LENGTH_LONG).show();
                }


                @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 onErrorLoadingWebPage(int iniErrorCode,
                                                  String inErrorMessage, String inFailingUrl) {

                }

                // had to be added: NOTE
                @Override
                public void onBackPressedCancelTransaction() {
                    // TODO Auto-generated method stub
                }

                @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();
                }
            });
        }

JsonParser Class

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();



            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();
                }
            }
        return jObj;
    }
}

and parameter values should be same both time.

Solution 2

Generating Checksum is quite easy.

  • Just get the Paytm App Checksum Kit from Github.
  • Extract the downloaded kit and put it in your server. If you are using a local server using xampp then the path would be c:/xampp/htdocs/paytm. I would recommend renaming the folder name to paytm or a small name.
  • Inside the kit there is a folder named lib. Inside this folder you will find a file named config_paytm.php, Open this file and put your Paytm Merchant Key here.
  • Now you can use the file generateChecksum.php to generate checksum.
  • Remember you need to pass every parameter that you will pass with transaction.
  • Below you can see a retrofit api code sample to send POST request to generateChecksum.php.

    //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
    );
    

This part is very important you have to send all the parameters. And order_id should be unique everytime.

Source: Paytm Integration in Android Example

Share:
12,901
Mayank Garg
Author by

Mayank Garg

Every day is a new morning...

Updated on June 09, 2022

Comments

  • Mayank Garg
    Mayank Garg about 2 years

    I am Integrating Paytm PGSDK_V2.0 in my android app. I have read all documentation on Github. I have understand everything.but the problem is in its earlier SDK where we can simply generate checksum using Paytm Merchant object Like:

    PaytmMerchant merchant=new PaytmMerchant("Checksum generation url","Checksum verification url");  
    

    and put this in Service Like this

     Service.initialize(Order,merchant,null);
    

    But in new SDK it change to

     Service.initialize(Order,null);
    

    So please help me how to generate checksum in new SDK

  • Naveen
    Naveen about 7 years
    Hi Ghanshyam, Can you please provide your JSONParser class please.
  • Ghanshyam Sharma
    Ghanshyam Sharma about 7 years
    Means response in Json format which i getting from server @Naveen
  • Naveen
    Naveen about 7 years
    What exactly JSONParser is [In doInBackground()] ?
  • Naveen
    Naveen about 7 years
    Thanks Ghanshyam, can you explain please about param in doInBackGround() ?
  • Ghanshyam Sharma
    Ghanshyam Sharma about 7 years
    In Params , OrderId is a random Int id which you generate for every order. MID is Merchant id which is provided to every merchant by paytm. CUST_ID is customer id which you use to identify every customer. you can use here customer email id for example. CHANNEL_ID is WAP for mobile platform. INDUSTRY_TYPE_ID this is also provided by Paytm to each merchant. WEBSITE is also provided by Paytm. TXN_AMOUNT is bill amount ANd CALLBACK_URL is verify checksum url @Naveen
  • Naveen
    Naveen about 7 years
    Thanks Ghanshyam you are very helpful, Can you please provide the MainActivity where doInBackGround in present ?
  • Ghanshyam Sharma
    Ghanshyam Sharma about 7 years
  • luttu android
    luttu android over 6 years
    Hi Ghanshyam,can you please provide ConfirmMerchent class please
  • gulab patel
    gulab patel about 2 years
    can we do this in android device not on server ?