App Redirect to Facebook Home Page - php

This is My Facebook Application Source
<?php
require 'facebook.php';
require 'config.php';
if (isset($_GET['code'])){
header("Location: " . $canvasPage);
exit;
}
$fb = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxxx',
'cookie' => true,
'fileUpload' => true,
));
$me = null;
$user = $fb->getUser();
if($user) {
try {
$me = $fb->api('/me');
} catch(FacebookApiException $e) {
error_log($e);
}
}
//edit the permissions needed
$permsneeded='publish_stream,user_photos';
if ($me){}
else {
$loginUrl = $fb->getLoginUrl(array(
'scope' => $permsneeded,
));
echo "
<script type='text/javascript'>
window.top.location.href = '$loginUrl';
</script>
";
exit;
}
if(isset($_GET['signed_request'])) {
$fb_args="signed_request=". $_REQUEST
['signed_request']; }
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
if (empty($data["user_id"]))
{
echo("");
}
$access_token = $data["oauth_token"];
try {
$my = $fb->api('/me');
}catch(FacebookApiException $e) {
error_log($e);
}
$nam = $my['name'];
$images = array(
0 => 'celeb/1.jpg',
1 => 'celeb/1.jpg',
3 => 'celeb/1.jpg',
4 => 'celeb/1.jpg',
5 => 'celeb/1.jpg',
6 => 'celeb/1.jpg',
);
$image = $images[ rand(0,(count($images)-1)) ];
Some other php code
?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://opengraphprotocol.org/schema/" >
My Code .
</html>
i got 2 Problems .
It is redirect to Facebook Home Page . See Demo : https://apps.facebook.com/246435698815637/
this is "$image = $images[ rand(0,(count($images)-1)) ];" is not working some time . it is didn't get image for imagecreatefromjpeg

Try like this and please avoid the blank statements.
if(!($me))
{
echo '<script> top.location.href="'.$facebook->getLoginUrl(array(
'req_perms' => $permsneeded,
'next' =>'https://apps.facebook.com/246435698815637/',
)). '";
</script>';
exit();
}
and second one is correct,it should work,but i don't get your point about imagecreatefromjpeg as you don't give any information about it.Paste your code where you have use that function.

Related

Error Class facebook\HttpClients\HttpClient Factory' not found in line Facebook/Facebook.php on line 148

I need some help, I am trying to implement facebook login in my website and right from the
get-go I am getting an error.
Error Class facebook\HttpClients\HttpClient Factory' not found
What does that even mean?
my code so far is pretty simple
in page one which for the example I called config.php, I write this little bit of code.
Page 1) config.php .
page 2) login.php
What am I doing wrong.. I am doing this on my own so I am pretty confused. Any help would be very much apprecitated.
I am not an expert. First time I am messing with facebook API so I apologize in advance.
require("vendor/autoload.php");
require_once $_SERVER["DOCUMENT_ROOT" ] ."/main_folder/vendor/facebook/graph-sdk/src/Facebook/autoload.php";
$facebook = new \Facebook\Facebook([
'app_id' => '****************',
'app_secret' => '*****************************',
'default_graph_version' => 'v6.0'
]);
require_once("../main_folder/config.php");
$facebook_output = '';
$facebook = $this->facebook;
$facebook_helper = $facebook->getRedirectLoginHelper();
if(isset($_GET['code']))
{
if(isset($_SESSION['access_token']))
{
$access_token = $_SESSION['access_token'];
}
else
{
$access_token = $facebook_helper->getAccessToken();
$_SESSION['access_token'] = $access_token;
$facebook->setDefaultAccessToken($_SESSION['access_token']);
}
$graph_response = $facebook->get("/me?fields=name,email", $access_token);
$facebook_user_info = $graph_response->getGraphUser();
if(!empty($facebook_user_info['id']))
{
$_SESSION['user_image'] = 'http://graph.facebook.com/'.$facebook_user_info['id']. '/picture';
}
if(!empty($facebook_user_info['name']))
{
$_SESSION['user'] = $facebook_user_info['name'];
}
if(!empty($facebook_user_info['email']))
{
$_SESSION['user_email_address'] = $facebook_user_info['email'];
}
}
else
{
$facebook_permissions = ['email'];
$facebook_login_url = $facebook_helper->getLoginUrl('https://www.stolve.com/stolve-master/login.php', $facebook_permissions);
$facebook_login_url = '<div align="center"><img src="php-login-with-facebook.gif alt="facebook logo"/></div>';
}
vendor dir must be in same dir as config.php and login.php
config.php
<?php
require_once __DIR__ . "/vendor/autoload.php";
$facebook = new Facebook\Facebook ([
'app_id' => '****************',
'app_secret' => '*****************************',
'default_graph_version' => 'v6.0'
]);
login.php
<?php
require_once "./config.php";
$facebook_output = '';
$facebook_helper = $facebook->getRedirectLoginHelper();
if(isset($_GET['code']))
{
if(isset($_SESSION['access_token']))
{
$access_token = $_SESSION['access_token'];
}
else
{
$access_token = $facebook_helper->getAccessToken();
$_SESSION['access_token'] = $access_token;
$facebook->setDefaultAccessToken($_SESSION['access_token']);
}
$graph_response = $facebook->get("/me?fields=name,email", $access_token);
$facebook_user_info = $graph_response->getGraphUser();
if(!empty($facebook_user_info['id']))
{
$_SESSION['user_image'] = 'http://graph.facebook.com/'.$facebook_user_info['id']. '/picture';
}
if(!empty($facebook_user_info['name']))
{
$_SESSION['user'] = $facebook_user_info['name'];
}
if(!empty($facebook_user_info['email']))
{
$_SESSION['user_email_address'] = $facebook_user_info['email'];
}
}
else
{
$facebook_permissions = ['email'];
$facebook_login_url = $facebook_helper->getLoginUrl('https://www.stolve.com/stolve-master/login.php', $facebook_permissions);
$facebook_login_url = '<div align="center"><img src="php-login-with-facebook.gif alt="facebook logo"/></div>';
}

