Facebook PHP SDK get page posts data is empty - php

I'm having a strange problem with the Facebook PHP SDK,
$response = $this->getConnection()->get("me/posts");
$feedEdge = $response->getGraphEdge();
var_dump($response); exit;
the getConnection() call provides me with a \Facebook\Facebook object with the default_access_token set but this works as I get a response from Facebook
But the body from the above var_dump gives:
["decodedBody":protected]=>
array(1) {
["data"]=>
array(0) {
}
}
What is really strange is when I use the Graph Explorer (as my Application and using the same Page) I see all the posts. So I thought maybe it was the access token was not working correctly so I copied and pasted the access token shown in from the graph explorer into my get() call to override the default like below unfortunately this did not work and I got exactly the same output.
$response = $this->getConnection()->get("me/posts", "EAA....");
$feedEdge = $response->getGraphEdge();
var_dump($response); exit;
So I'm unsure why the same token in one place would get the information when in another it would get an empty set the worst part is it's not like the Request is failing as that throws an exception it is like Facebook Graph API is reacting differently for my application when using the PHP-SDK verses using the Explorer.

So after hours of messing around testing stuff in the Graph API Explorer and the API I worked out, there is a problem with /me/posts endpoint when using the PHP SDK even if your using a manage_pages access_token it seems to lock on to the user that instead of the page unlike the graph explorer that the /me/posts, posts to the entity of the access_token.
So make sure to request /{page_id|user_id}/posts and it works correctly.

Related

Facebook API Changes? PHP Get Page Count Error

