Wordpress and Facebook php sdk 4.0 - facebook

I have wordpress 4.1 with the following plugin installed:
iThemes Security
WordPress SEO
I plugged in a function the facebook sdk.
This is the code:
//Footer
add_action('wp_footer', 'my_footer');
function my_footer() {
$post_to_check = get_post(get_the_ID());
if ( is_singular() && has_shortcode( $post_to_check->post_content, 'myshortcode' ) ) {
?>
<script>
var DEBUG = true;
jQuery(document).ready(function($){
$.ajax({
type : "POST",
url : "index.php",
data : { action : "value" },
success : function(response){
// the server has finished executing PHP and has returned something, so display it!
if(DEBUG){ console.log('AJAX done...'); }
}
});
});
</script>
<?php
}
}
//ajax
add_action('init', 'my_request');
function my_request() {
if ( isset($_POST['action']) && $_POST['action'] == 'value' ) {
session_start();
require_once __DIR__ . "/sdk/autoload.php";
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSDKException;
$app_id = getAppId();
$app_secret = getAppSecret();
$rdr_fb_url = curPageURL();
$required_scope = 'public_profile, email';
if(empty($app_id) || empty($app_secret))
exit('Error.');
FacebookSession::setDefaultApplication($app_id , $app_secret);
$helper = new FacebookRedirectLoginHelper($rdr_fb_url);
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
die(" Error : " . $ex->getMessage());
} catch(\Exception $ex) {
// When validation fails or other local issues
die(" Error : " . $ex->getMessage());
}
var_dump($session);
if ($session){
$user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());
echo 'Hi'.$user_profile->getName();
}else{
//display login url
$login_url = $helper->getLoginUrl( array( 'scope' => $required_scope ) );
}
?>
<div class="login">
Login
</div>
<?php
exit();
}
}
Works fine if i use this outside of wordpress.
In wp var_dump($session); retrive always null. (no error given) Even after accepting the terms of the application. it is as if he could not get the code in the url.
I also tried to disable the plugin, but nothing.
I need php, please don't tell me to use javascript.
Sorry for my bad english :P
Edit:
I use the permalink:
http://www.myste.com/%year%/%monthnum%/%postname%/
I think the problem is the rewrite rule that hide a facebook get.

Solved: I entered the code outside of the ajax call, in function my_footer() {

Related

Instagram OEmbed - OAuthException 200 Provide valid app ID

I keep getting the error message:
{message: '(#200) Provide valid app ID', type: 'OAuthException', code: 200,...
I can get the HTTP Get response with curl and by entering the URL, but when trying to use the exact same url in the Javascript SDK, i am getting the error told before.
Following is my JS script.
var pageAccessToken = 'APP_ID|CLIENT_ID';
$(document).ready(function() {
$.ajaxSetup({ cache: true });
$.getScript('https://connect.facebook.net/en_US/sdk.js', function(){
FB.init({
appId : 'APP_ID',
xfbml : true,
version : 'v13.0'
});
FB.getLoginStatus(function(response){
FB.api(
'/instagram_oembed',
'GET',
{"url":"https://graph.facebook.com/v13.0/instagram_oembed?url=INSTAGRAMURL&access_token=" + pageAccessToken},
function(response) {
console.log(response);
InstagramPage.innerHTML = response.html;
}
);
console.log(response);
});
});
});
Any ideas?
My app is live (I can get the correct information from HTTP Get)
EDIT:
As CBroe said i changed my code to the following and it now works.
FB.getLoginStatus(function(response){
FB.api(
'/instagram_oembed',
'GET',
{
"url":"INSTAGRAMURL",
access_token: pageAccessToken
},
function(response) {
console.log(response);
InstagramPage.innerHTML = response.html;
}
);
console.log(response);
});
});
So having both the parameters inside the {} works. I originally tried with 2 {}, which didn't work.
However, CBroe, as can be seen in facebook docs: https://developers.facebook.com/docs/facebook-login/guides/access-tokens
I can use the Client_ID in javascript.
Addition - After i wrote it in PHP (with the PHP SDK for facebook), to resolve having the Client ID readable in JS:
<?php
require_once __DIR__ . '/assets/src/Facebook/autoload.php'; // change path as needed
$fb = new \Facebook\Facebook([
'app_id' => 'APP-ID',
'app_secret' => 'APP-Secret',
'default_graph_version' => 'v13.0'
//'default_access_token' => '{access-token}', // optional
]);
/* PHP SDK v5.0.0 */
/* make the API call */
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get(
'/instagram_oembed?url=INSTAGRAMURL',
'APP-ID|APP-ID_or_Client-ID'
);
} 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;
}
$Node = $response->getDecodedBody();
echo <<< EOF
<div class=""InstagramResults">
EOF;
print_r($Node["html"]);
echo <<< EOF
</div>
EOF;
?>
´´´
You are trying to send a instagram_oembed endpoint URL, to the instagram_oembed endpoint. The url parameter should only be the INSTAGRAMURL.
And if you have to pass a different access token than what the SDK will use internally, then that needs to be passed as an additional parameter to the endpoint.
Note that you should not expose your client_id (actually, the app secret) in publicly available client-side code ever though. Everyone could steal it from there, and would have a valid app access token for your app.

