Facebook PHP API How to get current user profile_id? - javascript

After login with FB JavaScript API, how can I get the profile_id of that user? ('/me'), please help...I used many hours on google and facebook official dev site still no luck on this. How come this kind of simple user profile id also didn't provide in API documentation...is me noob or facebook?.
sesssion_start();
require_once 'autoload.php';
use Facebook\FacebookSession;
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;
use Facebook\FacebookJavaScriptLoginHelper;
FacebookSession::setDefaultApplication( 'APP_ID','APP_SECRET' );
$helper = new FacebookJavaScriptLoginHelper();
$session = new FacebookSession($_POST['access_token']);
$request = new FacebookRequest(
$session,
'GET',
'/me'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
$profile_id = $graphObject->getProperty('profile-id'); // HOW TO GET PROFILE ID??
P.S: I want profile id not user id...

I think You have to get user_id
A user represents a person on Facebook. The /{user-id} node returns a single user.
Here is the reference of Graph Api .. Check it in detail according to your requirement
https://developers.facebook.com/docs/graph-api/reference/user
For profile-id
check that link of Graph Api
Reference:
Profile /{profile-id}
A profile can be a:
User
Page
Group
Event
Application
The profile object is used within the Graph API to refer to the generic type that includes all of these other objects.
The individual reference docs for each profile type should be used instead.
Fields
When something has a profile, Graph API returns the fields for that object.
https://developers.facebook.com/docs/graph-api/reference/v2.5/profile/

Related

Parse Query Include method not including all data expected

I am doing a query onto a class where I have a pointer to a User.
I do query.include('byUser') and when I log out the query result it's shown but when I try to get a specific attribute like email. It doesnt exist.
I also first thought it was odd that I have to get the User details by doing:
const userDetails = query.get("byUser").attributes;
Do I have to do .attributes? And also why isn't the email showing up. Everything else seems to show up in the attributes section.
Thanks
Please note that in parse, you can not query the email field of other users. you can see the email field only if you are the signed in user. This is a security mechanism.
A. If you want to get the email field for a user object, you can do two things:
Pass the user session token to the query.
new Parse.Query(Parse.User).get(<userId>,{sessionToken:<userSessionToken>});
Use master key. (Note: You have to set the master key before.)
new Parse.Query(Parse.User).find({useMasterKey:true});
B. Your include method is correct and it it will fetch the byUser object. You do not need to use .attributes.
UPDATE:
You can also set a publicEmail field in your User class which will not be filtered out by parse-server. to automate this, you can write a cloud code.
Cloud Code Example (on parse-server V 3.0.0 and above):
PLEASE NOTE THAT YOU CAN NOT USE ASYNC FUNCTIONS FOR PARSE-SERVER < V 3.0.0
Parse.Cloud.beforeSave(Parse.User, async req=>{
if (!req.original && !req.master && req.object.get('email')){
req.object.set('publicEmail',req.object.get('email'));
}
})
Now, if new user sign up, this cloud code will automatically adds a new field to the user object publicEmail which is not filtered by parse-server.

How to use the WP REST API with a custom endpoint using the Javascript library?

I have a custom endpoint which does nothing but return a test string. I can reach that endpoint by navigating to mydomain.com/wp-json/mytools/v1/method/get_user_data and it correctly returns my test string, but, I want to be able to reach that endpoint using Javascript, and, I read that the wp-api handles authentication automatically so I should be able to get a current logged in user with this method.
What I need is to be able to use something like wp.api.mytools.method.get_current_user and get the information for the currently logged in user. Is this even possible?
This is the way I created the endpoint:
register_rest_route( 'mytools/v1', '/method/(?P<method>[\w]+)', array(
'methods' => 'GET',
'callback' => 'invoke_method',
));
And this is the invoke_method function:
function invoke_method( WP_REST_Request $request ) {
return wp_get_current_user();
}
This functionality is already implemented by WordPress at the WP_REST endpoint '.../wp-json/wp/v2/users/me. In addition to the logged-in cookie WP REST authentication requires a nonce specified by a query argument '_wpnonce'. The value of this nonce is generated by calling wp_create_nonce( 'wp_rest' ). A normal WordPress front-end page will include the script .../wp-includes/js/api-request.js. This script will define a global wpApiSettings.nonce which will contain this nonce so you can use the request '.../wp-json/wp/v2/users/me?_wpnonce=' + wpApiSettings.nonce. So, you can use jQuery.get().
jQuery.get(
'.../wp-json/wp/v2/users/me?_wpnonce=' + wpApiSettings.nonce,
function( response ) {
var userData = JSON.parse( response );
) }
);
If you only want to get the current user I don't think you need Backbone.js. Backbone.js will synchronise collections and models using CRUD and you are not doing any of this.
Overall, yes, it IS possible.
Specifically, if wp-api if you're referring to the node-wpapi JS library, then yes it does handle authentication. Otherwise, you will need to implement Authentication yourself, using Cookie, Nonce, Basic-Auth or JWT.
For second part, it is definitely possible to use something like wp.api.mytools.method.get_current_user to get information. What you'll need is a client library (node-wpapi), and extend it to include your classes and functions, such as mytools and method.
Hope this helps to clarify

