Trouble using Facebook App - php

I am trying to use FB App for auto posting. I have been trying to use the SDK from facebookapi as well as facebook-php-sdk-master
However, i am having trouble with setting up the Uris and domains on the FB App settings. I have tried all combinations - with 'localhost', with actual site domain 'landshoppe.com', with 'www', without 'www' etc. I am not able to understand what exactly needs to be entered into the Uri fields !
If somebody can explain and help me get the script working, I will be obliged.
I am attaching screenshots of what I am doing.
In the Basic FB settings, I have tried adding http://localhost as well as http://landshoppe.com
In the Site Url also I have tried same
In the Advanced settings, redirect Deauthorize Callback URL also I have tried these Uris
I have whitelisted IPs 127.0.0.1 and my server IP
Client OAuth Login, Web OAuth Login and
Embedded Browser OAuth Login tabs say 'Yes'
I have got 'http://localhost/fb-tokens/' in Valid OAuth redirect URIs
My Script settings are
$appid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$appsecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$pageId = '530139960390619';
$msg = 'Buy/Sell/rent Property in India. Redevelopment, Joint Ventures, Auction Properties';
$title = 'Landshoppe-The Property Destination';
$uri = 'http://localhost/'; //I have tried all combinations here
$desc = 'Buy an Apartment, Rent an Apartment,Land for Redevelopment, Land for sale, Commercial Property';
$pic = 'http://www.landshoppe.com/images/logo.jpg';
$action_name = 'Post to FB';
$action_link = 'http://www.landshoppe.com/';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
$user = $facebook->getUser();
// Contact Facebook and get token
if ($user) {
// you're logged in, and we'll get user acces token for posting on the wall
try {
$page_info = $facebook->api("/$pageId?fields=access_token");
if (!empty($page_info['access_token'])) {
$attachment = array(
'access_token' => $page_info['access_token'],
'message' => $msg,
'name' => $title,
'link' => $uri,
'description' => $desc,
'picture'=>$pic,
'actions' => json_encode(array('name' => $action_name,'link' => $action_link))
);
$status = $facebook->api("/$pageId/feed", "post", $attachment);
} else {
$status = 'No access token recieved';
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
// you're not logged in, the application will try to log in to get a access token
header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");
}
echo $status;
I am getting errors like
>
URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
>
And
>
'Cannot Load Url' because it is not added in App Domains'
>
I am at my wits end ! Kindly help me understand what needs to be the Uris that should be used in all these places.

Related

Post on Facebook without Share Prompt in PHP

Is there a possibility where I can make a button on which when I click, the contents directly get shared on facebook without showing our user the share prompt dialog box?
I referred it online and found that its possible through mobile devices:
http://www.mindfiresolutions.com/How-to-post-message-on-your-facebook-wall-without-using-Facebook-dialog-Box-1419.php
The question is can we make some sort of ajax call and get this done on web apps.
We used Following code
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'My app ID', /*Your APP ID*/
'secret' => 'My Secret ID', /*Your APP Secret Key*/
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
} catch(FacebookApiException $e) {
$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.';
}
$response = $facebook->api(
"/me/feed",
"POST",
array (
'message' => 'This is a test message',
'link' => 'www.google.com'
/* 'picture' => '{picture}',
'caption' => '{caption}',
'description' => '{description}'*/
)
);
?>
But its returns : " Fatal error: Uncaught OAuthException: (#200) The user hasn't authorized the application to perform this action throw in file"
Any help would be highly appreciated.
Thanks in advance.
Of course you can using the Graph API. On the button click you just have to make a \POST call to /me/feed.
Learn more about publishing a feed via Graph API and what all parameters are available here.
Permission required: publish_stream
Using PHP SDK:
$response = $facebook->api(
"/me/feed",
"POST",
array (
'message' => 'This is a test message',
'link' => '{link}',
'picture' => '{picture}',
'caption' => '{caption}',
'description' => '{description}'
)
);
Direct HTTP Request-
POST /me/feed
Host: graph.facebook.com
message=This+is+a+test+message
...
You can check your calls in Graph API Explorer
Edit:
To ask for the required permissions:
$params = array(
'scope' => 'publish_stream'
);
$login_url = $facebook->getLoginUrl($params);
You can read more about permissions here.
Try this way: https://developers.facebook.com/docs/reference/php/
When coding the wep app, you only have to provide the App Id and the App Secret, then you should have to specify the content to be posted.
You should try also the Javascript Facebook SDK, you'll find it here: https://developers.facebook.com/docs/javascript or you could go further and try the C# SDK, this one is a little bit more complex, but you will be able to do so much more.
Have fun coding!!!
Just go to https://developers.facebook.com/docs/opengraph/
Review it and place what kind of share you want.
This is the long process to be handle so. you need to study it.

How to obtain Facebook page access_token without logging in or having user interaction

I have been reading the Facebook documentation and I must be missing something, as I just cant understand how to get the access token for a page without actually logging in first. I am trying to create a PHP function using the PHP facebook API so that when I add new stories or tutorials on my site, my site's apps can then automatically post as the page a blurb about them on myy facebook page.
I have this function working but only when I get the access token from the Graph API Explorer, though the access tokens expire in about an hour. I can't seem to figure out how to programatically obtain the access_token for the page and query for a new one each time from within my PHP scripts so they don't expire and do not require user interaction.
function post_to_facebook($title, $message, $link, $picture) {
require '../facebook/src/facebook.php';
$page_token = 'xxx';
$page_id = 'xx';
$facebook = new Facebook(array(
'appId' => '<app_id>',
'secret' => '<app_secret>',
'cookie' => false,
));
$facebook->setAccessToken($page_token);
try {
$ret_obj = $facebook->api('/'.$page_id.'/feed', 'POST', array(
'caption' => $title,
'link' => $link,
'message' => $message,
'picture' => $picture
));
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
return false;
}
return true;
}
Can someone explain how I can go about retrieving the access token without manually having to look it up via graph api explorer or having a user login?
It's not possible.
The only correct (and legal) way to achieve the access token is with user interaction (through login process).

PHP Facebook API issue with business page

I have a Facebook app which posts news from a company website to the company's Facebook business page.
When I test it with my developer account's id or my private account id, it works great. But when I use the id of the business page, no news show up on the chronic.
This is my code:
<?php
require_once 'library/facebook.php';
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_APP_SECRET,
'cookie' => true,
));
if(is_null($facebook->getUser())){
header("Location:{$facebook->getLoginUrl(array('req_perms' => 'user_status,publish_stream,user_photos,offline_access,publish_checkins'))}");
exit;
}
if($facebookpost){
try {
$facebook->setFileUploadSupport("http://" . $_SERVER['SERVER_NAME']);
$img = $sitepath.$gfxpath.$filename;
$arguments = array(
'source' => '#' . $img,
'message' => utf8_encode(html_entity_decode(strip_tags($text))),
);
$facebook->api("/".FACEBOOK_PROFILE_ID."/photos", 'post', $arguments);
} catch (FacebookApiException $e) {
print $e;
}
}
?>
The app shows up correctly in the profile setting (image)
are there some different settings for business pages?
You need to use the page's access token to post updates to your page. You can get the access token for the page by calling the following API endpoint:
/me/accounts, then look for your page ID / Name.

