Send Facebook App Request/Invite using Graph Api - php

I have the following code that would get ur friends list using graph api
function getFriendsList(){
$response = $this->api('/me/friends');
return $response;
}
This returns friends id and name. using graph api
I then execute this code in my joomla module:
$fbClient = JFBConnectFacebookLibrary::getInstance();
$fbUserId = $fbClient->getUserId(TRUE);
//If FB User
if($fbUserId){
$f_list = $fbClient->getFriendsList();
after i get the array i display the firends picture
foreach ($f_list as $friend) {
for($i = 0; $i < count($friend); $i++)
{
echo '<img src="http://graph.facebook.com/'.$friend[$i]['id'].'/picture"><br/>';
}
}
}
This would create the profile photos of my friends.
My question is how do i create an onlick even so that when i click the photo i can send an individual facebook app request. ???

Sending Facebook app requests are not available via the graph api. You can use the app requests javascript dialog to send the request though, you would just need to specify the user's id in the "to" property as detailed in the documentation.
Sample function:
<script>
FB.init({ appId: '**appId**', status: true, cookie: true, xfbml : true });
function sendRequest(to) {
FB.ui({method: 'apprequests', to: to, message: 'You should learn more about this awesome site.', data: 'tracking information for the user'});
return false;
}
</script>
Then just wire an onclick for each image to something like onclick="return sendRequest('**friendId**');"

I had same problem. Though it is very late for answering question, it will help somebody. That's why answering this question.
Instead you can call this function in javascript:
it will give you all friends with photos. Also group of friends who are currently using same app. You can send request to any of them.
function sendRequestViaMultiFriendSelector() {
FB.ui({
method: 'apprequests',
message: "You should learn more about this awesome site."
});
}

Related

PHP error when trying to integrate facebook PHP SDK

I’m new to PHP and tying to set up a page as so users can login using Facebook PHP SDK and JavaScript SDK. I keep getting the fallowing error and I don’t seem to be able to find a solution.
I saw a similar post in here but I couldn’t give solution to the error.
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /homepages/9/d321009915/htdocs/kno_login/login.php on line 2
Here is my code:
<?php
echo '<div id='fb-root'></div>';
require_once("facebook.php");
$config = array();
$config['appId'] = 'some id';
$config['secret'] = 'something here';
$facebook = new Facebook($config);
?>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '293441190799565', // App ID
channelUrl : '//www.reyesmotion.com/kno_login/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked.
Learn more about options for the login button plugin:
/docs/reference/plugins/login/ -->
<?php
echo '<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>';
?>
Just change the outer single quotes to double
echo "<div id='fb-root'></div>";

I need help to setup facebook application

I have some problem to setup application on facebook, ok what is exactly problems?
Im load script
<script src="http://connect.facebook.net/en_US/all.js"></script>
And this
$(document).ready(function () {
// Pocetak callbacks funkicja
$("#oceni_fbPrijatelje").click(function() {
$("#sidecenter ,#sidedesno,#sidelevo").addClass("fb_over");
FB.init({
appId : 'xxxxxxxxx959971',
});
// 1. User se loguje i uzimamo neke informacija sa FB-a
FB.login(function(response) {
if(response.authResponse) {
accessToken = response.authResponse.accessToken;
signedRequest = response.authResponse.signedRequest;
// 2. Uzimamo informacija za logovane usere
FB.api('/me', function(response) {
facebook_id = response.id;
$.cookie("facebook_id", facebook_id);
// 3. Konacno iskace jebeni popup
FB.ui({
method: 'apprequests',
message: response.name + ' želi da vidi tvoje fotke na xxxxx.',
max_recipients: 10,
exclude_ids: [], // ovo nisam siguran dal radi :( ako radi dobro je.
title: 'Izaberi prijatelje i pozovi na xxxxx' ,
}, requestCallback);
} );
function requestCallback(response) {
// Handle callback here
$("#sidecenter ,#sidedesno,#sidelevo").removeClass("fb_over");
}
}
});
});
});
And popup is loaded fine on my site
So users can send invite to friends from my site on facebook.. but when users receive request on facebook simple this notification always is appers on their profil, you can click accept and facebook redirect to app url but request is still there simple cant accept this..
In the app option on facebook im setup
Canvas URL: http://mysite.com
So application will load my home page , but all works very strange and dont know why Application request always is stay on users profil...
You need to delete those requests.
According to Facebook:
It is the Developers' responsibility to delete a Request once it has
been accepted. For more information on how to delete a Request, please
see the Deleting Requests documentation.
When someone accept an invite he goes to app and the request id is added to the url. You can catch it from there and send a delete request.
$request_ids = explode(',', $_REQUEST['request_ids']);
function build_full_request_id($request_id, $user_id) {
return $request_id . '_' . $user_id;
}
foreach ($request_ids as $request_id) {
$full_request_id = build_full_request_id($request_id, $user_id);
$delete_success = $facebook->api("/$full_request_id",'DELETE');
}
You can find the full code and more information on deleting requests here:
http://developers.facebook.com/docs/requests/#deleting