How to get your website visitors to follow twitter accounts from your website

I am new on this forum, so accept my apologies if my question is inappropriate or is not clear enough.
I have a website where Twitter users are listed having follow button against each user, but when visitor click on 'follow' button then that user get followed from my Twitter account (which have app that is being used for authentication) instead of visitors account. so basically i want these accounts to be followed by visitors twitter account not mine.
when user clicks on follow button an ajax call is made to send username to page where following code runs to get that user followed.
<?php
ini_set('display_errors', 1);
require_once('lib/TwitterAPIExchange.php');
$uname=$_REQUEST['name'];
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "XXXXXX-XXXXXXXXXX",
'oauth_access_token_secret' => "XXXXXXXXXX",
'consumer_key' => "XXXXXXXXXX",
'consumer_secret' => "XXXXXXXXXX"
);
// Choose the url you want from the docs, this is the users/show
$url = 'https://api.twitter.com/1.1/friendships/create.json';
// The request method, according to the docs, is GET, not POST
$requestMethod = 'POST';
$varl=$uname;
// Set up your get string, we're using my screen name here
//$getfield = '?screen_name='.$varl;
$postfields = array(
'screen_name' => $varl
);
// Create the object
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
TwitterAPIExchange.php is php wrapper for twitter api request should i share that too ? Thanks in advance if anyone can help.
Don't do that from the server side. It's not necessary or appropriate.
Use Twitter web intents for this. They allow users of your site to perform a variety of actions using their logged-in Twitter account, including posting statuses, retweeting statuses, and following other Twitter users.

Facebook php api in Ajax facebox

