Can't get instagram newly added business account through API - facebook

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
}

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)

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.

(403) User does not have any Google Analytics account

i have issue with google api service account i have done successfull authentication and got the access token. when i try to run the query it shows error
Warning: You need to set Client ID, Email address and the location of
the Key from the Google API console:
http://developers.google.com/consoleThere wan a general error : Error
calling GE T
(403)
User does not have any Google Analytics account.
i have multiple websites and multiple accounts in it. the google account is an admin account please check the code below.
$key_file_location = 'key path';
$client = new Google_Client();
$client->setApplicationName("name");
$client->setClientId($client_id);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$client->setAccessType('offline_access');
$client->getAccessToken();
$service = new Google_Service_Analytics($client);
$analytics_id = 'ga:xxxxxx';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $service->data_ga->get($analytics_id, $lastWeek, $today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}

Facebook Getting Event from PAGE! not user PHP sdk v4.0.x graph 2.1

im trying to just get PAGE/Event from facebook and im still in doubt about how to do it
and if im doing it right or am i totally of track?
// for permanet session
$session = new FacebookSession("permanet app token");
// If you're making app-level requests: (copy paste from facebook :P)
$session = FacebookSession::newAppSession();
// To validate the session:
try {
$session->validate();
} catch (FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
echo $ex->getMessage();
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
echo $ex->getMessage();
}
if ( isset( $session ) && $session->validate() ) {
if($session) {
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/PAGE/events'
))->execute()->getGraphObject(GraphUser::className());
print_r($user_profile);
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
so im wondering is this wrong or is it okey i just wanna post events i don't wanna login and stuff like that
im sorry im not good at english or explaining, so if something is unclear please let me know and i will try to explain as best as i can!
If you just want to get public events from a page, when what you are doing is correct. Just make sure the events on the page are public.
You cannot, however, create or post events without logging in. Firstly, the API no longer allows you to create events via the API. Secondly, viewing private events will require to login so Facebook can determine if you have permission to view the event or not.

Laravel, Facebook API: retrieving friends of friends

In a previous thread we were strugling with the Facebook login using a Laravel app. Now, as the user logs into our app using Facebook, we are trying to get his friend's list in order to provide some qualified suggestions. So, here's what we are trying:
Route::get('login/fb/callback', function() {
// A FacebookResponse is returned from an executed FacebookRequest
$helper = new FacebookRedirectLoginHelper('http://yoururl/login/fb/callback');
$session = $helper->getSessionFromRedirect();
$request = new FacebookRequest($session, 'GET', '/me/friends');
try {
$response = $request->execute();
$me = $response->getGraphObject();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
print_r($me);//->getProperty("id"));
$user = new Giftee;
$user->name = $me->getProperty('first_name') . ' ' . $me->getProperty('last_name');
$user->email = $me->getProperty('email') . "#facebook.com.br";
$user->photo = 'https://graph.facebook.com/' . $me->getProperty('id') . '/picture?type=large';
$user->save();
});
As a result, we get:
object(Facebook\GraphObject)#146 (1) { ["backingData":protected]=> array(0) { } }
By reading the Facebook API docs, they pretty much say user_friends will only return friends of friends that already use your app and We could not see any login permission that would just return friends of friends (not only the ones using our app). In another words, is what we want really impossible?
You're not able to retrieve friends of friends. With Graph API v2.0, you even only get those friends of your app's users which also use your app.
And, all friends_* permissions have been removed. So I don't see a chance for you to implement what you want to achieve.