facebook Access Token 400 bad request - facebook

I am using following code to retrieve facebook accessToken
string url = "https://graph.facebook.com/oauth/access_token?" +
"client_id={0}" +
"&redirect_uri={1}" +
"&client_secret={2}" +
"&code={3}";
url = string.Format(url, clientId, redirectUri.EncodeUrl(), clientSecret, code);
//Create a webrequest to perform the request against the Uri
WebRequest request = WebRequest.Create(url);
try
{
//read out the response as a utf-8 encoding and parse out the access_token
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
//string urlRedirects = response.ResponseUri.ToString();
Encoding encode = Encoding.GetEncoding("utf-8");
if (stream != null)
{
StreamReader streamReader = new StreamReader(stream, encode);
string accessToken = streamReader.ReadToEnd().Replace("access_token=", "");
streamReader.Close();
response.Close();
return accessToken;
}
}
}
}
catch
{
return null;
}
however I am constantly receiving this ambiguous error message
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
I checked the code 100 "Invalid parameter" doesn't means much to me at all.
anyone have had similar problem?

Check you are adding correct code in the url
For example
http://www.xyz.com/?code=AQC399oXame3UKmoAMYnqkZOEXPDNa8ZUFEY9sc6I4YNQnNT-ZgHzpMNnQVZrCUBZVqJRIB1QrXC5xW58_8MNIgQol_PaQvYssUM8OiKjSY5aoqGLBMuCeeHsSqP_mRTd1xiK0iretZcXwMm_27lFYrWFw345Mxod_lfJuB8zI13E8wJUQiArXW_ZlGLNcyxh20#_=_
Code must be
code = AQC399oXame3UKmoAMYnqkZOEXPDNa8ZUFEY9sc6I4YNQnNT-ZgHzpMNnQVZrCUBZVqJRIB1QrXC5xW58_8MNIgQol_PaQvYssUM8OiKjSY5aoqGLBMuCeeHsSqP_mRTd1xiK0iretZcXwMm_27lFYrWFw345Mxod_lfJuB8zI13E8wJUQiArXW_ZlGLNcyxh20
code should not include following in the end
#_=_
If above did not solve the problem
2. redirect_uri must end with /
redirect_uri=http://www.xyz.com/
The following gives some times above mentioned error
redirect_uri=http://www.xyz.com
3. A lso make sure
App on Facebook and Website with Facebook Login are set with same addresss
e.g http://www.xyz.com/

You need to send the user to the Facebook Login page to get a valid code. The code should then be used to get the access_token for the user.
Follow the Authentication Guide.

I also got error message 400, when my app id and secret were wrong (i had messed up develop and production id-s and secrets).
Fixing them (watch also out for the correct host) fixed this problem for me.

Related

eBay REST API Get Offers Authetication Error

I am attempting to get eBay product IDs using the GetOffers request by sending it a product SKU.
My code is below, the problem I am currently having is that when I try to test this code is returns a 401 unauthorized. It's not returning any specific error code or anything descriptive.
I know my access token is valid I can't find any good examples on how to use this request.
public string getEbayOffers(string sku)
{
HttpResponseMessage response;
string accessToken = "tokenhere";
string param = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessToken));
string url = $"sell/inventory/v1/offer?sku={sku}";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.ebay.com/");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", param);
response = client.GetAsync(url).Result;
}
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
return null;
}
No need to convert your token to base64. The correct format should be "Bearer YOUR_USER_TOKEN". Replace YOUR_USER_TOKEN with your own token string.
Access token should be enough for getting offers but maybe you can try to use user token if above doesn't work.

Submitting POST request to Facebook Messenger API

