I'm trying to create a script that post on a facebook page (as an administrator) a status.
This is the script i'm using:
try {
$access_token = (new FacebookRequest( $session, 'GET', '/' . $pageID, array( 'fields' => 'access_token' ) ))
->execute()->getGraphObject()->asArray();
$access_token = $access_token['access_token'];
$page_post = (new FacebookRequest( $session, 'POST', '/'. $pageID .'/feed', array(
'access_token' => $access_token,
'message' => $message,
) ))->execute()->getGraphObject()->asArray();
} catch (FacebookRequestException $e) {
echo 'ERROR! ' . __LINE__ . $e->getMessage();
} catch (Exception $e) {
echo 'ERROR! ' . __LINE__ . $e->getMessage();
}
The script does work, and I see the post on facebook (ignore language):
The problem is that I'm the only one who can see this post. When other users enter the page, they can't see the post, and if I give them the post's url, it says that it doesn't exist.
You need to make your app public, on top of Status&Review tab in app dashboard.
As long as an app is in development mode, everything it “creates” on Facebook is only visible to app admins/developers/testers.
(This does not require to submit your app for review, since you will only be using it yourself. Only if you wanted to ask other users for permissions as well, you’d need to submit those for review.)
Related
I'm trying to create a ad via the Facebook Business SDK. Everything works well until I'm trying to create a AdCreativeVideoData. Code:
protected function createAdVideoCreative($thumbnail_url, $video_id, $name){
$video_data = new AdCreativeVideoData();
$video_data->setData(array(
AdCreativeVideoDataFields::IMAGE_URL => $thumbnail_url,
AdCreativeVideoDataFields::VIDEO_ID => $video_id,
AdCreativeVideoDataFields::CALL_TO_ACTION => array(
'type' => AdCreativeCallToActionTypeValues::LIKE_PAGE,
'value' => array(
'page' => FbAds::PAGE_ID,
),
),
));
$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
AdCreativeObjectStorySpecFields::PAGE_ID => FbAds::PAGE_ID,
AdCreativeObjectStorySpecFields::VIDEO_DATA => $video_data,
));
$creative = new AdCreative(null, FbAds::AD_ACCOUNT_ID);
$creative->setData(array(
AdCreativeFields::NAME => $name,
AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));
try {
$creative->create();
return $creative;
} catch (Exception $e) {
print("Create Ad Video Creative Exception: " . $e->getMessage() . " (" . $e->getCode() . ")");
exit;
}
}
The above method is called when the selected video is uploaded to Facebook via the following method:
protected function createAdVideo($video_path){
$video = new Advideo(null, FbAds::AD_ACCOUNT_ID);
$video->{AdVideoFields::SOURCE} = $video_path;
try {
$video->create();
return $video->{AdVideoFields::ID};
} catch (Exception $e) {
print("Create Ad Video Exception: " . $e->getMessage() . " (" . $e->getCode() . ")");
exit;
}
}
The problem is that when I'm trying to create the AdCreativeVideoData, the following error is thrown:
[message] => Invalid parameter
[type] => OAuthException
[code] => 100
[error_subcode] => 1885252
[is_transient] =>
[error_user_title] => Video not ready for use in an ad
[error_user_msg] => The video is still being processed. Please wait for the video to finish processing before using it in an ad.
[fbtrace_id] => AwW0d9+Piz1
As you can see, the video is not yet processed. My question is: how can I check the status of the video? Is there a endpoint available somewhere which I can ping to check the status? The documentation states that I can check the status, but the AdVideo object in the createAdVideo() method doesn't have a status field:
I'm at a loss here so I hope someone can shed a light on this problem. Thanks in advance!
AdVideo does not have a status field since then, but Video does: https://developers.facebook.com/docs/graph-api/reference/video
Internally it's the same id, so you can request https://graph.facebook.com/v4.0/{video-id}?fields=id,status which will return the status of the uploaded (Ad)Video.
I'll assume it is because the video is not uploaded at all.
Instead of using "source" try using "file_url". You may also want to add a parameter "title" so it will not be named untitled video- but it is not required.
And try using the SDK smarter like so:
$myVideoUpload = (new AdAccount("act_123456676"))-
>createAdVideo(
array() //fields
array( //params
"file_url"=>"http://whatever.com",
"title"=>"my title"
)
);
if this works, it'll return a json_encodes string with id=video_id.
If you want to be able to retrieve errors- if any- and a general method for all api calls, do use the graph api as such:
$fb = new Facebook(array(
"app_id"=>"blalaa",
"app_secret"=>"blaaaaa",
"default_graph_version"=>"v9.0"
));
$url = "/act_123456789/advideos";
$access_token = "my token";
$params =
array("file_url"=>"https://whatever.com","title"=>"some video");
try{
$response = $fb->post(
$url,
$params,
$access_token
)
$response = $response->getGraphNode();
} catch(FacebookResponseException $e) {
return "graph error:: " . $e->getMessage();
} catch(FacebookSDKException$e) {
return "sdk error:: " . $e->getMessage();
}
The last one can be applied to everything given that you have an access_token that has access to the specific edge that you are requesting thus only he URL needs to be changed accordingly along with the parameters.
Note:
While using the graph-api: Use POST if you want to change or create something, and GET if you only want to read.
I'm having a lot of trouble getting the Facebook API to work at all. Any example code I use gives me Server Error 500. I'm trying to post a link to my facebook page (this code is from the example code Facebook gives in its documentation). To clarify as well, I do have an app-id, secret-id, and I believe I got the right access token from the Graph API. I know I need a public_action permission to post a link, but the way I read it, I think the access token defaults with public_action.
<?php
$appid = '{app-id}';
$appsecret = '{app-secret}';
$redirect_uri = 'http://mywebsite.com';
// Define the root directoy
define( 'ROOT', dirname( __FILE__ ) . '/' );
// Autoload the required files
require_once( ROOT . 'facebook-php-sdk-v4-4.0-dev/autoload.php' );
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.2',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'User provided message',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/me/feed', $linkData, '{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();
echo 'Posted with id: ' . $graphNode['id'];
?>
I really do not know what I am doing wrong. Likewise, where it says "me" should that be my facebook user id? Thank you.
I have the below snippet and it works and posts to a Facebook page as my own user account on Facebook.
The values FACEBOOK_* are defined earlier in the codebase.
// SDK Version 5.0
$fb = new Facebook\Facebook([
'app_id' => FACEBOOK_APP_ID,
'app_secret' => FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.4',
]);
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/'.FACEBOOK_PAGE_ID.'/feed', $postData, FACEBOOK_ACCESS_TOKEN);
$postId = $response->getGraphNode();
Now my question is how can I get it to post as the actual page and not my account which is the admin of the page.
I've had a look at the SDK documentation and I've been going around in circles, there are many examples of v4 but as it's deprecated I'm trying to use v5 and just can't seem to figure it out, any links to post attribution or impersonation I find are dead links in v5 of the SDK.
From what I can see I need to make a call to /{user-id}/accounts to get an access token for the page from my user, https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
But to get a {user-id} I have to query the user, with something like the below example from the SDK documentation:
// Make sure to load the Facebook SDK for PHP via composer or manually
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
if($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();
}
The issue here is that I have no idea how to get a session which I need to get the user data for which gives me the access token to allow me pass the access token into my code snippet above that works, that's if I understand it all correctly!?
Any help greatly appreciated!
I work with classes, so I adapted my code to your examples above. Tested and working code.
After getting your user access token using the method you use (see the guide here), we have to obtain a long-lived access token. Add this to your code :
session_start();
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// There was an error communicating with Graph
echo $e->getMessage();
exit;
}
if (isset($accessToken)) {
$client = $fb->getOAuth2Client();
try {
$accessToken = $client->getLongLivedAccessToken($accessToken);
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo $e->getMessage();
exit;
}
$response = $fb->get('/me/accounts', (string) $accessToken);
foreach ($response->getDecodedBody() as $allPages) {
foreach ($allPages as $page ) {
if (isset($page['id']) && $page['id'] == $pageId) { // Suppose you save it as this variable
$appAccessToken = (string) $page['access_token'];
break;
}
}
}
$response = $fb->post(
'/'.$pageId.'/feed',
array(
"message" => "Message",
"link" => "http://www.example.com",
"picture" => "http://www.example.net/images/example.png",
"name" => "Title",
"caption" => "www.example.com",
"description" => "Description example"
),
$appAccessToken
);
// Success
$postId = $response->getGraphNode();
echo $postId;
} elseif ($helper->getError()) {
var_dump($helper->getError());
var_dump($helper->getErrorCode());
var_dump($helper->getErrorReason());
var_dump($helper->getErrorDescription());
exit;
}
Explanations : You have to know which pages you are administrator :
$response = $fb->get('/me/accounts', (string) $accessToken);
Then search the table to retrieve the access token of the page that interests us (I have chosen to take the id of the page referenced).
Finally, simply run the post function provided by the SDK :
$response = $fb->post(
'/'.$pageId.'/feed',
array(
"message" => "Message",
"link" => "http://www.example.com",
"picture" => "http://www.example.net/images/example.png",
"name" => "Title",
"caption" => "www.example.com",
"description" => "Description example"
),
$appAccessToken
);
I'm using php facebook api 4.0. I'm using below code to post photo on my timeline.
FacebookSession::setDefaultApplication($app_id, $app_sc);
$helper = new FacebookRedirectLoginHelper($url_page);
$loginUrl = $helper->getLoginUrl();
$session = new FacebookSession($access_token);
FacebookSession::enableAppSecretProof(false);
if($session) {
try {
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'source' => '#' . realpath('1.jpg'),
'message' => 'message'
)
))->execute()->getGraphObject();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
But I'm getting Exception occured, code: 324 with message: (#324) Requires upload file error. I think one thing is that, fileupload support should be set to on. But I don't know from where should I turn it on.
I am trying to post a simple message on my wall by using the Facebook PHP SDK but I get some troubles when I try to set up custom privacy rules, here is my code:
try {
$response = (new FacebookRequest(
$session, 'POST', '/me/feed', array(
'message' => #$_GET['message'],
'privacy' => json_encode(array(
'friends' => 'SOME_FRIENDS',
'value' => 'CUSTOM',
'allow' => implode(',', $friends)
))
)
))->execute()->getGraphObject();
echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
And i get the fallowing error:
Exception occured, code: 100 with message: (#100) 'friends' value was not recognized
Someone could help me ?
EDIT The problem is that i do not have the real ID of the the friends, but i do not know how to get it when they do not use my application, any idea ?
If you see the Publish documentation for Feed, the privacy settings you are using are invalid. As you can no longer get IDs of friends (unless they use the application), so you cannot restrict posts to a select number of friends who's IDs you do not know.