Facebook API Broken?
Ive got this code ive been using for a while now that looks at a facebook page and reports back how many fans the page has. However over the past few days its stopped working and im now getting the following error. Can anyone shed any light on why this is happening?
Error:
Warning: file_get_contents(https://graph.facebook.com/themeparkguide?access_token=2007*********3|9b5***********fcd&fields=fan_count): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in /homepages/28/d541****/htdocs/*********project/facebook_stats.php on line 4
0
Code:
<?php
function fbLikeCount($id,$appid,$appsecret){
$json_url ='https://graph.facebook.com/'.$id.'?access_token='.$appid.'|'.$appsecret.'&fields=fan_count';
$json = file_get_contents($json_url);
$json_output = json_decode($json);
//Extract the likes count from the JSON object
if($json_output->fan_count){
return $fan_count = $json_output->fan_count;
}else{
return 0;
}
}
echo fbLikeCount('coregenie','___APPID___','___APPSECRET___');
//https://stackoverflow.com/questions/37572559/facebook-graph-api-read-followers-count/42336057
?>
It works in the API Explorer: https://developers.facebook.com/tools/explorer/?method=GET&path=themeparkguide%3Ffields%3Dfan_count&version=v2.12
So i assume with some error logging, you would get the error that your App is inactive. Try with a different or new App instead. This should not be affected by the recent changes.
Side note: You should not use that script on every page load, better cache the result for some time. If a lot of users visit the page in a short time, you will hit the rate limit.
The Facebook API has changed .
The fan_count can be retrieved using an user token only after aprovement by Facebook Platform, completing the submission process .
The fan_count can be retrieved using page access tokens, to get fan count for that page .
Attention: Graph Explorer can get the page information if yours pages, so, be carefull on testing your apps, and use TEST USERS for testing insead your profile, ok ,
After test submit it for aprooval, and you be done !

POST Facebook Notification using Graph API

I'm trying to post notification using facebook graph api post method but I'm getting
(#15) This method must be called with an app access_token.
However the access_token which I'm sending in querystring is app access token which is fetched using this method
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".FB_APP_ID."&client_secret=".FB_SECRET."&grant_type=client_credentials";
I 've seen few guys have implemented it but don't know why its not working for me, someone pls tell me where I'm wrong in it.
Thanks
EDIT
I got it working, here is the change
This line of code will never work, because the internal access_token will override the app access_token which we are trying to pass in query string.
$this->facebook->api("/".$to_userId."/notifications?access_token=$app_token_url&template=message",'POST');
So Use this code
$data = array(
'href'=> 'https://apps.facebook.com/MY_APP/',
'access_token'=> $app_token,
'template'=> 'test'
);
try {
$this->facebook->api("/".$to_userId."/notifications",'POST',$data);
} catch (FacebookApiException $e) {
}
Is your app accidentally configured as a 'native/desktop' app in the app settings? if so, change it back to 'web'

Rendering SoundCloud widget for a private track using PHP API

I am trying to render a SoundCloud HTML5 widget using the PHP API, but every time I run the command I think should return the HTML for the widget, I simply get an Exception:
The requested URL responded with HTTP code 302
I realise this is a redirect. What I don't know is why that's all I ever get, or what to do about it to actually get the widget HTML.
The documentation on the API says that to embed the widget using PHP you should do this:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with your app credentials
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
// get a tracks oembed data
$track_url = 'http://soundcloud.com/forss/flickermood';
$embed_info = $client->get('/oembed', array('url' => $track_url));
// render the html for the player widget
print $embed_info['html'];
I'm running this:
// NB: Fully authorised SoundCloud API instance all working prior to this line
// $this->api refers to an authorised instance of Services_Soundcloud
try {
$widget = array_pop(
json_decode( $this->api->get('oembed', array('url' => $track_url)) )
);
print_r($widget);
} catch (Exception $e)
{
print_r($e->getMessage());
}
where "track_url" is actually the URL I get back when asking SoundCloud for a track object earlier in the app using the same API.
I'm not actually sure this URL is correct in the first place, because the track object I get back gives the 'uri' in the form:
[uri] => https://api.soundcloud.com/tracks/62556508
The documentation examples all have a straight http://soundcloud.com/username/track-permalink URL - but even using a known path to a public track the attempt to run the API oembed method fails... I still get a 302 Exception.
Finally, there are mentions of setting "allow_redirects" to false in the 'get' command, but this has no effect when I add to the parameters used to build the query to the API. I also tried adding additional cURL options, but that too had no effect.
I have definitely enabled API access to the track within SoundCloud.
Kind of banging my head off the wall on this. If anyone has any pointers I'd be very grateful to hear them. Just for clarity's sake, I am able to access all the user data, comments etc. via the API instance I have created, so it appears to be working fine.
Thanks for pointing this out. There was a bug in the documentation that lead you astray. Sorry about that. I've updated the docs to fix the bug. Here's the updated code sample:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with your app credentials
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setCurlOptions(array(CURLOPT_FOLLOWLOCATION => 1));
// get a tracks oembed data
$track_url = 'http://soundcloud.com/forss/flickermood';
$embed_info = json_decode($client->get('oembed', array('url' => $track_url)));
// render the html for the player widget
print $embed_info->html;
Note the differences:
You need to set CURLOPT_FOLLOWLOCATION to 1 as mentioned in the comments above.
You need to wrap the return from $client->get in json_decode
The result is an stdClass object, not an Array and so the html property has to be accessed using the -> operator.
Hope that helps. Feel free to comment in case you're still having problems and I'll amend my answer.

Get wall feed from a public Facebook page using Graph API - is it really this complex?

I have started off by reading Displaying Facebook posts to non-Facebook users which is of some use but I cannot believe it is this difficult to get a public feed from Facebook.
The page I want a feed from is public, you do not need to be logged into get to it.
Am I right in presuming that I need an access_token to get to this information, attempting to access the URL without results in an OAuth error.
So the flow should be like this (massively, overly complex):
Authenticate using a user (what if the user isn't on Facebook?)
Some complex OAuth nonsense - just to read the feed, I do not even want a like button or post to wall functionality
Get the feed using a PHP request to the correct URL with the user's access_token
Render the feed
Assuming the user isn't on Facebook, what do you do, use a generic app to get the feed?
Hardcode an auth request to Facebook using my generic app's ID and secret
Some complex OAuth nonsense
Get the feed using a PHP request to the correct URL with the app's access_token
Render the feed
Oh no, the auth has expired, re-auth and capture this new access_token for use in future requests.
This seems really complex for no reason other than Facebook wants to know EVERYTHING that is going on, it'd be easier to do a cURL and scrape the content from the public URL using XPath.
Any help on this would be great.
Thanks,
Jake
EDIT
An edit to show this is not an exact duplicate.
I had this working with an access_token in place, but now it fails, the token has expired and I can no longer use it to obtain information from the public wall.
I attempted to extend the expiration date of this token using the methods mentioned in other posts but this didn't work and the expiration was not extended - we are now here, with an invalid token and no further along.
It seems that the manual process of having to approve the OAuth request means that it is impossible to programatically get the feed of a public page.
Two years later, you can programmatically do this with a Facebook App (an example using PHP and Slim): https://developers.facebook.com/apps/
$base_api="https://graph.facebook.com/";
$client_id="XXXXXX";
$app_secret="XXXXXX";
//get a profile feed (can be from a page, user, event, group)
$app->get('/feed/:profileid/since/:start_date', function ($profile_id,$start_date) {
$start_time=date('m/d/Y h:i:s',$start_date);
$request = new FacebookRequest(
getSession(),
'GET',
'/'.$profile_id.'/feed?since='.$start_time
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
//do something with $graphObject
});
function getSession(){
$session = new FacebookSession(getAccessToken());
return $session;
}
function getAccessToken(){
global $base_api, $client_id, $app_secret;
$url=$base_api."oauth/access_token?client_id=".$client_id."&client_secret=".$app_secret."&grant_type=client_credentials";
$str = file_get_contents($url);
$token = str_replace ( "access_token=" , "" , $str );
return $token;
}
I have some success with reading in the direct feed without tokens etc.
(using magpie, simplepie or querypath or similar).
http://www.facebook.com/feeds/page.php?format=rss20&id=........
http://www.facebook.com/feeds/page.php?format=atom10&id=........
found on: http://ahrengot.com/tutorials/facebook-rss-feed/
Facebook has changed how to retrieve a public Facebook page's feed since the other answers were posted.
Check out my answer/question. It's not PHP, but it provides the URLs and process you need.

Automatic Soundcloud PHP Api authentication without user interaction

In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9

Categories