Laravel socialite: always grab default avatar - facebook

I'm allowing users to register using Scialite (Still working locally on Laravel homestead with openSSL enabled). it works fine with FB except the avatar it always get the default image. I'm testing with the same FB account that created the app (FB app is in development mode)
Code
public function handleProviderCallback($provider)
{
$userSocial = Socialite::driver($provider)->user();
$users = User::where(['email' => $userSocial->getEmail()])->first();
if($users){
Auth::login($users);
return redirect('/');
}else{
$avatar_file_name = 'test';
if(!empty($userSocial->getAvatar()) && $userSocial->getAvatar()!='' && $userSocial->getAvatar() != null)
{
$fileContents = file_get_contents($userSocial->getAvatar());
File::put(public_path() . '/uploads/' . $userSocial->getId() . ".jpg", $fileContents);
$avatar_file_name = $userSocial->getId() . ".jpg";
}
$user = User::create([
'name' => $userSocial->getName(),
'email' => $userSocial->getEmail(),
'avatar' => $avatar_file_name,
'provider_id' => $userSocial->getId(),
'provider' => $provider,
]);
Auth::login($user, true);
return redirect()->route('home');
}
}
When I dd($userSocial->getAvatar()) and copy the URL it opens the default avatar (the above image) why is that? Is there anything I have to do the the FB App or login code to get the real avatar of the user?

I've encountered this issue now. Socialite avatar retrieving was working fine around one month ago. But it is broken when I check it few days ago. So current solution is just appended access_token to retrieve image something like below.
https://graph.facebook.com/v3.3/[facebook_user_id]/picture?type=normal&access_token=[fbtoken]
please let me know if you find more easy solution.
result is:

Append the access_token to the query
Like so:
$social = Socialite::driver('facebook')->user();
$avatar = $social->avatar_original . "&access_token={$social->token}";
The $avatar variable will contain the correct url of the profile picture.

Related

Facebook Real Time Subscriptions Throws Exception Even when challenge is answered

