Oauth Authorization issue while integrating web app with Quickbooks - java

I am trying to integrate my web app with QuickBooks I implemented Connect to QuickBooks button and the intuit also grants the permission to the application.
However, I get We encountered a problem processing your request issue.
What might be the issue? I don't get any response in my call_back url too.
I used the code from Intuit Sample app.
public static String REQUEST_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_request_token";
public static String ACCESS_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_access_token";
public static String AUTHORIZE_URL = "https://appcenter.intuit.com/Connect/Begin";
public static String OAUTH_CONSUMER_KEY = "qyprdFHGmJjBj1jDH05Jen95Tu3PyW";
public static String OAUTH_CONSUMER_SECRET = "OMFkKCPRBQKrMoyaLg9mFYTM26kpJg8LPthbNzTB";
public static String OAUTH_CALLBACK_URL = "http://office.technology.com:8081/delegate/intuit/";
public Map<String, String> getRequestTokenSignPost() {
String authURL = null;
OAuthProvider provider = createProvider();
String consumerkey = OAUTH_CONSUMER_KEY;
String consumersecret = OAUTH_CONSUMER_SECRET;
LOG.info("Inside getRequestToken, Consumer Key and Secret: " + consumerkey + " " + consumersecret);
String callback_url = OAUTH_CALLBACK_URL;
LOG.info("callback URL: " + callback_url);
OAuthConsumer ouathconsumer = new DefaultOAuthConsumer(consumerkey, consumersecret);
try {
HttpParameters additionalParams = new HttpParameters();
additionalParams.put("oauth_callback", URLEncoder.encode(callback_url, "UTF-8"));
ouathconsumer.setAdditionalParameters(additionalParams);
} catch (UnsupportedEncodingException e) {
LOG.error(e.getLocalizedMessage());
}
String requestret = "";
String requestToken = "";
String requestTokenSecret = "";
try {
String signedRequestTokenUrl = ouathconsumer.sign(REQUEST_TOKEN_URL);
LOG.info("signedRequestTokenUrl: " + signedRequestTokenUrl);
URL url;
url = new URL(signedRequestTokenUrl);
HttpURLConnection httpconnection = (HttpURLConnection) url.openConnection();
httpconnection.setRequestMethod("GET");
httpconnection.setRequestProperty("Content-type", "application/xml");
httpconnection.setRequestProperty("Content-Length", "0");
if (httpconnection != null) {
BufferedReader rd = new BufferedReader(new InputStreamReader(httpconnection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
requestret = sb.toString();
}
String[] requestTokenSections = requestret.split("&");
for (int i = 0; i < requestTokenSections.length; i++) {
String[] currentElements = requestTokenSections[i].split("=");
if (currentElements[0].equalsIgnoreCase("oauth_token")) {
requestToken = currentElements[1];
} else if (currentElements[0].equalsIgnoreCase("oauth_token_secret")) {
requestTokenSecret = currentElements[1];
}
}
Map<String, String> requesttokenmap = new HashMap<String, String>();
try {
authURL = provider.retrieveRequestToken(ouathconsumer, callback_url);
} catch (OAuthNotAuthorizedException e) {
LOG.error(e.getLocalizedMessage());
}
ouathconsumer.setTokenWithSecret(ouathconsumer.getToken(), ouathconsumer.getTokenSecret());
requesttokenmap.put("requestToken", requestToken);
requesttokenmap.put("requestTokenSecret", requestTokenSecret);
requesttokenmap.put("authURL", authURL);
return requesttokenmap;
} catch (OAuthMessageSignerException e) {
LOG.error(e.getLocalizedMessage());
} catch (OAuthExpectationFailedException e) {
LOG.error(e.getLocalizedMessage());
} catch (OAuthCommunicationException e) {
LOG.error(e.getLocalizedMessage());
} catch (MalformedURLException e) {
LOG.error(e.getLocalizedMessage());
} catch (IOException e) {
LOG.error(e.getLocalizedMessage());
}
LOG.info("Error: Failed to get request token.");
return null;
}
public static OAuthProvider createProvider() {
OAuthProvider provider =
new DefaultOAuthProvider(OauthHelper.REQUEST_TOKEN_URL, OauthHelper.ACCESS_TOKEN_URL, OauthHelper.AUTHORIZE_URL);
return provider;
}
public String getAuthorizeURL(String requestToken, String requestTokenSecret) {
String authorizeURL = "";
try {
authorizeURL = AUTHORIZE_URL + "?oauth_token=" + requestToken;
} catch (Exception e) {
LOG.error(e.getLocalizedMessage());
}
LOG.info("Authorize URL: " + authorizeURL);
return authorizeURL;
}
I even get the Request token:
signedRequestTokenUrl: https://oauth.intuit.com/oauth/v1/get_request_token?oauth_signature=EHKmrR%2BV%2ByF4WRcBmpkdBeYEfuE%3D&oauth_callback=http%253Aoffice.technology.com%253A8081%252Fdelegate%252Fintuit&oauth_consumer_key=qyprdFHGaJjBj1jDH05Jen95Tu3PyW&oauth_version=1.0&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1390538706&oauth_nonce=-4612911034475731539
requestret: oauth_token_secret=XkXjGlS6bnFvOWYthCoew54W4ILcdMWQ3jaOMCQQ&oauth_callback_confirmed=true&oauth_token=qyprdRyUiXzU0QLLavn3L3TtdqvYts5CZyomkSk8miZDfB8Y

This:
public static String OAUTH_CALLBACK_URL = "http:office.technology.com:8081/delegate/intuit/";
Is not a valid URL, and it needs to be. Fix your URL.

I was able to fix the issue using an incognito window without any cookies for my quickbooks developer account.

Related

How can I get youtubeVideo Title from URL for android studio?

I want to get the youtube video title from a url so I found this code below (IOUtils) is depreciated any other way to do this
public class SimpleYouTubeHelper {
public static String getTitleQuietly(String youtubeUrl) {
try {
if (youtubeUrl != null) {
URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
youtubeUrl + "&format=json"
);
return new JSONObject(IOUtils.toString(embededURL)).getString("title");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
second way i tried
class getYoutubeJSON extends Thread {
String data = " ";
#Override
public void run() {
try {
URL url = new URL("http://www.youtube.com/oembed?url="+" https://www.youtube.com/watch?v=a4NT5iBFuZs&ab_channel=FilipVujovic"
+ "&format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
data =data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
// JSONArray users = jsonObject.getJSONArray("author_name");
Log.d("RT " , jsonObject.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This code gets a an error Cleartext HTTP traffic to www.youtube.com not permitted
so I found this answer Android 8: Cleartext HTTP traffic not permitted but I am still getting some error I don't understand.
I solved this problem by using the volley library.
My requested url was:
String Video_id = "jhjgN2d7yok";
String url = "https://www.youtube.com/oembed?url=youtube.com/watch?v=" +Video_id+ "&format=json";

Twitter fetching application only bearer token HTTP 403 Forbidden

I am trying to fetch the application only bearer token by using my consumer key and consumer secret following this. This is my implementation:
public class OAuthApplicationOnlyBearerTokenFetchTask extends AsyncTask<String, Void, String> {
private static Logger logger =
Logger.getLogger(OAuthApplicationOnlyBearerTokenFetchTask.class.getName());
final static String URL_TWITTER_OAUTH2_TOKEN = "https://api.twitter.com/oauth2/token";
final static String USER_AGENT = "TwitterMotion User Agent";
protected String mApplicationOnlyBearerToken;
#Override
protected String doInBackground(String... tokens) {
String consumerKey = tokens[0];
String consumerSecret = tokens[0];
String encodedCredentials = encodeKeysFrom(consumerKey, consumerSecret);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(URL_TWITTER_OAUTH2_TOKEN);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Host", "api.twitter.com");
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
urlConnection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
urlConnection.setRequestProperty("Content-Length", "29");
urlConnection.setUseCaches(false);
writeRequest(urlConnection, "grant_type=client_credentials");
String jsonResponse = readResponse(urlConnection);
logger.log(INFO, "jsonResponse of the bearer oauth request: ", jsonResponse);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
logger.log(Level.SEVERE, "HTTP 403 (Forbidden) returned from Twitter API call for bearer token. " +
"Check values of Consumer Key and Consumer Secret in tokens.properties");
throw new RejectedAuthorizationException(urlConnection.getResponseCode(), "HTTP 403 (Forbidden) returned attempting to get Twitter API bearer token");
}
JSONObject jsonResponseObject = new JSONObject(jsonResponse);
if (jsonResponseObject != null) {
mApplicationOnlyBearerToken = (String) jsonResponseObject.get("access_token");
} else {
// TODO
}
return mApplicationOnlyBearerToken;
} catch (Exception ex) {
logger.log(Level.SEVERE, "", ex);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(String applicationOnlyBearerToken) {
this.mApplicationOnlyBearerToken = applicationOnlyBearerToken;
}
public String getApplicationOnlyBearerToken() {
return mApplicationOnlyBearerToken;
}
private String encodeKeysFrom(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String combinedEncodedKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encode(combinedEncodedKey.getBytes(), Base64.NO_WRAP);
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
// TODO
return null;
}
}
private boolean writeRequest(HttpURLConnection connection, String requestBody)
throws IOException {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(connection.getOutputStream()));
bufferedWriter.write(requestBody);
bufferedWriter.flush();
return true;
}
catch (IOException ex) {
return false;
}
finally {
if (bufferedWriter != null) {
bufferedWriter.close();
}
}
}
private String readResponse(HttpURLConnection connection) throws IOException {
BufferedReader bufferedReader = null;
try {
StringBuilder stringBuilder = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + System.getProperty("line.separator"));
}
return stringBuilder.toString();
}
catch (IOException e) {
return null;
}
finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
}
}
But I am getting HTTP 403 Forbidden.
I also added permission on manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I can not understand what is the issue actually. Thanks in advance!
Never mind, I've found the bug.
String consumerKey = tokens[0];
String consumerSecret = tokens[0];
It should be
String consumerSecret = tokens[1];

Getter Method not working after doInBackground

Im trying to have a few getter methods for a few strings to get returned after getting them from an online JSON. In order to save space I decided to put that all in an object and call them from there.
Object:
public class InventoryItem extends AsyncTask<Void,Void,Void>{
String imageURL = "";
String itemName = "";
String itemDesc = "";
String itemRarity = "";
String itemType = "";
JSONObject itemJson = null;
InventoryItem(JSONObject json){
itemJson = json;
Log.d("StringSubclass","Inventory Item");
}
#Override
protected Void doInBackground(Void... voids) {
Log.d("StringSubclass","doInBG Inventory Item");
try {
imageURL = "http://www.bungie.net"+itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("icon");
Log.d("StringSubclass",imageURL);
itemName = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemName");
itemDesc = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemDescription");
itemRarity = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("tierTypeName");
itemType = itemJson.getJSONObject("Response").getJSONObject("data").getJSONObject("inventoryItem").getString("itemTypeName");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public String getItemType() {
return itemType;
}
public String getItemRarity() {
return itemRarity;
}
public String getItemDesc() {
return itemDesc;
}
public String getItemName() {
return itemName;
}
public String getImageURL() {
return imageURL;
}
}
The problem is that the getter methods at the end send back "" even though I changed their value in doInBackground.
This is how I called getImageURL():
InventoryItem subclass = new InventoryItem(makeJSON(HOST+"Manifest/6/"+subclassHash+"/"));
subclass.execute();
Log.d("StringSubclass",subclass.getImageURL());
intentHome.putExtra("SubclassImageURL",subclass.getImageURL());
makeJSON():
public JSONObject makeJSON(String url){
JSONObject json = null;
String apiKey = "36c346318fa54fc6bc659ad6321a6d41";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("X-API-KEY", apiKey);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
String response = "";
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
in.close();
JsonParser parser = new JsonParser();
JsonObject gson = (JsonObject) parser.parse(response);
json = new JSONObject(gson.toString());
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
I checked the URL and it is working fine in chrome.
Any help will be appreciated.
I kind of new to this so please explain as much as possible.
Thanks

Facebook integration in web application

How to solve error of getting same user information in login with Facebook for different user in my web application developed in Java?
Here is the main connection class to connect with facebook.
public class FBConnection
{
public static final String FB_APP_ID = "1729*******";
public static final String FB_APP_SECRET = "2c5******";
public static final String REDIRECT_URI = "http://example.com";
static String accessToken = "";
This method gives Code for getting access token from facebook.
public String getFBAuthUrl() {
String fbLoginUrl = "";
try {
fbLoginUrl = "http://www.facebook.com/dialog/oauth?" + "client_id="
+ FBConnection.FB_APP_ID + "&redirect_uri="
+ URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
+ "&scope=email,public_profile";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fbLoginUrl;
}
This method will generate graph url to fetch access token.
public String getFBGraphUrl(String code) {
String fbGraphUrl = "";
try {
fbGraphUrl = "https://graph.facebook.com/oauth/access_token?"
+ "client_id=" + FBConnection.FB_APP_ID + "&redirect_uri="
+ URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
+ "&client_secret=" + FB_APP_SECRET + "&code=" + code;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fbGraphUrl;
}
This method get access token from code got from redirect url.
public String getAccessToken(String code) {
if ("".equals(accessToken)) {
URL fbGraphURL;
try {
fbGraphURL = new URL(getFBGraphUrl(code));
} catch (MalformedURLException e) {
e.printStackTrace();
throw new RuntimeException("Invalid code received " + e);
}
URLConnection fbConnection;
StringBuffer b = null;
try {
fbConnection = fbGraphURL.openConnection();
BufferedReader in;
in = new BufferedReader(new InputStreamReader(fbConnection.getInputStream()));
String inputLine;
b = new StringBuffer();
while ((inputLine = in.readLine()) != null)
b.append(inputLine + "\n");
in.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Unable to connect with Facebook " + e);
}
accessToken = b.toString();
if (accessToken.startsWith("{")) {
throw new RuntimeException("ERROR: Access Token Invalid: " + accessToken);
}
}
return accessToken;
}

Search Tweets with pure Java 400 get Bad Request

I tried use search tweets use twitter search api.
But when i get bearer token then send request to
/1.1/search/tweets.json?count=2
Its response is 400 (Bad Request)
I don't know how is wrong... Anyone can help me ??
Here is my Code all from http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/
I also watch Application-only authentication but still don't know why.
Hope someone can tell me ....
private final static String getTokenURL = "https://api.twitter.com/oauth2/token";
private static String bearerToken;
static final String ACCESS_TOKEN = "1111111112-H************************************s";
static final String ACCESS_SECRET = "S************************************n";
static final String CONSUMER_KEY = "q************************************g";
static final String CONSUMER_SECRET = "Q************************************a";
public static void main(String[] args) {
new Thread(new Runnable() {
#Override
public void run() {
try {
bearerToken = requestBearerToken(getTokenURL);
searchTweets("https://api.twitter.com/1.1/search/tweets.json?count=2");
} catch (IOException e) {
System.out.println("IOException e");
e.printStackTrace();
}
}
}).start();
}
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret,
"UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
} catch (UnsupportedEncodingException e) {
return new String();
}
}
private static String requestBearerToken(String endPointUrl)
throws IOException {
HttpsURLConnection connection = null;
String encodedCredentials = encodeKeys(CONSUMER_KEY, CONSUMER_SECRET);
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
System.out.println(connection);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
connection.setRequestProperty("Authorization", "Basic "
+ encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
System.out.println(connection.getResponseCode());
System.out.println(connection.getResponseMessage());
String result = readResponse(connection);
JSONObject jsonResult=new JSONObject(result);
if (jsonResult.get("token_type") != null && jsonResult.get("token_type").equals("bearer") ) {
return jsonResult.getString("access_token");
}
return new String();
} catch (MalformedURLException | JSONException e) {
throw new IOException("Invalid endpoint URL specified.", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private static String searchTweets(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "MwTestTwitterAPI");
connection.setRequestProperty("Authorization", "Bearer " + bearerToken);
connection.setUseCaches(false);
String result = readResponse(connection);
System.out.println("fetchTimelineTweet---result:"+result);
if (result != null || result.equals("")) {
return result;
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
// Writes a request to a connection
private static boolean writeRequest(HttpURLConnection connection,
String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
} catch (IOException e) {
return false;
}
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
} catch (IOException e) {
return new String();
}
}
You're missing a query variable q, which is a required parameter.
Try changing your request url to: https://api.twitter.com/1.1/search/tweets.json?count=2&q=test

Categories

Resources