Socialite facebook driver get only first name - facebook

I know that this question is asked before but read before marking as dublicate.
So I am trying to get user's first name using Socialite 3.0, however I am not able to get it. I am getting the following error:
Undefined index: first_name
I know it was possible before but not anymore. Is it impossible now? According to the Facebook's documentation, I should be able to get it.
I tried pretty much every possible answer I found by googling and from StackOverflow without success.
This is what I did:
$providerUser = Socialite::driver('facebook')->stateless()->userFromToken($request->fb_token);
$attributes = ['first_name' => $providerUser->user['first_name']];
return $attributes;
I also tried like this:
$driver = Socialite::driver('facebook')
->fields([
'first_name'
]);
$user = $driver->userFromToken($request->fb_token);
return $user;
which gives me the following error:
The Response content must be a string or object implementing
__toString(), "object" given.

I finally did manage to get it working. So I had to do the following:
$providerUser = Socialite::driver('facebook')
->fields([
'first_name'
])->stateless()->userFromToken($request->fb_token);
$first_name = $providerUser->user['first_name'];
return $first_name;

Related

I POST my image by python through WP REST API, but the response is just the array of items in media library

First of all, I have found out what's wrong with my python code, but I really want some one to tell me how it popped out because I'm just a noob amateur.
I tried to post my album collected on my wordpress by using my python script as usual, but I got an unexpected throw-out when it start to image upload. My img upload function just like this:
def restImgUL(imgPath,imgName,token):
url='http://www.rainloongmusic.com/wp-json/wp/v2/media/'
file_extension = os.path.splitext(imgPath)[-1]
img = open(imgPath,'rb')
imgName = imgName.replace(";","")
_json = {
"title":imgName,
'caption': imgName,
"alt_text":imgName,
"description":imgName,
"status":"publish"
}
image_name = f"{imgName}{file_extension}"
headers = { 'Content-Type': '','Content-Disposition' : 'attachment; filename=%s'%image_name.encode("utf-8").decode("latin1"),"Authorization":"Bearer %s"%token}
res = requests.post(url=url,data=img,headers=headers,json=_json)
rrr = res.json()
if "id" in rrr:
return rrr["id"]
else:
print(rrr)
sys.exit()
The wrong response is an array include items in my first page of media library. I found some clues in rest api handbooks. If I attempt to GET /wp/v2/media, response will be like what I've recieved. But I use POST type request in my python code, I don't really understand what happened there. I have no choice but to try some other methods to bypass this problem. I tried to make a new endpoint and write something like this:
add_action( 'rest_api_init', function () {
register_rest_route( 'rlra/v1', '/media', array(
'methods' => 'POST',
'callback' => 'cmupload',
) );
} );
function cmupload(){
return "This is a test!!!"
}
However, I got rest_no_route when I POST to it. I changed the methods to GET eventually, and got the right text from my server. I think maybe something changed my POST request into a GET one? I tried to figure out with Charles, and found my connection with 302 permanent redirect. So I check my request link and change http into https, everything works.
So, could anyone tell me why a 302 redirect will change my POST request into GET, I've been worn-out due to the lost letter "s" in these days.

Not able to fetch contacts from yahoo api

I've included yahoo API to read user's yahoo contacts. However it's not fetching any data.
Please have a look at my code:
session_start();
include_once 'config.php'; //This file contains consumer key & all data
require_once ('Yahoo.inc'); //This is a standard Yahoo file, just copied it
$session = YahooSession::requireSession($consumer_key,$consumer_secret,$app_id);
if (is_object($session))
{
$user = $session->getSessionedUser(); //This is NOT NULL
$profile = $user->getProfile(); //This is NULL
$name = $profile->givenNme;
$guid = $profile->guid;
$contacts=$user->getContacts()->contacts; //This is NULL
if($contacts==NULL){
echo "No contacts";
}
}
Somehow getProfile() & getContacts() are not working at all, anyone can help spot the mistake?
Please check this thread: yahoo oauth $user->getProfile(); returns null. It solves the problem. You need to switch over to the new API. Otherwise, you may experience this kind of problems.

Get user's event list