I'm trying to subscribe from my app to Real Time Subscription of Facebook using v2.4 Graph API (after creating a callback function in fbcallback.php) using the code below from my index.php page (the appid and IP address obviously fake in this post):
try {
$response=$fb->sendRequest('POST','/1111/subscriptions',
array(
'object' => 'user',
'callback_url' => 'http://111.111.111.111/fbcallback.php',
'fields' => 'first_name',
'verify_token' => 'thisisaverifystringtestuser',
)
);
$graphNode = $response->getGraphNode();
}catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "exception:" . $e->getMessage(); }
While i'm sure from callback log that Facebook reaches my callback function and i use in it the code below:
<?php
define('VERIFY_TOKEN', 'thisisaverifystringtestuser');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' &&
$_GET['hub_verify_token'] == VERIFY_TOKEN) {
echo $_GET['hub_challenge'];
}
?>
i get the Message from my index page code looking like this:
exception:(#2201) response does not match challenge, expected value = '866531638', received='866531638'
Anyone encountered it?
P.S I created a test user from the app dashboard roles and configured him to subscribe to app on creation and also got (but not used) an access token for this user from dashboard also.....since i can't denote a specific user during the subscription proccess from my php code i expect (or wish) this user to be subscribed by my php code...am i wrong?
Looks like your script outputs more than just the hub_challenge value.
When I copy&paste the error message from your posting, and insert it in NotePad++, I get that part shown as
received='?866531638'
^
– so there seems to be some invisible/not display-able character before the actual value.
Make sure your script is saved as UTF-8 without BOM, and that it does not make any other output besides the hub_challenge value either. (That could include stuff outside of <?php … ?> tags as well.)

posted images in wall disappear

i'm posting some images using the following command:
$url_facebook = "https://api.facebook.com/method/stream.publish?message=".$messaggio."&attachment={\"name\":\"".$title."\",\"href\":\"".$action_link."\",\"caption\":\"".$caption."\",\"description\":\"".$description."\",\"media\":[{\"type\":\"image\",\"src\":\"".$image."\",\"href\":\"".$action_link."\"}]}&action_links=[{\"text\":\"".$link_name."\",\"href\":\"".$action_link."\"}]&target_id=".$target_uid."&uid=".$source_uid."&".$site_token."";
simplexml_load_file("".$url_facebook."");
the image i post in the wall (a group) is generated on the fly from PHP.
this is what happens:
i generate an image and save it to a folder
i post it with the code upon
i exit from the script
the next time a run the script (each hour) i delete all the old
created images , than repeat wath sayid upon
i noticed that the images just when published, are present and existing on the FB wall
BUT
the next time i launch the script (and so the images are deleted from my site) they disappear also from facebook
i understood that the images where uploaded to facebook, so they were not needed anymore on my space....
isn't so ?
i've this doubt also because, if i see on the red x on facebook (in the place of the images)
and i right click "proprerties", i can read :
"https://s-platform.ak.fbcdn.net/www/app_full_proxy.php?app=164286063695472&v=1&size=z&cksum=17f253305254403324260843c7a6989a&src=http%3A%2F%2Fwww.graficisismici.it%2FV6_00%2Ffacebook%2Ffacebook_link_285790.jpg%3F285790"
so it's seem that it's really a link to the original image
can you solve my doubt ?
meanwhile I modified the script to use the new Graph Api
<?php
$user = null;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if($user == 0) {
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
echo ("<script> top.location.href='".$login_url."'</script>");
} else {
$user_message = "Message";
$titolo = "Titolo";
$caption = "Caption";
$link_name = "Link Name";
$action_link = "Action Link";
$testo = "Text";
$image = "Image Link";
$target_uid = "XXXXXXXX"; // ID where to publish
//HTTP POST request to PAGE_ID/feed with the publish_stream
$post_url = '/'.$target_uid.'/feed';
try {
$params = array(
'message' => $user_message,
'name' => $titolo,
'caption' => $caption,
'link' => $action_link,
'description' => $link_name,
'picture' => $image,
'actions' => array(
array(
'name' => $testo,
'link' => $action_link
)
)
);
$post = $facebook->api($post_url,"POST",$params);
}
catch (FacebookApiException $e) {
$result = $e->getResult();
}
}
?>
I just would like to have a clarification about the image question.
Does the image have to still exist ?
Or once posted, I can delete them, as they still live on Fb ?
My questione born from the fact that i see (while using the old script in the top of this post) on the error log of my site a lof of row of 404 error (related to the missed images searched from Fb)
i understood that the images where uploaded to facebook, so they were not needed anymore on my space....
This is not the case. Facebook simply caches your content in their CDN. If you delete the source photos, when the content falls out of their cache, their attempt to refresh / re-fill the cache will fail and your users will get a broken image icon.
Does the image have to still exist ? Or once posted, I can delete them, as they still live on Fb ?
You should not delete them.

Force user to allow facebook permissions using Graph API

I developed Facebook application and I have some problems on "Allow access step",In initial stage user must authorize app and permissions.Currently if users skip extended permissions also landing to application home page , But I need to force user to accept all permissions, I got success when using FQL method , Now its not working , I cant find out the solution. Here is my code
$TotalPermissions = UserAndFriendsPermissions();
return true;
$tp = substr_replace($TotalPermissions ,"",-1);
$this->loadClassFile("Facebook", MAIN_PLUGIN_PATH."Common/facebook/facebook.php");
$facebook = new Facebook(array('appId' => $FBConnect["fb_app_id"],'secret' => $FBConnect["fb_secret_key"],));
$params = array('method' => 'fql.query','query' => "SELECT ".$tp." FROM permissions WHERE uid=me()");
$result = $facebook->api($params);
$totalp = count(explode(",",$tp));
$ap=0;
foreach ($result[0] as $key => $val)
{
if($val==1)
{
$ap++;
}
}
if($ap==$totalp)
{
return true;
}
else
{
?>
<?php
Redirect("https://apps.facebook.com/APP_NAMESPACE");
}
You cannot force users to accept all your extended permissions. What you can do is to check for permissions given and handle those cases accordingly i.e. redirecting users who have not given permission to a landing page which explains why you need those permissions.

Redirect back to page tab after user authenticates?

How should I go about redirecting the user back to my page's tab after they authenticate my app? I cannot put one specific url in for the redirect since my app will live on multiple pages. So somehow I need to grab the page's id and put it into the url. I've tried to use session variables but it doesn't seem to be working for me. :( Here's a portion of my code...
$signed_request = $facebook->getSignedRequest();
$_SESSION['TrueID'] = $signed_request['page']['id'];
$fbconfig['appBaseUrl'] = "http://www.facebook.com/pages/".$_SESSION['TrueID']."/".$_SESSION['TrueID']."?sk=app_241321439259320";
/*
* If user first time authenticated the application facebook
* redirects user to baseUrl, so I checked if any code passed
* then redirect him to the application url
* -mahmud
*/
if (isset($_GET['code'])){
header("Location: " . $fbconfig['appBaseUrl']);
exit;
}
//~~
//
if (isset($_GET['request_ids'])){
//user comes from invitation
//track them if you need
}
As you can see I'm trying to set a session variable to grab the page's id.. but that's not working for me :( The variable echo's out just fine when I visit my page.. but I'm guessing its getting lost somewhere during the authentication.
So when a Page add/install your app, you should store the page's link along with the page's id.
Now when your page tab is loaded, Facebook will send the page parameter which will contain the page id (along with other info, refer to the documentation). You retrieve that id, get the page's link from your db and construct your page tab link, which would be something like (where $page is the page's db record):
$redirect_uri = $page['page_link'] . '?sk=app_' . $APP_ID
Since you are using the PHP-SDK, this is how you construct your login:
$user = $facebook->getUser();
if(!$user) {
$url = $facebook->getLoginUrl(array('redirect_uri' => $redirect_uri, 'scope' => 'read_stream'));
echo "<script>top.location.href = '$url';</script>";
exit;
}
Of course you may not want to redirect to the login directly but instead have a call to action link:
Connect
Best way I found is to set the Site URL in the app settings to http://www.facebook.com/pages/
Then do something like this(tested):
$uid = '';
$facebook = new Facebook(array(
'appId' =>'xxxxxxxxxxxxxxx',
'secret' =>'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'cookie' => true,
'oauth' => true,
));
$uid = $facebook->getUser();
$signedrequest = $facebook->getSignedRequest();
$page_id = $signedrequest["page"]["id"];
$fb_access_token = $signedrequest["oauth_token"];
if($uid==''){
echo '<div id="authenticate">Authorize App</div>';
This might be a little bit of a hack, but it works well for my situation:) Hope it helps someone!

How to Get User unique identification upon Gmail login using Zend Framework

I had implemented oAuth Google using Zend Framework. All i can do right now is a user is authenticating using their gmail id and password and after that i am displaying his google Docs. But how to identify a user whether he is a old user or new user.
What is the unique Identification Google is providing after login in our website.
Thank You
$consumer = new Zend_Oauth_Consumer($oauthOptions);
if (!isset($_SESSION['REQUEST_TOKEN'])) {
$_SESSION['REQUEST_TOKEN'] = serialize($consumer->getRequestToken(array('scope' => implode(' ', $SCOPES))));
$approvalUrl = $consumer->getRedirectUrl(array('hd' => 'default'));
echo "<H2>LOGIN WITH GOOGLE</H2>";
exit(0);}
if (!isset($_SESSION['ACCESS_TOKEN'])) {
if (!empty($_GET) && isset($_SESSION['REQUEST_TOKEN'])) {
$_SESSION['ACCESS_TOKEN'] = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));}
}}
$accessToken = unserialize($_SESSION['ACCESS_TOKEN']);unset($_SESSION['REQUEST_TOKEN']);unset($_SESSION['ACCESS_TOKEN']);
You can store the returned ID from Google in a database and when authenticated (again) search for it. Get the Id like this:
$result = Zend_Auth::getInstance()->authenticate($adapter);
if ($result->isValid()) {
$identity = Zend_Auth::getInstance()->getIdentity();
// Do a database query on your users table looking for this $identity. If exists, they're logging back in