I'm integrating my web-based game to a Facebook Game . Facebook login, getting user id, getting user profile picture is OK . But i need to post somethings to wall (For example, John Doe earned 50 point!) .
I have offline_access and publish_Stream permissions for my Facebook App.
Now i want to publish some links automatically. I'm using Facebook PHP SDK with Yii.
I can get Facebook User ID etc... But i don't know how can i post somethings to user's wall, automatically (for example when user is offline).
I'm looking Graph API Post document's Publishing title. But i need access_token parameter for use this. And i'm not sure where is this access_token .
PHP-SDK 3.1.1
To generate app and user tokens. $app_access_token & $access_token
*The user access_token if you have offline access will never expire, unless user deAuthorizes your app. You would need to use for posting to a users wall when they are offline or not interacting with your application.*
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '135669679827333',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
$user = $facebook->getUser();
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;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// Create Application Access Token
$app_access = "https://graph.facebook.com/oauth/access_token?client_id=135669679827333&client_secret=xxxxxxxxxxxxxxxxxxxxxxxx&grant_type=client_credentials";
$app_access_token = file_get_contents($app_access);
// If we have a user who is logged in, create access_token with session.
if ($user) {
$access_token = $_SESSION['fb_135669679827333_access_token'];
}
?>
Take a look at the authentication doc which will show you how to get an access token.
you can get access token like this
$access_token = $session['access_token'];
now use $access_token where u need it
$my_friends_ids=file_get_contents("https://graph.facebook.com/me/friends?access_token=".$access_token);
here i am getting ids of all my friends
Related
I have a problem with my logging into my Facebook application.
When I click "login" I get redirected to Facebook to accept the permissions then Facebook redirects me back. But it doesn't change anything. The URL down is dynamic generated. When I try the same script on an other URL that's not dynamic it's work.
Here is the URL there i try to perform a login.
http://www.testaiq.se/test_592.html
What could be the problem? PHP is behind the URL over here.
require_once("facebook/facebook.php");
// Creating our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'XXX',
'secret' => 'XXX',
));
// Getting User ID
$user = $facebook->getUser();
// Get Access token
$access_token = $facebook->getAccessToken();
// 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.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
// Retrieving user's friend list using fb graph api
$user_profile = $facebook->api('/me','GET');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_likes'
));
}
I have crawled around lots of various answers but am still a bit confused with how I should be dealing with facebook access tokens.
One of the main problems I'm having is due to what information is being stored in my browser. For example, I log onto the app, the token expires, I can't logon again unless I clear cookies/app settings in browser.
I stumbled across this thread: How to extend access token validity since offline_access deprecation
Which has shown me how to create an extended access token through php.
My questions are:
1. Do I need to store the access token anywhere?
2. What happens when the access token expires or becomes invalid? At the moment, my app simply stops working when the short term access ones expire.
3. Is there a way I should be handling them to check if they have expired?
I am using the php sdk and have basically used the standard if( $user )... Like this:
require 'sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXXXXXXXXXXX',
));
$user = $facebook->getUser();
if( $user ){
try{
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if (!$user){
$params = array(
'scope' => 'email',
);
$loginUrl = $facebook->getLoginUrl( $params );
echo '<script type="text/javascript">
window.open("'. $loginUrl .'", "_self");
</script>';
exit;
}
if( $user ){
$access_token = $facebook->getExtendedAccessToken();
$get_user_json = "https://graph.facebook.com/me?access_token="
. $access_token;
// Rest of my code here...
}
Is there anything else I should be doing to handle tokens?
. Should I be passing the access token between pages or is it ok to just call it again at the top of each page like this:
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXXXXX',
'secret' => 'XXXXXXXXXXXX',
'redirect_uri' => 'http://localhost:8000/',
));
$token = $facebook->getExtendedAccessToken();
Let's go through your questions:
Do I need to store the access token anywhere?
This depends on your application. First of all ask yourself, do you need to perform actions on behalf of the user while he is not present (not logged in to your app)?
If the answer is yes, then you need to extend the user token which can be done using the PHP-SDK by calling this method while you have a valid user session: setExtendedAccessToken().
Also you should refer to this document: Extending Access Tokens
What happens when the access token expires or becomes invalid? ...
Is there a way I should be handling them to check if they
have expired?
This is where the catch clause in your code comes in handy, while facebook example only logs the error (error_log($e);) you should be handling it!
Facebook already has a tutorial about this: How-To: Handle expired access tokens.
Also you should refer to the Errors table and adjust your code accordingly.
Is there anything else I should be doing to handle tokens?
See above.
Should I be passing the access token between pages or is it ok to just
call it again at the top of each page
You shouldn't need to do any of that, because the PHP-SDK will handle the token for you; have you noticed that you are calling: $user_profile = $facebook->api('/me'); without appending the user access_token?
The SDK is adding it from its end so you don't have to worry about it.
I just had the same issue, but i solve it with some of your help. I'm using the php-sdk to connect to the Facebook API, so i just made this.
$facebook = new Facebook(array(
'appId' => 'API_ID',
'secret' => 'SECRET',
));
// Get User
$user = $facebook->getUser();
// Verifing if user is logged in.
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;
}
}
// Verify if user is logged in, if it is... Save the new token.
if($user){
// Request the access_token to the
$access_token = $facebook->getAccessToken()
// Saving the new token at DB.
$data = array('access_token' => $access_token);
$this->db->where('userid',$user);
$this->db->update('facebook', $data);
}
I have looked at the developers' page but there tons of tons stuff. Application authentication (will my PHP called app?), setting permissions, how to make post after authentication?, where to store authentication? etc etc and so on I wasn't able to get all what all they mean, and what is need in all that stuff.
I only want to make a wall post to the community/fan page's wall as community/fan page. What steps should my PHP application follow to make a wall post?
I've written an in-depth tutorial about this subject: How To: Post On Facebook Page As Page Not As Admin User Using PHP-SDK
In short:
You need at least the publish_stream and manage_pages permissions
Query your page object to get a page access token
And post!
A starting code from my tutorial:
<?php
// This code is just a snippet of the example.php script
// from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = 'page_id';
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "I'm a Page!"
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} 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 {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
}
?>
Note: you may need the offline_access if you want to post while you are not connected to Facebook (e.g.: from your CMS)
I was making a facebook application in which i have to show news feeds of the user who is using it. I am using graph API to do this. The problem is that its not getting me feeds.
I used it to show friends like this:
$friends = $facebook->api('/me/friends');
and it is working fine.
For news feeds i use this:
$feeds = $facebook->api('/me/home');
it shows me an error:
Fatal error: Uncaught IDInvalidException: Invalid id: 0 thrown in
/home/content/58/6774358/html/test/src/facebook.php on line 560
when i try to get Profile feed (Wall) by using this:
$feeds = $facebook->api('/me/feed');
it shows me an empty array.
These API calls are showing me results in the graph API page but don't know why not working in my application.Can any one help me please..
My full code is as follows
require_once 'src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'xxxxx',
'cookie' => true,
));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if (!empty($session)){
$fbme = $facebook->api('/me');
}
if ($fbme) {
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
}else{
$loginUrl = $facebook->getLoginUrl();
echo 'Logout';
}
$friends = $facebook->api('/me/friends?access_token='.$session["access_token"]);
$feeds = $facebook->api('/me/feed?access_token='.$session["access_token"]);
print('<pre>Herere:');print_r($feeds);die;
Did you ask for the read_stream permission during authentication?
What type of Authentication / "Allow" process did you go through?
JavaScript SDK? Facebook PHP SDK? XFBML Login Button?
EDIT- Here are helpful link that will get you started up:
Facebook PHP SDK
Authentication Process
Building Apps on Facebook.com
These are all official docs in Facebook and github.
EDIT: Follow this step by step:
From your original code, look for:
$loginUrl = $facebook->getLoginUrl();
Change it to:
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream'));
Uninstall your application first from your account:
http://www.facebook.com/settings/?tab=applications
Then try it again to show new Allow pop-up
EDIT:
It's also about the arrangement of code in the if statements. Use this code:
<?php
require_once 'src/facebook.php';
$session = $facebook->getSession();
$fbme = null;
if($session){
$fbme = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
$feeds = $facebook->api('/me/feed');
$logoutUrl = $facebook->getLogoutUrl();
echo 'Logout';
echo "<pre>".print_r($feeds,TRUE)."</pre>";
}else{
$loginUrl = $facebook->getLoginUrl(array('req_perms'=>'read_stream','canvas'=>1,'fbconnect'=>0));
echo '<script> top.location.href="'.$loginUrl.'"; </script>>';
}
Uninstall your app again from
http://www.facebook.com/settings/?tab=applications
and re-open the application
The Facebook PHP SDK should handle your access token for you, you don't need to append it to your graph API endpoint in you Facebook::api() call.
As #dragonjet pointed out, you need to request the read_stream extended permission from your FB User in order to get access to their feed. Though, the exception you pasted doesn't really match that kind of problem, and your request to /me/home doesn't throw a similar exception (or one about not having access).
I still think this is a permissions issue, so start here for trying to fix it. Here's an example of how to request the appropriate permission.
$facebook = new Facebook(array(
'appId' => FB_APP_ID, //put your FB APP ID here
'secret' => FB_APP_SECRET, //put your FB APP SECRET KEY here
'cookie' => true
));
$session = $facebook->getSession();
if ($session)
{
//check to see if we have friends_birthday permission
$perms = $facebook->api('/me/permissions');
}
//we do this to see if the user is logged & installed
if (empty($session) || empty($perms['read_stream']))
{
//get url to oauth endpoint for install/login
$loginUrl = $facebook->getLoginUrl(array(
//put the URL to this page, relative to the FB canvas
//(apps.facebook.com) here vvv
'next' => 'http://apps.facebook.com/path_to_your_app/index.php',
'req_perms' => 'read_stream'
));
//use javascript to redirect. the oauth endpoint cant be loaded in an
//iframe, so we have to bust out of the iframe and load it in the browser
//and tell the oauth endpoint to come back to the fb canvas location
echo "<script>window.top.location='{$loginUrl}';</script>";
exit;
}
print_r($facebook->api('/me/home'));
print_r($facebook->api('/me/feed'));
I'm totally new in Facebook and I want to do the following
User will come to my page and automatically redirect to facebook for specifying login credentials.
After that he will get redirected to my page. I want to know the user's ID, display name and profile pic.
How can I do it using php?
thanks a lot!!!
Vladimir
Online
You can use the Facebook PHP SDK (see on github). So you will have something like :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
You then have to check if you have a valid access token by making an API call. If it does not raise any exception, then you have a valid access token :
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
You need then to display the login or logout link :
<?php if ($user): ?>
Logout of Facebook
<?php else: ?>
Login with Facebook
<?php endif ?>
All the info you ask for are stored in the the array $user_profile, you can trying a var_dump($user_profile) to see where they are.
you may want to check the example page of the Facebook PHP SDK which is well documented.
Hope that helps.