Facebook SDK Invalid Scopes error - facebook-graph-api

I'm trying to get user's birthday but as soon as I add the user_birthday permission I get an error Invalid Scopes: user_birthday. This message is only shown to developers...
I have thought that it was deprecated first but found nothing about it, also 3.0's documentation has the user_birthday permission. (HERE)
$fb = new Facebook\Facebook([
'app_id' => 'XXXXXXXXXXXXXXX',
'app_secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'default_graph_version' => 'v3.0',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'user_birthday'];
$loginUrl = $helper->getLoginUrl('https://mywebsite.com/callback', $permissions);
$loginUrlFinal = 'https://www.facebook.com/dialog/oauth?client_id=XXXXXXXXXXXXXXX&redirect_uri='.$loginUrl.'&state='.urlencode($fb_params);
After this error about Invalid Scopes I'm redirected to my callback file with a "Bad request" error.
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
EDIT:
This happens with almost any permission I add, the only one worked so far is just email.
A request to OpenGraph with ?fields=email,user_birthday returns no birthday while id, name, email are working fine. I guess this happens because I did not approve the user_birthday permission but how can I do that if the permission screen is not opening due to Invalid Scopes?

After long hours of research, I found out that this was due to my app being "Live". Looks like only apps that are currently in development mode will have permissions working.
Hope it will help someone.

Related

Stuck on 'Ads API Access Level:development'

I try to have an app that can pause/resume my adset (accounts owned by myself).
I get no error message(or anything) output when requesting this
$adset = new AdSet($adsetid);
$adset->campaign_status = AdSet::STATUS_ACTIVE;
try{
$adset->updateSelf();
} catch (RequestException $e) {
$response = json_decode($e->getResponse()->getBody(), true);
var_dump($response);
}
But I see that the adset status did not change.
Now, I do see that the Marketing API, Settings section shows me that the API access Level is development and the app doesn't have Ads management standard access.
When I check permissions at App review > Permissions and features it shows 'Standard access' and 'ready to use'. (however not 'Active')
And at the same time my request count and error rate in the past 30 days are acceptable.
I don't understand what is missing to make it work. Can anyone help me out?
The code I have shown in my question was based on the code I copied from the Facebook marketing API documentation.
Strangely when I simulated my request using the Graph API Explorer and hit the "Get code" button it will suggest you a different code.
When I used that code instead of the code of the marketing API docs it did seem to work just as expected.
This code worked as opposed to the code from the docs:
$adsetid = "YOUR ADSET ID";
$access_token = "YOUR ACCESS TOKEN";
try {
$response = $fb->post(
'/'.$adsetid,
array (
'fields' => 'status',
'status' => 'ACTIVE'
),
$access_token
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();

Not Sure If Session Is Initiated Using Facebook PHP SDK

I'm trying to use Facebook's PHP SDK. The code that makes a call to Facebook to retrieve user's information is saved in a file called fbcall.php. The fbcall.php page is called through an href link from another page called index.php
The Entire Code (index.php):
<?php
echo "Login Here";
?>
Index.php is also my FacebookRedirectLoginHelper redirect url.
The question I have is that I'm not seeing an output for the following statement in the fbcall.php file and I'm not sure why?
echo "Name: " . $user_profile->getName();
I get the sense that my sessions isn't initiated but I'm sure how to validate this. And if it isn't initiated then I'm not sure what i'm doing wrong considering I'm following Facebook's guidelines here (or atleast I think I am).
The Entire Code (fbcall.php):
<?php
session_start();
// Make sure to load the Facebook SDK for PHP via composer or manually
require_once 'autoload.php';
//require 'functions.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// add other classes you plan to use, e.g.:
// use Facebook\FacebookRequest;
// use Facebook\GraphUser;
// use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication('AM USING MY APP ID HERE','AM USING MY SECRET KEY HERE');
$helper = new FacebookRedirectLoginHelper('http://localhost/facebook/index.php');
$params = array('email','public_profile', 'user_status', 'user_friends');
$loginUrl = $helper->getLoginUrl($params);
try {
$session = $helper->getSessionFromRedirect();
// var_dump($session);
} catch(FacebookRequestException $ex) {
} catch(\Exception $ex) {
}
if (isset($session)) {
var_dump($session);
}
else
{
$loginUrl = $helper->getLoginUrl();
header("location:".$loginUrl);
exit;
}
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
if(isset($session)) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
?>
Once the user grant your permissions, he/she will be redirected to index.php (because of your redirect_uri).
So there is two solutions:
- change you're redirect_uri to be fbcall.php
- move all fbcall.php logic to index.php, and change header("location:".$loginUrl); by echo "Login Here";

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
}
}

PHP facebook graphapi getting "An active access token must be used to query information about the current user."

I have this PHP code that i need help with
here is what i have
$facebook = new Facebook(array(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
'cookies' => 'true'
));
$FBuser = $facebook->getUser();
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . FB_APP_ID .
"&client_secret=" . FB_APP_SECRET .
"&grant_type=client_credentials";
So far so good.. but then i try
$permissions = $facebook->api("/me/permissions");
And i get the error
"An active access token must be used to query information about the current user."
I know the user has already installed my app. I must be missing something simple??
Thanks
Randy
This:
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . FB_APP_ID .
"&client_secret=" . FB_APP_SECRET .
"&grant_type=client_credentials";
Simply gets an access token for the APP. There is no user attached to this. Read this documentation about getting a user's login url. Then, the facebook SDK you have at that redirect_uri will finish the job for you, and get you an access_token. From there you just need to call $permissions = $facebook->api("/me/permissions"); and it should work just fine.
To be sure, after you get that access_token in your current script, run it in the debugger to ensure a user_id is tied to it.

Facebook OAuthException: (#1)

I have a few applications which upload image to user profile. A few hours ago all applications were working fine but now when uploading is requested, it gives this error
Fatal error: Uncaught OAuthException: (#1) An unknown error occurred thrown in applications/fb-sdk/facebook.php on line 543
I'm using the following code to publish image.
$FILE = "images/$image";
$args = array('message' => 'My msg ');
$args['image'] = '#' . realpath($FILE);
$data = $facebook->api('/'.$uid.'/photos', 'post', $args);
Is it because of some policy change or some new feature?
I have all the permissions like upload is set to true and application takes permission to upload file.
P.s: when the application is used 2nd time, it works fine.
You need to verify if the user is logged in AND has the permissions to post on wall. We're going to do that with a TRY/CATCH with a call to the user.
$userId = $facebook -> getUser();
if ($userId) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$userId = NULL;
error_log($e);
}
}
$app_permissions = array(
'scope' => 'publish_stream'
);
$logoutUrl = $facebook->getLogoutUrl();
$loginUrl = $facebook->getLoginUrl($app_permissions);
If the user is not logged in OR has authorized the app, you'll need to redirect him via header redirect or with a link.
if ($userId){
//Then you can call the facebook api
$data = $facebook->api('/'.$uid.'/photos', 'post', $args);
//... ...
}
That's the easiest way i've found.
EDIT : This question on stack has helped me : Facebook PHP SDK Upload Photos
No, the error is caused by the system cannot get the image file. Facebook will not allow the empty image field appear in the api. So it return Fatal error: Uncaught OAuthException: (#1) --- although it does not relate to the OAuth and OAuthException.