I am using Facebook SDK with HTC Sense Token,so i want to do that requests with user auth just with the token doing like this with the token i want to send requests with use a app(using the htc sense token) i had an appid but i had no secret code to post on facebook how to get the app htc sense app secret code to post on my wall,page etc
<?php
session_start();
require_once 'facebook-php-sdk/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
$api_key = 'FACEBOOK_APP_ID';
$api_secret = 'FACEBOOK_APP_SECRET';
$redirect_login_url = 'http://www.yoursite.com/somefolder/file.php';
/ initialize your app using your key and secret
FacebookSession::setDefaultApplication($api_key, $api_secret);
// create a helper opject which is needed to create a login URL
// the $redirect_login_url is the page a visitor will come to after login
$helper = new FacebookRedirectLoginHelper( $redirect_login_url);
// First check if this is an existing PHP session
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from the existing PHP sesson
$session = new FacebookSession( $_SESSION['fb_token'] );
try {
// validate the access_token to make sure it's still valid
if ( !$session->validate() ) $session = null;
} catch ( Exception $e ) {
// catch any exceptions and set the sesson null
$session = null;
echo 'No session: '.$e->getMessage();
}
} elseif ( empty( $session ) ) {
// the session is empty, we create a new one
try {
// the visitor is redirected from the login, let's pickup the session
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $e ) {
// Facebook has returned an error
echo 'Facebook (session) request error: '.$e->getMessage();
} catch( Exception $e ) {
// Any other error
echo 'Other (session) request error: '.$e->getMessage();
}
}
if ( isset( $session ) ) {
// store the session token into a PHP session
$_SESSION['fb_token'] = $session->getToken();
// and create a new Facebook session using the cururent token
// or from the new token we got after login
$session = new FacebookSession( $session->getToken() );
try {
// with this session I will post a message to my own timeline
$request = new FacebookRequest(
$session,
'POST',
'/me/feed',
array(
'link' => 'www.finalwebsites.com/facebook-api-php-tutorial/',
'message' => 'A step by step tutorial on how to use Facebook PHP SDK v4.0'
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
// the POST response object
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
$msgid = $graphObject->getProperty('id');
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (post) request error: '.$e->getMessage();
}
if ( isset ( $msgid ) ) {
// we only need to the sec. part of this ID
$parts = explode('_', $msgid);
try {
$request2 = new FacebookRequest(
$session,
'GET',
'/'.$parts[1]
);
$response2 = $request2->execute();
$graphObject2 = $response2->getGraphObject();
// the GET response object
echo '<pre>' . print_r( $graphObject2, 1 ) . '</pre>';
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (get) request error: '.$e->getMessage();
}
}
} else {
// we need to create a new session, provide a login link
echo 'No session, please login.';
}
You need to use a Token of your own App. Not sure why you would want to use the Token of the HTC Sense App for posting, afaik it is ONLY used for spamming - because a lot of permissions are already approved for it. Don´t do that, create your own authorization process for your own App: https://developers.facebook.com/docs/facebook-login
...and then go through Login Review with the additional permission: https://developers.facebook.com/docs/facebook-login/review
Trying to use/abuse/hijack another App is just wrong and definitely not allowed.
Related
I'm playing around a bit with Facebook API + PHP SDK but I'm stuck..
I'm trying to fetch all my wall posts and (if attached) the images.
Fetching all my posts goes fine but it doesn't automatically include the image. So my main question is 'How can I add fields to the fetch command'
Here is the code I'm using now:
/* handle the result */
try {
$response = $fb->get('/me/posts', $token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// Page 1
$feedEdge = $response->getGraphEdge();
According to the facebook documents I should use this:
$request = new FacebookRequest(
$session,
'GET',
'/me/posts',
array(
'fields' => 'full_picture,message'
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
/* handle the result */
But the execute and getGraphobject method don't even exist in my SDK files (which is the latest version)
To get specific fields, you can try changing
$response = $fb->get('/me/posts', $token);
to
$response = $fb->get('/me/posts?fields=full_picture,message', $token);
I have created 2 facebook apps, hosted in the same external domain. I have installed these two apps in a facebook page of mine and in both apps i am running the following php code at the beginning:
session_start();
// added in v4.0.0
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// start session
// init app with app id and secret
FacebookSession::setDefaultApplication( 'xxx','yyy' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/my_namespace/' );
try
{
$session = $helper->getSessionFromRedirect();
}
catch( FacebookRequestException $ex )
{
// When Facebook returns an error
}
catch( Exception $ex )
{
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) )
{
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
}
else
{
// show login url
echo 'Login';
}
When I run each application, the user identity that is shownn is equal for all properties except for user id:
One app 1, i see:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[id] => 1400416826952138
[email] => my_name#gmail.com
[first_name] => Name
[gender] => female
Etc
On app 2 I see:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[id] => 1397126750614479
[email] => my_name#gmail.com
[first_name] => Name
[gender] => female
Etc
As i am using the same user (my account) in both apps, why are there 2 different ID for the same user account?
Thanks
Nat
How to post to Facebook page with the App ID & Secret & Page ID without need to login with the user Admin of the page to get access token, the App owner who is the Admin of the page shouldn't be enough to auto post !?
I am using PHP & SDK4 of Facebook API.
You can´t post anywhere on Facebook without authorizing. If you want to post "as Page", you need to authorize a Page admin with the "publish_pages" permission and use a Page Token. You can´t get a User or Page Token without authorization, and of course you can´t automate the authorization process. Check out the docs for detailed information: https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish
You will also need to learn about Access Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
In fact all i wanted specifically to have permanent page access token so i can auto post forever without requiring authentication from the user each time for posting.
follow these steps to get it: Permanent Access Token
then use auto post code :
session_start();
define('FACEBOOK_SDK_V4_SRC_DIR', 'facebook-php-sdk-v4-4.0-dev/src/Facebook/');
require __DIR__ . '/facebook-php-sdk-v4-4.0-dev/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
// Facebook App
$api_key = 'xxxxxxxxxxxxxxxx'; //App ID
$api_secret = 'xxxxxxxxxxxxxxxx'; //App Secret
$page_id = 'xxxxxxxxxxxxxxxx'; //Page ID
$page_token = 'from the steps in the url';
$fb_post = array(
'message'=> 'test message',
'name'=> '',
'link'=> 'http://www.example.com/',
'picture'=> 'http://www.example.com/image.jpg',
'caption'=> '',
);
// start a session for this App
FacebookSession::setDefaultApplication($api_key, $api_secret);
try {
$session = new FacebookSession($page_token);
} catch(FacebookRequestException $e) {
die(" Error : " . $e->getMessage());
} catch(\Exception $e) {
die(" Error : " . $e->getMessage());
}
try {
// Auto posting
$page_post = (new FacebookRequest( $session, 'POST', '/'. $page_id .'/feed', $fb_post))->execute()->getGraphObject()->asArray();
// return post_id, optional
print_r( $page_post );
} catch (FacebookRequestException $e) {
// The Graph API returned an error
echo '<b style="color:blue;">'.$e->getMessage().'</b>';
} catch (\Exception $e) {
// Some other error occurred
echo '<b style="color:red;">'.$e->getMessage().'</b>';
}
I'm currently trying to integrate the lastest Facebook php sdk into a Phalcon project but I'm not having much luck.
I can get the SDK to work in a standalone project but the exact same code fails when integrated into a Phalcon project (either as a service or directly in a Controller).
The issue seems to be that the facebook redirect helper creates a "state" property which is appended to a loginUrl and then stored in a session. When a user is redirected back to my site after signing in, it checks this property against a querystring value. The state property is only generated and stored whenever you display the login url via the redirectHelpers getLoginUrl() method. Somehow, when I integrate this in Phalcon the session variable and the $_GET parameter never seem to match up. The simple example which works is as follows
// lots of requires
Facebook\FacebookSession::setDefaultApplication($appId,$secret);
$helper = new Facebook\FacebookRedirectLoginHelper('http://'.$_SERVER['HTTP_HOST'] .'/');
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
} // end if isset($_SESSION)
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login'; // this line would generate a new state
}
When I try using this exact same code in a controller in a phalcon project (or by setting "$me" up in the $di), the state check always fails even though I'm not generating a new login url. The only other difference is that in the simple project I require all the facebook files using require_once but in the Phalcon project I use
$loader->registerNamespaces(
array(
"Facebook" => __DIR__ . '/../../vendor/facebook/php-sdk-v4/src/Facebook/'
)
);
but replacing that with the requires doesn't seem to have an effect.
Anyone got any clues?
I've got it working by using registerClasses not registerNamespaces - but using v3.2.x so not a v4.
$loader->regeisterNamespaces( /* Projects' classes */ )
->registerClasses(array(
'Facebook' => __DIR__ . '/../../vendor/facebook/php-sdk/src/facebook.php'
))
->register();
ps.: Im using composer to load FacebookSDK so I have different path than yours.
Then I'm using it in Controller ordinary without using $di,
protected function getFacebook()
{
if (!$this->facebook) {
$this->facebook = new Facebook(array(
'appId' => $this->config->social->facebook->appId,
'secret' => $this->config->social->facebook->secret,
'fileUpload' => false,
'allowSignedRequest' => false,
));
}
return $this->facebook;
}
I've worked this one out. The issue was that the browser was automatically making a request to /favicon.ico as well,as I didn't have a favicon.ico this then rendered the default indexAction again and as such this was causing the getLoginUrl() method to fire again generating a new state. The simple fix is to just create a favicon, or define the error handling route for files not there (I was just using the boilerplate from the phalcon dev tools initially)
I'm trying to run the sample code for Facebook connect that I downloaded from http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
I get this error message :
[error] => Array
(
[message] => An active access token must be used to query information about the current user.
[type] => OAuthException
[code] => 2500
)
You can try on my website : http://facebook.oliverjordan.net/thinkdiff
Here is the fbmain.php code :
<?php
//facebook application
$fbconfig['appid' ] = "463007877113xxx";
$fbconfig['secret'] = "-sensor-";
$fbconfig['baseurl'] = "http://facebook.oliverjordan.net/thinkdiff/index.php"; //"http://thinkdiff.net/demo/newfbconnect1/php/sdk3/index.php";
//
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
}
$user = null; //facebook user uid
try{
include_once "facebook.php";
}
catch(Exception $o){
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
// We may or may not have this data based
// on whether the user is logged in.
// If we have a $user id here, it means we know
// the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown',
'redirect_uri' => $fbconfig['baseurl']
)
);
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
d($e); // d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user){
//get user basic description
$userInfo = $facebook->api("/$user");
//Retriving movies those are user like using graph api
try{
$movies = $facebook->api("/$user/movies");
}
catch(Exception $o){
d($o);
}
//update user's status using graph api
//http://developers.facebook.com/docs/reference/dialogs/feed/
if (isset($_GET['publish'])){
try {
$publishStream = $facebook->api("/$user/feed", 'post', array(
'message' => "I love thinkdiff.net for facebook app development tutorials. :)",
'link' => 'http://ithinkdiff.net',
'picture' => 'http://thinkdiff.net/ithinkdiff.png',
'name' => 'iOS Apps & Games',
'description'=> 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
d($e);
}
$redirectUrl = $fbconfig['baseurl'] . '/index.php?success=1';
header("Location: $redirectUrl");
}
//update user's status using graph api
//http://developers.facebook.com/docs/reference/dialogs/feed/
if (isset($_POST['tt'])){
try {
$statusUpdate = $facebook->api("/$user/feed", 'post', array('message'=> $_POST['tt']));
} catch (FacebookApiException $e) {
d($e);
}
}
//fql query example using legacy method call and passing parameter
try{
$fql = "select name, hometown_location, sex, pic_square from user where uid=" . $user;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}?>
Can anyone help me?
You must ensure that your access token is active. Or maybe you're in logout condition. Or try to clean the cookies and cache from your browser (ctrl+shift+del)
Please check if you are getting any Facebook exceptions like
An active access token must be used to query information about the
current user.
which causes 0 as user id in return from $facebook->getUser().
So please check with getAccessTokenFromCode() from base_facebook.php and verify access_token_response format as it may be in JSON format.
So try to use appropriate decoding method to get $response_params['access_token'] from $access_token_response.