I have written a facebook app which checks if an album exists, if it does not it creates one.
This was all working 2 weeks ago and now I go and check it to show the client and it is no longer working. I was thinking it could have something to do with Facebook and maybe they now require an SSL? I can't find any evidence of this on there website however.
The error I am getting is:
Warning: file_get_contents(https://graph.facebook.com/517578134925015/albums?access_token=AAAD5tUCp808BAIZBPk4eV11mlf9C92velLsDeZAm5mXhKZCkwpM3LNy7ax6BBmhuH4BVZBUN6Iycyt55NoXZAFSts9zHeCFNzT6FLJYucgT2SQG8fOYIP) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error in /var/www/vhosts/hidden/development/cms/backend/publishAlbum.php on line 59
My current code is:
//If no album ID is set, create a new album.
$graph_url = "https://graph.facebook.com/".$pageId."/albums?" . "access_token=". $pageAccessToken;
$postdata = http_build_query(
array(
'name' => $albumName
)
);
$opts = array('http' =>
array(
'method'=> 'POST',
'header'=>
'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents($graph_url, false, $context));
Any help is appreciated.
Thanks
EDIT:
The code I tried that uses the API.
$params = array(
'name' => 'testtest',
'message' => 'test test'
);
try{
$albumtResult = $facebook->api('/'.$pageId.'/albums', 'post', $params);
}
catch(FacebookApiException $e){
error_log($e);
$albumtResult = null;
}
$albumId = $albumtResult->id;
Here is the caught exception: http://pastebin.com/pxeyRTDn
Well, the reason for this error would be much easier to figure out, if you’d used the PHP SDK to make API calls, instead of doing them “by hand“ using file_get_contents … because using the SDK, you get an exception that should point to the error cause, whereas file_get_contents (by default) just throws a warning when it gets anything else than a 2xx HTTP status code for an answer, and does not let you access the response body (which will most likely contain a human-readable error message as well).
My advice: Use the SDK!
Otherwise, add to the context parameter that you want to see the returned data even if the status code signals an error. (details -> see manual)
After a lot of searching, someone created a bug report on Facebook that was almost identical to my problem.
Since being created it has had a lot of repo's and other people reporting that they are also having the same issue.
The priority on facebook has been changed to high so hopefully it gets fixed soon.
Facebook bug report: https://developers.facebook.com/bugs/376442565760536?browse=search_50361119879b15494037772
Thanks for everyones time.
Related
in my working code to post a message with url-based image, i have this setup:
$post_data = array(
'message' => 'nice kitten pic',
'url' => 'http://www.eastcottvets.co.uk/uploads/Animals/gingerkitten.jpg'
);
$request = new FacebookRequest($app, $access_token, 'POST', '/' . $page_id . '/photos', $post_data);
i tryed this, which does not work:
$post_data = array(
'message' => 'nice kitten pic',
'source' => realpath('pics/kitten.jpg')
);
But now i like to post an image, not with an url reference, but with a reference to the path of the image on my localhost.
Facebook Docu says:
"There are two separate ways of publishing photos to Facebook:
1: Attach the photo as multipart/form-data. The name of the object doesn't matter, but historically people have used source as the parameter name for the photo. How this works depends on the SDK you happen to be using to do the post.
2: Use a photo that is already on the internet by publishing using the url parameter:"
So, way Nr.2 works, but how do i use way nr.1, with "attach the photo as multipart/form-data" ?? - the docu laks an example for php sdk and in general.
the docu laks an example for php sdk and in general.
No, it doesn’t – you’ve just missed it: https://developers.facebook.com/docs/php/howto/example_upload_photo
The part most relevant to your question is the use of the fileToUpload to prepare a local file for upload.
Solution, for people wo might search aswell:
$post_data = array(
'message' => 'nice kitten pic',
'source' => $fb->fileToUpload('/var/www/myPublicToTheWebFolder/kitten.jpg'),
);
of course the path will be different, depending on server setup. but it has to be the full path you have to output there.
The goal of the script is to post automatically, on my profile and on my groups, the link to a specific page, once the content is created.
But all what I got when I launch the test script here below, is this returned string:
Graph returned an error: An active access token must be used to query information about the current user.
In fact, the token related to the app was given by FB Developers site.
I tried also the combination:
634060413388093|9ed702cc524a1cbb59ca1fb7a17839f1
But I still get the same return
<?php
$path = getcwd();
require_once $path . '/include/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '634060413388093',
'app_secret' => '9ed702cc524a1cbb59ca1fb7a17839f1',
'default_graph_version' => 'v2.2', ]);
$linkData = [
'link' => 'http://www.example.com/page',
'message' => 'here the new page on my site.',
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/me/feed', $linkData, '634060413388093|bnTyPyRtsZSLHoc1B1w772cz3BU');
} 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'];
?>
You need to use a user access token to read the feed of a user. 'me' refers to the user that is associated with the user access token. An app access token is not associated with any specific user.
This leads to the second point, which is much more important. You should never reveal your app secret, especially not on Stack Overflow or anywhere public. You should hide that part of your SO Question, or better yet, create a new FB application.
Ok I found the way in this moment. I tried any example andy help, any suggestion but it didn't work out.
Thus, I post it hoping it helps somebody else with my same issue:
The access token, is not app_id|app_secret but it's obtained in another way:
To get the correct access otken, one should go to:
https://developers.facebook.com
under "Tools & Support" select "Graph API Explorer"
On the upper right corner, there is a drop down menu called "Application".
Click and select the created application.
Select "Access Token" shown, and copy/paste it in the field aside $linkDAta variable:
$response = $fb->post('/me/feed', $linkData, '{access-token}');
At that point, launching the script as it is, it worked out :)
EDIT:
If you need to post in groups, just change the '/me/feed' with '{group_id}/feed'
Trying to upload photos by access token, album_id or user_id and URL but getting an error:
"(#324) Requires upload file"
"OAuthException"
I've checked the token and it's valid. Also upload from file works, but upload from URL does not. Facebook does not seem to want to recognise the "url" parameter. This is strange because I swear the other day when I tested this it worked fine.
Is anyone else having this problem?
My code:
$graph_url = "https://graph.facebook.com/ALBUM_ID/photos?access_token=TOKEN";
$postdata = http_build_query( array('message' => 'hello', 'url' => IMAGE_URL);
$opts = array('http' => array(
'method' => 'POST',
'header' =>
'Content-type: application/x-www-form-urlencoded',
'content' => $postdata));
$context = stream_context_create($opts);
$result = json_decode(file_get_contents($graph_url, false, $context));
I've also checked, it works in FB's graph API explorer, but does not work when using any REST client tool either.
UPDATE:
I got it to work by switching the order of the array inside http_build_query so that the URL is first (or removing the 'message' parameter). The second element is always ingored.
Can anyone see what I'm doing wrong? Why is the second parameter ignored in this case? While the upload "works" I'd still like the 'message' parameter to work so that the image description can also be loaded.
When you’re uploading an image via URL, you must not use the Content-type application/x-www-form-urlencoded – that’s for real file uploads done from your server, using the source parameter, only.
I got something wierd going on. I have 2 Facebook API calls (using the Facebook PHP-SDK) next to each other. The first call goes fine, but the second throws an exception:
"This API call requires a valid app_id"
Previous to the API Call I requested an Access Token with offline_access and publish_stream. The token is valid because API calls next to this "problem call" will do fine. to make things clear, a small snippet of my code:
// this call goes fine!
$user_info = $this->facebook->api('/'.$user_id );
// create the wallpost for Facebook
$wallpost = array(
'message' => 'some message',
'name' => 'Shoppe',
'caption' => "Ik heb een product toegevoegd",
'link' => site_url(),
'description' => $description,
'picture' => site_url("assets/img/logo.png")
);
// this throws an exception "This API call requires a valid app_id"
$result = $this->facebook->api('/'.$user_id.'/feed/','post',json_encode($wallpost) );
$user_id is valid value, so is all the info in the $wallpost
I don't know PHP so the details of string concat are lost on me, but the first thing that popped into my head reading this is that your request string on the POST may not be formatted like you think it is so PHP gets a malformed request, cannot find the app ID and throws you an error.
I would suggest taking the string you are creating for the api() call and printing it out before making the call and making sure it looks exactly like it is suppose to look before going over the wire.
We have an app running on a Facebook tab at the moment which is receiving a good deal of traffic. People are signing up every few seconds, and most are successful. However I am running into the following problems:
- access token not received at all (empty response, no error)
- or if it is received, then API call to /me fails (empty response, no error)
EDIT: Apparently limiting of API calls is not the issue, since the 600/600 calls/sec is per user which makes a lot more sense :).
Is anyone else experiencing such issues? I am getting about 20-30 successful app signups a minute and about 2-3 failing ones. Note: these are not users who deny access to the app - those are handled elsewhere...
EDIT: I am getting "failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request"
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$oauth_clientid."&redirect_uri=".urlencode($redirect_url)."&client_secret=".$oauth_secret."&code=".$code;
$access_token = file_get_contents($token_url);
Update: After modifying my code to use curl, there was some improvement, but it did not resolve the issue. The application in question is now past its peak usage, so obviously the number of errors have gone down drastically. It still happens sometimes. The errors are (most often):
Curl error (6): Couldn't resolve host 'graph.facebook.com'
Curl error (28): SSL connection timeout
...and other similar errors.
From my experience with a week or two of data, it seems to effect about a percent of requests when there is high traffic, less when there is low - but this is quite unscientific. :)
--
So the solution? Well there is none really. It seems that some percent of requests will fail and my (your) application needs to handle these errors as elegantly as possible.
My only question is, has anyone else had such experience with high traffic apps? (meaning in this case 100 000-500 000 daily pageviews and 50 000-100 000 active users)
Try to log the curl error and return value when you obtain the access_token the answer should be there.
I think it's because php_openssl extension is either absent or disabled. See this question to enable it. Or you can use cURL. Take fb_ca_chain_bundle.crt from PHP SDK official (or set CURLOPT_SSL_VERIFYPEER to false):
$base_url = 'https://graph.facebook.com/oauth/access_token';
$params = array();
$params['client_id'] = $client_id;
$params['client_secret'] = $client_secret;
$params['redirect_uri'] = $redirect_uri;
$params['code'] = $code;
$options = array(
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_CAINFO => __DIR__ .'/fb_ca_chain_bundle.crt',
CURLOPT_RETURNTRANSFER => true,
CURLINFO_HEADER_OUT => false,
CURLOPT_HEADER => false,
CURLOPT_URL => $base_url . '?' . http_build_query($params),
);
// Init cURL and send the request
$ch = curl_init();
curl_setopt_array($ch, $params);
$result = curl_exec($ch);
$infos = curl_getinfo($ch);
curl_close($ch);
var_dump($result, $infos);
EDIT: i warn you this is a quick copy and paste from my code so you would double check $options.