Facebook app help on basics and access token PHP SDK for a beginner

I would like to know how can I get an access token easily for my Facebook app? I'm new to this so a step by step explanation would be appreciated. I intend on making an app which displays user's data such as name, bio, dob and email. Moreover the app also shows the feed from a page. Using the page's id/name or category. So far I have this. Somethings might be extra here as I was trying to experiment.
//Loading the SDK
require_once("facebook.php");
//Setting up APP parameters
$config = array();
$config['appId'] = 'xxxxxxxxxxxx';
$config['secret'] = 'xxxxxxxxxxxx';
$facebook = new Facebook($config);
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
// Getting the user id
$user = $facebook->getUser();
$user_me = $facebook->api('/me','GET');
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$params = array(
'scope' => 'read_stream, user_about_me',
'redirect_uri' => 'http://fblabs.chimpitup.com/'
);
$loginUrl = $facebook->getLoginUrl($params);
}
If you are using the PHP SDK then you don't need to know the access token explicitly. You also don't need to get or set it using getAccessToken and setAccessToken. All of this is handled by the user clicking on the link generated from $facebook->getLoginUrl($params); and then the function getUser.
So remove
$access_token = $facebook->getAccessToken();
$facebook->setAccessToken($access_token);
Also the following line will trigger an error since it's not in a try-catch and it's redundant with the next few lines.
$user_me = $facebook->api('/me','GET');
After knowing you have authenticated with this
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
You can then make a call with a conditional
if ($user) {
$page_posts = $facebook->api('/PAGE_ID/posts');
}
Where PAGE_ID is the id of the page you are looking to get the feed from
$page_posts is a collection of post objects that can be accessed by looping through
foreach($page_posts['data'] as $post){
$post_link = $post['actions'][0]['link'];
$page_id = $post['from']['id'];
$page_name = $post['from']['name'];
$message = ($post['message']) ? $post['message'] : " ";
$name = ($post['name']) ? $post['name'] : " ";
$story = ($post['story']) ? $post['story'] : " ";
$post_time = $post['updated_time'];
}
For example displaying it in HTML
<div id="stream">
<?php foreach($user_posts['data'] as $post){
$post_link = $post['actions'][0]['link'];
$page_id = $post['from']['id'];
$page_name = $post['from']['name'];
$message = ($post['message']) ? $post['message'] : " ";
$name = ($post['name']) ? $post['name'] : " ";
$story = ($post['story']) ? $post['story'] : " ";
$post_time = $post['updated_time'];
?>
<div class="post">
<div class="picture">
<img src="http://graph.facebook.com/<?php echo $page_id; ?>/picture?type=square"/>
</div>
<div class="body">
<?php echo $page_name; ?>
<span class="message"><?php echo $message; ?></span><br>
<span class="message"><?php echo $name; ?></span><br>
<span class="message"><?php echo $story; ?></span>
<div class="meta">
<?php echo date("F j g:i a", strtotime($post_time)); ?>
</div>
</div>
</div>
<?php } ?>
</div><!-- end #stream -->
See https://developers.facebook.com/tools/explorer/?method=GET&path=facebook%2Fposts for an example of how a page posts is made up and https://developers.facebook.com/docs/reference/api/post/ to know how a post object is made
See the example https://github.com/facebook/facebook-php-sdk/blob/master/examples/example.php and PHP Getting Started Section https://developers.facebook.com/docs/php/gettingstarted/ and where some of the code in this answer was sourced https://github.com/phwd/hellopageposts/blob/master/index.php

Facebook - Publish Checkins using PHP SDK/JavaScript SDK

