PayPal how to set credentials programmatically in java sdk (express checkout) - java

I'm using PayPal Express Checkout to make reference payments. Right now, the sdk loads PayPal credentials (user id, password, signature) from a resource file (sdk_config.properties) - is there any way to set the credentials (user id, password, signature) from code?

I'm not familiar with their SDK but you should be able to just update the values of those constants or whatever types of variables they're using with your own dynamic values.
Alternatively, you might want to look into the Permissions API as it sounds like you're attempting to make calls on behalf of 3rd party users..??

We have made some good improvements to the PayPal Java SDK on integration steps. We are removing the need for sdk_config.properties file as they do not work as well, specially for multi-configuration settings.
Now, all you do is create an APIContext instance with clientId, clientSecret, and mode. You pass that context object for any API operation from there on.
Here is how the code would look like:
APIContext context = new APIContext(clientId, clientSecret, "sandbox");
Payment payment = new Payment();
// Fill in all the details.
payment.create(context);
Here is the wiki page explaining that: https://github.com/paypal/PayPal-Java-SDK/wiki/Making-First-Call

Related

upload file to dropbox by java

I am working on creating a simple desktop program in Java, and I want to upload files via this program to Dropbox, but the problem is that the access token has a short life (temporary), how can I make the access token have a long life, or if I can use the App key and App secret?
I need a simple solution like a method or a java example.
Is there anything better than Dropbox in this aspect and more flexible?
Thanks for any help.
This method works fine but the access token expires after a few hours
private void testUplaod() throws FileNotFoundException, IOException, DbxException {
DbxClientV2 client;
DbxRequestConfig config = new DbxRequestConfig("dropbox/TestUplaod");
try (InputStream in = new FileInputStream("D:\\t1.txt")) {
client = new DbxClientV2(config, ACCESS_TOKEN);
FileMetadata metadata = client.files().uploadBuilder("/t1.txt")
.uploadAndFinish(in);
}
I was expecting it would work sustainably.
When you get the access token, you should also receive a refresh token. When the access token expires, you make an API call with the refresh token to get a new one.
Dropbox is no longer offering the option for creating new long-lived access tokens. Dropbox is switching to only issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here.
Apps can still get long-term access by requesting "offline" access though, in which case the app receives a "refresh token" that can be used to retrieve new short-lived access tokens as needed, without further manual user intervention. It's not possible to get a refresh token from the "Generate" button; you need to use the OAuth flow. You can find more information in the OAuth Guide and authorization documentation. There's a basic outline of processing this flow in this blog post which may serve as a useful example.
The official Dropbox Java SDK can actually handle the process for you automatically, as long as you supply the necessary credentials, e.g., as shown retrieved in the examples.

PayPal API set return URL

With the oldest PayPal API, setting the return URL when a checkout is accomplishment, or when checkout is eliminated is easy, as described here:
Payment payment = new Payment();
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(cancelUrl);
redirectUrls.setReturnUrl(successUrl);
payment.setRedirectUrls(redirectUrls);
How can I accomplished this goal with new PayPal API?
I have already setting an url return (google.com for testing) in my sandbox account but it seems not work..
Which new API? There are several. Are you using the Checkout-Java-SDK? The best integrations do not use a redirect, and hence do not need a return URL.
Instead, implement two routes on your server that return JSON data -- one for 'Create Order' and one for 'Capture Order', documented here.
The approval flow to pair those two routes with is: https://developer.paypal.com/demo/checkout/#/pattern/server
This flow does not redirect away, hence there is no need or use for a return URL and if specified it will be ignored.
I have already setting an url return (google.com for testing) in my sandbox account but it seems not work.
That is for non-API integrations that use a link or HTML form post. There is no API integration that pays any attention to that profile setting.
I know this is an old post now but with REST API, there is a way to return these URLs. If you go to https://developer.paypal.com/api/orders/v2/ and click the application_context object link, you would be able to see the other details you can add to pass into your payload -- eg. brand_name, return_url, cancel_url etc. I do not think that Paypal has provided now an SDK but would love to know if there is. Right now, only the REST endpoints and payloads are available on their developer page.

How to set custom claims with FirebaseUser?

I'm trying to add some key-value pairs to custom claims but can't find any function for this. How do you do it on Android?
For example, I am able to set the Display Photo this way:
FirebaseUser user = ...;
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(Uri.parse(response.body().getPhotoURI()))
.build();
user.updateProfile(profileUpdates).addOnCompleteListener(task -> { ... });
Client SDK its a risk as malicious clients can also modify the data. May be claims can be added in console now which i am not certain. And that might be something that's what your looking for. From Controlling Data Access Using Firebase Auth Custom Claims:
It might sound like a good idea to add all sorts of criteria as custom claims. Perhaps you want to add a home address, additional photo URLs, or a profile description, for example. But this is not what custom claims are designed for. Data like addresses should be stored in a database, since it’s not related to authentication. Tokens are not profiles!
And from Set and validate custom user claims via the Admin SDK:
Custom claims can contain sensitive data, therefore they should only be set from a privileged server environment by the Firebase Admin SDK.
// Set admin privilege on the user corresponding to uid.
Map<String, Object> claims = new HashMap<>();
claims.put("admin", true);
FirebaseAuth.getInstance().setCustomUserClaims(uid, claims);
The new custom claims will propagate to the user's ID token the
next time a new one is issued.
And Using It:
// Verify the ID token first.
FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdToken(idToken);
if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) {
// Allow access to requested admin resource.
}
OR As Client:
// Lookup the user associated with the specified uid.
UserRecord user = FirebaseAuth.getInstance().getUser(uid);
boolean claim = Boolean.parseBoolean(user.getCustomClaims().get("admin"));
You might want to read this: Firebase Custom Claim Java
It's not possible to set custom claims directly in the client app. That would be considered a security problem. Custom claims is a flexible security mechanism that allows you to grant the user access to backend resources. If users could grant themselves custom claims, then they would be an ineffective method of securing resources.
You should use the Firebase Admin SDK to assign custom claims on a backend you control, and make sure that the claims only are granted for users in the specific situations that you allow - users should not be able to assign themselves custom claims.

