How to implement PayUmonney in Android & how to create a Hash key in local because I don't know how to create in server - performance

public void PayuMonney(){
**JAVA
this method i am using in my code but it's not done
here i am use payumonney code given to Documentation https://payumobile.gitbook.io/sdk-integration/android/payucheckoutpro. i trying too much but the toast appear in "invalid Hash"**
PayUPaymentParams.Builder builder = new PayUPaymentParams.Builder();
builder.setAmount(mAmount)
.setIsProduction(true)
.setProductInfo(mProductInfo)
.setKey(mMerchantKey)
.setPhone(mPhoneNumber)
.setTransactionId(mTXNId)
.setFirstName(mFirstName)
.setEmail(mEmailId)
.setSurl("https://www.payumoney.com/mobileapp/payumoney/success.php")
.setFurl("https://www.payumoney.com/mobileapp/payumoney/failure.php");
**Optional can contain any additional PG params**
PayUPaymentParams payUPaymentParams = builder.build();
***here i am calling Payuminney checkout process Sample code***
PayUCheckoutPro.open(
this,
payUPaymentParams,
new PayUCheckoutProListener() {
#Override
public void onPaymentSuccess(Object response) {
//Cast response object to HashMap
HashMap<String,Object> result = (HashMap<String, Object>) response;
String payuResponse = (String)result.get(PayUCheckoutProConstants.CP_PAYU_RESPONSE);
String merchantResponse = (String) result.get(PayUCheckoutProConstants.CP_MERCHANT_RESPONSE);
}
#Override
public void onPaymentFailure(Object response) {
//Cast response object to HashMap
HashMap<String,Object> result = (HashMap<String, Object>) response;
String payuResponse = (String)result.get(PayUCheckoutProConstants.CP_PAYU_RESPONSE);
String merchantResponse = (String) result.get(PayUCheckoutProConstants.CP_MERCHANT_RESPONSE);
}
#Override
public void onPaymentCancel(boolean isTxnInitiated) {
}
#Override
public void onError(ErrorResponse errorResponse) {
*//code give some error toast here i the onError fuction*
String errorMessage = errorResponse.getErrorMessage();
Toast.makeText(FinalPlaceOrderActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
}
#Override
public void setWebViewProperties(#Nullable WebView webView, #Nullable Object o) {
*//For setting webview properties, if any. Check Customized Integration section for more details on this*
}
#Override
public void generateHash(HashMap<String, String> valueMap, PayUHashGenerationListener hashGenerationListener) {
String hashName = valueMap.get(PayUCheckoutProConstants.CP_HASH_NAME);
String hashData = valueMap.get(PayUCheckoutProConstants.CP_HASH_STRING);
if (!TextUtils.isEmpty(hashName) && !TextUtils.isEmpty(hashData)) {
*//Do not generate a hash from local, it needs to be calculated from server-side only. Here, hashString contains hash created from your server side.
//here i am call the server file where generate a hash*
StringRequest OrderPlace = new StringRequest(Request.Method.POST, "url link", new Response.Listener() {
#Override
public void onResponse(String response) {
//here i am get hash from the server
System.out.println(response);
String merchandHsh = response;
HashMap<String, String> dataMap = new HashMap<>();
dataMap.put(hashName, merchandHsh);
hashGenerationListener.onHashGenerated(dataMap);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "We can't process this time..", Toast.LENGTH_SHORT).show();
}
}
) {
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("key", mMerchantKey);
map.put("texID", mTXNId);
map.put("amount", mAmount);
map.put("productname", mProductInfo);
map.put("name", mFirstName);
map.put("email", mEmailId);
return map;
}
};
Volley.newRequestQueue(FinalPlaceOrderActivity.this).add(OrderPlace);
}
}
}
);
}
but the toast appears a "Hash invalid". this method I am using in my code but it's not done
here I am using the pay money code given to Documentation https://payumobile.gitbook.io/sdk-integration/android/payucheckoutpro. I trying too much but the toast appears in "invalid Hash"
How to implement PayUmonney in Android & how to create a Hash key in local because I don't know how to create in server

Related

Trust Anchor for Certification path not found - https POST Request with Volley not working