I'm trying to publish checkin using Facebook Graph API. I've gone through Facebook API documentation (checkins) and also have the publish_checkins permission. However, my checkin is not getting published. May I know is there anything wrong or am I missing anything else? Thank you for your time :)
fbmain.php
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
// Session based API call
if ($user) {
try {
$me = $facebook->api('/me');
if($me)
{
$_SESSION['fbID'] = $me['id'];
$uid = $me['id'];
}
} catch (FacebookApiException $e) {
error_log($e);
}
}
else {
echo "<script type='text/javascript'>top.location.href='$loginUrl';</script>";
exit;
}
$loginUrl = $facebook->getLoginUrl(
array(
'redirect_uri' => $redirect_url,
'scope' => status_update, publish_stream, publish_checkins,
user_checkins, user_location, user_status'
)
);
main.php - Using PHP SDK (Wrong SDK used in this example, should use JavaScript SDK instead)
<?php
include_once "fbmain.php";
if (!isset($_POST['latitude']) && !isset($_POST['longitude']))
{
?>
<html>
<head>
//ajax POST of latitude and longitude
</head>
<body>
<input type="button" value="Check In!" onclick="checkin();"/></span>
</body>
</html>
<?php
}
else
{
?>
<script type="text/javascript">
function checkin()
{
try
{
$tryCatch = $facebook->api('/'.$uid.'/checkins', 'POST', array(
'access_token' => $facebook->getAccessToken(),
'place' => '165122993538708',
'message' =>'MESSAGE_HERE',
'coordinates' => json_encode(array(
'latitude' => '1.3019399200902',
'longitude' => '103.84067653695'
))
));
}
catch(FacebookApiException $e)
{
$tryCatch=$e->getMessage();
}
return $tryCatch;
}
</script>
<?php
}
?>
Question solved - Things to take note when publishing checkin
Make sure publish_checkins permission is granted.
Must use json_encode() to encode coordinates parameter for PHP SDK.
place and coordinates parameters are compulsory.
A re-authentication is required if you have just added publish_checkins permission to your existing list of allowed permissions.
Apparently, the configuration and the PHP checkin function that I have posted in the question are correct. However, I should use JavaScript SDK instead of PHP SDK for my case as pointed out by Nehal. For future references...
Using JavaScript SDK
function checkin()
{
FB.api('/me/checkins', 'post',
{ message: 'MESSAGE_HERE',
place: 165122993538708,
coordinates: {
'latitude': 1.3019399200902,
'longitude': 103.84067653695
}
},
function (response) {
alert("Checked in!");
}
);
}
You also need to learn PHP and variable scoping.
$facebook = new Facebook(array(
'appId' => FB_API_KEY,
'secret' => FB_SECRET_KEY,
'cookie' => true,
));
$loginUrl = $facebook->getLoginUrl(
array('scope' => 'status_update,publish_stream,publish_checkins,user_checkins,user_location,user_status,user_checkins')
);
// Session based API call
if ($user) {
try {
$me = $facebook->api('/me');
if($me)
{
$_SESSION['fbID'] = $me['id'];
}
} catch (FacebookApiException $e) {
error_log($e);
}
}
else {
echo "<script type='text/javascript'>top.location.href='$loginUrl';</script>";
exit;
}
function checkin($fb)
{
try
{
$tryCatch = $fb->api('/'.$_SESSION['fbID'].'/checkins', 'POST', array(
'access_token' => $fb->getAccessToken(), //corrected
'place' => '165122993538708',
'message' =>'I went to placename today',
'coordinates' => json_encode(array(
'latitude' => '1.3019399200902',
'longitude' => '103.84067653695'
))
));
}
catch(FacebookApiException $e)
{
$tryCatch=$e->getMessage();
}
return $tryCatch;
}
checkin($facebook); //calling the function and passing facebook object to function

redirect to facebook app page after grant permissions