How to access Bitbucket API from a Java Desktop App via Jersey+Oltu?

As the title states it, I want to access the bitbucket API from a native Java Desktop Application. Bitbucket requires Applications to use OAuth2, and for that I found that Oltu should do the job.
However, my knowledge of OAuth is very limited and so I am stuck at a very early point. Here is what I did so far:
Step 1: I registered an OAuth Consumer with my Bitbucket Account with the following details:
Name: jerseytestapp
Description:
CallbackURL: http://localhost:8080/
URL:
Question 1: Could I automate this step?
Step 2: I ran the following Java code:
package jerseytest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
public class BitbucketJersey {
public static void main(String[] args) {
OAuthClientRequest request;
try {
request = OAuthClientRequest
.authorizationLocation("https://bitbucket.org/site/oauth2/authorize")
.setClientId("jerseytestapp")
.setRedirectURI("http://localhost:8080")
.buildQueryMessage();
System.out.println(request.getLocationUri());
} catch (OAuthSystemException e) {
e.printStackTrace();
}
}
}
Step 3: I received the following locationURI and opened in Firefox
https://bitbucket.org/site/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=jerseytestapp
Question 2: Do I need to use the browser or can I do this from the java application?
I receive the following answer message in Firefox:
Invalid client_id
This integration is misconfigured. Contact the vendor for assistance.
Question 3: What would be the correct next steps, and what is wrong with my approach?
Answer 1: You can automate the creation of OAuth Consumers, but you probably don’t want to.
Bitbucket provides documentation on how to create a consumer through their APIs, although the documentation is lacking many pertinent fields. Even so, you could still craft an HTTP request programmatically which mimics whatever Bitbucket's web interface is doing to create consumers. So yes, it could be automated.
Here's why you probably don't want to. In your case, you have three things that need to work together: your application, the end user, and Bitbucket. (Or in terms of OAuth jargon for this flow, those would be the client, resource owner, and authorization server, respectively.) The normal way of doing things is that your application is uniquely identified by the OAuth Consumer that you’ve created in your account, and all usages of Bitbucket by your application will use that single OAuth Consumer to identify your application. So unless you’re doing something like developing a Bitbucket application that generates other Bitbucket applications, you have no need to automate the creation of other OAuth Consumers.
Answer 2: You can authorize directly from your Java application.
Bitbucket states that it supports all four grant flows/types defined in RFC-6749. Your code is currently trying to use the Authorization Code Grant type. Using this grant type WILL force you to use a browser. But that’s not the only problem with this grant type for a desktop application. Without a public webserver to point at, you will have to use localhost in your callback URL, as you are already doing. That is a big security hole because malicious software could intercept traffic to your callback URL to gain access to tokens that the end user is granting to your application only. (See the comments on this stackoverflow question for more discussion on that topic.) Instead, you should be using the Resource Owner Password Credentials Grant type which will allow you to authenticate a Bitbucket’s username and password directly in your application, without the need of an external browser or a callback URL. Bitbucket provides a sample curl command on how to use that grant type here.
Answer 3: The correct next steps would be to model your code after the following sample. What is wrong with your approach is that you are trying to use a grant type that is ill-suited to your needs, and you are attempting to use your OAuth Consumer's name to identify your application instead of your Consumer's key and secret.
The following code sample successfully retrieved an access token with my own username/password/key/secret combination, whose values have been substituted out. Code was tested using JDK 1.8.0_45 and org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0.
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("https://bitbucket.org/site/oauth2/access_token")
.setGrantType(GrantType.PASSWORD)
.setUsername("someUsernameEnteredByEndUser")
.setPassword("somePasswordEnteredByEndUser")
.buildBodyMessage();
String key = "yourConsumerKey";
String secret = "yourConsumerSecret";
byte[] unencodedConsumerAuth = (key + ":" + secret).getBytes(StandardCharsets.UTF_8);
byte[] encodedConsumerAuth = Base64.getEncoder().encode(unencodedConsumerAuth);
request.setHeader("Authorization", "Basic " + new String(encodedConsumerAuth, StandardCharsets.UTF_8));
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse response = oAuthClient.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
System.out.println("response body: " + response.getBody());
Your main problem was that you were giving the customer name instead of the client id:
.setClientId("jerseytestapp")
The only way to get the client id that I know of is to query:
https://bitbucket.org/api/1.0/users/your_account_name/consumers
However, even then it was still not working so I contacted bitbucket support. It turned out that the documentation is misleading. You actually need to use the client key instead.
.setClientId("ydrqABCD123QWER4567") // or whatever your case might be
https://bitbucket.org/site/oauth2/authorize?client_id=client_key&response_type=token