After authorization, Facebook redirects to my website but userID is not set

A user visits my application's canvas page which directs them to authorize the application. It then redirects them to my website where I use the PHP SDK to look up information about the user.
Unfortunately the userID is returning 0 after the redirect from Facebook.
$fb_user = $facebook->getUser();
This ONLY happens immediately after authorization. If the user navigates to another page on my site, or reloads the page, the correct UID is returned and everything works as expected.
Could the redirect happen before Facebook completes the authorization? Does Facebook send the userID in the redirect? (Can that be configured?)
Work-around for this issue:
On my canvas page, I access the request_ids and append them to the query string of the url for the authorization request. The authorization will forward the request_ids parameter on to my website.
Javascript on an "authorize" link:
top.location = "http://www.facebook.com/dialog/oauth?client_id=MY_CLIENT_ID&scope=PERMISSIONS,MORE_PERMISSIONS&redirect_uri=http://www.MY_WEB_SITE.com/?request_ids=<?php echo $_REQUEST['request_ids']; ?>";
Then, on my website, I check for the Faecbook user_id. If that is 0, I look for the request_id parameter. If there, I make an api call to the graph to get the associated user_id. I use the user_id INSTEAD OF calling /me:
if ($fb_user===0){ //if Facebook doesn't return the user (the bug)
$request_ids = explode( ',', $_REQUEST['request_ids'], 1 ); //get the request_ids param, limit this to one since all request_ids will reference the same user_id
$request_info = $facebook->api('/' + $request_ids[0],'GET'); //get the request info
$fb_user_profile = $facebook->api('/' + $request_info['to']['id']); // $request_info['to']['id'] is the associated user_id (who the request was sent to)
}
else {
$fb_user_profile = $facebook->api('/me');
}
A call to /me returns nothing since Facebook isn't returning a logged-in user. (The bug.)
This is boiled down a little bit, but you get the idea...
We get this, the first page after the authorisation callback either gives no user, no perms or both. Should be logged as a bug
Adam's workaround works great, but due to some reasons it didn't fully suit me. My solution was to get all required user data from JS authorization and write it into php session. Hope, it will help someone.
JS auth function:
FB.login( function( response ) {
if ( response.authResponse ) {
FB.api('/me', function( response ) {
$.ajax({
url: 'action.php',
type: 'POST',
data: {
id: response.id,
name: response.name,
birthday: response.birthday,
location_id: response.location.id,
location_name: response.location.name,
gender: response.gender,
email: response.email
},
success: function() {
location.href = 'some-page.php';
}
});
});
} else {
alert("Please agree to the Facebook permissions.");
}
}, { scope:'user_location, user_birthday, email, publish_actions' } );
Action.php
session_start();
$_SESSION['user_info']['id'] = $_REQUEST['id'];
$_SESSION['user_info']['name'] = $_REQUEST['name'];
$_SESSION['user_info']['birthday'] = $_REQUEST['birthday'];
$_SESSION['user_info']['location']['id'] = $_REQUEST['location_id'];
$_SESSION['user_info']['location']['name'] = $_REQUEST['location_name'];
$_SESSION['user_info']['gender'] = $_REQUEST['gender'];
$_SESSION['user_info']['email'] = $_REQUEST['email'];

how to get the email address and the user Id in fbml using cake php