this question is asked very often, but all the answers 2 or 3 years old. I have a login for my Android app and the date is saved in a MySQL database on my cloud server which has a SSL certificate.
When I test my app on my local machine everything is fine, but when I try to connect with my cloud server I get the message "Trust Anchor for Certification path not found". My credentials are ok.
I know that I have to set a sslSocketFactory. I tried so many, but one worked. I´m sitting now for days. May someone had a idea how to solve
here my code without sslSocketFactory
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.logintest, container, false);
btn_login = view.findViewById(R.id.btn_logintest);
email = view.findViewById(R.id.etEmail);
password = view.findViewById(R.id.etPassword);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
public void login() {
str_email = email.getText().toString();
str_password = password.getText().toString();
if(!str_email.equals("") && !str_password.equals("")) {
StringRequest request = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction= fragmentManager.beginTransaction();
DummyFragment dummyFragment = new DummyFragment();
fragmentTransaction.replace(R.id.container,dummyFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Log.e("Text: ", response);
Toast.makeText(getActivity(), "erfolgreicher Text: " +response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Text: " +error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("str_email", email.getText().toString());
params.put("str_password", password.getText().toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
try {
HashMap<String, String> headers = new HashMap<>();
String credentials = "xxxxxxxxx:xxxxxxxxxx";
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
return headers;
} catch (Exception e) {
Log.e(TAG, "Authentication failure");
Toast.makeText(getActivity(), "" +e, Toast.LENGTH_LONG).show();
}
return super.getHeaders();
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(request);
}
else {
if (email.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Bitte Email Adresse eingeben", Toast.LENGTH_SHORT).show();
} else if (password.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Bitte Passwort eingeben", Toast.LENGTH_SHORT).show();
}
}
}
});
return view;
}
}
I tried the code from android developer page, but some error. I tried to set network_security.xml but it didn't worked for me. When I test my credentials with postman I get response 200.

Parse JSON array data in android using Volley

JSON data format:
I am trying to fetch this array json data but not getting it.
[{"Items":"Chicken Burger","Price":"250","Quantity":"2"},
{"Items":"Hamburger","Price":"230","Quantity":"3"}]
MyCartActivity class:
I tried using Volley and I am now getting that JSONArray cannot be converted to JSONObject error. Can you mention where to change so that I can get my data?
final JsonObjectRequest request = new JsonObjectRequest (Request.Method.POST, fetchurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i=0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String Price = object.getString("Price");
String Name = object.getString("Items");
String Quantity = object.getString("Quantity");
adapter = new CartAdapter(MyCartActivity.this, list);
list.add(new CartPojo(Price, Name, Quantity));
adapter.notifyDataSetChanged();
progressbar.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
Adapter class:
public CartAdapter(Activity activity, List datalist) {
this.activity = activity;
this.datalist = datalist;
}
#Override
public int getCount() {
return datalist.size();
}
#Override
public Object getItem(int position) {
return datalist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.cart_item_layout, null);
TextView ItemName = convertView.findViewById(R.id.item_name);
TextView Price = convertView.findViewById(R.id.item_price);
TextView Quantity = convertView.findViewById(R.id.items_quantity);
CartPojo pojo = datalist.get(position);
ItemName.setText(String.valueOf(pojo.getName()));
Price.setText(String.valueOf(pojo.getPrice()));
Quantity.setText(String.valueOf(pojo.getQuantity()));
return convertView;
}
Please provide me some solutions....
The response can't be parsed into JSONObject, because its not that, but a JSONArray. You can send a simple StringRequest and then parse the response string into an JSONArray using JSONArray(response) constructor.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray arr = new JSONArray(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Or use the JsonArrayRequest. Here's an example.

While uploading image to server (error while uploading)

In my app I m sending 3 parameters to server latitude,longitude and image.Earlier i was using volley for sending the parameter, but since i have a image also I had to use Multipart in my code.But i m getting an error while uploadind. In the notification bar the uploading starts but after some times it says error in uploading
Below is the code for MultiPart:
public void send() {
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, REGISTER_URL)
.setMethod("POST")
.addParameter("action", "location")
.addFileToUpload(imagePath, "data")//Adding file
//.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Below is my volley code:
final String latitudee = String.valueOf(latitude);
final String longitudee =String.valueOf(longitude);
final String datae = imagePath;
//getting the actual path of the image
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MapsActivity.this,response,Toast.LENGTH_LONG).show();
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapsActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("action","location");
params.put("latitude",latitudee);
params.put("longitude",longitudee);
send();
// params.put("data", datae);
//Uploading code
return params;}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Please help me where I'm going wrong
You can send your others parameters through Multipart request library too. just add "add parameter" to send more parameters.

getting a 401 error on connecting to linkedin rest api with volley