Facebook App - auto login so can update status (php SDK)

I have built an app that allows users to update their status' externally. It uses the PHP SDK.
Is it possible to automatically login for registered users once they have initially authorised their facebook account via the app? I do not want them to have to login for every new session. Id like that once they have been authenticated the first time, they are always connected and not asked to login multiple times. Possibly by storing the access token in a database and this using this to connect somehow. Is this possible? I have noticed other apps that do this, but have no idea how they do this eg. ping.fm
Below is what I have so far, but this requires the user to select the "login" link when the session expires.
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'appid',
'secret' => 'secret',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//start the session if needed
if( session_id() ) {
} else {
session_start();
}
//do stuff when already logged in
//get the user's access token
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'offline_access');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
'/me',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
$facebookAuth = TRUE;
} else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
$facebook_login = $login_url;
}
if (isset($_GET['submit'])){
if ($_GET['facebook']){
//get the info from the form
$parameters = array(
'message' => $_GET['message']/*,
'picture' => $_POST['picture'],
'link' => $_POST['link'],
'name' => $_POST['name'],
'caption' => $_POST['caption'],
'description' => $_POST['description']*/
);
//add the access token to it
$parameters['access_token'] = $_SESSION['active']['access_token'];
//build and call our Graph API request
$newpost = $facebook->api(
'/me/feed',
'POST',
$parameters
);
if ($newpost){
echo 'posted to facebook';
} else {
echo 'not posted to facebook :0( ';
}
}
I did not check how ping.fm does it.
But after looking at the extended permissions list here:
http://developers.facebook.com/docs/reference/api/permissions/
xmpp_login (Provides applications that integrate with Facebook Chat the ability to log in users.)
Otherwise, i dont think its possible.
Even desktop Apps need to redirect the user to a browser for authentication.
This also may depend on whether the user has the "keep me logged in" checkbox marked on log-in.
Since you have the offline_access, then you basically can perform the actions regardless if the user is logged in or not.

Change facebook redirect URL on login

I'm trying to change the redirect URL for Facebook login on my site. This is so I can go to a page where I can create a new user in my database if they don't already exist and THEN redirect them to my main page. However, when I try to login, I get the following error on Facebook: An error occurred with PHP SDK Unit Tests. Please try again later.
My code (I want to redirect them to mysite.com/createfbuser.php):
public function getLoginUrl($params=array()) {
$this->establishCSRFTokenState();
$currentUrl = $_SERVER['SERVER_NAME'] . '/createfbuser.php';
return $this->getUrl(
'www',
'dialog/oauth',
array_merge(array(
'client_id' => $this->getAppId(),
'redirect_uri' => $currentUrl, // possibly overwritten
'state' => $this->state,
'scope' => 'email'),
$params));
}
EDIT The original code reads $currentUrl = $this->getCurrentUrl(); for a reference
First of all, you don't have to edit PHP SDK, below is the sample for authenticating the user and then redirecting to your landing page,
Make sure you replace:
YOUR-APP-ID-HERE with Your facebook application id,
YOUR-APP-API-SECRET-HERE with Your facebook application secret key
YOUR-REDIRECT-URL-HERE with Your landing page URL
<?php
// Requires Facebook PHP SDK 3.0.1: https://github.com/facebook/php-sdk/
require ('facebook.php');
define('FACEBOOK_APP_ID',"YOUR-APP-ID-HERE");
define('FACEBOOK_SECRET',"YOUR-APP-API-SECRET-HERE");
define('REDIRECT_URI',"YOUR-REDIRECT-URL-HERE");
$user = null;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if($user == 0) {
// If the user is not connected to your application, redirect the user to authentication page
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('redirect_uri' => REDIRECT_URI));
echo ("<script> top.location.href='".$login_url."'</script>");
} else {
// if the user is already connected, then redirect them to landing page or show some content
echo ("<script> window.location.href='".REDIRECT_URI."'</script>");
}
?>
If you want to get extended permissions, then simply add another "scope" parameter to the login url, ex:
$login_url = $facebook->getLoginUrl($params = array('redirect_uri' => REDIRECT_URI,'scope' => 'comma-separated-list-of-requested-extended-perms'));
For more details on permissions, refer facebook permissions docs
The URL you redirect to needs to be on the same domain as you've configured for your app in the app settings, beyond that there's no restriction really, you can set the redirect_url to any URL on your domain.
When you try to auth the app as an admin there should be a more specific error message visible - it's quite likely Error 191 ( see Facebook API error 191 for another possible cause and solution)

Categories