PayUmoney seamless Integration - android

experts
can you help me in seemless integration with PayUmoney payment Gateway in android
also if you have any sample of seemless integration please share
i have tried like this but showing me error of Marchentkey and salt is incorrect but i copied both from my account
below is code detail
MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Payu.setInstance(this);
proceedtopay();
}
public void proceedtopay(){
PaymentParams mPaymentParams = new PaymentParams();
String merchant_key="rjQUPktU"; // test gtkFFx XmOFYRT3
String salt="e5iIg1jwi8"; // test eCwWELxi aTZEImxcYO
mPaymentParams.setKey(merchant_key);
mPaymentParams.setAmount("15.0");
mPaymentParams.setProductInfo("Tshirt");
mPaymentParams.setFirstName("Waseem");
mPaymentParams.setEmail("waseemahmad241#gmail.com");
mPaymentParams.setTxnId("0123479543689");
mPaymentParams.setSurl("https://www.payumoney.com/mobileapp/payumoney/success.php");
mPaymentParams.setFurl("https://www.payumoney.com/mobileapp/payumoney/failure.php");
mPaymentParams.setUdf1("udf1l");
mPaymentParams.setUdf2("udf2");
mPaymentParams.setUdf3("udf3");
mPaymentParams.setUdf4("udf4");
mPaymentParams.setUdf5("udf5");
String hashSequence = merchant_key+"|0123479543689|15.0|productinfo|Waseem|waseemahmad241#gmail.com|udf1|udf2|udf3|udf4|udf5||||||"+salt;
String serverCalculatedHash= hashCal("SHA-512", hashSequence);
mPaymentParams.setHash(serverCalculatedHash);
mPaymentParams.setCardNumber("4012001037141112");
mPaymentParams.setCardName("test");
mPaymentParams.setNameOnCard("test");
mPaymentParams.setExpiryMonth("05");// MM
mPaymentParams.setExpiryYear("2020");// YYYY
mPaymentParams.setCvv("123");
mPaymentParams.setEnableOneClickPayment(1);
PostData postData = null;
try {
postData = new PaymentPostParams(mPaymentParams, PayuConstants.CC).getPaymentPostParams();
} catch (Exception e) {
e.printStackTrace();
}
if (postData.getCode() == PayuErrors.NO_ERROR) {
// launch webview
PayuConfig payuConfig = new PayuConfig();
payuConfig.setEnvironment(PayuConstants.STAGING_ENV);
payuConfig.setData(postData.getResult());
Intent intent = new Intent(this,PaymentsActivity.class);
intent.putExtra(PayuConstants.PAYU_CONFIG,payuConfig);
startActivityForResult(intent, PayuConstants.PAYU_REQUEST_CODE);
} else {
// something went wrong
Toast.makeText(this,postData.getResult(), Toast.LENGTH_LONG).show();
}
}
public static String hashCal(String type, String hashString) {
StringBuilder hash = new StringBuilder();
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance(type);
messageDigest.update(hashString.getBytes());
byte[] mdbytes = messageDigest.digest();
for (byte hashByte : mdbytes) {
hash.append(Integer.toString((hashByte & 0xff) + 0x100, 16).substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hash.toString();
}
and MyWebview Activity is
PaymentsActivity extends AppCompatActivity {
//String base_url="https://test.payumoney.in/_payment";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
Bundle bundle =getIntent().getExtras();
PayuConfig payuConfig =bundle.getParcelable(PayuConstants.PAYU_CONFIG);
WebView mWebView =(WebView) findViewById(R.id.webview);
// String url =//payuConfig.getEnvironment() == PayuConstants.PRODUCTION_ENV ? PayuConstants.PRODUCTION_PAYMENT_URL :PayuConstants.MOBILE_TEST_PAYMENT_URL;
byte[] encodedData = EncodingUtils.getBytes(payuConfig.getData(), "base64");
mWebView.postUrl(PayuConstants.TEST_PAYMENT_URL,encodedData);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {});
mWebView.setWebViewClient(new WebViewClient() {});

#SuppressLint("SetJavaScriptEnabled")
public class Payment extends AppCompatActivity {
WebView webView;
Context activity;
int mId;
/*private String mMerchantKey ="your marchant key"
private String mSalt = "your salt key"*/
private String mBaseURL = "https://test.payu.in";
private String mAction = ""; // For Final URL
private String mTXNId; // This will create below randomly
private String mHash; // This will create below randomly
private String mProductInfo = "product name"; //Passing String only
private String mFirstName; // From Previous Activity
private String mEmailId; // From Previous Activity
private double mAmount; // From Previous Activity
private String mPhone; // From Previous Activity
private String mServiceProvider = "";// "payu_paisa";
private String mSuccessUrl = "success url";
private String mFailedUrl = "failure url";
String MAM_ID = "mem_id";
String EMAIL = "email";
String ADD1 = "address_line1";
String ADD2 = "address_line2";
String REGION_ID = "region_id";
String CITY_ID = "city_id";
String PROMOCODE = "promocode";
String PIN_CODE = "pin_code";
String ADD_DATE = "add_date";
String PRICE = "price";
String CARD_DISCOUNT = "card_discount";
String PROMOCODE_DISCOUNT = "promocode_discount";
String TXNID = "tnx_id";
String DEVICE_ID = "device_id";
String PRODUCT_ID = "product_id";
boolean isFromOrder;
/*
Handler
*/
Handler mHandler = new Handler();
Bundle bundle;
SharedPreferences spfs;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
/**
* #param savedInstanceState
*/
#SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled", "JavascriptInterface"})
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview_for_payumoney);
spfs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
webView = (WebView) findViewById(R.id.payumoney_webview);
activity = getApplicationContext();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
// enabling action bar app icon and behaving it as toggle button
ab.setHomeButtonEnabled(true);
ab.setTitle("Payment Gateaway");
bundle = getIntent().getExtras();
if (bundle != null) {
Log.e("Bndle Data:- ", bundle.toString());
mFirstName = bundle.getString("Name");//NAME
mEmailId = bundle.getString("Email");// lOGIN IN PAYUMONEY ID
mAmount = 1.0;//bundle.getDouble("Price");// AMOUNT
mPhone = bundle.getString("Mobile"); // MOBILE ! REQUIRED
mId = 1;//bundle.getInt("id");
isFromOrder = true;// bundle.getBoolean("isFromOrder");
Log.e("Tag payment ", "" + mFirstName + " : " + mEmailId + " : " + mAmount + " : " + mPhone);
Random rand = new Random();
String randomString = Integer.toString(rand.nextInt()) + (System.currentTimeMillis() / 1000L);
mTXNId = hashCal("SHA-256", randomString).substring(0, 20);
mAmount = new BigDecimal(mAmount).setScale(0, RoundingMode.UP).intValue();
mHash = hashCal("SHA-512", mMerchantKey + "|" +
mTXNId + "|" +
mAmount + "|" +
mProductInfo + "|" +
mFirstName + "|" +
mEmailId + "|||||||||||" +
mSalt);
mAction = mBaseURL.concat("/_payment");
try {
Class.forName("com.payu.custombrowser.Bank");
} catch (Exception e) {
}
webView.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Handle the error
Log.e("WEB_VIEW_TEST", "error code:" + errorCode);
super.onReceivedError(view, errorCode, description, failingUrl);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
Log.e("onReceivedError", "error code:" + rerr);
Toast.makeText(activity, "Oh no! " + rerr.getDescription().toString(), Toast.LENGTH_SHORT).show();
}
/*#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(activity, "Oh no! " + error, Toast.LENGTH_SHORT).show();
}*/
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Toast.makeText(activity, "SSL Error! " + error, Toast.LENGTH_SHORT).show();
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (url.equals(mSuccessUrl)) {
RecepetUpload();
} else if (url.equals(mFailedUrl)) {
Log.e("Payment STatus", "failure");
Custom_Toast.show(getApplication(), "Payment Transcation Failed");
Intent intent = new Intent(Payment.this, MainActivity.class);
intent.putExtra("status", false);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
super.onPageFinished(view, url);
}
});
webView.setVisibility(View.VISIBLE);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setDomStorageEnabled(true);
webView.clearHistory();
webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
webView.setInitialScale(1);
webView.addJavascriptInterface(new PayUJavaScriptInterface(Payment.this), "PayUMoney");
/**
* Mapping Compulsory Key Value Pairs
*/
Map<String, String> mapParams = new HashMap<>();
mapParams.put("key", mMerchantKey);
mapParams.put("txnid", mTXNId);
mapParams.put("amount", String.valueOf(mAmount));
mapParams.put("productinfo", mProductInfo);
mapParams.put("firstname", mFirstName);
mapParams.put("email", mEmailId);
mapParams.put("phone", mPhone);
mapParams.put("surl", mSuccessUrl);
mapParams.put("furl", mFailedUrl);
mapParams.put("hash", mHash);
mapParams.put("service_provider", mServiceProvider);
Log.e("Url WEb View", mAction);
webViewClientPost(webView, mAction, mapParams.entrySet());
} else {
Toast.makeText(activity, "Something went wrong, Try again.", Toast.LENGTH_LONG).show();
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* Posting Data on PayUMoney Site with Form
*
* #param webView
* #param url
* #param postData
*/
public void webViewClientPost(WebView webView, String url,
Collection<Map.Entry<String, String>> postData) {
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body onload='form1.submit()'>");
sb.append(String.format("<form id='form1' action='%s' method='%s'>", url, "post"));
for (Map.Entry<String, String> item : postData) {
sb.append(String.format("<input name='%s' type='hidden' value='%s' />", item.getKey(), item.getValue()));
}
sb.append("</form></body></html>");
Log.d("TAG", "webViewClientPost called: " + sb.toString());
webView.loadData(sb.toString(), "text/html", "utf-8");
}
/**
* Hash Key Calculation
*
* #param type
* #param str
* #return
*/
public String hashCal(String type, String str) {
byte[] hashSequence = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashSequence);
byte messageDigest[] = algorithm.digest();
for (int i = 0; i < messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if (hex.length() == 1)
hexString.append("0");
hexString.append(hex);
}
} catch (NoSuchAlgorithmException NSAE) {
}
Log.e("Hex String", "" + hexString);
return hexString.toString();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onPressingBack();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
onPressingBack();
}
/**
* On Pressing Back
* Giving Alert...
*/
private void onPressingBack() {
final Intent intent;
if (isFromOrder)
intent = new Intent(Payment.this, MainActivity.class);
else
intent = new Intent(Payment.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Payment.this);
// Setting Dialog Title
alertDialog.setTitle("Warning");
// Setting Dialog Message
alertDialog.setMessage("Do you cancel this transaction?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Payment Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://https://secure.payu.in"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.local/https/https://secure.payu.in")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Payment Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://https://secure.payu.in"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.local/https/https://secure.payu.in")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
public class PayUJavaScriptInterface {
Context mContext;
/**
* Instantiate the interface and set the context
*/
PayUJavaScriptInterface(Context c) {
mContext = c;
}
public void success(long id, final String paymentId) {
mHandler.post(new Runnable() {
public void run() {
mHandler = null;
Toast.makeText(Payment.this, "Payment Successfully.", Toast.LENGTH_SHORT).show();
}
});
}
}
private void RecepetUpload() {
final ProgressDialog progDialog;
progDialog = ProgressDialog.show(Payment.this, "", "waiting");
try {
if (!progDialog.isShowing()) {
progDialog.show();
}
StringRequest postRequest = new StringRequest(Request.Method.POST,
"http://www.local.com/club-app/api-order-details", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Payment Status:--", "Success , " + mTXNId);
Custom_Toast.show(getApplication(), "Payment Transcation Success");
Intent intent = new Intent(Payment.this, MainActivity.class);
intent.putExtra("status", true);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
try {
if (progDialog.isShowing()) {
progDialog.dismiss();
}
Log.e("res Payment", "" + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
if (progDialog.isShowing()) {
progDialog.dismiss();
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(MAM_ID, "" + spfs.getString("mem_id", ""));
params.put(EMAIL, "" + mEmailId);
params.put(ADD1, "" + bundle.getString(ADD1));
params.put(ADD2, "" + bundle.getString(ADD2));
params.put(REGION_ID, "" + bundle.getString(REGION_ID));
params.put(CITY_ID, "" + bundle.getString(CITY_ID));
params.put(PIN_CODE, "" + bundle.getString(PIN_CODE));
params.put(ADD_DATE, "" + bundle.getString(ADD_DATE));
params.put(PRICE, "" + mAmount);
params.put(CARD_DISCOUNT, "" + bundle.getString(CARD_DISCOUNT));
params.put(PROMOCODE_DISCOUNT, "" + bundle.getString(PROMOCODE_DISCOUNT));
params.put(PROMOCODE, "" + bundle.getString(PROMOCODE));
params.put(TXNID, "" + mTXNId);
params.put(DEVICE_ID, "" + Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID));
params.put(PRODUCT_ID, "" + bundle.getString(PRODUCT_ID));
Log.e("Bndle Params:- ", params.toString());
return params;
}
};
int socketTimeout = 60000;// 30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
Volley.newRequestQueue(this).add(postRequest);
} catch (Exception e) {
if (progDialog.isShowing()) {
progDialog.dismiss();
}
Log.e("", " Exception Occurs - " + e);
}
}
}

Related

Linkedin API: No value for accessTokenValue and "access toke is not set" error

public void signInWithLinkedIn(View view) {
//First check if user is already authenticated or not and session is valid or not
if (!LISessionManager.getInstance(this).getSession().isValid()) {
//if not valid then start authentication
LISessionManager.getInstance(getApplicationContext()).init(LinkedInActivity.this, buildScope()//pass the build scope here
, new AuthListener() {
#Override
public void onAuthSuccess() {
// Authentication was successful. You can now do
// other calls with the SDK.
Toast.makeText(LinkedInActivity.this, "Successfully authenticated with LinkedIn.", Toast.LENGTH_SHORT).show();
//on successful authentication fetch basic profile data of user
//LISessionManager.getInstance(getApplicationContext()).clearSession();
fetchBasicProfileData();
}
#Override
public void onAuthError(LIAuthError error) {
// Handle authentication errors
//LISessionManager.getInstance(getApplicationContext()).clearSession();
Log.e("AUTH ERROR", "Auth Error :" + error.toString());
Toast.makeText(LinkedInActivity.this, "Failed to authenticate with LinkedIn. Please try again.", Toast.LENGTH_SHORT).show();
}
}, true);//if TRUE then it will show dialog if
// any device has no LinkedIn app installed to download app else won't show anything
} else {
//LISessionManager.getInstance(getApplicationContext()).clearSession();
Toast.makeText(this, "You have already been authenticated.", Toast.LENGTH_SHORT).show();
//if user is already authenticated fetch basic profile data for user
fetchBasicProfileData();
}
}
private static Scope buildScope() {
//Check Scopes in Application Settings before passing here else you won't able to read that data
// Scope.R_CONTACTINFO
return Scope.build(Scope.R_BASICPROFILE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
Log.d("Access token->", LISessionManager.getInstance(getApplicationContext()).getSession().getAccessToken().getValue());
}
/**
* method to fetch basic profile data
*/
private void fetchBasicProfileData() {
//In URL pass whatever data from user you want for more values check below link
//LINK : https://developer.linkedin.com/docs/fields/basic-profile
String url = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,public-profile-url,picture-url,email-address,picture-urls::(original))";
APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
apiHelper.getRequest(this, url, new ApiListener() {
#Override
public void onApiSuccess(ApiResponse apiResponse) {
// Success!
JSONObject responseObject = apiResponse.getResponseDataAsJson();
try {
profileURL = responseObject.getString("publicProfileUrl");
imgURL = responseObject.getString("pictureUrl");
fetchConnectionsData();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onApiError(LIApiError liApiError) {
// Error making GET request!
Log.e("FETCH PROFILE ERROR", "Fetch profile Error :" + liApiError.getLocalizedMessage());
Toast.makeText(LinkedInActivity.this, "Failed. Please try again.", Toast.LENGTH_SHORT).show();
}
});
}
Linkedin returns "No value for accessTokenValue" and "access toke is not set". It was working like last month but suddenly it does not work and I could not find anything wrong with the code. After much digging on Google, I am still unable to find a solution. Or am I using the v1 api which I should not? Any help will be greatly appreciated.
This is because the token generated by Linkedin SDK can not be verified by backend. The best solution is to open a webview and use Linkedin web apis- Step 1 - Create a new Class LinkedinActivity
public class LinkedinActivity {
/****FILL THIS WITH YOUR INFORMATION*********/
//This is the public api key of our application
private static final String API_KEY = "apikey";
//This is the private api key of our application
private static final String SECRET_KEY = "secretcode";
//This is any string we want to use. This will be used for avoiding CSRF attacks. You can generate one here: http://strongpasswordgenerator.com/
private static final String STATE = "123456789";
//This is the url that LinkedIn Auth process will redirect to. We can put whatever we want that starts with http:// or https:// .
//We use a made up url that we will intercept when redirecting. Avoid Uppercases.
private static final String REDIRECT_URI = "https://example.com";
/*********************************************/
//These are constants used for build the urls
private static final String AUTHORIZATION_URL = "https://www.linkedin.com/oauth/v2/authorization";
private static final String ACCESS_TOKEN_URL = "https://www.linkedin.com/uas/oauth2/accessToken";
private static final String SECRET_KEY_PARAM = "client_secret";
private static final String RESPONSE_TYPE_PARAM = "response_type";
private static final String GRANT_TYPE_PARAM = "grant_type";
private static final String GRANT_TYPE = "authorization_code";
private static final String RESPONSE_TYPE_VALUE = "code";
private static final String CLIENT_ID_PARAM = "client_id";
private static final String STATE_PARAM = "state";
private static final String REDIRECT_URI_PARAM = "redirect_uri";
/*---------------------------------------*/
private static final String QUESTION_MARK = "?";
private static final String AMPERSAND = "&";
private static final String EQUALS = "=";
private WebView webView;
private ImageView close_icon;
private ProgressDialog pd;
//private OauthInterface oauthInterface;
String accessToken;
Context context;
Dialog dialog;
public LinkedinActivity(#NonNull Context context) {
this.context = context;
}
public void showLinkedin() {
dialog = new Dialog(context, R.style.AppTheme);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
dialog.setContentView(R.layout.linkedin_activity);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
pd = ProgressDialog.show(context, "", "Loading...", true);
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LinkedinData linkedinData = (LinkedinData) context;
linkedinData.linkedCancel();
dialog.dismiss();
}
return true;
}
});
//oauthInterface = new OauthPresenter(this);
//get the webView from the layout
webView = (WebView) dialog.findViewById(R.id.activity_web_view);
close_icon = (ImageView) dialog.findViewById(R.id.close_icon);
close_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinkedinData linkedinData = (LinkedinData) context;
linkedinData.linkedCancel();
dialog.dismiss();
}
});
//Request focus for the webview
webView.requestFocus(View.FOCUS_DOWN);
//Show a progress dialog to the user
//Set a custom web view client
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
//This method will be executed each time a page finished loading.
//The only we do is dismiss the progressDialog, in case we are showing any.
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String authorizationUrl) {
//This method will be called when the Auth proccess redirect to our RedirectUri.
//We will check the url looking for our RedirectUri.
if (authorizationUrl.startsWith(REDIRECT_URI)) {
Log.i("Authorize", "");
Uri uri = Uri.parse(authorizationUrl);
//We take from the url the authorizationToken and the state token. We have to check that the state token returned by the Service is the same we sent.
//If not, that means the request may be a result of CSRF and must be rejected.
String stateToken = uri.getQueryParameter(STATE_PARAM);
if (stateToken == null || !stateToken.equals(STATE)) {
Log.e("Authorize", "State token doesn't match");
return true;
}
//If the user doesn't allow authorization to our application, the authorizationToken Will be null.
String authorizationToken = uri.getQueryParameter(RESPONSE_TYPE_VALUE);
if (authorizationToken == null) {
Log.i("Authorize", "The user doesn't allow authorization.");
return true;
}
Log.i("Authorize", "Auth token received: " + authorizationToken);
//Generate URL for requesting Access Token
String accessTokenUrl = getAccessTokenUrl(authorizationToken);
//We make the request in a AsyncTask
new PostRequestAsyncTask().execute(accessTokenUrl);
} else {
//Default behaviour
Log.i("Authorize", "Redirecting to: " + authorizationUrl);
webView.loadUrl(authorizationUrl);
}
return true;
}
});
//Get the authorization Url
String authUrl = getAuthorizationUrl();
Log.i("Authorize", "Loading Auth Url: " + authUrl);
//Load the authorization URL into the webView
webView.loadUrl(authUrl);
dialog.show();
}
private static String getAccessTokenUrl(String authorizationToken) {
return ACCESS_TOKEN_URL
+ QUESTION_MARK
+ GRANT_TYPE_PARAM + EQUALS + GRANT_TYPE
+ AMPERSAND
+ RESPONSE_TYPE_VALUE + EQUALS + authorizationToken
+ AMPERSAND
+ CLIENT_ID_PARAM + EQUALS + API_KEY
+ AMPERSAND
+ REDIRECT_URI_PARAM + EQUALS + REDIRECT_URI
+ AMPERSAND
+ SECRET_KEY_PARAM + EQUALS + SECRET_KEY;
}
/**
* Method that generates the url for get the authorization token from the Service
*
* #return Url
*/
private static String getAuthorizationUrl() {
return AUTHORIZATION_URL
+ QUESTION_MARK + RESPONSE_TYPE_PARAM + EQUALS + RESPONSE_TYPE_VALUE
+ AMPERSAND + CLIENT_ID_PARAM + EQUALS + API_KEY
+ AMPERSAND + REDIRECT_URI_PARAM + EQUALS + REDIRECT_URI
+ AMPERSAND + STATE_PARAM + EQUALS + STATE
+ AMPERSAND + "scope=r_emailaddress";
}
private class PostRequestAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(context, "", "loading", true);
}
#Override
protected String doInBackground(String... urls) {
if (urls.length > 0) {
String url = urls[0];
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
try {
HttpResponse response = httpClient.execute(httpost);
if (response != null) {
//If status is OK 200
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
//Convert the string result to a JSON Object
JSONObject resultJson = new JSONObject(result);
//Extract data from JSON Response
int expiresIn = resultJson.has("expires_in") ? resultJson.getInt("expires_in") : 0;
accessToken = resultJson.has("access_token") ? resultJson.getString("access_token") : null;
Log.e("Tokenm", "" + accessToken);
if (expiresIn > 0 && accessToken != null) {
Log.i("Authorize", "This is the access Token: " + accessToken + ". It will expires in " + expiresIn + " secs");
//Calculate date of expiration
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, expiresIn);
long expireDate = calendar.getTimeInMillis();
////Store both expires in and access token in shared preferences
SharedPreferences preferences = context.getSharedPreferences("user_info", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("expires", expireDate);
editor.putString("accessToken", accessToken);
//oauthInterface.oauthAuthentication(accessToken, "linkedin", new HackedPrefence(getApplicationContext()).getDevice_token());
editor.commit();
return accessToken;
}
}
}
} catch (IOException e) {
Log.e("Authorize", "Error Http response " + e.getLocalizedMessage());
} catch (ParseException e) {
Log.e("Authorize", "Error Parsing Http response " + e.getLocalizedMessage());
} catch (JSONException e) {
Log.e("Authorize", "Error Parsing Http response " + e.getLocalizedMessage());
}
}
return accessToken;
}
#Override
protected void onPostExecute(String status) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
LinkedinData linkedinData = (LinkedinData) context;
linkedinData.LinkedinSuccess(status);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
interface LinkedinData {
void linkedCancel();
void LinkedinSuccess(String Token);
}
}
Step 2 - Call LinkdinActivity.java class using the following code
new LinkedinActivity(this).showLinkedin();
You can call the above code on the click of a button. Example
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new LinkedinActivity(this).showLinkedin();
}
});
Here is linkedin_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<WebView
android:id="#+id/activity_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/close_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginRight="10dp"
android:layout_marginTop="22dp"
android:src="#drawable/ic_close_black"
android:layout_alignParentRight="true"/>
</RelativeLayout>