I'm struggling to connect to the Facebook Messenger API. The server keeps returning:
The remote server returned an error: (400) Bad Request.
I've been at this for a few days, tried multiple methods, even tried a few VS packages that don't quite work. I've checked my Auth Token several times, and I don't know what else it might be.
Is there something obvious that's causing a bad request? I've copied the root URL from Facebook's API page. The token in the code below has been removed. The application throws an exception when I attempt to read the response. (WebResponse FBresponse = FBrequest.GetResponse();)
private string FBSendMessage(string user, string message)
{
string result = null;
string FBroot = "https://graph.facebook.com/v2.6/me/messages?access_token=";
string token = "EAA...DZD";
string FBURI = FBroot + token;
string FBstring = "{ \"recipient\": { \"id\":\"" + user + "\" }, \"message\": { \"text\":\"" + message + "\" } }";
try
{
//using (WebClient FBclient = new WebClient())
//{
// result =
// FBclient.UploadString(FBURI, FBstring);
//}
HttpWebRequest FBrequest = (HttpWebRequest)WebRequest.Create(FBURI);
FBrequest.Credentials = CredentialCache.DefaultCredentials;
FBrequest.ProtocolVersion = HttpVersion.Version11;
FBrequest.Method = "POST";
FBrequest.ContentType = "application/json";
byte[] FBbytes = Encoding.UTF8.GetBytes(FBstring);
FBrequest.ContentLength = FBbytes.Length;
Stream FBstream = FBrequest.GetRequestStream();
FBstream.Write(FBbytes, 0, FBbytes.Length);
FBstream.Close();
WebResponse FBresponse = FBrequest.GetResponse();
Output((((HttpWebResponse)FBresponse).StatusDescription), Log.Error);
FBstream = FBresponse.GetResponseStream();
StreamReader FBreader = new StreamReader(FBstream);
result = FBreader.ReadToEnd();
FBreader.Close();
FBresponse.Close();
}
catch(Exception ex)
{
Output(ex.Message, Log.Error);
}
return result;
}
I have determined that my code isn't the issue. The issue is that I'm making a request with an invalid user id. Facebook creates a user ID in the application context that isn't the same as your default user id. I have to receive a message to learn that contextualized id before I can send a message.

Yammer API - Posting to External Networks