I just started to use FQL, and I was trying some FB examples that worked fine.
But I try to make my own exapmles, but didn't work...
I was trying to get the list of activities of a loged user, with this FQL code:
$f = new Facebook($configure); //configure is already ok
$user_id = $f->getUser();
if($user_id){
$ret = $f->api(array('method' => 'fql.query',
'query' => 'select eid, uid, rsvp_status
from event_member
where uid = '.$user_id.';'));
//I splitted the query here because is too long.
//In my PHP code is all in one line
print_r($ret);
}
but it returns a empty array.
I try it with my FB profile, even I accepted some incoming events, but I still get an empty list...
What am I doing wrong?
Thanks!
Well the query is perfectly right. I got the result using this.
Have you set the permissions: user_events and friends_events for the user?
Well, I fix the problem...
The problem was in the redirect. I changed it to:
header("Location: ".$f->getLoginUrl(array('scope' => 'user_events, friends_events', 'redirect_uri' => 'mywebsite')

Facebook Graph API - Get ID from Facebook Page URL

I have seen this question but what I want is different.
I want to get the Facebook ID not from a general URL (and therefore conditional if it has Like button or not). I want to get the Facebook ID given a Facebook page using the Graph API.
Notice that Facebook pages can have several formats, such as:
http://www.facebook.com/my_page_name
http://www.facebook.com/pages/my_page_name
http://www.facebook.com/my_page_ID
I know I could do some regex to get either the my_page name or my_page_ID, but I am wondering if any one know if GraphAPI is supporting what I want.
It seems to me that the easiest solution to what you describe is to just get the id/name from the url you have using lastIndexOf("/") (which most languages have an equivalent for) and then get "https://graph.facebook.com/" + id.
The data that this url returns has the id (i.e.: 6708787004) and the username (i.e.: southpark), so regardless of which identifier you use (what you extract from the url using lastIndexOf), you should get the same result.
Edit
This code:
identifier = url.substring(url.lastIndexOf("/"))
graphUrl = "https://graph.facebook.com/" + identifier
urlJsonData = getGraphData(graphUrl)
Should work the same (that is result with the same data) for both:
url = http://www.facebook.com/southpark
And
url = http://www.facebook.com/6708787004
(you'll obviously need to implement the getGraphData method).
Also, the 2nd url form in the question is not a valid url for pages, at least not from my tests, I get:
You may have clicked an expired link or mistyped the address. Some web
addresses are case sensitive.
The answer to the question is posted above but the method shown below works fine we do not have to perform the regex on the facebook page urls
I got the answer by this method
FB.api('/any_fb_page_url', function(response){
console.log(response);
});
any_fb_page_url can be any of the following types
https://www.facebook.com/my_page_name
https://www.facebook.com/pages/my_page_name
https://www.facebook.com/my_page_ID
This are also listed in question above
This code is tested on JS console available on Facebook Developers site tools
You can get the page id by using the below api
https://graph.facebook.com/v2.7/smhackapp?fields=id,name,fan_count,picture,is_verified&access_token=access_token&format=json
Reference image
This answer is updated and checked in 2019:
and it is very simple because you do not need to extract anything from the link. for examples:
https://www.facebook.com/pg/Vaireo-Shop-2138395226250622/about/
https://www.facebook.com/withminta
https://www.facebook.com/2138395226250622
https://graph.facebook.com/?id=link&access_token=xxxxxxxx
response:
{
"name": "Vaireo Shop",
"id": "2138395226250622"
}
full nodeJS answer:
async function getBusinessFromFBByPageURL(pageURL: string) {
const accessToken = process.env.fb_app_access_token;
const graphUrl = `https://graph.facebook.com/?id=${pageURL}? access_token=${accessToken}`;
const fbGraphResponse = await Axios.get(graphUrl);
<?php
function getFacebookId($url) {
$id = substr(strrchr($url,'/'),1);
$json = file_get_contents('http://graph.facebook.com/'.$id);
$json = json_decode($json);
return $json->id;
}
echo getFacebookId($_GET['url']);
?>
Thats a PHP example of how to get the ID.
As of Nov 26 2021 none of these solutions work.
Facebook has locked down the API so you need an App Review.
https://developers.facebook.com/docs/pages/overview/permissions-features#features
This answer takes into account that a URL can end with a trailing slash, something that Facebook event pages seem to have in their URLs now.
function getId(url) {
var path = new URL(url).pathname;
var parts = path.split('/');
parts = parts.filter(function(part) {
return part.length !== 0;
});
return parts[parts.length - 1];
}
You can Use Requests and re Modules in python
Code:
import requests,re
profile_url = "https://www.facebook.com/alanwalker97"
idre = re.complie('"entity_id":"([0-9]+)"')
con = requests.get(profile_url).content
id = idre.findall(con)
print("\n[*] ID: "+id[0])
Output:
[*] ID: 100001013078780
Perhaps you can look through the https://developers.facebook.com/docs/reference/api/#searching docs: search against a couple of types and if you find what you're looking for go from there.

using Zend_Gdata_Spreadsheets for public spreadsheets?

I have this code which is working, to load a Google Spreadsheet and load some data from it. If the spreadsheet in question is public, how do i modify the code to not require a username/password?
$key="keytothespreadsheet";
$user="test#example.com";
$pass="*****";
$authService = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $authService);
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($key);
$feed = $gdClient->getWorksheetFeed($query);
print_r($feed);
In the following line, the HTTP client is optional:
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);
So, just don't pass it. The following are equivalent:
$gdClient = new Zend_Gdata_Spreadsheets();
// or
$gdClient = new Zend_Gdata_Spreadsheets(null);
// or
$gdClient = new Zend_Gdata_Spreadsheets(new Zend_Http_Client());
Like #Matt, I wanted to access a public spreadsheet without supplying credentials. Thanks to #Derek Illchuk, I got part of the way there. It still wasn't working, however, until I learned the following:
Note that the File > Publish to the Web feature is not the same thing as Sharing Settings > Public On The Web. If you forget to enable "Publish to the Web", you'll get this error: "Expected response code 200, got 400 The spreadsheet at this URL could not be found. Make sure that you have the right URL and that the owner of the spreadsheet hasn't deleted it."
In the "Publish to the Web" settings, be sure to uncheck "Require viewers to sign in with their ___ account.". Otherwise you'll get this error: "Expected response code 200, got 403 You do not have view access to the spreadsheet. Make sure you are properly authenticated."
According to Google's documentation, "The spreadsheets feed only supports the 'private' visibility and the 'full' projection." However, I found that I needed to specify 'public' visibility and 'basic' projection. Otherwise I got this error:
"Expected response code 200, got 501 Bad or unsupported projection for this type of operation."
Here is what worked for me:
$spreadsheetService = new Zend_Gdata_Spreadsheets(null);
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$query->setWorksheetId($worksheetId);
$query->setVisibility('public'); //options are 'private' or 'public'
$query->setProjection('basic'); //options are 'full' or 'basic'
$cellFeed = $spreadsheetService->getCellFeed($query);
foreach ($cellFeed as $cellEntry) {
$text = $cellEntry->content->text;
//Do something
break; //I only wanted the first cell (R1C1).
}