Hope u all are doing good.Our today's tutorial is PayUmoney Android integration. As we all know PayUmoney is a payment gateway it work electronic payment service to your website through its various partnerships with banks and payment instrument companies. Through PayUmoney , your clients would be able to make electronic payments through credit card, debit card and online net banking account.
Steps to integrate with the PayUmoney Android SDK –
1.Download PayUmoney Android SDK from PayUmoney site.
2.Create new android project named PayMoneyDemo.(or whattever you want)
3.Import PayUmoney SDK as a module or Gradle Project-
a. Go to Project Structure under file in the Android Studio.
a. Go to Project Structure under file in the Android Studio.
b. Click on your app and then select the Dependencies tab on the top.
Then click on Add (+ sign) on the top right corner and click on Module Dependency.
After this, select PayUmoney SDK.This will add PayUmoney SDK as a dependency to app.
Once you add the SDK as module you will need to call the some PayUmoney functions from app when the user clicks on Pay Now button on your app.
1. In your activity_main.layout file add following lines.
//activity_main.layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.myworldweb.payumoneydemo.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Amount"
android:id="@+id/edit_amount"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PAY NOW"
android:id="@+id/button_pay"
android:layout_below="@+id/edit_amount"
android:layout_centerHorizontal="true"
android:layout_marginTop="47dp"
android:onClick="makePayment"/>
</RelativeLayout>
2.In your MainActivity.java add following code
//MainActivity.java
package com.myworldweb.payumoneydemo;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.payUMoney.sdk.PayUmoneySdkInitilizer;
import com.payUMoney.sdk.SdkConstants;
import com.payUMoney.sdk.utils.SdkHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
EditText amt =
null;
Button pay = null;
String txnId;
public static
final String TAG = "PayUMoneySDK Sample";
@Override
protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
amt =
(EditText) findViewById(R.id.edit_amount);
pay = (Button)
findViewById(R.id.button_pay);
}
private boolean
isDouble(String str) {
try {
Double.parseDouble(str);
return
true;
} catch
(NumberFormatException e) {
return
false;
}
}
private double
getAmount() {
Double amount = 10.0;
if
(isDouble(amt.getText().toString())) {
amount =
Double.parseDouble(amt.getText().toString());
return
amount;
} else {
Toast.makeText(getApplicationContext(), "Paying Default Amount
₹10", Toast.LENGTH_LONG).show();
return
amount;
}
}
public void
makePayment(View view) {
String phone =
"8380894057";
String
productName = "purse";
String
firstName = "meera";
txnId =
"0nf7" + System.currentTimeMillis();
String
email="meerag@gmail.com";
String sUrl =
"https://test.payumoney.com/mobileapp/payumoney/success.php";
String fUrl =
"https://test.payumoney.com/mobileapp/payumoney/failure.php";
String udf1 =
"";
String udf2 =
"";
String udf3 =
"";
String udf4 =
"";
String udf5 =
"";
boolean
isDebug = true; //for live mode make it
false
String key = "dRQuiA"; //for live mode add key given by PayUmoney
String
merchantId = "4928174";
////for live mode add merchantId given by PayUmoney
PayUmoneySdkInitilizer.PaymentParam.Builder builder = new
PayUmoneySdkInitilizer.PaymentParam.Builder();
builder.setAmount(getAmount())
.setTnxId(txnId)
.setPhone(phone)
.setProductName(getProductInfo())
//setting ur product information
.setFirstName(firstName)
.setEmail(email)
.setsUrl(sUrl)
.setfUrl(fUrl)
.setUdf1(udf1)
.setUdf2(udf2)
.setUdf3(udf3)
.setUdf4(udf4)
.setUdf5(udf5)
.setIsDebug(isDebug)
.setKey(key)
.setMerchantId(merchantId)
;
PayUmoneySdkInitilizer.PaymentParam paymentParam = builder.build();
// server
side call required to calculate hash with the help of <salt>
//
<salt> is already shared along with merchant <key>
/* serverCalculatedHash
=sha512(key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|<salt>)
(e.g.)
sha512(FCstqb|0nf7|10.0|product_name|piyush|piyush.jain@payu.in||||||MBgjYaFG)
9f1ce50ba8995e970a23c33e665a990e648df8de3baf64a33e19815acd402275617a16041e421cfa10b7532369f5f12725c7fcf69e8d10da64c59087008590fc
*/
// Recommended
calculateServerSideHashAndInitiatePayment(paymentParam);
// testing
purpose
/* String salt = "";
String
serverCalculatedHash=hashCal(key+"|"+txnId+"|"+getAmount()+"|"+productName+"|"
+firstName+"|"+email+"|"+udf1+"|"+udf2+"|"+udf3+"|"+udf4+"|"+udf5+"|"+salt);
paymentParam.setMerchantHash(serverCalculatedHash);*/
//
PayUmoneySdkInitilizer.startPaymentActivityForResult(MainActivity.this,
paymentParam);
}
public static
String hashCal(String str) {
byte[] hashseq
= str.getBytes();
StringBuilder
hexString = new StringBuilder();
try {
MessageDigest algorithm =
MessageDigest.getInstance("SHA-512");
algorithm.reset();
algorithm.update(hashseq);
byte
messageDigest[] = algorithm.digest();
for (byte
aMessageDigest : messageDigest) {
String
hex = Integer.toHexString(0xFF & aMessageDigest);
if
(hex.length() == 1) {
hexString.append("0");
}
hexString.append(hex);
}
} catch
(NoSuchAlgorithmException ignored) {
}
return
hexString.toString();
}
private void
calculateServerSideHashAndInitiatePayment(final
PayUmoneySdkInitilizer.PaymentParam paymentParam) {
// Replace
your server side hash generator API URLString url =
"https://test.payumoney.com/payment/op/calculateHashForTest";
String url =
"https://test.payumoney.com/payment/op/calculateHashForTest";
Toast.makeText(this, "Please wait... Generating hash from server
... ", Toast.LENGTH_LONG).show();
StringRequest
jsonObjectRequest = new StringRequest(Request.Method.POST, url, new
Response.Listener<String>() {
@Override
public
void onResponse(String response) {
Log.i("Meera", "Server calculated Hash : " + response);
try {
JSONObject jsonObject = new JSONObject(response);
if
(jsonObject.has(SdkConstants.STATUS)) {
String status = jsonObject.optString(SdkConstants.STATUS);
if (status != null || status.equals("1")) {
String hash = jsonObject.getString(SdkConstants.RESULT);
Log.i("app_activity", "Server calculated Hash : " + hash);
paymentParam.setMerchantHash(hash);
PayUmoneySdkInitilizer.startPaymentActivityForResult(MainActivity.this,
paymentParam);
} else {
Toast.makeText(MainActivity.this,
jsonObject.getString(SdkConstants.RESULT),
Toast.LENGTH_SHORT).show();
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new
Response.ErrorListener() {
@Override
public
void onErrorResponse(VolleyError error) {
if
(error instanceof NoConnectionError) {
Toast.makeText(MainActivity.this,
MainActivity.this.getString(R.string.connect_to_internet),
Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(MainActivity.this,
error.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}) {
@Override
protected
Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map=new HashMap<String ,String>();
return
paymentParam.getParams();
}
};
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
protected void
onActivityResult(int requestCode, int resultCode, Intent data) {
if
(requestCode == PayUmoneySdkInitilizer.PAYU_SDK_PAYMENT_REQUEST_CODE) {
if(data !=
null && data.hasExtra("result")){
String
responsePayUmoney = data.getStringExtra("result");
if(SdkHelper.checkForValidString(responsePayUmoney))
showDialogMessage(responsePayUmoney);
} else {
showDialogMessage("Unable to get Status of Payment");
}
if
(resultCode == RESULT_OK) {
Log.i(TAG, "Success - Payment ID : " +
data.getStringExtra(SdkConstants.PAYMENT_ID));
String
paymentId = data.getStringExtra(SdkConstants.PAYMENT_ID);
showDialogMessage("Payment Success Id : " + paymentId);
} else if (resultCode ==
RESULT_CANCELED) {
Log.i(TAG, "failure");
showDialogMessage("cancelled");
} else if
(resultCode == PayUmoneySdkInitilizer.RESULT_FAILED) {
Log.i("app_activity", "failure");
if
(data != null) {
if
(data.getStringExtra(SdkConstants.RESULT).equals("cancel")) {
}
else {
showDialogMessage("failure");
}
}
//Write your code if there's no result
} else if
(resultCode == PayUmoneySdkInitilizer.RESULT_BACK) {
Log.i(TAG, "User returned without login");
showDialogMessage("User returned without login");
}
}
}
private void
showDialogMessage(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(TAG);
builder.setMessage(message);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
@Override
public
void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
public String
getProductInfo()
{
JSONObject
productInfoObj = new JSONObject();
JSONArray
productPartsArr = new JSONArray();
JSONObject
productPartsObj1 = new JSONObject();
JSONObject
paymentIdenfierParent = new JSONObject();
JSONArray
paymentIdentifiersArr = new JSONArray();
JSONObject
paymentPartsObj1 = new JSONObject();
JSONObject
paymentPartsObj2 = new JSONObject();
try {
// Payment
Parts
productPartsObj1.put("name", "purse");
productPartsObj1.put("description", "red colour");
productPartsObj1.put("value", "1");
productPartsObj1.put("isRequired", "true");
productPartsObj1.put("settlementEvent",
"EmailConfirmation");
productPartsArr.put(productPartsObj1);
productInfoObj.put("paymentParts", productPartsArr);
// Payment
Identifiers
paymentPartsObj1.put("field", "CompletionDate");
paymentPartsObj1.put("value", "31/10/2017");
paymentIdentifiersArr.put(paymentPartsObj1);
paymentPartsObj2.put("field", "TxnId");
paymentPartsObj2.put("value", txnId);
paymentIdentifiersArr.put(paymentPartsObj2);
paymentIdenfierParent.put("paymentIdentifiers",
paymentIdentifiersArr);
productInfoObj.put("", paymentIdenfierParent);
} catch
(JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return
productInfoObj.toString();
}
}
boolean isDebug = false; //for live mode make it false
2.Create you own php at server to generate hashes- payUHash.php
$key=$_POST["key"];
$salt="XXXXXXXX";
$txnId=$_POST["txnid"];
$amount=$_POST["amount"];
$productName=$_POST["productInfo"];
$firstName=$_POST["firstName"];
$email=$_POST["email"];
$udf1=$_POST["udf1"];ch
$udf2=$_POST["udf2"];
$udf3=$_POST["udf3"];
$udf4=$_POST["udf4"];
$udf5=$_POST["udf5"];
$payhash_str = $key . '|' . checkNull($txnId) . '|' .checkNull($amount) . '|' .checkNull($productName) . '|' . checkNull($firstName) . '|' . checkNull($email) . '|' . checkNull($udf1) . '|' . checkNull($udf2) . '|' . checkNull($udf3) . '|' . checkNull($udf4) . '|' . checkNull($udf5) . '|' . $salt;
function checkNull($value) {
if ($value == null) {
return '';
} else {
return $value;
}
}
$hash = strtolower(hash('sha512', $payhash_str));
$arr['result'] = $hash;
$arr['status']=0;
$arr['errorCode']=null;
$arr['responseCode']=null;
$arr['hashtest']=$payhash_str;
$output=$arr;
echo json_encode($output);
?>
4. Now your payu app is all set to live mode. Run it. Check it for live card credential or netbanking pay option.
Thanks,
Meera
give me the link for download sdk.
ReplyDeletei am not able to import
if (jsonObject.has(SdkConstants.STATUS))
if (requestCode == PayUmoneySdkInitializer.PAYU_SDK_PAYMENT_REQUEST_CODE)
i will test it
ReplyDeleteSdkConstants cannot resolve
ReplyDeletewhere is PHP???
ReplyDelete