I've used the Yammer API extensively for accessing current users internal network. All API calls have been working correctly (GET's and POST's) with the original token extracted from;
"https://www.yammer.com/oauth2/access_token.json?client_id={App ID}&client_secret={App Secret}&code={Access Code}"
and using the headers; "Authorization : Bearer {Token}" and "Cookie : {Cookies Received from HTML request}.
I've gotten the tokens for all accessible networks using;
"https://www.yammer.com/api/v1/oauth/tokens.json".
Accessing external networks beyond this point has proved troublesome. I changed the header to "Authorization : Bearer {NetworkToken}". While I am able to GET details from external networks, I cannot POST to external networks. I always receive a '401 Unauthorized' response. The 'Unauthorized' requests include deleting messages and liking messages in external networks.
Is there another step between being able to read data from an external network and enabling POST methods?
If I could get any insight into this i'd be extremely grateful!
Cheers!
When accessing external networks, you need to set the authToken to the authToken for that external network.
Step 1 - Get all auth tokens:
yam.platform.request({
url: "oauth/tokens.json",
type: 'GET',
success: function (msg) {
accessTokens = msg;
/....
},
error: function (msg) {
console.log(msg);
error(msg);
}
Step 2: Set the authToken to the correct external network
var currentToken = "";
$.each(accessTokens, function (i,val) {
if (val.network_permalink == $.cookie('networkPermalink')) {
currentToken = val;
}
});
While I was working on a project last month, I used the following way to post message.
The message has to be Byte encrypted in UTF-8 format.
Specify the content type as "application/x-www-form-urlencoded".
So, an example code would be:
HttpWebRequest a = (HttpWebRequest)WebRequest.Create(postUrl);
a.Headers.Add("Authorization", "Bearer" + authToken);
a.Method = "POST";
byte[] message = Encoding.UTF8.GetBytes("body=" + message + "&replied_to_id=" + threadID);
a.ContentType = "application/x-www-form-urlencoded";
a.ContentLength = message.Length;
using (var postStream = request.GetRequestStream())
{
postStream.Write(message, 0, message.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var postStreamForResponse = response.GetResponseStream())
{
StreamReader postReader = new StreamReader(postStreamForResponse);
string results = postReader.ReadToEnd();
postReader.Close();
}
I've discovered quite a few inconsistencies quirks with the Yammer API. I've figured out external networks in their totality now. Here are some things that may not be clear;
When doing a POST or DELETE request, do not include the network_permalink in the url! Only include the network_permalink when you're doing a GET request. This was my main issue.
Required request headers;
Content-Type : application/x-www-form-urlencoded
Accept : application/json
Cookie : _workfeed_session_id=(A code that can be extracted from the response from your first request with an auth token)
Authorization : Bearer (Access token for whichever network you wish to access)
Oh and just FYI, to request threads within the 'All Company' group this is the url; https://www.yammer.com/(network_permalink)/api/v1/messages/general.json
Thanks for the answers!

504 error accessing Kinvey handshake(Rest api)

I have been trying to get the Kinvey handshake for the REST api to work for a while now but have not had any luck. I am using libgdx's net class to send the http request. Wverytime I send the request I get a 504(Gateway Timeout) error. I am following the instructions on the website so I am not sure why I would get that error.
Here is my attempt:
HttpRequest request = new HttpRequest(HttpMethods.GET);
request.setHeader("GET", "/appdata/:App_key");
request.setHeader("Host:", "baas.kinvey.com");
String authHeader = "Basic " + Base64Coder.encodeString("App_key:App_secret");
request.setHeader("Authorization:", authHeader);
request.setUrl("https://baas.kinvey.com/appdata/App_key");
System.out.println("HTTP REQUEST: " + request.getHeaders());
responseListener listener = new responseListener() {
public void handleHttpResponse (HttpResponse httpResponse) {
HttpStatus status = httpResponse.getStatus();
if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {
System.out.println("HTTP SUCCESS!");
} else {
System.out.println("HTTP ERROR: " + status.getStatusCode());
}
System.out.println("HTTP :" + httpResponse.getResultAsString());
}
#Override
public void failed(Throwable t) {
t.printStackTrace();
System.out.println("REQUEST FAILED!" +t.getMessage());
super.failed(t);
}
};
Gdx.net.sendHttpRequest(request, listener);
As far as I can tell, there is something wrong with the header. I have tested the Url which takes me to a login screen. The login works after I put in the App key as the user name and the Master secret as the password. Is there something obviously wrong? Is there a way I can debug this further?
I'm an engineer at Kinvey and can help you out with this.
A couple things:
first, there are some extra headers there that you don't need. While they might not be the cause of the issue, it is still safe to remove:
request.setHeader("GET", "/appdata/:App_key");
request.setHeader("Host:", "baas.kinvey.com");
Note that GET is set when you create the HttpRequest, and Host is set when you define the URL.
Second, get rid of the colon after "authorization" when setting your header, make it look like this:
request.setHeader("Authorization", authHeader);
Also, you mention that it works with your master secret but not with your app secret? Can you ensure that you are base64 encoding both?
One last thing-- ensure that you replace App_Key with your actual app key, in the URL as well as in the headers.

Send notification through facebook application using rest fb api

I am trying to send notification to facebook users via facebook application using restfb api. When tried to publish such notification, it shows an exception
"com.restfb.exception.FacebookGraphException: Received Facebook error response of type
GraphMethodException: Unsupported post request".
Below is my code:
FacebookType = facebookAppAccessToken.publish("user_id/notification?access_token=app_access_token"),
FacebookType.class, Parameter.with("template","send_notification"),
Parameter.with("href,"sample_link"));
Please help me resolving this. Thanks in advance
public void sendNotification(String externalUserId, String message) {
AccessToken appAccessToken = new DefaultFacebookClient()
.obtainAppAccessToken(APP_KEY, APP_SECRET);
FacebookClient facebookClient = new DefaultFacebookClient(
appAccessToken.getAccessToken());
try {
facebookClient.publish(externalUserId
+ "/notifications", FacebookType.class,
Parameter.with("template", message));
} catch (FacebookOAuthException e) {
if (e.getErrorCode() == 200) {
//Not an app user
} else if (e.getErrorCode() == 100) {
//Message cannot be longer than 180 characters
}
}
}
Handle error codes appropriately. And you can add href and ref as per your requirement.
Here are Details of parameters.