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

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)

Related

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.

i am trying to get FACEBOOK COVER via graph API, but i cant.

try {
$requestCover = $fb->get('me?fields=cover'); //getting user Cover
$requestProfileCover=$fb->get('/me');
// $cover = $requestCover->getGraphUser();
// $profile = $requestProfileCover->getGraphUser();
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
echo ' error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK error: ' . $e->getMessage();
exit;
}
print_r($requestCover); // showing cover details on the screen
echo "<img src='".$requestCover['source']."'/>";
Error:
Fatal error: Uncaught Error: Cannot use object of type
Facebook\FacebookResponse as array in
C:\xampp\htdocs\fb_app\twibook\index.php:165 Stack trace: #0 {main}
thrown in C:\xampp\htdocs\fb_app\twibook\index.php on line 165
CBroe is pointing you to the correct function to use, to get your data. I am using this answer as trying to explain what you should try doesn't fit well into the comments. (Haven't worked with this api yet, so I am not sure about the actual solution to your problem, but the description of handling your problem should be accurate)
By calling $requestCover = $fb->get('me?fields=cover'); you are setting $requestCover to an object of class FacebookResponse.
Because it is an object, you can't access it's properties as you would when handling the elements of an array. You either have to use the ->-operator to access them if they are public, or you have to use specific methods.
In this case, for the class FacebookResponse, there are methods you have to use. The one CBroe pointed you to, will return an array with the different data of the body of the response, so first write the return value of the call to this method on a variable and then you (should) have an array with your values.
try {
$requestCover = $fb->get('me?fields=cover'); //getting user Cover
$requestProfileCover=$fb->get('/me');
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
echo ' error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK error: ' . $e->getMessage();
exit;
}
$responseBody = $requestCover->getDecodedBody();
echo "<img src='" . $responseBody ['source'] . "'/>";
print_r($requestCover); // should print an array

Facebook Graph API: Create/Update Event Picture not working

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