I am currently developing in social engine in zend framework.
Social engine has this built in plugin that let you stay connected to facebook even you are logged out to facebook site. So when you're posting status in my social engine site, it will still be posted on your wall even you're not logged in facebook site(I mean here in facebook.com) but I don't know how to do this in my custom widget in social engine that's why I thought I should just use the Facebook SDK.
I was successful using Facebook SDK but the problem is that it asks the user to login every time the script detects that the user is not logged in facebook.com .
How to solve this??
I can actually retrieve the user details like openid, facebookemail. Yeps, that's only the thing I know :(
I've developed same kind of application in Zend-Framework. I've used Facebook/PHP-SDK with oAuth 2.0.
In this case you need to save access tocken in your database for the particular user. and with that access token you can get any data as well as post to. Yes for that you need to grant necessary permission from the user for your Facebook APP.
Here is the two function that I've used in my application to fetch the access token , extended it and store in the database.
/**
* Getting User Acess Tocken , extended it and save it in to database......
*/
public function getAccessToken($user_id,$fb_account_id)
{
$access_token=$this->facebook->getAccessToken();
$extended_access_token=$this->getExtendedAccessToken($access_token);
/**
* To save Access tocken and other necessary option
*/
$usr_bus_model = new Application_Model_UserBusinessAccounts;
$usr_bus_model->loadAccount($user_id,'Facebook',(int)$fb_account_id);
$usr_bus_model->details=$extended_access_token;
$usr_bus_model->save();
return $extended_access_token;
}
/**
* Exrending User Acess Tocken.....
*/
public function getExtendedAccessToken($access_token)
{
$token_url="https://graph.facebook.com/oauth/access_token";
$params=array('client_id'=>self :: appId,'client_secret'=>self :: appSecretId,'grant_type'=>'fb_exchange_token','fb_exchange_token'=>$access_token);
$response = $this->curl($token_url,$params);
$response = explode ('=',$response);
$response = explode ('&',$response[1]);
$response = $response[0];
return $response;
}
Hope it helps.
Related
I am integrating Facebook login in my site. I am using Facebook SDK 4.0. My app API version is 2.4. I am trying to get basic profile info when user successfully log in with Facebook. But problem is - I am able to get only user id and his full name. Other stuffs like first name, last name, gender etc. are not being received. Also of course I need email of the person and user profile picture later on some stage. Here is my working code which is printing only name and id:
<?php
// start session
session_start();
$app_id = 'app_id'; // Facebook App ID
$api_secret = 'app_secret'; // Facebook App Secret
$required_scope = 'public_profile, publish_actions, email'; // Permissions required
$redirect_url = 'site_url/index.php'; // FB redirects to this page with a code
require_once __DIR__ . "/facebook-php-sdk-v4.0/autoload.php";
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRedirectLoginHelper;
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication($app_id,$api_secret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( $redirect_url );
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>";
echo print_r( $graphObject, 1 );
echo "</pre>";
} else {
// show login url
echo 'Login';
}
Following info is printed:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[name] => Fname Lname
[id] => ID
)
)
You can see that I have already given scope parameter. But its not helping me. Then I started search on STO and found some solution which suggest us to add following line of code if you are using API v2.4 to explicitly mention the fields you want:
$request = (new FacebookRequest($this->session, 'GET', '/me/?fields=friends,id,name,birthday,email,picture,gender,location,address,email,hometown'))->execute()->getGraphObject()->asArray();
But when I used above code, it again didn't work instead i got blank screen not even id and name as before.
I also visited Facebook developer docs but they are so long, complex and not enough user friendly a developer can follow them easily in short time.
I think there is a lot of confusion regarding Facebook login. There are so many articles on web and each illustrating their own method. Some uses PHP and other uses JavaScript too which popups the login window. Honestly speaking I am very confused at this level and can't understand which is the best, recommended and working method of accomplish the task. Thus I'm in search of following questions:
I want help in making my above code working so that it can fetch all info about user including email and profile pic too.
Some method of login with Facebook takes user full login page and some other displays a popup for login and user remains on the same page after successful login which initially generated the popup window. How both are different?
What is best practice of login with Facebook. Also which SDK and Graph API version one should use?
While Generating a login URL you must pass on the scopes for which you seek permission. You can generate this by modifying,
echo 'Login';
to
echo 'Login';
This is just a example and may not cover all your requirement. You may have to add more scopes as per your requirement.
Above three scopes are permitted by default and you don't have to go through an app verification by facebook. But if you add any other scope, you may have to go through a an approval process before you can go live with an app.
And of-course since v2.4 you must explicitly ask for each field. Before email was supplied by default with /me, not any more. you must add it like,
/me?fields=id,first_name,last_name,friends,email
Login with a facebook will not ask for a login if user is already logged in and will go to permission screen straight away if user has not given permission to this app before. If user has already given all permission and he is already logged in facebook, clicking on login with facebook link will redirect user to redirect handler straight away.
I suggest, you should always use latest stable facebook apis.
UPDATE
Just realized that facebook allows account creation with a phone-number. So, if user has created an account with phone-number instead of an email, in api response you will receive phone-number in place of email like below,
...
'email' => '465454654654'
...
So, your code must handle this situation.
im building a facebook app and i want to notify the user
https://developers.facebook.com/docs/games/notifications
im using facebook php sdk
what i do:
user auths the app and accepts permission
i get the accesstoken like:
$facebook->getAccessToken()
and then i generate a long-time token like:
public function generateLongTimeToken($token){
$long_time_token_req_body = array(
"grant_type"=>"fb_exchange_token",
"client_id"=>$this->facebookOptions["appId"],
"client_secret"=>$this->facebookOptions["secret"],
"fb_exchange_token"=>$token
);
$query = http_build_query($long_time_token_req_body);
$lttreq = file_get_contents("https://graph.facebook.com/oauth/access_token?".$query);
$lttresp = parse_str($lttreq, $output);
if ( array_key_exists("access_token", $output)){
$this->logger->info("Facebook-app: Successfuly generated long_time_token");
return $output["access_token"];
}else {
$this->logger->err("Facebook-app: generating oauth long_time_token failed \n".$lttreq);
return false;
}
}
some later i use this token for background processes to post on the users wall and them all work fine
now i also want to notificate the user like that :
public function notifyUser($message,$facebookClientId,$token){
$appsecret_proof= hash_hmac('sha256', $token, $this->facebookOptions["secret"]);
$req_body = array(
"access_token"=>$token,
"appsecret_proof"=>$appsecret_proof,
"href"=>"/index",
"template"=>$message,
"ref"=>"post"
);
$query = http_build_query($req_body);
$url = "https://graph.facebook.com/".$facebookClientId."/notifications?".$query;
$lttreq = file_get_contents($url);
return $lttreq;
}
but when i try to notify the user i always get empty data back
when i open the url in browser with all parameters facebook returns the same
{
data: [ ]
}
so i have no idea whats going on,when i look on SO i only find about people posting to sites but i want to notify the user itself
thanks for any help
First, from the Facebook docs:
Currently, only apps on Facebook.com can use App Notifications.
Notifications are only surfaced on the desktop version of
Facebook.com.
Also, an App Token is needed, not a User Token.
Btw, file_get_contents is very bad, use CURL for Facebook. May be another reason why it does not work. A basic example of using CURL with the Facebook API: http://www.devils-heaven.com/extended-page-access-tokens-curl/
Additional Info: I recently wrote a blogpost about App Notifications, it is in german but the small code part may be interesting for you: http://blog.limesoda.com/2014/08/app-notifications-facebook-apps/
When I try to update the profile description of a soundcloud account via their php sdk, I get a 403 error every time. The app is authenticated and I am able to do things like place comments, but I'm not able to update anything on the profile (particularly the description field).
I'm using the standard code, found in their official documentation:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('YOUR_ACCESS_TOKEN');
// get the current user
$user = json_decode($client->get('me'));
// update the user's profile description
$user = json_decode($client->post('me', array(
'description' => 'I am using the SoundCloud API!'
)));
print $user->description;
Please help me find out where the error comes from, because I'm all out of ideas.
Our bad, the user documentation that you point to there had two problems:
Updates to the user resource should use the PUT method, not POST.
Arguments need to be namespaced properly.
I've modified the documentation to fix these two problems. New code sample:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('ACCESS_TOKEN');
// get the current user
$user = json_decode($client->get('me'));
// update the user's profile description
$user = json_decode($client->put('me', array(
'user[description]' => 'I am using the SoundCloud API!'
)));
print $user->description;
Hope that helps and sorry again for the confusion. Let me know if you run into any more problems.
To update user related information you need to login to Sound Cloud as user and then authenticate your application to use your personal data, else you will get 403 for all user related information while updating / delete. For posting any comments you don't need this authentication
http://developers.soundcloud.com/docs#authentication
Refer
Getting Information about the Authenticated User
Once the user has signed into SoundCloud and approved your app's authorization request, you will be able to access their profile and act on their behalf. We have provided a convenient endpoint for accessing information about the authenticated user.
I am building a little website for an event. The idea is to add the attending persons from the facebook event to this website. The problem is that the attending service needs an access_token. I don't want a user to log in to the app, I just want to use the app access_token. But this doesn't seem to work.
I have the following php code for receiving the access_token:
// get facebook auth_token
$FB_APP_ID = '****';
$FB_APP_SECRET = '***';
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=" . $FB_APP_ID . "&client_secret=" . $FB_APP_SECRET . "&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
parse_str($app_token); // creates: $access_token
In javascript I am using the following code:
/**
* Gets all the attending Users
* #param function callback: the function to call, when data loading is ready
* #param function callback: the function to call, when data loading is broken
* #return void
*/
this.getAttending = function(callback, errorHandler)
{
FB.api('/' + this.eventId + '/attending', function(response) {
if(response.error) {
errorHandler(response.error['message']);
} else {
callback(response.data);
}
} , {access_token: facebook.accessToken} );
}
I receive the error:
Invalid OAuth access token.
The access token looks like:
111737995591905|l9e3niEMM1RsIUhwHZv3pn3c19M
THe user access token looks like:
145634995501895|2.AQBcWfbvdzhloLYc.3600.1312138800.1-1146858041|cjCkHZqquyyFyX2dY0q2YCaSyy0
When i try to use the user access token, everything works fine. But when I hardcode the token, this will not work for other users. When I try the token that the server parsed for me, I get die invalid token action. Does somebody knows a solution for this?
It is a public event, and I don't want the user to login before he/she knows who is attending?
Is this possible at all?
Thanx!
Did you encode the token while hard coding? | should be %7C .
Cant think of anything else that might have gone wrong for the moment
Why not get an access token for yourself and then hard code that in your application (assuming it is running on a secure server where no one else can steal the credentials). Then anyone visiting the page can view the guest list using your own access token which is permissioned to view the list.
The client_credentials grant type is not meant for accessing user data, only application data. I don't know how the rest of the application works but I'm assuming that you need a user access token to see user data.
The way i got around this was designating the offline_access permission, it generates an access token that never expires so you can use it indefinitely. You would then in theory authorize only your Facebook account to have the event data pulled from it. You could then view and serve your event details to your website no problem.
I'm able to update the status on my PROFILE wall using this code:
require_once 'facebook-platform/php/facebook.php';
$facebook = new Facebook('APP API KEY','APP SECRET KEY');
$user_id = 'MY USER ID';
$facebook->api_client->users_setStatus('This is a new status');
...after authorizing using this address:
http://facebook.com/authorize.php?api_key=MYAPPAPIKEY&v=1.0&ext_perm=publish_stream
This code, however, does not work to update the status on my Facebook PAGE Wall. Are there additional parameters that I can add to the authorize.php url to specify authorizing the PAGE and not just my profile?
Or, are there better ways to post updates to Fan Page Walls?
Thanks!
I solved the problem by consulting the Facebook desktop application documentation (even though this is a web application).
I first had to authorize offline access with this url (replacing 'MYAPIKEY'):
http://www.facebook.com/login.php?api_key=MYAPIKEY&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access
Then, I needed to grant 'publish_stream' permissions to the PAGE with this url (replacing 'MYAPIKEY' and 'THEPAGEID'):
http://www.facebook.com/connect/prompt_permissions.php?api_key=MYAPIKEY&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=popup&ext_perm=publish_stream&enable_profile_selector=1&profile_selector_ids=THEPAGEID
I could then use the following code to publish to the Fan Page wall:
require_once 'facebook-platform/php/facebook.php';
$facebook = new Facebook(MYAPIKEY, MYAPISECRET);
try{
$facebook->api_client->stream_publish('INSERT_STATUS_HERE',null,null,null,'THEPAGEID');
}catch(Exception $o ){
print_r($o);
}
Based on the above, i tried out a couple of querystring parameters on the graph API authorize URL, and it appears this works:
https://graph.facebook.com/oauth/authorize?client_id=[APP_ID]&redirect_uri=[REDIRECT_URL]&scope=publish_stream&enable_profile_selector=1&profile_selector_ids=[PAGE_IDS]
EDIT: Never mind, the above displays all the UI correctly, but still get the "(#200) The user hasn't authorized the application to perform this action" error --- it's clear it doesn't work because the access token contains my USER id but not the page's ID.