Need a full response in JSON/String from payu money Android. Getting Only PaymentId

I am using WebView client for payu money in Android, below is my source code for the same. In success I am getting only paymentId but I need other info like (payment status, payment mode etc) please check the below code and suggest me how can I get it.
public class PayMentGateWay extends Activity {
private ArrayList<String> post_val = new ArrayList<String>();
private String post_Data="";
WebView webView ;
final Activity activity = this;
private String tag = "PayMentGateWay";
private String hash,hashSequence;
ProgressDialog progressDialog ;
String merchant_key = "SHja8Z05";
String salt="0tR0sybux9";
String action1 ="";
String base_url="https://secure.payu.in";//
int error=0;
String hashString="";
Map<String,String> params;
String txnid ="";
String SUCCESS_URL = "https://www.payumoney.com/mobileapp/payumoney/success.php" ;
String FAILED_URL = "https://www.payumoney.com/mobileapp/payumoney/failure.php" ;
Handler mHandler = new Handler();
static String getFirstName, getNumber, getEmailAddress, getRechargeAmt;
ProgressDialog pDialog ;
#SuppressLint("JavascriptInterface") #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressDialog = new ProgressDialog(activity);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
webView = new WebView(this);
setContentView(webView);
Intent oIntent = getIntent();
getFirstName = oIntent.getExtras().getString("FIRST_NAME");
getNumber = oIntent.getExtras().getString("PHONE_NUMBER");
getEmailAddress = oIntent.getExtras().getString("EMAIL_ADDRESS");
getRechargeAmt = oIntent.getExtras().getString("RECHARGE_AMT");
//post_val = getIntent().getStringArrayListExtra("post_val");
//Log.d(tag, "post_val: "+post_val);
params= new HashMap<String,String>();
params.put("key", merchant_key);
params.put("amount", getRechargeAmt);
params.put("firstname", getFirstName);
params.put("email", getEmailAddress);
params.put("phone", getNumber);
params.put("productinfo", "Recharge Wallet");
params.put("surl", SUCCESS_URL);
params.put("furl", FAILED_URL);
params.put("service_provider", "payu_paisa");
params.put("lastname", "");
params.put("address1", "");
params.put("address2", "");
params.put("city", "");
params.put("state", "");
params.put("country", "");
params.put("zipcode", "");
params.put("udf1", "");
params.put("udf2", "");
params.put("udf3", "");
params.put("udf4", "");
params.put("udf5", "");
params.put("pg", "");
/*for(int i = 0;i<post_val.size();){
params.put(post_val.get(i), post_val.get(i+1));
i+=2;
}*/
if(empty(params.get("txnid"))){
Random rand = new Random();
String rndm = Integer.toString(rand.nextInt())+(System.currentTimeMillis() / 1000L);
txnid=hashCal("SHA-256",rndm).substring(0,20);
params.put("txnid", txnid);
}
else
txnid=params.get("txnid");
//String udf2 = txnid;
String txn="abcd";
hash="";
String hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if(empty(params.get("hash")) && params.size()>0)
{
if( empty(params.get("key"))
|| empty(params.get("txnid"))
|| empty(params.get("amount"))
|| empty(params.get("firstname"))
|| empty(params.get("email"))
|| empty(params.get("phone"))
|| empty(params.get("productinfo"))
|| empty(params.get("surl"))
|| empty(params.get("furl"))
|| empty(params.get("service_provider"))
){
error=1;
}
else{
String[] hashVarSeq=hashSequence.split("\\|");
for(String part : hashVarSeq)
{
hashString= (empty(params.get(part)))?hashString.concat(""):hashString.concat(params.get(part));
hashString=hashString.concat("|");
}
hashString=hashString.concat(salt);
hash=hashCal("SHA-512",hashString);
action1=base_url.concat("/_payment");
}
}
else if(!empty(params.get("hash")))
{
hash=params.get("hash");
action1=base_url.concat("/_payment");
}
webView.setWebViewClient(new MyWebViewClient(){
public void onPageFinished(WebView view, final String url) {
progressDialog.dismiss();
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//make sure dialog is showing
if (!progressDialog.isShowing()) {
progressDialog.show();
}
}
});
webView.setVisibility(View.VISIBLE);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setDomStorageEnabled(true);
webView.clearHistory();
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUseWideViewPort(false);
webView.getSettings().setLoadWithOverviewMode(false);
//webView.addJavascriptInterface(new PayUJavaScriptInterface(getApplicationContext()), "PayUMoney");
webView.addJavascriptInterface(new PayUJavaScriptInterface(), "PayUMoney");
Map<String, String> mapParams = new HashMap<String, String>();
mapParams.put("key",merchant_key);
mapParams.put("hash",PayMentGateWay.this.hash);
mapParams.put("txnid",(empty(PayMentGateWay.this.params.get("txnid"))) ? "" : PayMentGateWay.this.params.get("txnid"));
Log.d(tag, "txnid: "+PayMentGateWay.this.params.get("txnid"));
mapParams.put("service_provider","payu_paisa");
mapParams.put("amount",(empty(PayMentGateWay.this.params.get("amount"))) ? "" : PayMentGateWay.this.params.get("amount"));
mapParams.put("firstname",(empty(PayMentGateWay.this.params.get("firstname"))) ? "" : PayMentGateWay.this.params.get("firstname"));
mapParams.put("email",(empty(PayMentGateWay.this.params.get("email"))) ? "" : PayMentGateWay.this.params.get("email"));
mapParams.put("phone",(empty(PayMentGateWay.this.params.get("phone"))) ? "" : PayMentGateWay.this.params.get("phone"));
mapParams.put("productinfo",(empty(PayMentGateWay.this.params.get("productinfo"))) ? "" : PayMentGateWay.this.params.get("productinfo"));
mapParams.put("surl",(empty(PayMentGateWay.this.params.get("surl"))) ? "" : PayMentGateWay.this.params.get("surl"));
mapParams.put("furl",(empty(PayMentGateWay.this.params.get("furl"))) ? "" : PayMentGateWay.this.params.get("furl"));
mapParams.put("lastname",(empty(PayMentGateWay.this.params.get("lastname"))) ? "" : PayMentGateWay.this.params.get("lastname"));
mapParams.put("address1",(empty(PayMentGateWay.this.params.get("address1"))) ? "" : PayMentGateWay.this.params.get("address1"));
mapParams.put("address2",(empty(PayMentGateWay.this.params.get("address2"))) ? "" : PayMentGateWay.this.params.get("address2"));
mapParams.put("city",(empty(PayMentGateWay.this.params.get("city"))) ? "" : PayMentGateWay.this.params.get("city"));
mapParams.put("state",(empty(PayMentGateWay.this.params.get("state"))) ? "" : PayMentGateWay.this.params.get("state"));
mapParams.put("country",(empty(PayMentGateWay.this.params.get("country"))) ? "" : PayMentGateWay.this.params.get("country"));
mapParams.put("zipcode",(empty(PayMentGateWay.this.params.get("zipcode"))) ? "" : PayMentGateWay.this.params.get("zipcode"));
mapParams.put("udf1",(empty(PayMentGateWay.this.params.get("udf1"))) ? "" : PayMentGateWay.this.params.get("udf1"));
mapParams.put("udf2",(empty(PayMentGateWay.this.params.get("udf2"))) ? "" : PayMentGateWay.this.params.get("udf2"));
mapParams.put("udf3",(empty(PayMentGateWay.this.params.get("udf3"))) ? "" : PayMentGateWay.this.params.get("udf3"));
mapParams.put("udf4",(empty(PayMentGateWay.this.params.get("udf4"))) ? "" : PayMentGateWay.this.params.get("udf4"));
mapParams.put("udf5",(empty(PayMentGateWay.this.params.get("udf5"))) ? "" : PayMentGateWay.this.params.get("udf5"));
mapParams.put("pg",(empty(PayMentGateWay.this.params.get("pg"))) ? "" : PayMentGateWay.this.params.get("pg"));
webview_ClientPost(webView, action1, mapParams.entrySet());
}
private final class PayUJavaScriptInterface {
PayUJavaScriptInterface() {
}
/**
* This is not called on the UI thread. Post a runnable to invoke
* loadUrl on the UI thread.
*/
#JavascriptInterface
public void success(long id, final String paymentId) {
mHandler.post(new Runnable() {
public void run() {
mHandler = null;
/*Intent intent = new Intent();
intent.putExtra(Constants.RESULT, "success");
intent.putExtra(Constants.PAYMENT_ID, paymentId);
setResult(RESULT_OK, intent);
finish();*/
// new PostRechargeData().execute();
Intent intent=new Intent(PayMentGateWay.this,MainActivity.class);
intent.putExtra("test",getFirstName);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Successfully payment", Toast.LENGTH_LONG).show();
}
});
}
#JavascriptInterface
public void failure(final String id, String error) {
mHandler.post(new Runnable() {
#Override
public void run() {
//cancelPayment();
Toast.makeText(getApplicationContext(),"Cancel payment" ,Toast.LENGTH_LONG).show();
}
});
}
#JavascriptInterface
public void failure() {
failure("");
}
#JavascriptInterface
public void failure(final String params) {
mHandler.post(new Runnable() {
#Override
public void run() {
/*Intent intent = new Intent();
intent.putExtra(Constants.RESULT, params);
setResult(RESULT_CANCELED, intent);
finish();*/
Toast.makeText(getApplicationContext(),"Failed payment" ,Toast.LENGTH_LONG).show();
}
});
}
}
public void webview_ClientPost(WebView webView, String url, Collection< Map.Entry<String, String>> postData){
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body onload='form1.submit()'>");
sb.append(String.format("<form id='form1' action='%s' method='%s'>", url, "post"));
for (Map.Entry<String, String> item : postData) {
sb.append(String.format("<input name='%s' type='hidden' value='%s' />", item.getKey(), item.getValue()));
}
sb.append("</form></body></html>");
Log.d(tag, "webview_ClientPost called");
//setup and load the progress bar
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Loading. Please wait...");
webView.loadData(sb.toString(), "text/html", "utf-8");
}
public void success(long id, final String paymentId) {
mHandler.post(new Runnable() {
public void run() {
mHandler = null;
// new PostRechargeData().execute();
Toast.makeText(getApplicationContext(),"Successfully payment\n redirect from Success Function" ,Toast.LENGTH_LONG).show();
}
});
}
public boolean empty(String s)
{
if(s== null || s.trim().equals(""))
return true;
else
return false;
}
public String hashCal(String type,String str){
byte[] hashseq=str.getBytes();
StringBuffer hexString = new StringBuffer();
try{
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashseq);
byte messageDigest[] = algorithm.digest();
for (int i=0;i<messageDigest.length;i++) {
String hex=Integer.toHexString(0xFF & messageDigest[i]);
if(hex.length()==1) hexString.append("0");
hexString.append(hex);
}
}catch(NoSuchAlgorithmException nsae){ }
return hexString.toString();
}
//String SUCCESS_URL = "https://pay.in/sccussful" ; // failed
//String FAILED_URL = "https://pay.in/failed" ;
//override the override loading method for the webview client
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*if(url.contains("response.php") || url.equalsIgnoreCase(SUCCESS_URL)){
new PostRechargeData().execute();
Toast.makeText(getApplicationContext(),"Successfully payment\n redirect from webview" ,Toast.LENGTH_LONG).show();
return false;
}else */if(url.startsWith("http")){
//Toast.makeText(getApplicationContext(),url ,Toast.LENGTH_LONG).show();
progressDialog.show();
view.loadUrl(url);
System.out.println("myresult "+url);
//return true;
} else {
return false;
}
return true;
}
}
/******************************************* send record to back end ******************************************/
/*class PostRechargeData extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(PayMentGateWay.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args)
{
String strStatus = null;
ProfileSessionManager ProSessionManager = new ProfileSessionManager(PayMentGateWay.this);
String getUserid = ProSessionManager.getSpeculatorId();
String getSpeculationId = "0";
String rechargeAmt = getRechargeAmt;
String postAction = "1";
//http://speculometer.com/webService/stockApp/speculationMoneyreports.php?
//access_token=ISOFTINCstockAppCheckDevelop&speculator=1&speculation=&amount=1000&action=1
ServiceHandler sh = new ServiceHandler();
String upLoadServerUri = ServiceList.payment_money_url+"speculator="+getUserid+"&speculation="+getSpeculationId+"&amount="+rechargeAmt+"&action="+postAction;
try{
String jsonStr = sh.makeServiceCall(upLoadServerUri, ServiceHandler.POST);
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jobjDoc = jsonObj.optJSONObject("document");
JSONObject jobjRes = jobjDoc.optJSONObject("response");
strStatus = jobjRes.getString("status");
//strMessage = jobjRes.getString("message");
String strUserId = jobjRes.getString("user_id");
} catch (Exception e) {
e.printStackTrace();
}
return strStatus;
}
protected void onPostExecute(final String strStatus)
{
runOnUiThread(new Runnable()
{
public void run()
{
pDialog.dismiss();
if(strStatus != null && strStatus.equalsIgnoreCase("0")){
Toast.makeText(getApplicationContext(),"Your recharge amount not added in wallet." ,Toast.LENGTH_LONG).show();
}else if(strStatus != null && strStatus.equalsIgnoreCase("1")){
Toast.makeText(getApplicationContext(),"Your recharge amount added in wallet." ,Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(activity, MainActivity.class);
startActivity(intent);
}
});
}
}*/
/******************************************* closed send record to back end ************************************/
}
i have also faced the same issue. when contacted them they said on free version they only returns "paymentId", for rest of the fields you have to pay them. for further information about this please email your queries to "techsupport#payumoney.com"

