Code that I had written to fetch a Facebook page's posts using an app access token has suddenly stopped working. The JSON response's data object is an empty array. I'm not getting any error messages. When I try making the same request using an access token generated by the Graph API explorer, I get back a valid JSON response containing data. I've tried resetting my app's secret and generating a new access token, but I still get back an empty data object.
When I use the Facebook access token debugger, the only information returned is the App ID.
I generated my app access token by making a GET request to https://graph.facebook.com/oauth/access_token?client_id=<app_id>&client_secret=<app_secret>&grant_type=client_credentials
I don't have control over the page I'm trying to fetch data from, but I can contact the admin. Are there any permissions I should have them check?
Without any error messages or feedback, I'm at a loss on how to debug this. Does anyone have any advice?
This works perfectly.
Demo
token = 'valid_access_token';
page = '20531316728';
url = 'https://graph.facebook.com/'+page+'/feed?access_token="+token+"&fields=id,message&limit=10';
comments = [];
$.ajax({
'async': false,
'url': url,
'dataType': "json",
'success': function (data) {
$('.result').html(JSON.stringify(data));
},
'error': function(data){
$('.result').html(JSON.stringify(data));
}
});
Related
I'm trying to get user data from fitbit using fitbit api but the process seems confusing to me. I have tried several ways but could not succeed. I have searched in the internet for solution and found this
http://www.staze.org/retrieving-steps-data-fitbit-api/
But this process is also not working for me.
How to fix the code I mentioned to get data from fitbit or is there any other way to get data using PHP?
You need to do lot of homwwork Dude ;) Anyways...
To access Fitbit Data you can use OAuth 2.0 authentication
You need to pass tokenType and accessCode in any ajax call and you will get response
Now to get accessCode you need to register an App on Fitbit site
You can read API doc for more details
Here is sample code how to access Fitbit Profile using tokenType and accessCode
and I can assure you this is working Code so if your code doesnt work
it means you are doing somthing wrong in above steps
function getProfile() {
var authCode = token_type + " " + access_token;
$.ajax({
url: "https://api.fitbit.com/1/user/-/profile.json",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", fitbitAccessCode);
},
success: function(jsonObject) {
// logic ...
},
error: function(error) {
alert("Error");
}
});
}
I have a php application that accesses Asana API. I am able to create a project in Asana. However, the ajax call to the API class is returning a readystate=0.
While troubleshooting in firebug I also noticed that the network console has a 302, 400(??), and 200 status code. I thought 400 status code is related to invalid request or malformed url, but the project gets created anyway.
Any idea?
Update: More information.
I have a Ajax call to a php file which intern calls Asana API to getAuth code and tokens before calling the API services.
I believe I am getting the CORS warning and hence the readystate=0 and the 400 error. However because rest of my script proceeds with the token it was inserting records anyways. However, after the tokens expired (3600 sec), now I am unable to insert records. I know if I call the php file directly it works without the CORS error.
$.ajax({
type: 'POST',
url: "oa/asana.php",
data: {apiprovider:"asana",type:"addnewproject",notes:"notes",name:"name",id:"id",resource:"projects"},
//dataType:"json",
//contentType: "application/json",
success: function(data) {
console.log(data);
},
error: function( error )
{
console.log("asana api error");
console.log(JSON.stringify(error)) ;
},
async:true
});
my php code looks like this.
...$asana = new AsanaAuth(API_KEY,API_SECRET,callbackUrl);
if (!isset($_GET['code'])) {
$url = $asana->getAuthorizeUrl();
header('Location:' . $url);
} else {
$asana->getAccessToken($_GET['code']);
if ($asana->hasError()) {
echo 'Error response code: ' . $asana->responseCode;
}
else {
echo $asana->response;
}
}
Is there a better way to do this outside of Ajax call?
OK here's how I fixed it. Partly my understanding was wrong and I made a wrong assumption.
This is purely based on my application's need and this may not be applicable to all.
I have a settings page where the user clicks on the Asana app to authorize the connection. This is not a Ajax call but a hyperlink to a file which is also my redirect uri. Within this file I check if the user has already authorized if not I call authorize, get tokens and store the refresh token in the database for future use.
In the other parts of my application, when the user clicks on create an asana project, I check for the validity of the access token if it has expired, I refresh and get another token again.
Earlier, I was trying to call this from one page (which in a normal user flow will never happen -in my application). So right now there is no Ajax call for authorize but calling the refresh token, and Asana API endpoints are through Ajax and they work fine.
Hope this helps someone in future.
I was implementing FB social login in website based on PHP. I checked FB website and found it easy to implement. Below is the approach i have followed and i am not sure that i have any security issues here.
I have used Facebook JS SDK approach.
and is as follows:
var appID = 'xxxxxxxxxxxxxxx';
window.fbAsyncInit = function() {
FB.init({
appId : appID, // App ID
channelUrl : '',
status : true,
cookie : true,
xfbml : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
FB.api('/me?fields=id,name,email,permissions', function(response) {
//alert('Good to see you, ' + response.name + '.');
});
}else{
}
});
};
function login() {
if( navigator.userAgent.match('CriOS') ){
}
else{
FB.login(function(response) {
if (response.authResponse) {
replace_login();
} else {
// cancelled
alert('User cancelled login or did not fully authorize.');
}
},{scope: 'email,public_profile,user_friends'});
}
}
function replace_login(){
FB.api('/me?fields=id,name,email', function(response) {
$.ajax({
url: "s-account",
type: 'POST',
data: response,
dataType: 'json',
beforeSend: function(){
$("#signin_fb").button('loading');
},
success: function(data) {
$("#signin_fb").button('reset');
window.location.reload();
},
error: function(){
$("#signin_fb").button('reset');
}
});
});
}
And in PHP at server side, i am storing user detail like social_id, name and email in database through ajax call and if DB operation is successful then i am setting Session Variable in my website with username and email and user is logged in successfully.
For logout, i am using my own logout function to destroy Website user session and user is successfully logged out.
Now, where is the security risk? because if user is logged out and then try to login again JS SDK shall get a new Access Token through new response.
This whole authentication process boils down to the ajax call to s-account. You're sending name and email from FB.api() to your back end application in a POST request and as you didn't mention, I presume you're not verifying the access token with these details on the server side and you're simply making a session based on these details.
The security issue
Now, the security issue is that you're using a client side authentication on the server side. A user can simply generate a POST request to s-account with a fake response like Facebook with any username and email address and your PHP application will authenticate the user and make a valid session without verifying if the details are coming from a legit source. Your authentication is completely broken at this stage because a malicious user can login with any account by generating a simple POST request to s-account with any email and username.
How to fix
Facebook provides an end-point in the graph API which validates an access token and returns the details of the user associated with this access token. From the Docs:
This endpoint returns metadata about a given access token. This
includes data such as the user for which the token was issued, whether
the token is still valid, when it expires, and what permissions the
app has for the given user.
The Fb.Login() will generate the access token as response.authResponse.accessToken and userId as response.authResponse.userID. You need to send this accessToken & userID along with the other user details in your ajax call to s-account and then use the following API end-point to validate if the details are legit.
curl -X GET "https://graph.facebook.com/v2.6/debug_token?input_token=USER_ACCESS_TOKEN_FROM_AJAX_CALL&access_token=YOUR_APP_ACCESS_TOKEN"
If the the access token is valid, you'll get the following response with the userID for which this token was issued.
{
"data": {
"app_id": "YOUR_APP_ID",
"application": "YOUR_APP_NAME",
"expires_at": 1462777200,
"is_valid": true,
"scopes": [
"email",
"manage_pages",
"pages_messaging",
"pages_messaging_phone_number",
"public_profile"
],
"user_id": "THE_USER_ID_ASSOCIATED_WITH_THE_TOKEN"
}
}
Now you can compare this userID with the userID you received in the ajax call and check if the details are legit.
How to get your APP_ACCESS_TOKEN
To debug the user access token using the debug_token API, you need to generate your APP access token on the server side using the following API end-point.
curl -X GET "https://graph.facebook.com/v2.6/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials"
This will return your app access token in response.
{
"access_token": "YOUR_APP_ACCESS_TOKEN_HERE",
"token_type": "bearer"
}
I want to publish feeds on the Facebook Page by API. I have followed the facebook documentation creating app in the facebook developer. Before I have registered a account facebook (example: test_account) and after that I have created the page for the business activity (example: test_page) where the manage admin is "test_account".
I have gone to the API by Graph API Explorer
https://developers.facebook.com/tools/explorer
I have granted the "publish_actions" and taken the access token generated by interface tool as followed image
After that I have tried the call POST request to test the publish feeds on the page facebook (test_page) by
https://graph.facebook.com/{id_page_business}/feed?message=test_message&access_token={access_token_APP}
and I have received the new ID_feed and I have seen the feed on facebook page and OK, but the access token the day after was expired. How can I have the access token that don't expired ?
I have tried another solution to obtain the access token from the call GET request (as documentation)
(STEP 1)
so I have obtained access token associated to the APP (see below)
access_token={APP_ID}|xxxxxxxxxxxxxxxxxxxxxjw
(STEP 2) I have sended call GET request
https://graph.facebook.com/{APP_ID}/accounts?access_token=APP_ID}|xxxxxxxxxxxxxxxxxxxxxjw
and I have obtained the followed response:
{
data: [1]
0: {
id: "xxxxxxxx"
login_url: "https://developers.facebook.com/checkpoint/test-user-login /132173517148280/"
access_token: "123456........"
}
paging: {
cursors: {
before: "yMTczNTE3MTQ4Mjgw"
after: "yMTczNTE3MTQ4Mjgw"
}
}
}
(STEP 3) So I have tried the call POST request to publish the feed on the facebook page with the last access token (123456........) and I have received
{
id: "1256xxxxxx_133346xxxxxx"
}
but in the page business I don't see the feed... WHY?
IMPORTANT:I have noticed if I call the request GET API to obtain all feeds page (https://graph.facebook.com/ID_PAGE/feed?access_token=CAAPG1DFdxrs...........) I can see the feeds published, but into the facebook interface timeline I don't see the feed.
I have noticed that the feed publish by API return:
message: "test"
created_time: "2015-11-29T16:39:44+0000"
id: "APP_ID_138999329797136"
The second part the id is different respect when I publish the feed with access token get from the API Graph.
You need to have extended token on page access token to post on the page. App access token will provide you all read access to the page but will not allow you to post.
Below steps must help -
Get the page access token using -
https://graph.facebook.com/{APP_ID}/accounts?access_token={APP_ID}|xxxxxxxxxxxx
Using the page access token obtain the extended token, below is how I had implemented using VB.NET
Dim parameters As Object = New ExpandoObject()
parameters.client_id = FB_APP_ID
parameters.client_secret = FB_APP_SECRET
parameters.grant_type = "fb_exchange_token"
parameters.fb_exchange_token = short_token 'FBClient.AccessToken
Dim result As Object = FBClient.Get("oauth/access_token", parameters)
Use this extended token to post on page. It worked for me, hope it helps you.
I have managed to send and retrieve data from facebook for invitatin using
FB.ui({
method: 'apprequests',
to: sendto,
message: 'Win Mega Prizes!',
title: 'Enter in this contest!'
},
function (response) {
if (response && response.request_ids) {
var requests = response.request_ids.join(',');
alert(requests);
window.location.href = "http://www.rmyserver/index.php?invitations="+requests+"&contest_id="+c_id+"&page_id="+page_id+"&user="+from+"&g_id="+g_id+"&sendto="+sendto+"&single=1";
} else {
alert('canceled');
}
PHP
foreach($requests as $request_id) {
// Get the request details using Graph API
echo $request_content = json_decode(file_get_contents("https://graph.facebook.com/$request_id?$app_token"), TRUE);
But i want to use single user app request , as per docs i need to use TO: filed but this doesnt work, request is sent as well i get invitation id but php code used above returns false.
Am i missing something
you can try direct url example given here https://developers.facebook.com/docs/reference/dialogs/requests/#frictionless_requests
that should work fine from php
This works for me:
FB.ui({
method:'apprequests',
message:'I want you to open up your heart a little.',
to:123456798,
// filters:['app_non_users'], // commented: let users send notifications to app users too, probably a good idea to make them revisit?
data:'' // send data what you would like to track, FB will send that back in the URL for us
// #todo send google campaign parameters
});
Moreover you are doing it wrong on PHP side, you would need to redirect the user to a URL where the invitation friend selector would be displayed. There is no way in my knowledge to directly send an invitation to users using PHP.