Facebook Graph API: Create/Update Event Picture not working - facebook

I want to update an event's picture as described in the Event API.
$eventId = '291145580981541';
$accessToken = $facebook->getAccessToken(); // have tested, is correct
$data = array('source' => '#'.realpath($file));
try {
$result = $facebook->api('/$eventId/picture?access_token=$accessToken', 'POST', $data);
echo $result;
} catch(Exception $e) {
echo "Exception: $e";
}
The result I get:
Exception: OAuthException: (#200)
What am I doing wrong?

Error #200 is a permissions error. You most likely don't have the create_event permission
https://developers.facebook.com/docs/reference/api/event/#picture

Related

Access private facebook group's posts using Graph API ( v 7.0 )

I am trying to get private groups posts by using graph api v7.0 by unfortunately i did not get posts returned an error Graph returned an error: (#803) Cannot query users by their username (SAAME)
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get(
'/SAAME/feed',
'{access-token}'
);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
//$graphNode = $response->getGraphNode();
$data = (array) $response;
var_dump ($data);
https://developers.facebook.com/docs/graph-api/reference/v7.0/group/feed
Check out the requirements, especially the bold ones:
Your app must be approved for the Groups API feature.
The app must be installed on the Group. (can only be done as group admin)
A User access token. (i assume any user token of a group member is ok)

Can't get instagram newly added business account through API

I am facing issue for Instagram business accounts retrieving from API.
Client is already authorized my app and after some time they converted there Instagram personal account to business account.
When i try to fetch newly added Instagram business account they are not showing in API response.
Every time i have to remove app from account and re-authorized. I re-authenticated app still not get newly added business account.
Guys any solution for this ??
Here is a screenshot for more info http://nimb.ws/zfwl7e
function fb_reauthenticate_relink()
{
$helper = $this->fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile', 'manage_pages', 'read_insights', 'publish_pages', 'instagram_basic', 'instagram_manage_comments', 'instagram_manage_insights'];
$loginUrl = $helper->getReAuthenticationUrl('facebook_reauthenticate_callback', $permissions);
redirect($loginUrl);
}
function facebook_reauthenticate_callback()
{
$helper = $this->fb->getRedirectLoginHelper();
try
{
$accessToken = $helper->getAccessToken();
} catch (Facebook\Exceptions\FacebookResponseException $e)
{
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e)
{
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$raw_accessToken = (string) $accessToken;
$oAuth2Client = $this->fb->getOAuth2Client();
$longLivedAccessToken = (string) $oAuth2Client->getLongLivedAccessToken($raw_accessToken);
$url = "https://graph.facebook.com/v3.1/me/accounts?fields=instagram_business_account,connected_instagram_account,global_brand_page_name,access_token&access_token=" . $longLivedAccessToken;
$request_response = $this->curl_request($url);
// In $request_response didn't get newly added business profile
}

Requesting page insight for Facebook getting error "Graph returned an error: An unknown error has occurred. "

$helper = $fb->getRedirectLoginHelper();
$permissions = ['email','manage_pages','pages_manage_cta','publish_pages','publish_actions'];
giving permissions.
$loginUrl = $helper->getLoginUrl('http://localhost/Facebook/insight.php', $permissions);
echo 'Log in with Facebook!';
facebook Insight code.
$fb->setDefaultAccessToken($accessToken);
Get user groups detail
$requestPageInsights = $fb->request('GET', '/1364467436924381/insights/, $accessToken');
//Make a batch request
$batch = ['page-insights' => $requestPageInsights];
try {
$responses = $fb->sendBatchRequest($batch);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
Graph returned an error: An unknown error has occurred.
Just experienced the same issue.
The error seems to be with batched requests - The solution for us was to change the code to do the requests individually.

Code to access Facebook Graph API with PHP SDK not working when reloading page

I'm writing some code to get the Facebook pages administered by a Facebook user, using Facebook Graph API. My code asks for authorization of the user and gets a token that enables it to get this information, which is then stored in a session. The problem is that if I reload the page, the stored token is unset and I will not be able to get the Facebook pages administered by the Facebook user.
The token is apparently revoked via the 'validateExpiration()' function when the page is reloaded.
What am I missing?
Here is my code:
session_start();
// Load the Facebook PHP SDK
require_once __DIR__ . '/facebook-sdk-v5/autoload.php';
define('APP_ID', 'xxxxxxxxxxxxxxxx');
define('APP_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$fb = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.7'
]);
if(isset($_SESSION['fb_access_token'])) {
echo '$_SESSION["fb_access_token"] = ' . $_SESSION['fb_access_token'] . '<br>';
// Create a new AccessToken object from its string code. Needed?
$accessToken = new Facebook\Authentication\AccessToken($_SESSION['fb_access_token']);
$expirationDate = $accessToken->getExpiresAt();
echo 'Token expires at: ' . var_dump($expirationDate) . '<br>'; // Returns null!
// verifies the validity and expiration of the token
$oAuth2Client = $fb->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
try {
echo 'Validating token<br>';
$tokenMetadata->validateAppId(APP_ID);
$tokenMetadata->validateExpiration(); // This apparently throws an exception
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'I will now unset the token<br>';
unset($accessToken);
unset($_SESSION['fb_access_token']);
}
if(!isset($accessToken)){
echo 'Token not set!';
exit;
}
// Check permissions
if (isset($accessToken)) {
$response = $fb->get('/me/permissions', $accessToken);
$permissions = $response->getDecodedBody();
echo 'Permissions: ';
print_r($permissions);
$permissions_list = [];
foreach($permissions['data'] as $perm) {
if($perm['status'] == 'granted') {
$permissions_list[] = $perm['permission'];
}
}
echo 'Permissions list: ';
print_r($permissions_list);
if(!in_array('pages_show_list', $permissions_list)) {
echo 'I will now unset the token<br>';
unset($accessToken);
unset($_SESSION['fb_access_token']);
}
}
} else {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if(isset($accessToken)) {
// Logged in!
// Save the string code of the AccessToken to re-create it later
$_SESSION['fb_access_token'] = (string) $accessToken;
echo '$_SESSION["fb_access_token"] = ' . $_SESSION['fb_access_token'] . '<br>';
try {
$response = $fb->get('/me/accounts', $accessToken);
$data = $response->getDecodedBody();
echo '<pre>';
print_r($data);
echo '</pre>';
exit;
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile','pages_show_list']; // Optional permissions
$redirect_url = "https://www.example.com/this_file.php";
$loginUrl = $helper->getLoginUrl($redirect_url, $permissions);
echo 'Log in with Facebook!';
}
I finally got it!
The problem is that the Facebook AccessToken is an object with two properties: a string code, and a datetime PHP object with the expiration time - see the code in:
Github repository of Facebook's PHP SDK. The first time I get a fresh token, its expiration time is set and everything works fine. But when I store its code in a session and try to recreate it with
$accessToken = new Facebook\Authentication\AccessToken($_SESSION['fb_access_token']);
I'm not setting the expiration time, which the object defaults to the UNIX time 0 (i.e. January 1, 1970). Since after I invoke the function validateExpiration(), this will return that the access token has expired (it just looks at the expiration time in the AccessToken object) and will fire an exception.
Solution: Do not re-validate the stored token. The validateAppId(APP_ID) continues to be valid. For the expiration time, either store it (for example in a session) and use it when recreating the AccessToken object, or make a call to the Graph API. If this call returns an error (probably because of a token which was expired or a permission which was revoked by the user), ask the user for a new token via Facebook Login.

facebook php sdk 4 version, unable to fetch user albums

I am developing a facebook application via php sdk 4 version.
My code is as follows:
try {
$session = $helper->getSession();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
if ($session) {
try {
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$me = $response->getGraphObject();
$user_id = $me->getProperty('id');
echo $user_id;
$accessToken = $session->getAccessToken();
echo $accessToken;
echo "<br>".$user_id;
$request = new FacebookRequest($session, 'GET', '/me/albums');
$response = $request->execute();
$userAlbums = $response->getGraphObject();
echo $userAlbums['data'][0]['id'];
} catch(FacebookRequestException $e) {
echo $e->getMessage();
}
} else {
$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/lykebook/');
$auth_url = $helper->getLoginUrl(array('user_friends', 'publish_actions', 'user_photos', 'user_status', 'friends_photos','friends_status','publish_stream'));
echo "<script>window.top.location.href='".$auth_url."'</script>";
}
But the problem is I am not getting any album data. I don't know what the problem is? The earlier request i.e: /me is working fine. I checked that by printing $user_id. But the next request for getting albums is not working i.e /me/albums. Help me in correcting this.
Try using the getGraphObjectList() method since you are expecting more than one object. Then the result will be an array of GraphObject objects, see here.
From here, you need to access these as objects and not arrays with the helper methods available (e.g. getProperty()).
Otherwise, you can retrieve the array backing this object with asArray().
You could use getGraphEdge, here below the code:
$fb->setDefaultAccessToken($accessToken);
try {
$response = $fb->get('/me/albums');
$albums = $response->getGraphEdge();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
foreach ($albums as &$value) {
echo $value;
}