Android ProgressDialog Won't be dismiss after Paytm Transation on success

when the paytm WebView calls "back to Activity" return. what should be the Approach to handle waiting for transation Complete.
My progress Dialog opened before Paytm Screen open but When returned from paytm screen to activity progress dialog not dismissing..
please any help or idea about this issue....
1.OnSuccess of transaction i opened paytmcheckout() method
in this method i want to Dismiss or cancel the progressbarDialog.
But it is not dismiss here.
public void paytmCheckout(){
if(_progressDialog.isShowing()) {
_progressDialog.hide();
_progressDialog.dismiss();
}
}
2. progressDialog Declared globally
ProgressDialog _progressDialog;
onButtonClick()
calls openpaytm Method
My OpenPaytm method::
private void openPaytm() {
int price;
if (discount != 0) {
price = modalPlan.getInrPrice() - discount;
} else {
price = modalPlan.getInrPrice();
}
//Here`
//my progressDialog is opened here successfully
//
if(_progressDialog==null){
mLoginFormView.setVisibility(View.INVISIBLE);
final ProgressDialog _progressDialog = ProgressDialog.show(
getActivity(),
"Transation",
"Progress....",
true,
true
);
}
Random randomGenerator = new Random();
randomInt = randomGenerator.nextInt(1000);
Service = PaytmPGService.getStagingService(); //for production environment
PaytmMerchant Merchant = new PaytmMerchant("https://app.mobikyte.com/paytm/generateChecksum.php", "https://app.mobikyte.com/paytm/verifyChecksum.php");
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("REQUEST_TYPE", "DEFAULT");
paramMap.put("ORDER_ID", "" + modalAddCampign.getOrderId());
paramMap.put("MID", "Audian53591216301431");
paramMap.put("CUST_ID", modalLogin.getClientid());
paramMap.put("CHANNEL_ID", "WAP");
paramMap.put("INDUSTRY_TYPE_ID", "Retail");
paramMap.put("WEBSITE", "AudianzN");
paramMap.put("TXN_AMOUNT", "" + price);
paramMap.put("THEME", "merchant");
String par = paramMap.toString();
Log.e("TESTING:", "Paytm Params" + par);
PaytmOrder Order = new PaytmOrder(paramMap);
Service.initialize(Order, Merchant, null);
Service.startPaymentTransaction(getActivity(), false, false, new PaytmPaymentTransactionCallback() {
#Override
public void onTransactionSuccess(Bundle bundle) {
Log.d("TEST", "Bundle = =" + bundle);
paytmCheckout();
}
#Override
public void onTransactionFailure(String s, Bundle bundle) {
Log.e("Error", "someErrorOccurred :" + s);
//Not dismissing here also
_progressDialog.dismiss();
// _progressDialog.cancel();
}
#Override
public void networkNotAvailable() {
Log.e("Error", "NetworkErrorOccurred :");
}
#Override
public void clientAuthenticationFailed(String s) {
Log.e("Error", "clientAuthenticationFailed :" + s);
}
#Override
public void someUIErrorOccurred(String s) {
Log.e("Error", "someUIErrorOccurred :" + s);
}
#Override
public void onErrorLoadingWebPage(int i, String s, String s1) {
Log.e("Error", "onErrorLoadingWebPage :" + s1);
}
});
}

