this is my first question on stackoverflow.hope i can find my solutuon .i am integrating paypal in android.my device is showing "payment of this marchent are not allowed(invalid client id).here is my code
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_PRODUCTION;
// note that these credentials will differ between live & sandbox
// environments.
private static final String CONFIG_CLIENT_ID ="my client id";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Rajeev Lochan Sharma")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(
Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afcl);
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startService(intent);
ButterKnife.inject(this);
_request3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// signup();
new Test().execute(_names.getText().toString(), _placeofbirth.getText().toString(), _timeofbirth.getText().toString()
);
thingToBuy = new PayPalPayment(new BigDecimal("10"), "USD",
"quote", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(AfcRequest1Activity.this,
PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
});
}
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
private class Test extends AsyncTask {
protected void onPreExecute() {
super.onPreExecute();
//here you can some progress dialog or some view
}
#Override
protected String doInBackground(String... Params) {
String res = "";
try {
byte[] result = null;
String str = "";
HttpClient client;
HttpPost post;
ArrayList<NameValuePair> nameValuePair;
HashMap<String, String> mData;
Iterator<String> it;
HttpResponse response;
StatusLine statusLine;
//here is url api call url
post = new HttpPost("http://astro360horoscope.com/backend/api/form_amc_afc.php");
nameValuePair = new ArrayList<NameValuePair>();
mData = new HashMap<String, String>();
mData.put("username", Params[0]);
mData.put("placeofbirth", Params[1]);
mData.put("timeofbirth", Params[2]);
//for now nothing is there
it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "utf-8"));
client = new DefaultHttpClient();
response = client.execute(post);
statusLine = response.getStatusLine();
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "utf-8");
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
//here we get the response if all is correct
res = str;
} else {
res = str;
return res;
}
} catch (Exception e1) {
res = "error:" + e1.getMessage().toString();
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(AfcRequest1Activity.this,
PayPalFuturePaymentActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
System.out.println(confirm.toJSONObject().toString(4));
System.out.println(confirm.getPayment().toJSONObject()
.toString(4));
Toast.makeText(getApplicationContext(), "Order placed",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
System.out.println("The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
System.out
.println("An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("FuturePaymentExample", auth.toJSONObject()
.toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(getApplicationContext(),
"Future Payment code received from PayPal",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("FuturePaymentExample",
"an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Application Correlation ID from the SDK
String correlationId = PayPalConfiguration
.getApplicationCorrelationId(this);
Log.i("FuturePaymentExample", "Application Correlation ID: "
+ correlationId);
// TODO: Send correlationId and transaction details to your server for
// processing with
// PayPal...
Toast.makeText(getApplicationContext(),
"App Correlation ID received from SDK", Toast.LENGTH_LONG)
.show();
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
Related
I want to show my image in imageview after click but i don't know why this error occur and i searched a lot on this but i could no find solution of this problem and i tried to implement code after see solution but it doesn't work,so i m confused what's going wrong.This is my code:
package kmsg.com.onetouch.activity;
public class UploadDocumentActivity extends AppCompatActivity {
JSONParser parser;
Bitmap photo;
ImageView mImgDocument;
Button mBtnBill,mBtnPres,mBtnGetFile,mBtnUpload;
EditText mEtBillDate,mEtbillValue,mEtStoreRefID,mEtDoctorID;
LinearLayout mBillLinear,mPresLinear;
String mBillDate,mBillValue,mStoreRefID,mDoctorID;
boolean flag= true;
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_document);
parser = new JSONParser(this);
init();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
private void init() {
mImgDocument=(ImageView)findViewById(R.id.imgDocument);
mBtnBill=(Button)findViewById(R.id.btnBill);
mBtnPres=(Button)findViewById(R.id.btnPres);
mBtnGetFile=(Button)findViewById(R.id.btnGetFile);
mBtnUpload=(Button)findViewById(R.id.btnUpload);
mEtBillDate=(EditText)findViewById(R.id.et_billDate);
mEtbillValue=(EditText)findViewById(R.id.et_billValue);
mEtStoreRefID=(EditText)findViewById(R.id.et_refID);
mEtDoctorID=(EditText)findViewById(R.id.et_doctorID);
mBillLinear=(LinearLayout)findViewById(R.id.bill_linear);
mPresLinear=(LinearLayout)findViewById(R.id.prescription_linear);
}
public void getBill(View view) {
flag= true;
mPresLinear.setVisibility(View.GONE);
mBillLinear.setVisibility(View.VISIBLE);
}
public void getPrescription(View view) {
flag=false;
mBillLinear.setVisibility(View.GONE);
mPresLinear.setVisibility(View.VISIBLE);
}
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureNm = getPictureName();
imageFile = new File(pictureDirectory , pictureNm);
Uri pictureUri = Uri.fromFile(imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
/* public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CAMERA_REQUEST);
}
}
*/
private String getPictureName(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "paymentProof" + timestamp + ".jpg";
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_CANCELED){
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImgDocument.setImageBitmap(photo);
}
}
}
private boolean validateFormForBill() {
mBillDate = mEtBillDate.getText().toString().trim();
mBillValue = mEtbillValue.getText().toString().trim();
mStoreRefID = mEtStoreRefID.getText().toString().trim();
mEtBillDate.setError(null);
mEtbillValue.setError(null);
mEtStoreRefID.setError(null);
if (TextUtils.isEmpty(mBillDate.trim())) {
mEtBillDate.setError("Bill Date cannot be blank");
return false;
}
if (TextUtils.isEmpty(mBillValue.trim())) {
mEtbillValue.setError("Bill Value cannot be blank");
return false;
}
if (TextUtils.isEmpty(mStoreRefID.trim())) {
mEtStoreRefID.setError("Ref ID cannot be blank");
return false;
}
return true;
}
private boolean validateFormForPres() {
mDoctorID = mEtDoctorID.getText().toString().trim();
mEtDoctorID.setError(null);
if (TextUtils.isEmpty(mDoctorID.trim())) {
mEtDoctorID.setError("Doctor ID cannot be blank");
return false;
}
return true;
}
public void uploadDocument(View view) {
if (UtilityServices.checkInternetConnection(UploadDocumentActivity.this)) {
if (flag) {
if (UploadDocumentActivity.this.validateFormForBill()) {
new UploadBill().execute();
}
} else {
if (UploadDocumentActivity.this.validateFormForPres()) {
// new UploadPres().execute();
}
}
}else {
Toast.makeText(this, R.string.no_internet, Toast.LENGTH_SHORT).show();
}
}
private class UploadBill extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("billAmt", mBillValue));
partList.add(new StringPart("billDate", mBillDate));
partList.add(new StringPart("storeId", mStoreRefID));
System.out.println("Data"+mBillDate+mBillValue+mStoreRefID);
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")));
/* try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}*/
String url = Constants.UPLOAD_BILL;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
private class UploadPres extends AsyncTask<String,String,String> {
String status= null;
String msg = null;
JSONObject responseObject;
#Override
protected String doInBackground(String... strings) {
List<Part> partList = new ArrayList<>();
partList.add(new StringPart("storeId", mDoctorID));
partList.add(new StringPart("userMobile", SharedPrefManager.getString("mobile")+""));
try {
partList.add(new FilePart("file", imageFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String url = Constants.UPLOAD_PRESCRIPTION;
System.out.println("partList:"+partList);
responseObject = parser.makeHttpRequestWithMultipart(url, partList);
try {
// Simulate network access.
if (responseObject != null) {
System.out.println("responseObject: " + responseObject.toString());
try {
status = responseObject.getString(Constants.SVC_STATUS);
return status;
} catch (JSONException e) {
e.printStackTrace();
}
}
if (responseObject.has(Constants.SVC_MSG)) {
try {
msg = responseObject.getString(Constants.SVC_MSG);
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
super.onPostExecute(success);
if (success != null) {
System.out.println(Constants.STATUS_SUCCESS);
if (Constants.STATUS_SUCCESS.equals(success)) {
System.out.println("Successful Svc Call:"+ "post object task details called");
Toast.makeText(UploadDocumentActivity.this, "Successful Svc Call:"+ "post object task details called", Toast.LENGTH_LONG).show();
} else {
System.out.println(success);
try {
AlertDialog alertDialog = new AlertDialog.Builder(UploadDocumentActivity.this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage(responseObject.getString(Constants.SVC_MSG));
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
UtilityServices.appendLog("Show Dialog: "+e.getMessage());
}
}
} else {
System.out.println("svcstatus is null");
}
}
}
}
This is my class and i am trying to capture an image on click a button and then save into directory after that show into imageview and then want to send to server,i hope you will help me as a best programmer.
this question may be a duplicate of this.
Basically, when you pass an OutPut file to the intent, you cannot read data from extra, you have to make sure that CameraApplication has access to your files. You are getting this exception, because CameraApplication cannot save the file on your directory, you need to add a file provider...
Please make your code is same as the base android documentation.
Try This
public void getFile(View view) {
if (ContextCompat.checkSelfPermission(UploadDocumentActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(UploadDocumentActivity.this,new String[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE);
} else {
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureNm = getPictureName();
File output=new File(dir, pictureNm);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
I have an app where users can subscribe to membership by paying with their Paypal account. How can I get back a confirmation stating if the user has paid for the subscription or not? Please help me with some code or edit my code. How can i know if a user has already subscribed to membership or has not subscribed? Here is my code.
public class MainActivity extends Activity {
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
// note that these credentials will differ between live & sandbox
// environments.
private static final String CONFIG_CLIENT_ID = "EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Hipster Store")
.merchantPrivacyPolicyUri(
Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(
Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
//Intent intent = new Intent(this, PayPalService.class);
//intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
//startService(intent);
findViewById(R.id.order).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
thingToBuy = new PayPalPayment(new BigDecimal("1"), "USD",
"HeadSet", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(MainActivity.this,
PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
});
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(MainActivity.this,
PayPalFuturePaymentActivity.class);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data
.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
System.out.println("Responseeee" + confirm);
Log.i("paymentExample", confirm.toJSONObject().toString());
System.out.println(confirm.toJSONObject().toString(4));
System.out.println(confirm.getPayment().toJSONObject()
.toString(4));
Toast.makeText(getApplicationContext(), "Order placed"+confirm.toString(),
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
System.out.println("The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
System.out
.println("An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.e("FuturePaymentExample", auth.toJSONObject()
.toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.e("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(getApplicationContext(),
"Future Payment code received from PayPal",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("FuturePaymentExample",
"an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.e("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Application Correlation ID from the SDK
String correlationId = PayPalConfiguration
.getApplicationCorrelationId(this);
Log.i("FuturePaymentExample", "Application Correlation ID: "
+ correlationId);
// TODO: Send correlationId and transaction details to your server for
// processing with
// PayPal...
Toast.makeText(getApplicationContext(),
"App Correlation ID received from SDK", Toast.LENGTH_LONG)
.show();
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
}
I have some places in a listView. These are picked from a Google Map, for which I would like to take a picture. One for each. These photos should be available online, so I have searched for some proper solutions. I've choosed imgur's API.
Is it possible to link pictures with places? I would like to make mapping between uploaded pictures and listView items.
Photo picker and uploader class:
public class OAuthTestActivity extends Activity {
public static final int REQUEST_CODE_PICK_IMAGE = 1001;
private static final String AUTHORIZATION_URL = "https://api.imgur.com/oauth2/authorize";
private static final String CLIENT_ID = "CLIENT_ID";
private LinearLayout rootView;
private String accessToken;
private String refreshToken;
private String picturePath = "";
private Button send;
private String uploadedImageUrl = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = new LinearLayout(this);
rootView.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(llp);
rootView.addView(tv);
setContentView(rootView);
String action = getIntent().getAction();
if (action == null || !action.equals(Intent.ACTION_VIEW)) { // We need access token to use Imgur's api
tv.setText("Start OAuth Authorization");
Uri uri = Uri.parse(AUTHORIZATION_URL).buildUpon()
.appendQueryParameter("client_id", CLIENT_ID)
.appendQueryParameter("response_type", "token")
.appendQueryParameter("state", "init")
.build();
Intent intent = new Intent();
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else { // Now we have the token, can do the upload
tv.setText("Got Access Token");
Uri uri = getIntent().getData();
Log.d("Got imgur's access token", uri.toString());
String uriString = uri.toString();
String paramsString = "http://callback?" + uriString.substring(uriString.indexOf("#") + 1);
Log.d("tag", paramsString);
List<NameValuePair> params = URLEncodedUtils.parse(URI.create(paramsString), "utf-8");
Log.d("tag", Arrays.toString(params.toArray(new NameValuePair[0])));
for (NameValuePair pair : params) {
if (pair.getName().equals("access_token")) {
accessToken = pair.getValue();
} else if (pair.getName().equals("refresh_token")) {
refreshToken = pair.getValue();
}
}
Log.d("tag", "access_token = " + accessToken);
Log.d("tag", "refresh_token = " + refreshToken);
Button chooseImage = new Button(this);
rootView.addView(chooseImage);
chooseImage.setText("Choose an image");
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
});
send = new Button(this);
rootView.addView(send);
send.setText("send to imgur");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (picturePath != null && picturePath.length() > 0 &&
accessToken != null && accessToken.length() > 0) {
(new UploadToImgurTask()).execute(picturePath);
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
if (send == null) return;
if (picturePath == null || picturePath.length() == 0) {
send.setVisibility(View.GONE);
} else {
send.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("tag", "request code : " + requestCode + ", result code : " + resultCode);
if (data == null) {
Log.d("tag" , "data is null");
}
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_PICK_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
Log.d("tag", "image path : " + picturePath);
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
}
// Here is the upload task
class UploadToImgurTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
final String upload_to = "https://api.imgur.com/3/upload";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(upload_to);
try {
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("image", new FileBody(new File(params[0])))
.build();
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(entity);
final HttpResponse response = httpClient.execute(httpPost,
localContext);
final String response_string = EntityUtils.toString(response
.getEntity());
final JSONObject json = new JSONObject(response_string);
Log.d("tag", json.toString());
JSONObject data = json.optJSONObject("data");
uploadedImageUrl = data.optString("link");
Log.d("tag", "uploaded image url : " + uploadedImageUrl);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean.booleanValue()) { // after sucessful uploading, show the image in web browser
Button openBrowser = new Button(OAuthTestActivity.this);
rootView.addView(openBrowser);
openBrowser.setText("Open Browser");
openBrowser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setData(Uri.parse(uploadedImageUrl));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
}
I have integrated citrus payment gateway in an android app..I am not getting where do I get the response..if the the transaction is successfull or failed.
Here is my code..the problem is whenever the transaction is completed or succesfull the citrus pay library display a screen with appropriate message and when I click back then I get the result in onActivityResult...I want the result immediately after the transaction is completed..Thanks
I am following steps from here : http://www.citruspay.com/DevelopersGuide/android/plugandplay.html
if (res.equalsIgnoreCase("true")) {
setupCitrusConfigs();
CitrusFlowManager.startShoppingFlow(CheckOut.this,
User_Email, Txt_Phone.getText().toString(), String.valueOf(Amt_Payable));
}
private void setupCitrusConfigs() {
CitrusFlowManager.initCitrusConfig("kkkkkkk-signup",
"dfdffgfdgfdgffdgdfgdfgdfgdfgfdg", "fgfgfdgfdg-signin",
"fgfdgdfgfdgfgfdgfgdfffd", getResources().getColor(R.color.white),
CheckOut.this, Environment.SANDBOX, "vvvvvvvvd", sandboxBillGeneratorURL,
returnUrlLoadMoney);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
Log.d("CheckOut","request code " + requestCode + " resultcode " + resultCode);
if(requestCode == Constants.REQUEST_CODE_PAYMENT && resultCode == RESULT_OK && data != null) {
// You will get data here if transaction flow is started through pay options other than wallet
TransactionResponse transactionResponse = data.getParcelableExtra(Constants
.INTENT_EXTRA_TRANSACTION_RESPONSE);
// You will get data here if transaction flow is started through wallet
ResultModel resultModel = data.getParcelableExtra(ResultFragment.ARG_RESULT);
// Check which object is non-null
if(transactionResponse != null && transactionResponse.getJsonResponse() != null) {
try {
JSONObject json = new JSONObject(transactionResponse.getJsonResponse());
String Status = json.getString("TxStatus");
if(Status.equalsIgnoreCase("SUCCESS")){
db.EmptyCart();
Intent i = new Intent(CheckOut.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
Log.e("Trans", "Transaction Successfull " + Status);
}else {
Log.e("Trans","Transaction Failed "+Status);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
// Decide what to do with this data
Log.d(TAG, "transaction response" + transactionResponse.getJsonResponse());
} else if(resultModel != null && resultModel.getTransactionResponse() != null){
// Decide what to do with this data
try {
JSONObject json = new JSONObject(resultModel.getTransactionResponse().getJsonResponse());
String Status = json.getString("TxStatus");
if(Status.equalsIgnoreCase("SUCCESS")){
db.EmptyCart();
Intent i = new Intent(CheckOut.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
Log.e("Trans", "Transaction Successfull " + Status);
}else {
Log.e("Trans","Transaction Failed "+Status);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
} else {
Log.d(TAG, "Both objects are null!");
}
}
}
Pay using Debit Card
CitrusClient citrusClient = CitrusClient.getInstance(context); // Activity Context
// No need to call init on CitrusClient if already done.
DebitCardOption debitCardOption = new DebitCardOption("Card Holder Name", "4111111111111111", "123", Month.getMonth("12"), Year.getYear("18"));
Amount amount = new Amount("5");
// Init PaymentType
PaymentType.PGPayment pgPayment = new PaymentType.PGPayment(amount, BILL_URL, debitCardOption, new CitrusUser("developercitrus#gmail.com","9876543210"));
citrusClient.simpliPay(pgPayment, new Callback<TransactionResponse>() {
#Override
public void success(TransactionResponse transactionResponse) { }
#Override
public void error(CitrusError error) { }
});
Pay using Credit Card
CitrusClient citrusClient = CitrusClient.getInstance(context); // Activity Context
// No need to call init on CitrusClient if already done.
CreditCardOption creditCardOption = new CreditCardOption("Card Holder Name", "4111111111111111", "123", Month.getMonth("12"), Year.getYear("18"));
Amount amount = new Amount("5");
// Init PaymentType
PaymentType.PGPayment pgPayment = new PaymentType.PGPayment(amount, BILL_URL, creditCardOption, new CitrusUser("developercitrus#gmail.com","9876543210"));
citrusClient.simpliPay(pgPayment, new Callback<TransactionResponse>() {
#Override
public void success(TransactionResponse transactionResponse) { }
#Override
public void error(CitrusError error) { }
});
Pay using Net Banking Option
CitrusClient citrusClient = CitrusClient.getInstance(context); // Activity Context
// No need to call init on CitrusClient if already done.
NetbankingOption netbankingOption = new NetbankingOption("ICICI Bank","CID001");
// Init Net Banking PaymentType
PaymentType.PGPayment pgPayment = new PaymentType.PGPayment(amount, BILL_URL, netbankingOption, new CitrusUser("developercitrus#gmail.com","9876543210"));
citrusClient.simpliPay(pgPayment, new Callback<TransactionResponse>() {
#Override
public void success(TransactionResponse transactionResponse) { }
#Override
public void error(CitrusError error) { }
});
I am using sandbox account and following the tutorial http://androiddevelopmentanddiscussion.blogspot.com/2014/05/paypal-integration-in-android.html
I have given the client id which i have achieved by logging into sandbox account from my selling tools->api access
Here is my code:
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName(" ")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
PayPalPayment thingToBuy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
public void onBuyPressed(View pressed) {
// PAYMENT_INTENT_SALE will cause the payment to complete immediately.
// Change PAYMENT_INTENT_SALE to PAYMENT_INTENT_AUTHORIZE to only authorize payment and
// capture funds later.
if(pressed.getId() == R.id.button1){
thingToBuy = new PayPalPayment(new BigDecimal("8"), "USD", "Painting 1", PayPalPayment.PAYMENT_INTENT_SALE);
}else if(pressed.getId() == R.id.button2){
thingToBuy = new PayPalPayment(new BigDecimal("4"), "USD", "Painting 2", PayPalPayment.PAYMENT_INTENT_SALE);
}
Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(MainActivity.this, PayPalFuturePaymentActivity.class);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm =
data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
Toast.makeText(
getApplicationContext(),
"PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
.show();
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(TAG,"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
} else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth =
data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
try {
Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
Toast.makeText(
getApplicationContext(),
"Future Payment code received from PayPal", Toast.LENGTH_LONG)
.show();
} catch (JSONException e) {
Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
"FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
}
private void sendAuthorizationToServer(PayPalAuthorization authorization) {
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Application Correlation ID from the SDK
String correlationId = PayPalConfiguration.getApplicationCorrelationId(this);
Log.i("FuturePaymentExample", "Application Correlation ID: " + correlationId);
// TODO: Send correlationId and transaction details to your server for processing with
// PayPal...
Toast.makeText(
getApplicationContext(), "App Correlation ID received from SDK", Toast.LENGTH_LONG)
.show();
}
#Override
public void onDestroy() {
// Stop service when done
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
Here is the log message:
01-12 06:32:04.143: E/paypal.sdk(1778): request failure with http statusCode:401,exception:org.apache.http.client.HttpResponseException: Unauthorized
01-12 06:32:04.143: E/paypal.sdk(1778): request failed with server response:{"error":"invalid_client","error_description":"The client credentials are invalid"}
01-12 06:32:04.143: E/PayPalService(1778): invalid_client
I am new in this topic so explanation would be nice.
Use your sandbox credential (Client id) here.
private static final String CONFIG_CLIENT_ID = "";
Or follow below links:
Paypal integration using SDK
Paypal integration using gradle integration