I am trying to get email address of a user through linkedin's rest api. I am using volley for the request. But it shows 401 error. Can anyone help me through this. Below is the code. Access token is for r_basicprofile and r_emailaddress permissions
private static final String PROFILE_URL = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)";
private static final String OAUTH_ACCESS_TOKEN_PARAM ="oauth2_access_token";
private static final String QUESTION_MARK = "?";
private static final String EQUALS = "=";
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private static final String HEADER_AUTHORIZATION = "Authorization";
private static final String HEADER_SRC = "x-li-src";
private static final String HEADER_LI_FORMAT = "x-li-format";
private static final String HEADER_LI_VER = "x-li-msdk-ver";
private static final String CONTENT_VALUE = "application/json";
private static final String HEADER_SRC_VALUE = "msdk";
private static final String HEADER_LI_FORMAT_VALUE = "json";
private TextView welcomeText;
private ProgressDialog pd;
String accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fflifind_friends);
welcomeText = (TextView) findViewById(R.id.activity_profile_welcome_text);
//Request basic profile of the user
SharedPreferences preferences = this.getSharedPreferences("user_info", 0);
accessToken = preferences.getString("accessToken", null);
if(accessToken!=null){
String profileUrl = getProfileUrl(accessToken);
Log.d("profile url", profileUrl);
// new GetProfileRequestAsyncTask().execute(profileUrl);
doServer(profileUrl);
}
}
private Map<String, String> getLiHeaders(String accessToken) {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(HEADER_CONTENT_TYPE, CONTENT_VALUE);
headers.put(HEADER_AUTHORIZATION, "Bearer " + accessToken);
headers.put(HEADER_SRC, HEADER_SRC_VALUE);
headers.put(HEADER_LI_FORMAT, HEADER_LI_FORMAT_VALUE);
//headers.put(HEADER_LI_VER, BuildConfig.MSDK_VERSION);
return headers;
}
private static final String getProfileUrl(String accessToken){
String url = PROFILE_URL
+ QUESTION_MARK
+ OAUTH_ACCESS_TOKEN_PARAM + EQUALS + accessToken;
return url;
}
public void doServer(String url)
{
final ProgressDialog dialog = ProgressDialog.show(this, null, "Loading data ");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
dialog.dismiss();
Log.d("Jsonres-", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
// TODO Auto-generated method stub
Log.d("error ","err");
Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getLiHeaders(accessToken);
}
};
NetworkRequestQueue.getInstance(this).addToRequestQueue(jsObjRequest);
}
Use this method to get the profile information of linkedin account and define what you want from profile in PROFILE_LINK string mention below it's working fine for me.I hope its solved your problem.
public static final String HOST="https://api.linkedin.com/";
public static final String PROFILE_LINK=HOST+"v1/people/~:(id,firstName,lastName,picture-url)?oauth2_access_token=";
public static final String JSON_FORMAT=AMPERSAND+"format=json";
private void profileRequestAsyncTask(final String accessToken) {
showProgressDialog();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(activity);
String url=PROFILE_LINK+accessToken+JSON_FORMAT;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.e(TAG, "onResponse: "+response );
JSONObject dataAsJson= null;
try {
dataAsJson = new JSONObject(response);
String id=dataAsJson.getString("id");
String firstName=dataAsJson.getString("firstName");
String lastName=dataAsJson.getString("lastName");
String pictureUrl=dataAsJson.getString("pictureUrl");
Log.e(TAG, "onResponse: "+id+"="+firstName+"-"+lastName+"-"+pictureUrl );
String username=firstName+" "+lastName;
insertLinkedinAccount(id,username,pictureUrl,accessToken,expires);
editor.clear();
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
//Log.e(TAG, "onApiSuccess:profileData- "+firstName+"-"+lastName+"-"+profileId);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error );
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}

AsyncTask HttpConnection in Android

I want to create httpconnection using asyntask.three parameters are posted to the server
username,password and a search item.the search is provided by the user in an EditText such so that when the user clicks a button,the search item is sent to the server.I want to execute the doInbackground() method in the OnclickListener and display the response from the server on listviews.This is the AsyncTask Class
public class PostToServer extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
}
#Override
protected String doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
String postURL = "url";
String username ="username";
String password = "password";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", username));
params.add(new BasicNameValuePair("pass", password));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
This the class where the click event is called
public class StartPost extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
}
Button Submit = (Button) findViewById(R.id.btn_search);
EditText textvalue = (EditText)findViewById(R.id.searcheditText);
String value = textvalue.getText().toString();
PostToServer post = new PostToServer();
CheckInternetConnection check = new CheckInternetConnection(null);
private OnClickListener click = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.btn_search:
post.execute();
break;
}
}
};
}
Questions
1.What am I doing wrong because it seems the post is not working and How can I display the server results from the onPostExecute()?
Thank You.
Create a onPostExecute method to display the results on your textview.
protected onPostExecute (String result){
TextView tv = (TextView) findViewById(R.id.textview1);
if(result != null){
tv.setText(result);
}
}

Resources