I have used one javascript function which is being called after login on facebook connect.
var FB_API_KEY = "api key";
var FB_CHANNEL_PATH = "xd_receiver.htm";
FB.init(FB_API_KEY, FB_CHANNEL_PATH, {permsToRequestOnConnect : "email"});
FB.Connect.ifUserConnected(FB_ConnectPostAuthorization);
function FB_ConnectPostAuthorization() {
var user_box = document.getElementById("user_id");
user_box.innerHTML =
"<span>"
+"<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
+"Welcome , <fb:name uid ='loggedinuser' useyou='false'></fb:name>"
+"You are signed in with your facebook account"
+"</span>";
FB.XFBML.Host.parseDomTree();
FB_RequireFeatures(["Api"], function(){
var api = FB.Facebook.apiClient;
var fb_uid = api.get_session().uid;
$.post('/users/fb_login/', {'fb_uid': fb_uid}, function(response) {
if (response != "yes") {
api.users_hasAppPermission("email", function(result) {
if (!result) {
FB.Connect.showPermissionDialog("email", redirect_to_done_page);
} else {
redirect_to_done_page()
}
})
} else {
redirect_to_done_page()
}
});
});
}
function redirect_to_done_page() {
window.location = "xyz";
}
I have added a facebook connect button which calls the above function.
I am only able to get the user name and profile pic in through fbml tags. How do I get the user email and user id.
Please guide me.
I don't think you can get email through fbml, because with it you can just show it and there is no point.
Actually you need to have a PHP part of the FB API which you can help you with that task.
Although you can use this very good plugin for CakePHP. It's really easy to get it working and you can get the user's email for sure.
I've never used the FB api,but I'd be surprised if they gave out emails. Oh... it's Facebook. I eat my words.

Facebook Graph API, how to get users email?

