How to Integrate Paytm Payment Gateway in Android App. These facts can provide you with how mobile payments will evolve in the coming years. payments as well as mobile retail. They also explain why it’s important to create mobile apps that have payment gateways that are integrated to ensure that the operation of your app is smooth and smooth and an easy, quick, and secure checkout experience.
Android, as well as iOS, are two distinct platforms, and mobile app development is different for both platforms in a variety of ways. Also, choosing the right payment method for these platforms needs you to consider the various aspects we have described in this article. In this article, we’ll exclusively discuss how to integrate payment gateways into Android applications. First, let’s look at the following:
What is a mobile payment gateway?
Mobile payment gateways are a device that allows businesses to process and authorize payments through mobile applications. It utilizes encryption protocols and security protocols to transfer transaction information in a secure manner.
Simply and in a short manner, a mobile payment gateway functions as an application that allows the exchange of money in exchange for products or services between customers and business.
What is the best mobile payment processor for your Android application
Before you can integrate the mobile payment gateway into your Android application, consider the following questions:
- Do you need to incorporate a payment service that allows you to customize the payment page to match the image of your business? (Option #1)
- Do you want to control the page for payment and provide an exceptional experience for your customers? (Option 2)
- You have botha mobile and website, but receive the majority of traffic to your website. So, you’re looking for a solution that works ideal for your website, however, it improves the experience of payment for mobile users too. (Option #3)
How to Integrate Paytm Payment Gateway in Android App
Hey in these tutorial i am share integrate paytm getaway in your Android mobile plate form its very easy just follow step and integrate .
Step 1:- Start your android studio .
Step 2 :- Creat a project pytem getway .
Step 3:- After create your project add dependencies in your app basd build.gradle
dependencies { compile 'com.android.support:support-v4:22.2.1' /*compile files('libs/PGSDK_V2.0.jar')*/ compile 'com.android.volley:volley:1.0.0' //implementation 'com.paytm:pgplussdk:1.1.2' compile 'com.paytm:pgplussdk:1.1.2' }
Add paytem getway pgplussdk sdk
compile ‘com.paytm:pgplussdk:1.1.2’
Step 4:- Add user permission in your mainfests file
<uses-permission android:name=“android.permission.INTERNET”/>
<uses-permission android:name=“android.permission.ACCESS_NETWORK_STATE”/>
Step 5:- Opne your xml file full code and add these code
Merchantapp.xml
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:weightSum="1"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Paytm" android:textStyle="bold" android:textSize="18dip" android:layout_gravity="center_horizontal" android:layout_marginBottom="10dip"/> </LinearLayout> <Button android:layout_width="217dp" android:layout_height="wrap_content" android:id="@+id/start_transaction" android:text="@string/start_transaction" android:onClick="onStartTransaction" android:layout_gravity="center" android:textStyle="bold" android:textSize="16dip" android:layout_marginTop="10dip" android:layout_weight="2.05" /> </LinearLayout> </ScrollView>
Step 6:- Add code in your java file
MerchantActivity.java
public class MerchantActivity extends Activity {
public static final String StoreDetail_URL="******";
public static final String KEY_order_id = "order_id";//database key
public static final String KEY_amount = "amount";
public static final String KEY_t_id = "t_id";
public static final String KEY_status="status";
String Status,Amount,OrderId,TXNID;
PaytmPGService Service;
String CHECKSUMHASH1,orderid,customerid;
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchantapp);
requestQueue = Volley.newRequestQueue(MerchantActivity.this);
//initOrderId();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
//This is to refresh the order id: Only for the Sample App's purpose.
@Override
protected void onStart(){
super.onStart();
//initOrderId();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
public void onStartTransaction(View view) {
CHECKSUMHASH1="";
orderid="";
customerid="";
CallVolley( "http://***************/paytm/app/response.php");
}
public void CallVolley(String a)
{
try {
Random r = new Random(System.currentTimeMillis());
orderid = "ORDER" + (1 + r.nextInt(2)) * 100000 + r.nextInt(100000);
customerid="CUST" + (1 + r.nextInt(2)) * 10000 + r.nextInt(10000);
StringRequest strRequest = new StringRequest(Request.Method.POST, a,
new Response.Listener<String>()
{
@Override
public void onResponse(String response)
{
try {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
JSONObject jsonObject = new JSONObject(response.toString());
CHECKSUMHASH1 = jsonObject.has("CHECKSUMHASH") ? jsonObject.getString("CHECKSUMHASH") : "";
Toast.makeText(MerchantActivity.this, CHECKSUMHASH1, Toast.LENGTH_SHORT).show();
CallPaytmIntegration();
}
catch (JSONException je)
{
je.printStackTrace();
}
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
@Override
protected Map<String, String> getParams()
{
HashMap<String,String> map=new HashMap<>();
map.put("MID"," *********** "); //Provided by Paytm
map.put("ORDER_ID",orderid); //unique OrderId for every request
map.put("CUST_ID",customerid); // unique customer identifier
map.put("INDUSTRY_TYPE_ID","********"); //Provided by Paytm
map.put("CHANNEL_ID","WAP"); //Provided by Paytm
map.put("TXN_AMOUNT","1"); // transaction amount
map.put("WEBSITE","APPPROD");//Provided by Paytm
map.put("CALLBACK_URL","https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID="+orderid);//Provided by Paytm
Log.e("MAP",map.toString());
return map;
}
};
requestQueue.add(strRequest);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "--" + e, Toast.LENGTH_SHORT).show();
}
}
public void CallPaytmIntegration()
{
Service = PaytmPGService.getProductionService();
Map<String, String> paramMap = new HashMap<String,String>();
paramMap.put("MID"," *************"); //Provided by Paytm
paramMap.put("ORDER_ID",orderid); //unique OrderId for every request
paramMap.put("CUST_ID",customerid); // unique customer identifier
paramMap.put("INDUSTRY_TYPE_ID","******"); //Provided by Paytm
paramMap.put("CHANNEL_ID","WAP"); //Provided by Paytm
paramMap.put("TXN_AMOUNT","1"); // transaction amount
paramMap.put("WEBSITE","APPPROD");//Provided by Paytm
paramMap.put("CALLBACK_URL","https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID="+orderid);//Provided by Paytm
paramMap.put( "CHECKSUMHASH",CHECKSUMHASH1);
PaytmOrder Order = new PaytmOrder(paramMap);
//Create Client Certificate object holding the information related to Client Certificate. Filename must be without .p12 extension.
//For example, if suppose client.p12 is stored in raw folder, then filename must be client.
//PaytmClientCertificate Certificate = new PaytmClientCertificate ("password" , "filename" );
//Set PaytmOrder and PaytmClientCertificate Object. Call this method and set both objects before starting transaction.
//Service.initialize(Order, Certificate);
//OR
Service.initialize(Order, null);
//Start the Payment Transaction. Before starting the transaction ensure that initialize method is called.
Service.startPaymentTransaction(this, true, true, new PaytmPaymentTransactionCallback() {
@Override
public void someUIErrorOccurred(String inErrorMessage) {
Log.d("LOG", "UI Error Occur.");
Toast.makeText(getApplicationContext(), " UI Error Occur. ", Toast.LENGTH_LONG).show();
}
@Override
public void onTransactionResponse(Bundle inResponse) {
Log.d("LOG", "Payment Transaction : " + inResponse);
Status =inResponse.getString("STATUS");
Amount=inResponse.getString("TXNAMOUNT");
OrderId=inResponse.getString("ORDERID");
TXNID=inResponse.getString("TXNID");
UserLogin();
Toast.makeText(getApplicationContext(), "Payment Transaction response "+inResponse.toString(), Toast.LENGTH_LONG).show();
Log.e("RESPONSE",inResponse.toString());
}
@Override
public void networkNotAvailable() {
Log.d("LOG", "UI Error Occur.");
Toast.makeText(getApplicationContext(), " UI Error Occur. ", Toast.LENGTH_LONG).show();
}
@Override
public void clientAuthenticationFailed(String inErrorMessage) {
Log.d("LOG", "UI Error Occur.");
Toast.makeText(getApplicationContext(), " Severside Error "+ inErrorMessage, Toast.LENGTH_LONG).show();
}
@Override
public void onErrorLoadingWebPage(int iniErrorCode,
String inErrorMessage, String inFailingUrl) {
}
@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();
}
});
}
}
Step 7:- Create a response.php for generated CHECKSUMHASH1
http://example.in/paytm/app/response.php
<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
//require_once("./encdec_paytm.php");
require_once("encdec_paytm.php");
$checkSum = "";
$paramList = array();
$paramList["MID"] = "";
$paramList["ORDER_ID"] = "";
$paramList["CUST_ID"] = "";
$paramList["INDUSTRY_TYPE_ID"] = "";
$paramList["CHANNEL_ID"] = "";
//$paramList["THEME"] = "merchant";
$paramList["TXN_AMOUNT"] = "";
$paramList["WEBSITE"] = "";
$paramList["CALLBACK_URL"] = "";
//Here checksum string will return by getChecksumFromArray() function.
//$checkSum = getChecksumFromArray($paramList,"*********");
//print_r($paramList);
//echo $checkSum;
foreach($_POST as $key=>$value)
{
$pos = strpos($value, $findme);
$pospipe = strpos($value, $findmepipe);
if ($pos === false || $pospipe === false)
{
$paramList[$key] = $value;
}
}
//Here checksum string will return by getChecksumFromArray() function.
//$checkSum = getChecksumFromArray($paramList,"*****");
$checkSum = getChecksumFromArray($paramList,"********");
//print_r($_POST);
echo json_encode(array("CHECKSUMHASH" => $checkSum,"ORDER_ID" => $_POST["ORDER_ID"], "payt_STATUS" => "1"));
//Sample response return to SDK
// {"CHECKSUMHASH":"*********","ORDER_ID":"asgasfgasfsdfhl7","payt_STATUS":"1"}
?>
Step 8 :- Create Any other encdec_paytm.php to include in your response.php
this api is provide by paytm but if you have not used these code.
<?php function encrypt_e($input, $ky) { $key = $ky; $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc'); $input = pkcs5_pad_e($input, $size); $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', ''); $iv = "@@@@&&&&####$$$$"; mcrypt_generic_init($td, $key, $iv); $data = mcrypt_generic($td, $input); mcrypt_generic_deinit($td); mcrypt_module_close($td); $data = base64_encode($data); return $data; } function decrypt_e($crypt, $ky) { $crypt = base64_decode($crypt); $key = $ky; $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', ''); $iv = "@@@@&&&&####$$$$"; mcrypt_generic_init($td, $key, $iv); $decrypted_data = mdecrypt_generic($td, $crypt); mcrypt_generic_deinit($td); mcrypt_module_close($td); $decrypted_data = pkcs5_unpad_e($decrypted_data); $decrypted_data = rtrim($decrypted_data); return $decrypted_data; } function pkcs5_pad_e($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } function pkcs5_unpad_e($text) { $pad = ord($text{strlen($text) - 1}); if ($pad > strlen($text)) return false; return substr($text, 0, -1 * $pad); } function generateSalt_e($length) { $random = ""; srand((double) microtime() * 1000000); $data = "AbcDE123IJKLMN67QRSTUVWXYZ"; $data .= "aBCdefghijklmn123opq45rs67tuv89wxyz"; $data .= "0FGH45OP89"; for ($i = 0; $i < $length; $i++) { $random .= substr($data, (rand() % (strlen($data))), 1); } return $random; } function checkString_e($value) { $myvalue = ltrim($value); $myvalue = rtrim($myvalue); if ($myvalue == 'null') $myvalue = ''; return $myvalue; } function getChecksumFromArray($arrayList, $key, $sort=1) { if ($sort != 0) { ksort($arrayList); } $str = getArray2Str($arrayList); $salt = generateSalt_e(4); $finalString = $str . "|" . $salt; $hash = hash("sha256", $finalString); $hashString = $hash . $salt; $checksum = encrypt_e($hashString, $key); return $checksum; } function getChecksumFromString($str, $key) { $salt = generateSalt_e(4); $finalString = $str . "|" . $salt; $hash = hash("sha256", $finalString); $hashString = $hash . $salt; $checksum = encrypt_e($hashString, $key); return $checksum; } function verifychecksum_e($arrayList, $key, $checksumvalue) { $arrayList = removeCheckSumParam($arrayList); ksort($arrayList); $str = getArray2Str($arrayList); $paytm_hash = decrypt_e($checksumvalue, $key); $salt = substr($paytm_hash, -4); $finalString = $str . "|" . $salt; $website_hash = hash("sha256", $finalString); $website_hash .= $salt; $validFlag = "FALSE"; if ($website_hash == $paytm_hash) { $validFlag = "TRUE"; } else { $validFlag = "FALSE"; } return $validFlag; } function verifychecksum_eFromStr($str, $key, $checksumvalue) { $paytm_hash = decrypt_e($checksumvalue, $key); $salt = substr($paytm_hash, -4); $finalString = $str . "|" . $salt; $website_hash = hash("sha256", $finalString); $website_hash .= $salt; $validFlag = "FALSE"; if ($website_hash == $paytm_hash) { $validFlag = "TRUE"; } else { $validFlag = "FALSE"; } return $validFlag; } function getArray2Str($arrayList) { $paramStr = ""; $flag = 1; foreach ($arrayList as $key => $value) { if ($flag) { $paramStr .= checkString_e($value); $flag = 0; } else { $paramStr .= "|" . checkString_e($value); } } return $paramStr; } function redirect2PG($paramList, $key) { $hashString = getchecksumFromArray($paramList); $checksum = encrypt_e($hashString, $key); } function removeCheckSumParam($arrayList) { if (isset($arrayList["CHECKSUMHASH"])) { unset($arrayList["CHECKSUMHASH"]); } return $arrayList; } function getTxnStatus($requestParamList) { return callAPI(PAYTM_STATUS_QUERY_URL, $requestParamList); } function initiateTxnRefund($requestParamList) { $CHECKSUM = getChecksumFromArray($requestParamList,PAYTM_MERCHANT_KEY,0); $requestParamList["CHECKSUM"] = $CHECKSUM; return callAPI(PAYTM_REFUND_URL, $requestParamList); } function callAPI($apiURL, $requestParamList) { $jsonResponse = ""; $responseParamList = array(); $JsonData =json_encode($requestParamList); $postData = 'JsonData='.urlencode($JsonData); $ch = curl_init($apiURL); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($postData)) ); $jsonResponse = curl_exec($ch); $responseParamList = json_decode($jsonResponse,true); return $responseParamList; }
After complete these step to run your project and test that
Read More Tutorial