Post a Link from PHP - php

I have this script:
This code should post a Text and a Link to a WebSite
<?
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('facebook.php');
$c = array(
'appId' => '4102137023*****',
'secret' => '*****c4a60cb08*****7c0333*****',
);
$facebook = new Facebook($c);
$uid = $facebook->getUser();
echo "Userid: " . $uid;
echo "<BR>";
?>
<html>
<head></head>
<body>
<?
if($uid){
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'angel-craft.de',
'message' => 'Wenn ihr das hier seht freut euch auf ein Game'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please login.';
echo $e->getType();
echo $e->getMessage();
}
// Give the user a logout link
echo '<br />logout';
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please login.';
}
?>
</body>
</html>
This should post a link with a text
but the Userid($uid) stays empty.
And YES this is the Demo script from FB dev.

I've used this successfully.
<?php
require 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '-----',
'secret' => '-----',
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$Name = $me['first_name'];
$properties = array(
array(
'text'=>'Property Link',
'href'=>'http://www.yahoo.com'
),
array(
'text'=>'Property Link',
'href'=>'http://www.yahoo.com'
)
);
// Link that is adjacent to "Like" and "Comment" at the very bottom of the post.
$action_links = array(
'name'=>'Test',
'link'=>'http://www.yahoo.com'
);
// Dictates who can see the post.
$privacy = array(
'value'=>'ALL_FRIENDS'
);
// api('/me/feed', 'post',... = Wall Post.
$wallPost = $facebook->api('me/feed', 'post', array(
'message'=> 'Testing',
'link'=> 'http://www.yahoo.com',
'properties'=>$properties,
'actions'=>$action_links
)
);
} catch (FacebookApiException $e) {
error_log($e);
}
}
$par = array();
$par['req_perms'] = "email, publish_stream";
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
?>

I found the bug, The cert was old. Thanks to all :)

Related

PHP Facebook SDK

Hi i need help with a small error i received
Warning: Illegal string offset 'name' in C:\xampp\htdocs\facebooktest.php on line 41
You are logged into centralrp using your facebook account! [1] when im tring to show the name
<?php
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => '*',
'secret' => '*',
'allowSignedRequest' => false // optional but should be set to false for noncanvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
if (!isset($_SESSION['user']['facebookposted']))
{
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'app.com',
'message' => 'Just logged into App with Facebook.'
));
echo '<pre>Post ID: ' . $ret_obj['id'] . '</pre>';
$_SESSION['user']['facebookposted'] = true;
//ADD THE LOGIN STUFF HERE LATER
}
else
{
$_SESSON['user']['loggedin'] = true;
echo 'You are logged into centralrp using your facebook account! ['.$user_id['name'].']';
}
// Give the user a logout link
echo '<br />logout';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'publish_stream'
));
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
// To post to a user's wall, we need publish_stream permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
echo 'Please login.';
}
?>
There is no name key in $user_id because $user_id is not an array.
if you need the name, get it like this:
try {
$user_info = $facebook->api('/me/');
echo '<pre>Name: ' . $user_info['name'] . '</pre>';
} catch(FacebookApiException $e) {
echo 'There was an error';
}

Not getting any information from Facebook login