My app is inside a fan page, when i request permission it will show the dialog.
The problem is after user accept, they are redirected to real app page (url here app is hosted)
for understand better i have the url generated with facebook PHP SDK
https://www.facebook.com/dialog/oauth?client_id=341572315885516&redirect_uri=https%3A%2F%2Fmywebapp.com%2Fyii%2Folivi%2Ffacebook%2Fapp%2Fid%2F1%2F&state=40e532d364f67631cfc1ef6061609157&canvas=1&fbconnect=0&scope=user_about_me%2Cuser_birthday
As we can see will redirect outside of facebook, i want redirect back
in that case: https://www.facebook.com/mypage/app_341572315885516
Any way to solve this situation? I have tried a lot of things nothing works...
Wheres my code:
<?php $userid = Yii::app()->facebook->getUser(); ?>
<?php $results = NULL;//$results = Yii::app()->facebook->api('/me'); ?>
<?php
$signed_request = Yii::app()->facebook->getSignedRequest();
if(!isset($signed_request['page']) || !isset($signed_request['page']['liked']))
{
$this->renderPartial('_nofan', array('model'=>$model));
}
else
{
if(!$signed_request['page']['liked'])
{
$this->renderPartial('_nofan', array('model'=>$model));
}
else
{
try
{
$results = Yii::app()->facebook->api('/me');
}
catch (FacebookApiException $e) {
}
if(!$userid || !$results)
{
$loginUrl = Yii::app()->facebook->getLoginUrl(array('scope'=>'user_about_me,user_birthday'));
/*echo "<script type='text/javascript'>top.location.href = '{$loginUrl}';</script>";*/
Yii::app()->clientScript->registerScript('login-perm', 'top.location.href = "'.$loginUrl.'";', CClientScript::POS_HEAD);
//$this->redirect($loginUrl);
/*Yii::app()->facebook->addJsCallback("FB.login(function(response) {
if (response.authResponse) {
// user is logged in and granted some permissions.
} else {
// User cancelled login or did not fully authorize.
}
}, {scope:'user_about_me,user_birthday'});");*/
}
// FAN
//echo 'Olá';
}
}
?>
Thanks
You can try redirect_uri paramaeter,
Ex:
$redirecturl = https://www.facebook.com/mypageonfacebook/app_APPID;
$params = array('scope' => 'email, publish_actions', 'redirect_uri' => $redirecturl);
$loginUrl = $facebook->getLoginUrl($params);
echo("<script> top.location.href='".$loginUrl."'</script>");
hope this will help you.. thanks..

How to authorize Facebook app using redirect in canvas?

I'm trying to get into making Facebook apps but I'm having trouble getting authorization working in a redirect scheme inside the canvas.
Using the javascript api, I got it working pretty easily in a popup scheme:
$("#loginButton").click(function(e) {
FB.login(function(response) {
if (response.perms) {
perms();
}
}, {perms : 'publish_stream'});
But the popup should be an unnecessary extra click, because every other application I see requests the authorization before even showing you the landing page. Like this:
http://i.imgur.com/yBGzL.png
I figure they're simply using a redirect scheme. So I spent the entire day trying the different ways I could find:
header("Location: https://graph.facebook.com/oauth/authorize?client_id=" . $gAppId . "&redirect_uri=" . urlencode($gUrl) . "&perms=publish_stream");
header("Location: http://www.facebook.com/login.php?v=1.0&api_key=" . $gApiKey . "&next=" . urlencode($gUrl) . "&canvas=");
header("Location: http://www.facebook.com/connect/uiserver.php?app_id=" . $gAppId . "&next=" . urlencode($gUrl) . "&return_session=0&fbconnect=0&canvas=1&legacy_return=1&method=permissions.request");
But all of them, instead of showing the authorization request stuff, show a link like this:
http://i.imgur.com/bLwPQ.png
Hilariously, if I open the iframe's address in a new tab, I get the authorization request like I wanted. But I want it to display immediately, without an extra click, like every other app.
Here's an example of an app that is doing authorization and requesting permissions all in one go, in redirect form, before even displaying the landing page:
www.facebook.com/send.fortune.cookies
How are they doing it?
I know that this is months old now... but this is what you should do to add permission checking to your canvas.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$accesstoken=$session['access_token'];
} catch (FacebookApiException $e) {
error_log($e);
}
}
if($me)
{
// do what you have to do
}else {
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'publish_stream'
)
);
echo '<script>top.location="'.$loginUrl.'";</script>';
//echo '<fb:redirect url="' . $loginUrl . '" />';
//header('Location: '.$loginUrl);
}
The problem is that server side redirection is only redirecting your inner app frame instead of redirecting the whole page, and Facebook doesn't like displaying their system dialogs inside frames.
You would need some client side redirection, probably something along those lines:
<script>
<?php
if($doRedirect) {
echo 'top.location="http://redirect_url";';
}
?>
</script>
Using FB Javascript SDK, it can be done something like --
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
loggedIn(response);
} else {
top.location = encodeURI("https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_APP_URI&response_type=token");
}
Maybe this helps :
if(!$facebook->api_client->users_isAppUser())
{
?>
<fb:redirect url="http://www.facebook.com/login.php?v=1.0&api_key=111111111111&next=http%3A%2F%2Fapps.facebook.com%2Fapp_name%2F&canvas=&req_perms=publish_stream"/>
<?php
}