events fql return empty array - facebook-graph-api

I'm trying to retrieve users events using the facebook php sdk, but i'm stuck, the api return an empty array
$user = $me['id'];
$fql = "SELECT eid, name, start_time, end_time
FROM event
WHERE eid IN (SELECT eid
FROM event_member
WHERE uid = 1552544515)
ORDER BY start_time LIMIT 5";
$params = array(
'method' => 'fql.query',
'query' => $fql,
);
try {
$result = $facebook->api($params);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
thanks in advance.

If this is returning nothing, the most likely reason is that your user hasn't granted the user_events Permission during the Authentication flow.
Looking at your comments above, you may have added user_events to the permissions granted when a user goes through the Authenticated Referrals flow or via App Center, but regular users accessing the app directly need to go through one of the authentication flows from the document above, you're probably not doing this

Related

Laravel Socialite - Facebook extend/replace token with a one with more permissions

I'm using Laravel 5.4 and Socialite to allow the visitor of my site to log in.
Situation
I recently obtained the user_events permission cause I wanted to add some functionalities to my website.
Before this, some users got registered in my database along with their user token in the database. (token than includes the default permissions but not user_events)
I updated the SocialAuthController.php to reflect the new permission on the new created user and this is working great
return Socialite::driver('facebook')
->scopes(['public_profile', 'user_events'])
->redirect();
Problem
If a user is already registered in the database with his token, it is impossible to run this command $fb->get('me/events') since the token does not include the user_events permissions.
Questions
Is there a way to force a user to grab a new token with a new permission without having to remove him from the database ? ( I have data associated with users) ?
SocialAuthController
public function handleProviderCallback(SocialAccountService $service)
{
$user = $service->createOrGetUser(Socialite::driver('facebook')->user());
}
SocialeAccountService
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialAccount::whereProvider('facebook')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook',
'nickname' => $providerUser->getNickname(),
'avatar' => $providerUser->avatar_original,
'token' => $providerUser->token,
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}

Facebook API - App using Oauth to update status of page