posting in group on behalf of user using facebook graph API

I am trying to post on behalf of user. I have used tutorial given on this page: http://25labs.com/updated-post-to-multiple-facebook-pages-or-groups-efficiently-v2-0/ .
I could successfully perform authentication but could not post on behalf.
Here is the source code : https://github.com/karimkhanp/fbPostOnBehalf
Testing can be done here: http://ec2-54-186-110-98.us-west-2.compute.amazonaws.com/fb/
Does any one experienced this?
I'm not familiar with the batch process that the tutorial is using but below is a code sample that posts to a Facebook group
<?php
# same this file as
# test.php
include_once "src/facebook.php";
$config = array(
'appId' => "YOURAPPID",
'secret' => "YOURAPPSECRET",
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
class PostToFacebook
{
private $facebook;
private $pages;
public function initialise($config){
$this->name = "Facebook";
// current necessary configs to set
// $config = array(
// 'appId' => FB_APP_ID,
// 'secret' => FB_APP_SECRET,
// 'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
// );
$this->facebook = new Facebook($config);
try{
// if user removes app authorization
$this->hasAccess = $this->has_permissions();
if($this->hasAccess){
$this->groups = $this->getGroupData();
}
}
catch(Exception $err){
}
}
public function postMessageToGroup($message, $groupid){
$messageResponse = array(
'STATUS' => 0
);
$fbMessageObj = array(
"message" => strip_tags($message),
);
try
{
$user_page_post = $this->facebook->api("/$groupid/feed", 'POST', $fbMessageObj);
if($user_page_post && !empty($user_page_post['id'])){
$messageResponse['STATUS'] = 200;
$messageData = array(
'id' => $user_page_post['id'],
'link' => 'http://facebook.com/' . $user_page_post['id'],
);
$messageResponse['data'] = $messageData;
}
else{
$messageResponse['STATUS'] = 302;
}
}
catch(Exception $err){
$messageResponse['STATUS'] = 500;
$messageResponse['data'] = array($err);
}
return $messageResponse;
}
// TODO: should read a template somewhere
function show_login() {
$login_url = $this->facebook->getLoginUrl( array( 'scope' => implode(",",$this->permissions()) ));
return 'Login to Facebook and Grant Necessary Permissions';
}
// TODO: should read a template somewhere
public function toString()
{
if($this->hasAccess){
if($this->groups){
$msg = "";
$msg .= '<select name="group_id"><option value=""></option>';
foreach($this->groups as $group) {
$msg .= '<option value="' .
'' . urlencode($group['id']) .
'">' .
$group['name'] .
'</option>' .
'';
}
$msg .= '</select>';
return $msg;
}
else
return "No Groups";
}
else{
return $this->show_login();
}
}
function getGroupData(){
$raw = $this->facebook->api('/me/groups', 'GET');
$data = array();
if (null != $raw && array_key_exists('data', $raw))
return $raw['data'];
return null;
}
// check if current instance has access to facebook
function has_permissions() {
$user_id = #$this->facebook->getUser();
#print_r($user_id);
if($user_id == null) return false;
$permissions = $this->facebook->api("/me/permissions");
foreach($this->permissions() as $perm){
if( !array_key_exists($perm, $permissions['data'][0]) ) {
return false;
}
}
return true;
}
// permissins needed to post
function permissions(){
return array('manage_pages', 'user_groups');
}
}
$fb = new PostToFacebook();
$fb->initialise($config);
if(!$fb->has_permissions())
{
echo $fb->show_login();
}
else{
?>
<form method="post" action="test.php">
<textarea name='message'></textarea>
<?php echo $fb->toString(); ?>
<input type='submit'>
</form>
<?php
}
if(!empty($_POST)){
$response = $fb->postMessageToGroup($_POST['message'], $_POST['group_id']);
if($response['STATUS'] == 200)
print_r("<a href='" . $response['data']['link'] . "'>" . $response['data']['id'] ."</a>");
else
{
echo "ERROR!";
print_r($response);
}
}
?>

Using Facebook SDK to extract you friends info (more than just name or ID)

i am using FB SDK v.3.2.3 , and i'm trying to retrieve the events that my friends are going to. So far, my code can retrieve the list of friends who are using my app. The documentation on FB tells the event can be pulled out by using "me/events", but since i want my friend's event to be pulled, i used "me/friends/event" or "me/friends?fields=event", but it still does not work. Someone has an idea about it? Below is my code --
<pre>
require_once('facebook.php');
$config = array(
'appId' => 'xxx',
'secret' => 'xxx'
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
echo "<pre>";
print_r($user_profile);
echo "</pre>";
$dost = $facebook->api('/me/friends','GET');
foreach ($dost as $friend) {
echo "<pre>";
print_r($friend);
echo "</pre>";
}
echo '<br><a href=' . $facebook->destroySession() . '>Logout</a>';
} catch(FacebookApiException $e) { }
} else {
$params = array(
'scope' => 'public_profile, user_friends, email',
'redirect_url' => 'http://xxxxx.com',
'auto_logout_link' => 'true',
'show_faces' => 'true'
);
$login_url = $facebook->getLoginUrl($params);
echo 'Please login.';
}
Try it:
//...
$dost = $facebook->api('/me/friends','GET');
foreach ($dost["data"] as $value) {
$friend_id = $value['id'];
$events = $facebook->api('/'.$friend_id.'/events');
print_r($events);
}
//...
Facebook changed the privacy policy for friends - your friends also need to give permission to your app