How to auto-authenticate with box.com java sdk

My question is similar to this post:
How to get an access token without Box’s authorization page
In that post, he asks:
I have been granted access(collaborate) in a folder. What I need is to access the folder daily and fetch files from it. Right now the developer token I generate expires in 1 hour. Is there a way I can get the authorization code without the first leg, which requires a user interface. This way I can refresh the access toke whenever I fetch files.
The highest rated answer from "Skippy Ta" tells me most of what I need to know EXCEPT the following:
How do I authenticate using the developer token and how do I refresh? From the github repo for the HelloWorld sample app (https://github.com/box/box-java-sdk-v2) I downloaded, I see these two steps:
boxClient.authenticate(boxOAuthToken);
for the initial authentication, and
boxClient.addOAuthRefreshListener(new OAuthRefreshListener() {
#Override
public void onRefresh(IAuthData newAuthData) {
// TODO: Update the stored access token.
}
});
for the refresh.
I'm having trouble putting all this together. First, the authenticate method does not accept a String boxOAuthToken, it accepts an IAuthData object, whatever that is. So I cannot conduct the initial authentication.
Even if I were to achieve initial authentication, I could not refresh, because I don't know how to access the token once I'm authenticated in order to store it, and if I stored that token as a String, I don't know how to wrap it in the proper object and conduct the update alluded to by the
// TODO: Update the stored access token.
comment above. Thanks for any help you can offer.
You can take a look at the javafx login UI: https://github.com/box/box-java-sdk-v2/tree/master/BoxJavaFxOAuth
But anyway if you need to build a BoxOAuthToken object from access token and refresh token and authenticate from it, here is what you can do:
HashMap<String, String> tokenMap = new HashMap<String, String>();
tokenMap.put("access_token", access);
tokenMap.put("refresh_token", refresh);
BoxOAuthToken token = new BoxOAuthToken(tokenMap);
boxClient.authenticate(token);
As for the refresh, the sdk auto-refreshes. The only time you need to worry about it is when your app quits and you need to persist the auth. At that point you can save the oauth token out. The refresh listener is used to update the oauth token for you so at the point you need to save oauth out, you have the latest oauth data.

Categories

Resources