I have built an app using the PHP Facebook SDK. It allows users to authenticate my app with facebook OAth so that they can update their status' via my App. This works great, however a lot of my users have business pages and they want to update the status on their business page not their main personal feed. How is this possible? Below is what I have so far.
if ($status != ''){
try {
$parameters = array(
'message' => "$status"/*,
'picture' => $_POST['picture'],
'link' => $_POST['link'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description']*/
);
//add the access token to it
$parameters['access_token'] = $access_token;
//build and call our Graph API request
$newpost = $facebook->api(
'/me/feed',
'POST',
$parameters
);
$success['status'] = "$xml->status";
$xml2 = new XMLGenerator($success, 'facebook','status');
$returnData = $xml2->output;
$returnData = APIResponse::successResponse('200', "$xml->status");
} catch (Exception $e) {
$returnData = APIResponse::errorResponse('400', 'Facebook Error: '.$e);
}
I assume I would have to change '/me/feed'? but to what? What is they have multiple pages how would my app know which page to post to?
Any help with this would be much appreciated.
You can substitute me with the PAGE_ID to post to a page e.g., /013857894/feed. Make sure that you have completed the OAuth process with the manage_pages and publish_stream permissions. You can learn more at the link below:
https://developers.facebook.com/docs/reference/api/page/#statuses
If the user has multiple Pages then you will first need to give them some way of selecting which page they want to post to. You can find out which Facebook Pages a given user is the administrator of by calling /me/accounts for that user. You can find out more about this approach in the Connections section of this page:
https://developers.facebook.com/docs/reference/api/user/

Error OAuthException: (#200) when inviting to Event

I am getting the Error:
Fatal error: Uncaught OAuthException: (#200)
when i try to invite people via an App to an event.
My Steps:
1. Getting long lived token with Permissions: create_event create_note publish_actions publish_stream rsvp_event user_events
2. Getting Userids who are friends and not already invited to the event.
3. Split into 50 Persons per Invite and send it.
Code for Inviting:
$friends = $facebook->api(array(
'method' => 'fql.query',
'query' => "SELECT uid,name FROM user WHERE uid IN
(SELECT uid1 FROM friend WHERE uid2=me()) AND NOT
(uid IN (SELECT uid FROM event_member where eid = '$eventid'))"));
foreach ($friends as $value)
{
if (!isset($allids))
{
$allids = $value['uid'];
}
else
{
$allids .= ',' . $value['uid'];
}
$count++;
$invitedusers++;
if ($count > 49)
{
//$splitinvite = $facebook->api($eventid . '/invited?users=' . $allids, 'POST');
unset($allids);
$count = 0;
}
}
$facebook->api($eventid . '/invited?users=' . $allids, 'POST');
I already seperated the Userids to make sure that they are setted correctly in the format Userid_1,Userid_2,Userid_3
I checked the token with the graph token debugger and all permissions are setted correctly.
Anyone an idea?
One posibility is the following Code. But this works realy slow because it sends a query for each person.
It takes up 30 Seconds for checking 37 people. Querying 50 people at once as shown above invites over 1000 people in 30 seconds.
I would appreacheate it if anyone can try to find a better way!!!
The best way would be filtering the FQL query (if is posible).
Slow working Code:
foreach ($friends as $value)
{
try
{
$splitinvite = $facebook->api($eventid . '/invited?user=' . $value['uid'],'POST');
$count++;
}
catch (Exception $e)
{
// Users privacy setting blocked inviting him, has blocked you or has blocked you from inviting
}
}

Facebook API - saving OAuth access token in session

I am trying to find a way to keep connected with the Facebook API once authorised using OAuth but am having problems. I dont want the users of my App to have to login via Facebook every time they want to use my app.
I store the oauth access toekn in a database after the user authenticates with facebook and I have "offline_access" permissions set, so in theory, this should be possible.
However, I get "Uncaught OAuthException: An active access token must be used to query information about the current user." when trying to connect to Facebook API using a saved Oauth token stored in a database.
header("p3p: CP=\"ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV\""); // hack to stop facebook wierd cookie problems
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'appid',
'secret' => 'secretid',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//get the user's access token
$access_token = $facebook->getAccessToken();
} else {
//see if authorisation already set up in DB
$query = mysql_query("SELECT oauth_token FROM PingSocialMediaUsers WHERE oauth_provider = 'facebook' AND clientID = '$clientID'");
$result = mysql_fetch_row($query);
$access_token = $result[0];
}
if($access_token) {
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'offline_access');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
'/me',
'GET',
array(
'access_token' => $access_token
)
);
//add to details database
//find the user by ID
if ($user != ''){
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE oauth_provider = 'facebook' AND oauth_uid = '$user'");
$result = mysql_fetch_array($query);
// If does not exist add to database
if(empty($result)){
$query = mysql_query("INSERT INTO PingSocialMediaUsers (oauth_provider, clientID, oauth_uid, username, oauth_token, oauth_secret) VALUES ('facebook', $clientID, $user, '{$accounts['name']}', '$access_token', '')");
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
//update the tokens
$query = mysql_query("UPDATE PingSocialMediaUsers SET oauth_token = '$access_token', oauth_secret = '' WHERE oauth_provider = 'facebook' AND oauth_uid = '$user'");
}
//save the information inside the session
$_SESSION['_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
}
$facebookAuth = TRUE;
Facebook pass an expires field when it pass your application the access token and default as per the Facebook is 2hours.
there are other factors why which a access_token can expire and here are the complete details for you
Ankur Pansari
How-To: Handle expired access tokens
Now next we can talk about offline_access which means
It Enables your app to perform authorized requests
on behalf of the user at any time. By default,
most access tokens expire after a short time period to ensure applications
only make requests on behalf of the user when the are actively
using the application. This permission makes the
access token returned by our OAuth endpoint long-lived.
So it all means you have to make sure you always using valid access_token.For details about various permission here is a reference link
Facebook Permissions

Getting users friend data using FB Graph API

I am attempting to access a user's friends work and education history using the Graph API. I have included both permissions in the auth dialogue. I have tried accessing them using FQL but have had no luck.
try{
$fql = "select friends_education_history from permissions where uid=" . $user;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
I'd prefer to access the info without using FQL but at this point, I need to figure out ANY way. Is there a way to do something like this:
if($user_id) {
try {
$friends = $facebook->api("/me/friends");
}
catch(Exception $o){
d($o);
}
}
?>
And then call the respective variables?
Your FQL query would look something like this:
SELECT education,work from user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())
Above query will fetch all education and work objects from friends of the logged in user.
SELECT education,work from user WHERE uid = <YOUR FRIENDS USER ID>
Above query will get education and work for just the one user id you provide
Hope this helps!
The User graph api object has fields education and work.
Permissions user_education_history & friends_education_history are required for the first, user_work_history & friends_work_history for the second.
These fields are optional & a user can restrict their visibility via her profile page, so even having granted the permissions the api may return nothing.
Use the Graph api explorer to have a play.