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.
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 struggling pulling data with the GRAPH API in php. I am not understanding the docs that well on Facebook Developers. I also cannot find any examples to help either.
I would like to have my API give me the following (between the first of the month and last day of the month):
New Likes
Visits
Organic Reach (monthly totals)
Organic Reach (for each day in the month)
Paid Reach (monthly totals)
Paid Reach (for each day in the month)
Cost to date
Engagement
Organic Impressions
Paid Impressions
I have gotten as far as being able to pull data, but when I test to use the insights portions it doesn't give me data. For example I have this:
// Sets the default fallback access token so we don't have to pass it to each request
$fb->setDefaultAccessToken('{access-token}');
try {
$response = $fb->get('/{page-id}/insights/page_impressions?since=1443650400&until=1446246000', $accessToken);
$graphEdge = $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;
}
And it returns this:
Facebook\GraphNodes\GraphEdge Object
(
[request:protected] => Facebook\FacebookRequest Object
(
[app:protected] => Facebook\FacebookApp Object
(
[id:protected] => *******************
[secret:protected] => ********************
)
[accessToken:protected] => *******************
[method:protected] => GET
[endpoint:protected] => /{page-id}/insights/page_impressions?since=1443650400&until=1446246000
[headers:protected] => Array
(
[Content-Type] => application/x-www-form-urlencoded
)
[params:protected] => Array
(
)
[files:protected] => Array
(
)
[eTag:protected] =>
[graphVersion:protected] => v2.5
)
[metaData:protected] => Array
(
[paging] => Array
(
[previous] => https://graph.facebook.com/v2.5/{page-id}/insights/page_impressions?access_token=*******************&appsecret_proof=*******************&since=1440968400&until=1443564000
[next] => https://graph.facebook.com/v2.5/{page-id}/insights/page_impressions?access_token=*******************&appsecret_proof=*******************&since=1446159600&until=1448755200
)
)
[parentEdgeEndpoint:protected] =>
[subclassName:protected] =>
[items:protected] => Array
(
)
)
I don't see any information in there that I can use and that is just for the page_impressions. I have even changed the dates to start at July 31st before and end on October 31st and still got nothing.
My two questions are:
1. What did I do wrong?
2. How to make multiple calls to get all of the data in the list above?
Thank you in advanced!
What did I do wrong?
Since the response didn't throw error, please make sure you meets these requirements:
For Insights metrics that were not publicly available (page_impressions, page_stories, etc.), your access token must have read_insights permission.
Insights are only generated for a Facebook Page that has more than 30 people that like it. (Your Facebook Page must have > 30 followers)
For point 1, Facebook Graph Api will not throw error if you don't have the permission, it just won't give you the data (because it's not public). For this, you must apply a submission for read_insight permission for your Facebook App and get reviewed by the Facebook team for approval.
Or (the-not-recommended-way) check:
How to get a never expiring Facebook Page Access Token
This is how to show your metrics data using Graph Api Explorer:
Login to Graph Api Explorer
Click 'Get Token' and then 'Get User Access Token'
Click 'Extended Permissions' tab and check read_insights and click Get Access Token.
Grant yourself the permissions you requested.
Now enter a test query into the Graph API query field and click submit:
There you will see your metrics' datas. If it's not generating any data, then it's because point 2. (must have > 30 Likes)
How to make multiple calls to get all of the data in the list above?
Facebook allows batch request, example using php-sdk:
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.5',
]);
$fb->setDefaultAccessToken('user-access-token');
// Example : Get page impression
$requestPageImpression = $fb->request('GET', '/{page-id}/insights/page_impressions?since=1443650400&until=1446246000"');
// Example : Get Organic page impressions
$requestPageImpressionOrganic = $fb->request('GET', '{page-id}/insights/page_impressions_organic');
// Add more variable and API req, according to your list
// $requestPageStories = $fb->request('GET','....');
// etc...
$batch = [
'page-impression' => $requestPageImpression,
'page-impression-organic' => $requestPageImpressionOrganic,
// add more for your list
];
echo '<h1>Make a batch request</h1>' . "\n\n";
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;
}
foreach ($responses as $key => $response) {
if ($response->isError()) {
$e = $response->getThrownException();
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
echo '<p>Graph Said: ' . "\n\n";
var_dump($e->getResponse());
} else {
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
echo "Response: " . $response->getBody() . "</p>\n\n";
echo "<hr />\n\n";
}
}
What I'm doing is creating a post with the Facebook PHP SDK(v4)(and the app is set to use the v2.3 API) with the privacy settings of value to SELF, then later on changing the value to CUSTOM, and allow to the ids of the friends that have accepted the app.
Until recently everything worked fine, and now out of the blue I'm getting this error(nothing changed on our part): "(#100) Object does not support message editing", which I couldn't locate in their documentation. Has anybody encountered this situation and this error?
Here is the code I'm using (like I said everything worked fine until recently)(if you need more details please let me know)
$fb_token = 'FB_TOKEN';
$FB_session = new FacebookSession($fb_token);
try {
$FB_session->validate();
} catch (FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
//echo $ex->getMessage();
throw new RestException(501,'FB error: '. $ex->getMessage());
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
//echo $ex->getMessage();
throw new RestException(501,'FB error: '. $ex->getMessage());
}
//make posting request to FB
if($FB_session) {
try {
$fb_array = array(
'privacy' => array(
'value' => 'CUSTOM',
'allow' => 'USER_ID'
)
);
$fb_req = new FacebookRequest(
$FB_session, 'POST', "/POST_ID", $fb_array
);
$response = $fb_req->execute()->getGraphObject();
//echo "Posted with id: " . $response->getProperty('id');
$fb_post_id = $response->getProperty('id');
} catch(FacebookRequestException $e) {
//echo "Exception occured, code: " . $e->getCode();
//echo " with message: " . $e->getMessage();
throw new RestException(501,'FB error: '. $e->getCode() .'-'. $e->getMessage());
}
}
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.)
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.