I'm using the Graph API, but I can't figure out how to get a logged-in users email address.
The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday"
All well and good, but how do I access that info?
This is what I have so far:
$json = $facebook->api('/me');
$first = $json['first_name']; // gets first name
$last = $json['last_name'];
The only way to get the users e-mail address is to request extended permissions on the email field. The user must allow you to see this and you cannot get the e-mail addresses of the user's friends.
http://developers.facebook.com/docs/authentication/permissions
You can do this if you are using Facebook connect by passing scope=email in the get string of your call to the Auth Dialog.
I'd recommend using an SDK instead of file_get_contents as it makes it far easier to perform the Oauth authentication.
// Facebook SDK v5 for PHP
// https://developers.facebook.com/docs/php/gettingstarted/5.0.0
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.4',
]);
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
$response = $fb->get('/me?locale=en_US&fields=name,email');
$userNode = $response->getGraphUser();
var_dump(
$userNode->getField('email'), $userNode['email']
);
Open base_facebook.php
Add Access_token at function getLoginUrl()
array_merge(array(
'access_token' => $this->getAccessToken(),
'client_id' => $this->getAppId(),
'redirect_uri' => $currentUrl, // possibly overwritten
'state' => $this->state),
$params);
and Use scope for Email Permission
if ($user) {
echo $logoutUrl = $facebook->getLogoutUrl();
} else {
echo $loginUrl = $facebook->getLoginUrl(array('scope' => 'email,read_stream'));
}
Just add these code block on status return, and start passing a query string object {}. For JavaScript devs
After initializing your sdk.
step 1: // get login status
$(document).ready(function($) {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
console.log(response);
});
});
This will check on document load and get your login status check if users has been logged in.
Then the function checkLoginState is called, and response is pass to statusChangeCallback
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
Step 2: Let you get the response data from the status
function statusChangeCallback(response) {
// body...
if(response.status === 'connected'){
// setElements(true);
let userId = response.authResponse.userID;
// console.log(userId);
console.log('login');
getUserInfo(userId);
}else{
// setElements(false);
console.log('not logged in !');
}
}
This also has the userid which is being set to variable, then a getUserInfo func is called to fetch user information using the Graph-api.
function getUserInfo(userId) {
// body...
FB.api(
'/'+userId+'/?fields=id,name,email',
'GET',
{},
function(response) {
// Insert your code here
// console.log(response);
let email = response.email;
loginViaEmail(email);
}
);
}
After passing the userid as an argument, the function then fetch all information relating to that userid. Note: in my case i was looking for the email, as to allowed me run a function that can logged user via email only.
// login via email
function loginViaEmail(email) {
// body...
let token = '{{ csrf_token() }}';
let data = {
_token:token,
email:email
}
$.ajax({
url: '/login/via/email',
type: 'POST',
dataType: 'json',
data: data,
success: function(data){
console.log(data);
if(data.status == 'success'){
window.location.href = '/dashboard';
}
if(data.status == 'info'){
window.location.href = '/create-account';
}
},
error: function(data){
console.log('Error logging in via email !');
// alert('Fail to send login request !');
}
});
}
To get the user email, you have to log in the user with his Facebook account using the email permission. Use for that the Facebook PHP SDK (see on github) as following.
First check if the user is already logged in :
require "facebook.php";
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
If he his not, you can display the login link asking for the email permission :
if (!$user) {
$args = array('scope' => 'email');
echo 'Login with Facebook';
} else {
echo 'Logout';
}
When he is logged in the email can be found in the $user_profile array.
Hope that helps !
Assuming you've requested email permissions when the user logged in from your app and you have a valid token,
With the fetch api you can just
const token = "some_valid_token";
const response = await fetch(
`https://graph.facebook.com/me?fields=email&access_token=${token}`
);
const result = await response.json();
result will be:
{
"id": "some_id",
"email": "name#example.org"
}
id will be returned anyway.
You can add to the fields query param more stuff, but you need permissions for them if they are not on the public profile (name is public).
?fields=name,email,user_birthday&token=
https://developers.facebook.com/docs/facebook-login/permissions
You can retrieve the email address from the logged in user's profile. Here is the code snippet
<?php
$facebook = new Facebook(array(
'appId' => $initMe["appId"],
'secret' => $initMe["appSecret"],
));
$facebook->setAccessToken($initMe["accessToken"]);
$user = $facebook->getUser();
if ($user) {
$user_profile = $facebook->api('/me');
print_r($user_profile["email"]);
}
?>
First, activate your application at the Facebook Developer center. Applications in development mode are not allowed to retrieve the e-mail field.
If the user is not logged in, you need to login and specify that your application/site will need the e-mail field.
FB.login(
function(response) {
console.log('Welcome!');
},
{scope: 'email'}
);
Then, after the login, or if the user is already logged, retrieve the e-mail using the Facebook API, specifying the field email:
FB.api('/me', {fields: 'name,email'}, (response) => {
console.log(response.name + ', ' + response.email);
console.log('full response: ', response);
});
https://graph.facebook.com/me
will give you info about the currently logged-in user, but you'll need to supply an oauth token. See:
http://developers.facebook.com/docs/reference/api/user
The email in the profile can be obtained using extended permission but I Guess it's not possible to get the email used to login fb. In my app i wanted to display mulitple fb accounts of a user in a list, i wanted to show the login emails of fb accounts as a unique identifier of the respective accounts but i couldn't get it off from fb, all i got was the primary email in the user profile but in my case my login email and my primary email are different.
Make sure your Facebook application is published. In order to receive data for email, public_profile and user_friends your app must be made available to public.
You can disable it later for development purposes and still get email field.
The following tools can be useful during development:
Access Token Debugger: Paste in an access token for details
https://developers.facebook.com/tools/debug/accesstoken/
Graph API Explorer: Test requests to the graph api after pasting in your access token
https://developers.facebook.com/tools/explorer
Make sure to fully specify the version number of the API as something like "v2.11" and not "2.11"
I'm not sure what it defaults to if this is incorrect, but I got some odd errors trying to just retrieve the email when I missed the v.
For me the problem with collecting user's email addres on PHP side (getGraphUser() method) was, that the default behavior of facebook-rendered button (on WEBSIDE side, created with xfbml=1) is to implicity calling FB.login() with the scope NOT including "email".
That means you MUST:
1) call
FB.login(....,{scope: email})
manifestly, creating your own button to start login process
OR
2) add scope="email" attribute to the xfbml button
<div class="fb-login-button" data-size="large" data-button-type="continue_with" data-
layout="rounded" data-auto-logout-link="false" data-use-continue-as="true" data-
width="1000px" scope="email"></div>
to be able to collect email address on PHP side.
Hope it helps.

Categories