I'm implementing Facebook login on my website, it's working without error but ultimately I'm not able to get any information of a user.
I've following code.
<?php
include 'library.php';
include 'facebook.php';
$app_id = "XXXXXXXXX";
$app_secret = "XXXXXXXXX";
$site_url = "XXXXXXXXX";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$user = $facebook->getUser();
if($user){
try{
$user_profile = $facebook->api('/me');
}catch(FacebookApiException $e){
$user = NULL;
}
}
if($user){
$logoutUrl = $facebook->getLogoutUrl();
}else{
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email',
'redirect_uri' => $site_url,
));
}
if($user){
Echo "Email : " . $user_profile['email'];
}
$user_fbid = $fbuser;
$user_email = $user_profile["email"];
$user_fname = $user_profile["first_name"];
$user_image = "https://graph.facebook.com/".$user_fbid."/picture?type=large";
echo $loginUrl = $facebook->getLoginUrl( array('scope' => 'email,read_stream'));
What's wrong with this? Can anyone point out? I've gone though a number of questions but none of them seemed to work for me & I finally ended up posting a question myself.
EDIT
When asking for login, it displays permissions correctly like email, friend list, your likes etc. So basically it's asking correctly & even though I approve, information is not coming up. Tried with a couple of users.
EDIT
Try use this code, and work from there ... That's how I figured it out
<HTML>
<BODY>
<?php
require_once("fb/facebook.php");
$config = array(
'appId' => 'XXXXX',
'secret' => 'XXXXXXX',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$uid = $facebook->getUser();
$loginParams = array('scope' => 'email');
$loginUrl = $facebook->getLoginUrl($loginParams);
$logoutParams = array('next' => 'http://fb_logouturi');
$logoutUrl = $facebook->getLogoutUrl($logoutParams);
echo $uid . '</br>';
echo 'Login:' . $loginUrl . '</br>';
echo 'Logout:' . $logoutUrl . '</br>';
if($uid) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$user_profile = $facebook->api('/me','GET');
echo "</br>First Name: " . $user_profile['first_name'];
echo "</br>Last Name: " . $user_profile['last_name'];
echo "</br>Email: " . $user_profile['email'];
echo "</br>Gender: " . $user_profile['gender'];
echo "</br><img src='http://graph.facebook.com/" . $uid ."/picture?type=large'>";
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
?>
</BODY>
</HTML>

Facebook Authentication window does not display?

I have a file named fbmain.php which do Authentication part of my facebook app. But it doesn't display the Authentication window?
//fbmain.php
<?php
//facebook application
//set facebook application id, secret key and api key here
$fbconfig['appid' ] = "MY_APP_ID";
$fbconfig['secret'] = "MY_APP_SECRET";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,status_update,user_birthday,user_location,user_work_history,user_likes,user_photos'
)
);
if (!$session) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if ($session) {
echo "<br/>session ok"; //It create a session and disply 'session ok' string
try {
$uid = $facebook->getUser();
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
}
?>
Can anyone please help me with this?
Which version of PHP-SDK you are using??
I think you can get rid of getSession() and use just getUser().
change your code as below and try again..
$uid = $facebook->getUser();
if ($uid) {
// do some api calls or something else
}
else
{
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
}
else in index.php just include your fbmain.php and use a image button where you can link the $loginurl..

Facebook Iframe application authentication?

I have developed a Facebook application that runs inside an iframe in the Facebook canvas. For it to work properly I request extended permissions from the user. If the user hasn't authorized the application I send him/her to a login page with the getLoginUrl() method in the PHP SDK.
It works, but it's not pretty. The method sends the user to a landing page before the authentication page. It looks like this:
When I click "Go to Facebook.com" I see the actual page for permission requests (I also get right to the permissions page if I print the url, copy it and enter it into a new browser window). How do I make Facebook skip this step when I do the redirect from an Iframe?
My code looks like this (using CodeIgniter and Facebook PHP SDK):
$this->facebook = new Facebook(array(
'appId' => '{MY_APP_ID}',
'secret' => '{MY_SECRET}',
'cookie' => TRUE,
'domain' => $_SERVER['SERVER_NAME']
));
$this->facebook->getSession();
try {
$this->me = $this->facebook->api('/me');
}
catch (FacebookApiException $e) {
$this->me = NULL;
}
if ( is_null($this->me) ) {
redirect($this->facebook->getLoginUrl(array(
'req_perms' => 'offline_access,read_stream,publish_stream,user_photos,user_videos,read_friendlists',
'next' => $this->config->item('base_url').'fblogin.php?redirect_uri='.$this->uri->uri_string()
)));
}
I think you need to redirect the parent frame (i.e. _top) rather than the iFrame itself?
The way I do it is set up an INDEX.PHP file with the following
//if user is logged in and session is valid.
if ($fbme){
//fql query example using legacy method call and passing
parameter
try{
$fql = "select name, hometown_location, sex,
pic_square from user where uid=" .
$uid;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => 'http://apps.facebook.com/yoursite/'
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
Then point your canvas url to http://yoursite.com/INDEX.php
The callback url in the above code which will be in INDEX.PHP sets where to look after permissions are granted.
FBMain.php looks like this
//set application urls here
$fbconfig['http://www.yoursite.com/iframeapp/YOURMAINPAGE.php/']
= "http://www.tyoursite.com/YOURMAINPAGE.php/";
$fbconfig['http://apps.facebook.com/CANVASBASEURL']
= "http://apps.facebook.com/CANVASBASEURL";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['APPID'],
'secret' => $fbconfig['SECRET'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms'=>'email,publish_stream,status_update,user_birthday,user_location'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
} ?>
Hope its a little clearer. It took me a while to figure it out, but I got there, thought I would help.

Facebook post on page with PHP SDK

I'd like to post on page - throught my site. . I didn't find anything that could help me in documentation. Also none of google results gave mi answer.
function post_facebook($data=null){
$result = "";
require_once (ROOT. "/apps/configuration/models/ConfigurationItem.php");
require_once (ROOT . "/components/facebook/facebook.php");
$this->ConfigurationItem = new ConfigurationItem($this->getContext());
$row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_login');
$apiid=$row['value'];
$row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_pass');
$secret=$row['value'];
$facebook = new Facebook(array(
'appId' => $apiid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getSession();
print_r($session);
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
$message=$data['facebook_text'];
$attachment = array(
'message' => $data['facebook_text'],
'name' => $data['name'],
'link' => $this->getLinkToLatestNews(),
'description' => '',
);
if($data['thumb_file_tree_id'] !== NULL) $attachment = $_SERVER['HTTP_HOST']."media/file/image_by_id/".$data['thumb_file_tree_id']."/?w=400&h=500";
try {
$facebook->api('/162618213751448/feed/', 'post', $attachment);
$result = "Facebook: Sent";
} catch (FacebookApiException $e) {
$result = "Facebook: Failed";
error_log($e);
}
} else {
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
exit;
}
return $result;
}
The wrong part is:
$session = $facebook->getSession();
$me = null;
if ($session) {
(...)
} else {
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
exit;
}
I want to allow user to login on specified FB account (this with page), and then send. App settings allow only this account to post, so it should be ok... But isn't. When I log out FB account, session still exists, but returns exception. What's wrong?
if you want to post on a fan page where you are adminstrator.. do the next
Your application needs to have this permission minimum:
$this->loginUrl = $this->facebook->getLoginUrl(
array(
'scope' => 'manage_pages,offline_access,publish_stream',
'redirect_uri' => $url,
)
);
After you are logged into:
//get pages or applications where you are administrator
$accounts = $this->facebook->api('/me/accounts');
//page where i want to post
$page_id = '227870047252297';
foreach($accounts['data'] as $account)
{
if($account['id'] == $page_id)
{
$token = $account['access_token'];
}
}
$attachment = array(
'access_token' => $token,
'message' => 'mensaje',
'name' => 'titulo',
'link' => 'http://...',
'description' => 'xxxxx',
'picture'=> 'http://...',
);
try{
$res = $this->facebook->api('/'.$page_id.'/feed','POST',$attachment);
} catch (Exception $e){
echo $e->getMessage();
}
If I understand this correctly, you want to send a message to the user's wall who's connected to your application via your website the moment they log in? If so, try this. Rework the script to prevent constant posting, but this model, in theory, should work.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
// Place messaging portion here instead.
$message = $facebook->api('/me/feed', 'post', array(
'message'=> '<Message>',
'picture' => '<Picture URL>',
'link'=> '<URL>',
'description'=>'Description',
'name'=> '<Name of Post>',
'privacy'=> '<ALL_FRIENDS (Default)>',
'caption'=> '<Caption>',
)
);
} catch (FacebookApiException $e) {
error_log($e);
}
So if the user is connected with your application and the session is valid, it will automatically send the post to their news feed (Wall).

Categories