I'm trying to load some php fql calls in to an ajax facebox (its like lightbox), i include a file with the following code in, but it does not work without the redirect ($my_url), is there any way to make the code ignore the redirect? Or do i need to use the javascript sdk from facebook?
$app_id = 'APP ID';
$app_secret = 'APP SECRET';
$my_url = 'LINK HERE';
$code = $_REQUEST["code"];
$bruger = "me()";
//auth user
if(empty($code)) {
$dialog_url = 'https://www.facebook.com/dialog/oauth?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url) ;
echo("<script>top.location.href='" . $dialog_url . "'</script>");
}
$token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
. $app_id . '&redirect_uri=' . urlencode($my_url)
. '&client_secret=' . $app_secret
. '&code=' . $code;
// response is of the format "access_token=AAAC..."
$access_token = substr(file_get_contents($token_url), 13);
Have you tried using the Facebook PHP SDK? I highly recommend moving away from depreciated FQL as once you get to grips with the new API it is very easy to use
Once you have set up $facebook you can then just make API calls with $facebook->api('/query');
I'm not 100% sure what information you are trying to retrieve from your question however but I have put together a Lightbox / Facebook myself, even using tag data to pick people out of the picture so feel free to provide more detail and I will try to provide a more comprehensive answer
EDIT:
In order to build queries and test data returned you can use the Graph API Explorer and construct the query you want to test against your own Facebook Application
I'm trying to fetch friendlist
After you've setup $facebook then you can retrieve your friends by using
$fb_friends = $facebook->api("/me?fields=friends");
Next:
50 latest tagged photos and likes
To retrieve the latest 50 tagged photos and likes you'll need to do:
$fb_photos = $facebook->api("/me?fields=photos.limit(50)");
$fb_likes = $facebook->api("/me?fields=likes.limit(50)");
// I should mention that each time api() is called, the server makes a HTTPS request to Facebook, so it is worth condensing api queries to reduce load time:
$fb_data = $facebook->api("/me?fields=photos.limit(50),likes.limit(50)");
$fb_photos = $fb_data['photos'];
$fb_likes = $fb_data['likes'];
If you want the latest 50 of photos and likes chronologically sorted, you can array_merge() the two arrays and use a subval sort function for created_time, then just take the first 50.
I'm going to insert all the basic info into mysql (stuff like name, facebook id, email ect.) I'm going to use the fb id inserted into myslq, to view the friendlist, likes and photos
Right then, when you user logs on you will need to request extended permissions from them to access data like photos, likes and friends. When your user logs into facebook with the link you provide to them on your website, you need to call
$loginUrl = $facebook->getLoginUrl(array( 'scope' => 'read_stream,user_likes,user_photos,friends_photos,user_friends'));`
The scope is defined by the permissions stated here
Once you have been granted access to that information by the user you can retrieve profile information with $user = $facebook->api("/me"); and store the facebook ID, name etc in your database.
To get a better look at the data you'll be handing for photos then make sure that you click Get access token at the top of the page and grant permission to access photos and likes
Any more questions feel free to ask and I will provide more detail, hope that helps mate!

How to programmatically subscribe a user to a google calendar using javascript?

Hey i'm able to authenticate and authorize a user with the javascript API for google calendar. what i want to do next is subscribe that user to a public calendar. I was thinking i could just call the google.gdata.calendar.CalendarEntry constructor with the id of the calendar but that didn't work
var entry = google.gdata.calendar.CalendarEntry("idOfCalendar");
i also tried creating an instance of a entry id with google.gdata.atom.Id("idOfCalendar"); and adding that to the CalendarEntry constructor. Using the set methods didn't work either.
I use the InsertEntry method to add the entry but i get the following error
Error: Valid calendar id must be supplied for adding calendar to favorites list in allcalendars projection.
I can access the events of this calendar using google.gdata.calendar.CalendarEventQuery()
The google api for javascript doesn't give a lot of examples anyone know the answer to my problem or a good resource for working with the google calendar api? do you think i should be using php or jason instead?
** Edit
I found an example of what I want in the Java Api link so i tried
function addSubscriptionToCalendar() {
var feedUri = "http://www.google.com/calendar/feeds/default/allcalendars/full";
var calendarEntry = new google.gdata.calendar.CalendarEntry();
calendarEntry.setId("nhl_21_%54oronto+%4daple+%4ceafs#sports#group.v.calendar.google.com");
calendarService.insertEntry(feedUri, calendarEntry, function(){alert("calendar added")}, handleError);
}
but i got the same error
You should be using owncalendars feed to modify/add calendar entry for the authenticated user not allcalendars.
Sounds like your calendar id is invalid. The id from your second example appears to be URL encoded. Try using the decoded value:
nhl_21_Toronto Maple Leafs#sports#group.v.calendar.google.com
The gdata API for calendars has been switched off; the new way to do this is via: https://developers.google.com/google-apps/calendar/v3/reference/calendarList/insert

Categories

Resources