FB Developer: Uncaught OAuthException: (#120) Invalid album id

i'm trying to post photos on a fanpage and I get this error:
Fatal error: Uncaught OAuthException: (#120) Invalid album id thrown in /home/eyikmdnu/public_html/jack/facebook-sdk/base_facebook.php on line 1264
This is the code of the page (obv the token, the secret etc are not the "original"
require_once("../facebook-sdk/facebook.php");
define("APP_ID", "*****");
define("APP_SECRET", "********");
$fanpage_token = "*******";
$user_access_token = "********";
$config = array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'fileUpload' => true // optional
);
$facebook = new Facebook($config);
//pagina = 358226040977616
//album id = 402459486554271
//$access_token = $_POST['access_token'];
//echo $access_token;
$facebook->setAccessToken($fanpage_token);
echo "Access Token Settato <br>\n";
$facebook->setFileUploadSupport(true);
echo "setFileUploadSupport(true) settato <br>\n";
$img_url = "images/jack.png";
//$img_url = $_POST['url'];
echo "$img_url = $img_url <br>\n";
$page_id = "358226040977616";
$album_id = "402459486554271";
echo "Page id: $page_id <br>\n";
echo "Album id: $album_id <br>\n";
$real_img_url = realpath($img_url);
echo "Real img url: $real_img_url <br>\n";
$args = array(
'message' => 'message to write in legend',
'image' => "#" . $img_url,
'aid' => $album_id,
'no_story' => 1,
'access_token' => $fanpage_token
);
echo "<br>\n";
print_r($args);
echo "<br>\n";
$photo = $facebook->api("/".$album_id."/photos", 'post', $args);
print_r($photo);
Need help! :O
I solved, the problem is that I should use the access_token of the page, that is not static, well I have to look in my /profile/accounts
$params = array('access_token' => $access_token);
$accounts = $facebook->api('/giacomo.torricelli/accounts', 'GET', $params);
foreach($accounts['data'] as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
$fanpage_token = $account['access_token'];
}
}
Thanks

$signed_request = $facebook->getSignedRequest();

im try to make a fan gate content for my facebook fan page by singed_request. The code work perfectly but i don't want redirect in iframe, i need redirect after the user click LIKE to another page. How i can remove iframe and insert a redirect?
this is my code:
<?php
require_once('facebook.php');
$app_id = "id";
$app_secret = "secret";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
function parsePageSignedRequest() { if (isset($_REQUEST['signed_request'])) { $encoded_sig = null; $payload = null; list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2); $sig = base64_decode(strtr($encoded_sig, '-_', '+/')); $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true)); return $data; } >return false; } if($signed_request = parsePageSignedRequest()) { if($signed_request->page->liked) { echo "<iframe allowtransparency=\"true\" frameborder=\"0\" SCROLLING=\"YES\" style=\"width: 800px; height: 1000px;\" src=\"http://onlyimagination.com/dm3theme2\" id=\"any_name\" name=\"anyname\"><iframe>";
} else { echo "<img src=\"http://www.onlyimagination.com/facebook/crazyvideo/img.jpg\" width=\"582\" height=\"487\">"; } }
?>
This will only work if don't have any output before your code
if ($signed_request = parsePageSignedRequest()) {
if ($signed_request->page->liked) {
header('Location: http://onlyimagination.com/dm3theme2');
} else {
echo "<img src=\"http://www.onlyimagination.com/facebook/crazyvideo/img.jpg\" width=\"582\" height=\"487\">";
}
}

Categories