post to facebook feed as account posting to instead of app owner - php

I followed these instructions and some others to create an app and get tokens: facebook: permanent Page Access Token?
I used the following php code to post using the app:
<?php
require_once 'src/Facebook/autoload.php'; $fb = new \Facebook\Facebook([ 'app_id' => 'apkey', 'app_secret' => 'appsecret', 'default_graph_version' => 'v2.10', //'default_access_token' => '{access-token}', // optional ]);
$linkData = [
"message" => "Wonderful message.",
]; $pageAccessToken ='pageaccesstoken';
try { $response = $fb->post('/targetfeed/feed', $linkData, $pageAccessToken); } 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();
?>
I replace the keys and specific data with description.
My issue is that when I run this script it posts to the feed, but it posts as the app owner. I created the app in my personal account, and went through the token process using that account. I was granted admin access to the account that I want to post to, but when I post to that account it is posting as my person page and I instead want it to post as if I am posting as the account that I am posting to.
I am sure it some access token setting or permissions things, but I cannot figure it out. Any suggestions?

Related

Facebook PHP SDK 5.0 - Posting to group

I have been stumped for a while now. I'm attempting to write myself a small app to automatically post to a number of groups that I am members of in FB. I'm a PHP novice, but this is about my strongest skill set for what FB allows in terms of access that I can tell. So far, I CAN post to my own wall no problem but once I try and post to my own FB testing group I'm stumped. Here is my code so far...
<?php
require_once __DIR__ . '/vendor/autoload.php';
require 'src/config.php';
require 'src/facebook.php';
$fb = new Facebook\Facebook([
'app_id' => $config['App_ID'],
'app_secret' => $config['App_Secret'],
'default_graph_version' => 'v2.8',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'Test post to my feed.',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/{group_id}/feed', $linkData, $config['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;
}
?>
Currently the error that this is generating is:
Graph returned an error: (#200) Insufficient permission to post to target on behalf of the viewer
I have made the app Public and generated the access token with manage_pages and publish_pages. Unfortunately I'm out of ideas as of this point. Any help would be greatly appreciated. Thanks in advance.
OK. I figured out my problem at this point. It was that I had to go into the App Settings in my FB user account and change my App from "Only Me" to Public. Once I did that I was able to post to my groups. Next will be to figure out how to post into the proper fields for a "Sell Something" type of post and then to test it in groups that I'm not an admin of.
I figure it has to be possible to post into non-admin groups since there are a number of services out there for FB auto-posting and they have to get around it somehow.

PHP-Facebook post as page without page token

I use Laravel socialite package and I take
permission('manage_pages',
'publish_pages',
'publish_actions',
'ads_management',
'business_management', 'ads_read'),
After than get access token in callback.
When I try post as page with access token but post seems like visitor post.
What am I supposed to do? Here is my code:
$fb = new Facebook([
'app_id' => 'appid',
'app_secret' => 'appsecret',
'default_graph_version' => 'v2.7',
]);
$params=[
'message'=>'Example Post',
'access_token'=>'ACCESS_TOKEN',
];
try{
$ret=$fb->post('/PAGEID/feed',$params);
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: '.$e->getMessage();
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: '.$e->getMessage();
exit;
}
$graphNode = $ret->getGraphNode();
print_r($graphNode);
You need to use a Page Token with the publish_pages permission. If it gets posted as visitor, you are using a User Token.
More information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

Getting an access token from the Facebook Graph API

I'm trying to display facebook status updates for a sports team on their website using the facebook graph api, but can't seem to get a valid access token.
Here's my code.
require_once APPPATH.'/third_party/facebook-php-sdk-v4/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '123123123123',
'app_secret' => 'fghdfghtyjdfghdghjfghjfghj',
'default_graph_version' => 'v2.5'
]);
$fb->setDefaultAccessToken('123123123123|dfhjfgytdfghdfhgdsfjd');
$helper = $fb->getCanvasHelper();
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;
}
if (isset($accessToken)) {
// Logged in.
} else {
echo 'access token not set - THIS IS WHERE I ALWAYS SEEM TO END UP';
}
exit;
Is there anything obvious I'm doing wrong?
This is what I used in a Laravel 4 app to connect. Basically when the user clicks on a 'Log in' button,
1- Create the Facebook instance with app_id, app_secret and default_graph_version.
2- Get a redirectLoginHelper object to get a loginUrl with a code that facebook will provide when you call $helper->getLoginUrl($redirectUrl, (array) $permissionsNeeded)
3- Redirect to that url
4- Create facebook instance and getRedirectLoginHelper again as step 1 and 2
5- Check if you received the 'code' parameter in the url the helped returned
6- Get the access token: $accessToken = $helper->getAccessToken()
In the code I'm providing, I do all this steps in one method. I check if there's a code parameter in the request, if not I request it and redirect. The next time the code runs, when I check if code is there, it continues to the next step
$fb = new Facebook([
'app_id' => 'facebook_app_id',
'app_secret' => 'facebook_app_secret',
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
if(Input::get('code') == '') {
$permissions = ['manage_pages, publish_actions'];
$loginUrl = $helper->getLoginUrl('http://yoururl.dev/uri', $permissions);
return Redirect::to($loginUrl);
}
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
//Handle error
}
In this case, the Log in button goes to www.domain.app/connect, the URL that the redirectLoginHelper returns is the same, but with the code parameter: www.domain.app/connect?code=ntasd341251

Share link in facebook with php-sdk

I'm trying to share a link on Facebook with the php-sdk. Using Graph API Explorer in https://developers.facebook.com/tools/explorer and choosing the app that I create and the admin user for the page, it give me the access token and can share the link perfectly, but from the code with the same token I always get the error
Graph returned an error: Invalid OAuth access token.
I understand that is an authentication error but, avoid the authentication is not the purpose of use the token?, if not, how can be logged the admin user for do the task and why is not mentioned in https://developers.facebook.com/docs/php/howto/example_post_links/5.0.0 .The idea is to share the link with the user page administrator, not with the user logged on my site. This is the code.
public function shareOnFacebook($link)
{
$pageId = "XXXXXXXXXXX";
$accessToken = "YYYYYYYYYYYYYY";
$appId = "ZZZZZZZZZZZ";
$appSecret = "SSSSSSSSSSSSS";
$fb = new Facebook([
'app_id' => '{'.$appId.'}',
'app_secret' => '{'.$appSecret.'}',
'default_graph_version' => 'v2.2',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'User provided message',
];
try {
$response = $fb->post('/'.$pageId.'/feed', $linkData, '{'.$accessToken.'}');
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
You should replace the whole field with your access token:
$response = $fb->post('/'.$pageId.'/feed', $linkData, '{'.$accessToken.'}');
Should be
$response = $fb->post('/'.$pageId.'/feed', $linkData, $accessToken);
I suppose adding the access token to the $linkData should work as well.

FacebookSDK search by username/pagename

I'm trying to access public information for a user based on their username/pagename.
I'm doing this:
$uname = 'csga5000';
$session = new Facebook\Facebook([
'app_id' => self::$FACEBOOK_APP_ID,
'app_secret' => self::$FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.2'
]);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $session->get('/search?q='+$uname+'&type=user');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
print_r($e);
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
But the exception is thrown, here is the output:
Graph returned an error: (#803) Some of the aliases you requested do not exist: v2.20
Alternatively(Got this from looking at the source code)
$response = $session->sendRequest('GET','/search',['q'=>$uname,'type'=>'user']);
Returns "Graph returned an error: An access token is required to request this resource." I stole a reference from somewhere using app id and secret as the token in this format:
$response = $session->sendRequest('GET','/search',['q'=>$uname,'type'=>'user'], self::$FACEBOOK_APP_ID.'|'.self::$FACEBOOK_APP_SECRET);
This throws: "Graph returned an error: A user access token is required to request this resource."
I don't understand why a USER access token is required :/
Anyone know how to search for a user based on username in php? I've seen other examples that were slightly outdated, but I was pretty much the same as what they claim worked.
Edit:
The information we want to acquire is primarily follower count.
First of all, you can´t search for users by username anymore. Earlier this was possible by just using a simple API call: graph.facebook.com/username
This does not work anymore, and the Search API only allows to search for the name (first/last). You are not supposed to use the username anymore.
That being said, you need to authorize yourself and use a User Token, as the error message tells you. That´s just how it is, and you can read it in the docs too:
Searches across Page and Place objects requires an app access token.
All other endpoints require a user access token.
Source: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.4#search
More information about Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
It seems to be the case that it's not possible(at the time) to access more than a user's name publicly. OAuth is required to access the public profile (which is a default permission).
Using the graph api explorer you can verify this using the endpoint /{user-id} and trying to get additional information for a user with whatever id.
The return is like this:
{
"name": "John Doe",
"id": "100003216243221"
}
You can get first and last name as well, by appending:
?fields=name,first_name,last_name
But access to other information fails, even when public. (I only tested location, which clearly has an additional permission).
EDIT!
HOWEVER:
If you wish to access a facebook page, some information is accessible.
This is some of the information returned if no fields are specified: about, id, can_post, category, check_ins, has_added_app, is_community_page, is_published, likes, link, location, name, phone, talking_about_count, username, website, were_here_count.
Using the endpoint:
{page-username-or-id}?fields=engagement,is_permanently_closed,emails,picture
Can retrieve other information fields (assuming they're public).
So code for this:
Facebook sdk v4:
$session = FacebookSession::newAppSession();
$session->validate();
$ret = new FacebookRequest(
$session, 'GET', '/'.$uname.'?fields=name,engagement,phone,link,is_community_page,is_permanently_closed,influences,hometown,general_info,emails,bio,birthday,description,location,username,likes,picture'
);
$ret = $ret->execute()->getGraphObject()->asArray();
If you want to catch exceptions, you can look the thrown exceptions up: https://developers.facebook.com/docs/php/
This works for the same request for facebook sdk v5 (though, I don't know that the way I called send request is advised):
$uname = 'tbdsolutions5000';
$session = new Facebook\Facebook([
'app_id' => self::$FACEBOOK_APP_ID,
'app_secret' => self::$FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.2'
]);
try {
$response = $session->sendRequest('GET','/'.$uname,[
//Optionally:
//'fields' => 'comma, separated, fields'
],
self::$FACEBOOK_APP_ID.'|'.self::$FACEBOOK_APP_SECRET
);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
print_r($e);
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$response = $response->getGraphObject()->asArray();

Categories