I am trying to echo my name but I got an error: Trying to get property of non-object. Please help. I also have problem getting the user access token though I have no problem getting the app access token.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
require_once('facebook.php');
$config = array();
$config['appId'] = "MY_APP_ID";
$config['secret'] ="MY_APP_SECRET";
$facebook = new Facebook($config);
$app_id = "MY_APP_ID";
$app_secret = "MY_APP_SECRET";
$my_url = "http://localhost:8080/samplewebsite/index.php/";
$code = $_REQUEST['code'];
if(empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(),TRUE));
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state']
. "&scope=publish_actions,read_stream";
header("Location: " . $dialog_url);
}
else
{
echo "Hello, your OAuth code is " . $code . "<br>";
}
if ($_REQUEST['state'] == $_SESSION['state'])
{
$facebook->api('oauth/access_token',array(
'client_id' => $app_id,
'client_secret' => $app_secret,
'type' => 'client_cred',
'code' => $code,
));
$token = $facebook->getAccessToken();
echo "<br>" . "Hello, Your access_token is: " . $token;
$graph_url = "https://graph.facebook.com/me?access_token=" . $token;
//$user = json_decode(file_get_contents($graph_url));
//echo $user->name;
function curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$user = json_decode(curl($graph_url));
echo $user->name;
}
?>
</body>
</html>
You are trying to echo $user->name but json_decode will not return an object by default. It returns an associative array unless you pass in TRUE as a second parameter.
So if you change:
$user = json_decode(curl($graph_url));
to:
$user = json_decode(curl($graph_url), TRUE);
It might work as you want it to. If not, try looking at what your curl() call returns and then what $user actually contains with something like var_dump().
Related
I found following code from here, it is supposed to work and it has 2 errors.
First one is : Trying to get property of non-object on line 38, which starts from
if ($decoded_response->error)
Second error is Trying to get property of non-object on line 54 which starts from
echo("success" . $decoded_response->name);
So following code is my full code that gets access token.
<html>
<head></head>
<body>
<?php
require_once('src/facebook.php');
include_once('src/base_facebook.php');
$app_id = "413030352142786";
$app_secret = "518852750047ba579316a19d81c1e115";
$my_url = "134061970136571";
// known valid access token stored in a database
$access_token = "CAAF3ph9rwcIBAD5GrDLZBI6TFKlSb4jccEmIorCVjtfIeKIq7FjGKntMI5qnZCaNlXL8qy2g0gbjof3sRJYmgoDckG5ZBWpZBHjgZAn1e3sHTyxDdWwcCaZAiCylP5ayoWIMZBZCgNBL71I3myFYoDUYNZB4dH0xKJjAZD";
#$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
</body>
</html>
Thank you for your reply !!!
According to the Facebook docs, using App_access_token is as simple as:
$appid = 'xxx';
$secret = 'yyyyyyyyy';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getUser()>0;
if($session){
$access_token = 'access_token='.$facebook->getAccessToken();
$app_access_token = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=$appid&client_secret=$secret&grant_type=client_credentials");
}
My problem is that $access_token is fine but $app_access_token always returns false, what am I doing wrong?
-EDIT-
If I open the app_access_token URL in my browser I can see the access token! It seems to fail the file_get_contents... ?
The file_get_contents could be creating problems, may be due to some php config settings. (Discussion here: file_get_contents returns empty string)
I'll recommend you to use cURL instead, something like that-
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
echo get_content('http://example.com');
If the problem persists, re-check the values of app_id and secret in the url.
I file_get_contents not working try this :
Enable php ini setting for allow_url_fopen, then restart the server.
Here is the working code :
<?php
$facebook_appid = "facebook_appid"; // Facebook appplication id
$facebook_secret = "facebook_secret"; // Facebook secret id
$redirect_uri = "https://192.168.75.44/facebook_login/fb_login.php"; // return url to our application after facebook login ## should be SAME as in facebook application
//$cancel_url = ""; // redirect url if user denies the facebook login ## should be SAME as in facebook application
$scope = "user_photos,email,user_birthday,user_online_presence,offline_access"; // User permission for facebook
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = time(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
echo $params['access_token'];
}
?>
I have this problem with my code, iam trying to upload an image to a users wall, but it give me following error:
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /var/www/parkourjams.dk/emilaagaard/customers/fbgen/core/facebook/base_facebook.php on line 1238
My code is:
<?php
session_start();
require 'facebook/facebook.php';
$app_id = "438648619527874";
$app_secret = "HIDDEN";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'fileUpload' => true,
'cookie' => true
));
$post_login_url = "http://emilaagaard.dk/customers/fbgen/core/test.php";
$code = $_REQUEST["code"];
if (empty($code)) {
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&scope=publish_stream";
echo("<script>top.location.href='" . $dialog_url
. "'</script>");
} else {
$token_url="https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
// curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
echo "Token: " . $access_token . "<br /><br />";
$graph_url= "https://graph.facebook.com/me/photos?"
. "access_token=" .$access_token;
// Post it!
$user = $facebook->getUser();
$args = array(
'message' => 'Photo Caption',
'image' => '#'.realpath("ac.png")
);
$user = $facebook->getUser();
$user_profile = $facebook->api('/me');
if ($user) {
print_r($user);
echo "Username: " . $user_profile['username'];
try {
// We have a valid FB session, so we can use 'me'
$data = $facebook->api('/me/photos', 'post', $args);
echo $data;
} catch (FacebookApiException $e) {
print $e;
}
} else {
echo "Dead user";
$loginUrl = $facebook->getLoginUrl();
print ', try login</script>';
}
echo '</body></html>';
}
?>
I really hope for someone out there can help me, iam tired and have probably code-blinded my self for staying up all night after a party to finish this.
Thanks!
if you are testing it on local server
insert
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
after curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
insert
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
$facebook->setAccessToken($access_token);
before $user = $facebook->getUser();
I'm totally frustrated with my first facebook app project. I'm having major issues with what seems to be a simple task.
I want to setup a cron job on my server (easy) that will post something smart on a facebook page (not my profile), and it should be posted as page. I coded myself into a corner and am totally confused now... Can anyone help, please?
I've been thru pretty much every error message and am now stuck on
"OAuthException: Error validating application."
Here's what I have now:
First php -> Gets a new Access Token for my page access. This part seems to work fine, as I get the next page called and receive a new access token.
<?php
require_once 'facebook.php';
$app_id = "1234....";
$app_secret = "5678....";
$my_url = "http://.../next.php";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// known valid access token stored in a database
$access_token = "abc....";
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?
client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
} else {
echo "other error has happened";
}
} else {
// success
echo("success" . $decoded_response->name);
}
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
Next php -> Read the access token and post on the wall. I get the access token from my query string, but then why do I receive the error message. My id, secret and page id are all in order...
<?php
require_once 'facebook.php';
$app_id = "1234....";
$app_secret = "5678....";
$page_id = "0909....";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$access_token = $_GET['code'];
echo($access_token);
try {
$attachment = array(
'access_token' => $access_token,
'message'=> "Hello World"
);
$result = $facebook->api('/'.$page_id.'/feed','POST',
$attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
?>
I'm sure there is a simpler way to do so.... and a way to actually make it work!
Any help is appreciated!
I followed this script
Update facebook page status from that page itself
and this
https://developers.facebook.com/blog/post/500
Thank you.
// firstly include the fb sdk
$facebook = new Facebook(array(
'appId' => 'your app id',
'secret' => 'your app secret',`enter code here`
'cookie' => true,
));
$session = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_status,publish_stream,email,user_location,user_birthday,friends_birthday,manage_pages',
'redirect_uri' => 'http://www.example.com/'
)
);
$logoutUrl = $facebook->getLogoutUrl(
array(
// any url u want to redirsct onto
'redirect_uri' => 'http://www.example.com/'
)
);
// when redirected from facebook get the code
$code = $_GET['code'];
//
$my_url = 'http://www.example.com/';
$app_id = 'your app id ';
$app_secret = 'your app secret ';
// here we have the access token so we will play with it
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code ;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
}
// here we got the access token of user over here in $user_access_token
// now we will get for our page
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $user_access_token
);
$page_id = 'your page id ';
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
// write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> 'hello world posting like admin!',
'page_id'=> $page_id
);
$result = $facebook->api('/'.$page_id.'/feed','POST',$attachment);
//$result = $facebook->api('/me/feed','POST', $attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
From your code, it appears you are not getting a PAGE access token which you need, but instead you're using a USER access token, hence why the API doesn't like it. For more information on how to get a PAGE access token from a USER one, please see the Page login section of https://developers.facebook.com/docs/authentication/
After many hours of trial and error, here's my solution that works so far.
<?php
require_once 'facebook.php';
//------ vars
$app_id = "123...";
$app_secret = "abc...";
$page_id = "999...";
$my_url = "http://exactly the same as defined /";
//------ fb object
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
//------ verification CODE
// this is not pretty -> the code should be received with a another graph query...
// but I couldn't get this to work. Thus I'm using my last known Verification Code
$code = "ABC123...";
//------ get USER access token
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&code=" . $code
. "&redirect_uri=" . $my_url;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
} else {
echo("No code");
}
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $user_access_token
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> 'hello world!'
);
$result = $facebook->api('/me/feed','POST', $attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
?>
I have the following code which I think is very close to working but I keep getting the following error:
{"error":{"message":"(#324) Requires upload file","type":"OAuthException"}}
but I cannot figure out how to specify the upload file... I have tried both image and source, both give the same error. Any thoughts, help, suggestions would be greatly appreciated as I have been struggling with this for a couple of days and it seems like it should not be this hard...
<html>
<head>
<title>Photo Upload</title>
</head>
<body>
<?php
$app_id = "MY APP ID GOES HERE";
$app_secret = "MY APP SECRET GOES HERE";
$post_login_url = "MY URL GOES HERE";
$album_name = "Test Album";
$album_description = "Blah Blah event Photos";
$photo_source = realpath("C:\\Users\\Public\\Pictures\\Sample Pictures\\Lighthouse.jpg");
$photo_message = 'Here is the lighthouse';
$code = $_REQUEST["code"];
echo "code ==>" . $code . '<br/><br/>';
//Obtain the access_token with publish_stream permission
if(empty($code)){
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($post_login_url)
. "&scope=publish_stream,user_photos";
echo("<script>top.location.href='" . $dialog_url .
"'</script>");
}
else {
$token_url= "https://graph.facebook.com/oauth/"
. "access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
echo "access_token ==>" . $access_token . '<br/><br/>';
// Create a new album
$graph_url = "https://graph.facebook.com/me/albums?"
. "access_token=". $access_token;
$postdata = http_build_query(
array(
'name' => $album_name,
'message' => $album_description
)
);
$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));
// Get the new album ID
$album_id = $result->id; //upload photo
echo "album_id ==>" . $album_id . '<br/><br/>';
// Upload the photo
$args = array( 'message' => $photo_message,
'image' => $photo_source
);
$ch = curl_init();
$url = 'https://graph.facebook.com/'.$album_id.'/photos?
access_token='.$access_token;
echo "url ==>" . $url . '<br/><br/>';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
echo "data ==>" . $data . "<br>";
}
?>
</body>
</html>
You need to set the config var fileUpload to true when creating a new instance of the Facebook class as described in the documentation here and here. And you also need the photo_upload permission ;-)
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = true; // <-- set this to 'true' otherwise it won't work
$facebook = new Facebook($config);
You are using file name instead of file itself in your Graph API call.
You should prefix file name with #
$args = array( 'message' => $photo_message,
'image' => '#'.$photo_source
);