Payumoney Integration Error

In this code when I run it is redirecting to payu and displaying Some error Occurred message
public class PayMentGateWay extends ActionBarActivity {
/**
* Adding WebView as setContentView
*/
WebView webView;
/**
* Context for Activity
*/
Context activity;
/**
* Order Id
* To Request for Updating Payment Status if Payment Successfully Done
*/
int mId; //Getting from Previous Activity
/**
* Required Fields
*/
// Test Variables
/*
private String mMerchantKey = "FCyqqZ";
private String mSalt = "sfBpGA8E";
private String mBaseURL = "https://test.payu.in";
*/
// Final Variables
private String mMerchantKey = "9HwJ5t";
private String mSalt = "2JIfn3ez";
private String mBaseURL = "https://test.payu.in";
private String mAction = ""; // For Final URL
private String mTXNId; // This will create below randomly
private String mHash; // This will create below randomly
private String mProductInfo = "Recharge"; //Passing String only
private String mFirstName; // From Previous Activity
private String mEmailId; // From Previous Activity
private double mAmount; // From Previous Activity
private String mPhone; // From Previous Activity
private String mServiceProvider = "payu_paisa";
private String mSuccessUrl = "www.google.com";
private String mFailedUrl = "www.facebook.com";
boolean isFromOrder;
/**
* Handler
*/
Handler mHandler = new Handler();
/**
* #param savedInstanceState
*/
#SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled", "JavascriptInterface"})
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
/**
* Setting WebView to Screen
*/
setContentView(R.layout.webview);
/**
* Creating WebView
*/
webView = (WebView) findViewById(R.id.webview);
/**
* Context Variable
*/
activity = getApplicationContext();
/**
* Actionbar Settings
*/
/*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
// enabling action bar app icon and behaving it as toggle button
ab.setHomeButtonEnabled(true);
ab.setTitle(getString(R.string.paymentgateway));*/
/**
* Getting Intent Variables...
*/
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mFirstName = bundle.getString("name");
mEmailId = bundle.getString("email");
mAmount = bundle.getInt("amount");
mPhone = bundle.getString("phone");
mId = bundle.getInt("id");
isFromOrder = bundle.getBoolean("isFromOrder");
/**
* Creating Transaction Id
*/
Random rand = new Random();
String randomString = Integer.toString(rand.nextInt()) + (System.currentTimeMillis() / 1000L);
mTXNId = hashCal("SHA-256", randomString).substring(0, 20);
//mAmount = new BigDecimal(mAmount).setScale(0, RoundingMode.UP).intValue();
/**
* Creating Hash Key
*/
mHash = hashCal("SHA-512", mMerchantKey + "|" +
mTXNId + "|" +
mAmount + "|" +
mProductInfo + "|" +
mFirstName + "|" +
mEmailId + "|||||||||||" +
mSalt);
/**
* Final Action URL...
*/
mAction = mBaseURL.concat("/_payment");
/**
* WebView Client
*/
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(activity, "Oh no! " + error, Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Toast.makeText(activity, "SSL Error! " + error, Toast.LENGTH_SHORT).show();
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (url.equals(mSuccessUrl)) {
Intent intent = new Intent(PayMentGateWay.this, MainActivity.class);
intent.putExtra("status", true);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else if (url.equals(mFailedUrl)) {
Intent intent = new Intent(PayMentGateWay.this, MainActivity.class);
intent.putExtra("status", false);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
super.onPageFinished(view, url);
}
});
webView.setVisibility(View.VISIBLE);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setDomStorageEnabled(true);
webView.clearHistory();
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUseWideViewPort(false);
webView.getSettings().setLoadWithOverviewMode(false);
webView.addJavascriptInterface(new PayUJavaScriptInterface(PayMentGateWay.this), "PayUMoney");
/**
* Mapping Compulsory Key Value Pairs
*/
Map<String, String> mapParams = new HashMap<>();
mapParams.put("key", mMerchantKey);
mapParams.put("txnid", mTXNId);
mapParams.put("amount", String.valueOf(mAmount));
mapParams.put("productinfo", mProductInfo);
mapParams.put("firstname", mFirstName);
mapParams.put("email", mEmailId);
mapParams.put("phone", mPhone);
mapParams.put("surl", mSuccessUrl);
mapParams.put("furl", mFailedUrl);
mapParams.put("hash", mHash);
mapParams.put("service_provider", mServiceProvider);
String postData = "hash="+ mHash + "&key="+ mMerchantKey+"&txnid=01237&amount=10&productinfo=p111&firstname=navraj&email=navraj#navraj.net&" + "phone=9991940305&salt="+ mSalt+"&surl="+"www.facebook.com"+"&furl="+"www.google.com";
// webView.postUrl(mAction, EncodingUtils.getBytes(postData, "base64"));
// In case of using PayU PG //url = payuConfig.getEnvironment() == PayuConstants.PRODUCTION_ENV? PayuConstants.PRODUCTION_PAYMENT_URL : //PayuConstants.MOBILE_TEST_PAYMENT_URL ; //webView.postUrl(url, EncodingUtils.getBytes(payuConfig.getData(), "base64"));
webViewClientPost(webView, mAction, mapParams.entrySet());
} else {
Toast.makeText(activity, "Something went wrong, Try again.", Toast.LENGTH_LONG).show();
}
}
/**
* Posting Data on PayUMoney Site with Form
*
* #param webView
* #param url
* #param postData
*/
public void webViewClientPost(WebView webView, String url,
Collection<Map.Entry<String, String>> postData) {
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body onload='form1.submit()'>");
sb.append(String.format("<form id='form1' action='%s' method='%s'>", url, "post"));
for (Map.Entry<String, String> item : postData) {
sb.append(String.format("<input name='%s' type='hidden' value='%s' />", item.getKey(), item.getValue()));
}
sb.append("</form></body></html>");
Log.d("TAG", "webViewClientPost called: " + sb.toString());
webView.loadData(sb.toString(), "text/html", "utf-8");
}
/**
* Hash Key Calculation
*
* #param type
* #param str
* #return
*/
public String hashCal(String type, String str) {
byte[] hashSequence = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashSequence);
byte messageDigest[] = algorithm.digest();
for (int i = 0; i < messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if (hex.length() == 1)
hexString.append("0");
hexString.append(hex);
}
} catch (NoSuchAlgorithmException NSAE) {
}
return hexString.toString();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
onPressingBack();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
onPressingBack();
}
/**
* On Pressing Back
* Giving Alert...
*/
private void onPressingBack() {
final Intent intent;
if(isFromOrder)
intent = new Intent(PayMentGateWay.this, MainActivity.class);
else
intent = new Intent(PayMentGateWay.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PayMentGateWay.this);
// Setting Dialog Title
alertDialog.setTitle("Warning");
// Setting Dialog Message
alertDialog.setMessage("Do you cancel this transaction?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
public class PayUJavaScriptInterface {
Context mContext;
/**
* Instantiate the interface and set the context
*/
PayUJavaScriptInterface(Context c) {
mContext = c;
}
public void success(long id, final String paymentId) {
mHandler.post(new Runnable() {
public void run() {
mHandler = null;
Toast.makeText(PayMentGateWay.this, "Payment Successfully.", Toast.LENGTH_SHORT).show();
}
});
}
}
}

How to insert to db in payumoney android integration?

This is my code :
public class PayUMoneyActivity extends AppCompatActivity {
/**
* Adding WebView as setContentView
*/
WebView webView;
/**
* Context for Activity
*/
Context activity;
/**
* Order Id
* To Request for Updating Payment Status if Payment Successfully Done
*/
int mId; //Getting from Previous Activity
/**
* Required Fields
*/
// Test Variables
/*
private String mMerchantKey = "FCyqqZ";
private String mSalt = "sfBpGA8E";
private String mBaseURL = "https://test.payu.in";
*/
// Final Variables
private String mMerchantKey = "Your Merchant Key";
private String mSalt = "Salt";
private String mBaseURL = "https://secure.payu.in";
private String mAction = ""; // For Final URL
private String mTXNId; // This will create below randomly
private String mHash; // This will create below randomly
private String mProductInfo = "Food Items"; //Passing String only
private String mFirstName; // From Previous Activity
private String mEmailId; // From Previous Activity
private double mAmount; // From Previous Activity
private String mPhone; // From Previous Activity
private String mServiceProvider = "payu_paisa";
private String mSuccessUrl = "your success URL";
private String mFailedUrl = "Your Failure URL";
boolean isFromOrder;
/**
* Handler
*/
Handler mHandler = new Handler();
/**
* #param savedInstanceState
*/
#SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled"})
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
/**
* Setting WebView to Screen
*/
setContentView(R.layout.activity_webview_for_payumoney);
/**
* Creating WebView
*/
webView = (WebView) findViewById(R.id.payumoney_webview);
/**
* Context Variable
*/
activity = getApplicationContext();
/**
* Actionbar Settings
*/
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
// enabling action bar app icon and behaving it as toggle button
ab.setHomeButtonEnabled(true);
ab.setTitle(getString(R.string.title_activity_online_payment));
/**
* Getting Intent Variables...
*/
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
mFirstName = bundle.getString("name");
mEmailId = bundle.getString("email");
mAmount = bundle.getDouble("amount");
mPhone = bundle.getString("phone");
mId = bundle.getInt("id");
isFromOrder = bundle.getBoolean("isFromOrder");
Log.i(TAG, "" + mFirstName + " : " + mEmailId + " : " + mAmount + " : " + mPhone);
/**
* Creating Transaction Id
*/
Random rand = new Random();
String randomString = Integer.toString(rand.nextInt()) + (System.currentTimeMillis() / 1000L);
mTXNId = hashCal("SHA-256", randomString).substring(0, 20);
mAmount = new BigDecimal(mAmount).setScale(0, RoundingMode.UP).intValue();
/**
* Creating Hash Key
*/
mHash = hashCal("SHA-512", mMerchantKey + "|" +
mTXNId + "|" +
mAmount + "|" +
mProductInfo + "|" +
mFirstName + "|" +
mEmailId + "|||||||||||" +
mSalt);
/**
* Final Action URL...
*/
mAction = mBaseURL.concat("/_payment");
/**
* WebView Client
*/
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Toast.makeText(activity, "Oh no! " + error, Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Toast.makeText(activity, "SSL Error! " + error, Toast.LENGTH_SHORT).show();
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (url.equals(mSuccessUrl)) {
Intent intent = new Intent(PayUMoneyActivity.this, PaymentStatusActivity.class);
intent.putExtra("status", true);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else if (url.equals(mFailedUrl)) {
Intent intent = new Intent(PayUMoneyActivity.this, PaymentStatusActivity.class);
intent.putExtra("status", false);
intent.putExtra("transaction_id", mTXNId);
intent.putExtra("id", mId);
intent.putExtra("isFromOrder", isFromOrder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
super.onPageFinished(view, url);
}
});
webView.setVisibility(View.VISIBLE);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setCacheMode(2);
webView.getSettings().setDomStorageEnabled(true);
webView.clearHistory();
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setUseWideViewPort(false);
webView.getSettings().setLoadWithOverviewMode(false);
webView.addJavascriptInterface(new PayUJavaScriptInterface(PayUMoneyActivity.this), "PayUMoney");
/**
* Mapping Compulsory Key Value Pairs
*/
Map<String, String> mapParams = new HashMap<>();
mapParams.put("key", mMerchantKey);
mapParams.put("txnid", mTXNId);
mapParams.put("amount", String.valueOf(mAmount));
mapParams.put("productinfo", mProductInfo);
mapParams.put("firstname", mFirstName);
mapParams.put("email", mEmailId);
mapParams.put("phone", mPhone);
mapParams.put("surl", mSuccessUrl);
mapParams.put("furl", mFailedUrl);
mapParams.put("hash", mHash);
mapParams.put("service_provider", mServiceProvider);
webViewClientPost(webView, mAction, mapParams.entrySet());
} else {
Toast.makeText(activity, "Something went wrong, Try again.", Toast.LENGTH_LONG).show();
}
}
/**
* Posting Data on PayUMoney Site with Form
*
* #param webView
* #param url
* #param postData
*/
public void webViewClientPost(WebView webView, String url,
Collection<Map.Entry<String, String>> postData) {
StringBuilder sb = new StringBuilder();
sb.append("<html><head></head>");
sb.append("<body onload='form1.submit()'>");
sb.append(String.format("<form id='form1' action='%s' method='%s'>", url, "post"));
for (Map.Entry<String, String> item : postData) {
sb.append(String.format("<input name='%s' type='hidden' value='%s' />", item.getKey(), item.getValue()));
}
sb.append("</form></body></html>");
Log.d("TAG", "webViewClientPost called: " + sb.toString());
webView.loadData(sb.toString(), "text/html", "utf-8");
}
/**
* Hash Key Calculation
*
* #param type
* #param str
* #return
*/
public String hashCal(String type, String str) {
byte[] hashSequence = str.getBytes();
StringBuffer hexString = new StringBuffer();
try {
MessageDigest algorithm = MessageDigest.getInstance(type);
algorithm.reset();
algorithm.update(hashSequence);
byte messageDigest[] = algorithm.digest();
for (int i = 0; i < messageDigest.length; i++) {
String hex = Integer.toHexString(0xFF & messageDigest[i]);
if (hex.length() == 1)
hexString.append("0");
hexString.append(hex);
}
} catch (NoSuchAlgorithmException NSAE) {
}
return hexString.toString();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
onPressingBack();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
onPressingBack();
}
/**
* On Pressing Back
* Giving Alert...
*/
private void onPressingBack() {
final Intent intent;
if(isFromOrder)
intent = new Intent(PayUMoneyActivity.this, ProductInCartList.class);
else
intent = new Intent(PayUMoneyActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PayUMoneyActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Warning");
// Setting Dialog Message
alertDialog.setMessage("Do you cancel this transaction?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
public class PayUJavaScriptInterface {
Context mContext;
/**
* Instantiate the interface and set the context
*/
PayUJavaScriptInterface(Context c) {
mContext = c;
}
public void success(long id, final String paymentId) {
mHandler.post(new Runnable() {
public void run() {
mHandler = null;
Toast.makeText(PayUMoneyActivity.this, "Payment Successfully.", Toast.LENGTH_SHORT).show();
}
});
}
}
}
The function onPageFinished() does not get invoked. The respective intent is not being called, when the payment succeeds. The webview just redirects to the success page. Can anyone help me in resolving this error? I also need to add the bundle variables to the db, on redirecting to success page.

Categories

Resources