Facebook PHP SDK works in Firefox but not in Chrome - php

The question might sound a bit dull at first and I'm baffled myself..
I'm developing a PHP application that relies heavily on the Facebook API, thus is using the PHP SDK to connect and getting the currently logged in user via
$fb->getUser();
I have also included the Javascript SDK but its currently only fetching the logged in user and prints their data object to the console.
Today I began to implement a local dev-version of the app, set up a second dev-app on Facebook, connected them and voila.. it doesn't work.
getUser() always returns 0 for me locally.
What I just found out though is that it works in Firefox.
I var_dump the getUser() value, and recieve a full user id (mine) in Firefox, but 0 in Chrome (and yes, I'm logged in to Facebook on both browsers).
I cleared the cache, cookies, destroyed the session.. I just cant imagine what difference the browser makes for a PHP request to Facebook?
Has anybody ever experienced anything like this?
Obviously the app_key and secret must be correct because it works on Firefox.
Edit: just for reference, the live version of the application (hosted) works well in Chrome, it's only this very local app that I can't get to work.
Edit#2: This is the Javascript that I run on the app
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : {$_connect.app_id}, // App ID
channelUrl : '{$_connect.channel_file}', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
{if !$_user.is_authorized}
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
if (me.name) {
console.log(me);
//window.location = 'index.php';
// redirection is currently causing loop
}
})
} else {}
});
{/if}
};
// 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/de_DE/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>

I just cant imagine what difference the browser makes for a PHP request to Facebook?
The only thing, of course, can be the parameters.
And in this scenario, it’s most likely the cookies – the cookies, that Facebook sets on successful login and that the browser has to accept and send back to the server, for the PHP SDK to be able to recognize the logged in user.
So, check if your Chrome accepts these cookies when you are testing your app locally.

I think, you need to authenticate via JS SDK in both browsers also, I believe there's some OAuth logic behind JavaScript requests.
However, Chrome nowadays tries to block or simply not execute cross domain js requests. Try looking into net console if anything like that happens to you. If it does
Try checking domain + protocol /http(s)/ of your local environment. I believe you should be using https while calling js api
Consider using channel file, which should solve / prevent these crossbrowser calls issues as described in JavaScript SDK Documentation
If nothing from above helps you, I guess you could develop the app, test it on FFox and then once it's deployed test it with real setting.
Good luck.

Related

Redirect to URL (via header) vs. copying pasting URL in browser

Noticed that token information when sent to a 3rd party service in the in format "https://domaindotcom/login/token/blah.blah.blah.blah" works fine when copying and pasting it into the browser.
Now, when the same token is sent from a webpage sitting on an internal website via a PHP redirect (using the header function) we get issues. The redirect executes, the token triggers the event with the vendor, but it fails to finalize.
The page sits on a web server which is NOT accessible by the world.
Differences perhaps in what information gets sent out via these two methods?
Would a browser send more info when a PHP script is triggered on it such as referer?
Perhaps referer information received via the PHP header redirect function, and the vendor attempts to ping back (if their server detects a referer), but since the server is not accessible it may be flagged and process killed?
Would appreciate thoughts and ideas on what may be happening. Thank you!
This most likely has to do with their cookie settings. Specifically, if the cookie setting of the domain you are redirecting to contains SameSite=strict, the first request after a redirect from another domain will not include cookies.
var str = window.location.href;
var stringWithNumbers = str;
var n = 1;
console.log(str);
var changedString = stringWithNumbers.replace(/\/(\w+)/ig,v => n++ == 4 ? "ltfgt" : v);
console.log(changedString);
var st = changedString.split('ltfgt')[0];
console.log(st)
var str2 = "/Videos/folder/pencil.html";
var res = st.concat(str2);
console.log(res);
window.location.href=res;
var rplc= st.replace("ltfgt","/Videos/folder/pencil.html");
console.log(rplc);

Redirect a user if on mobile device (not tablet) but provide back link

This is completely new to me and haven't a clue what I'm doing so I would really prefer a simple to implement solution (if it exists).
I need to redirect users who visit www.domain.co.uk (hosted on Wordpress) on mobile devices (not tablets) to a specific page like this (with WP's permalinks):
www.domain.co.uk/mobile-home
From that mobile page, I also need to provide a link back to the desktop homepage on the same domain, like this:
www.domain.co.uk/desktop-home
I had been playing with code similar to this in my header.php file:
<script>if( 'ontouchstart' in window ) window.location = 'mobile.html';</script>
but it will just redirect a mobile user back to the mobile version if I link directly to the desktop page. How can I get the functionality I require?
UPDATE
Ok, my first step is to direct my mobile visitors to the mobile page. So I have pasted the following code into my page template of the homepage for my website and tested seems to work. I've put it just beneath the opening 'body' tag:
<script>
if( /Android|webOS|iPhone|iPod|BlackBerry|IEMobile/i.test(navigator.userAgent) ) {
window.location = "176.32.230.17/domain.co.uk/m";
}
</script>
Now I'm having trouble linking back to the homepage using the below code. It takes me back to the hompage but the homepage has the code above detecting the device and keeps taking me back to the mobile site. Am I putting the device detection in the right place?:
Link back to desktop website
You can detect a mobile browser with the user agent property of navigator and redirect the visitor to the mobile page. Differ between tablet and mobile isn't reliable possible(i.E. is the Galaxy Note a tablet or mobile?)
if( /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) ) {
window.location = "yourmobileurl.com/?ref=desktop";
}
On the server you can check the ref var for desktop and show the visitor a link to get back and store the choice in a session
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
Please ref this link :http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/
It explains how to detect device using javascript
So from using #Phillip's code I have managed to come up with a complete solution to my question.
I place the following JS in my header.php template to detect if user agent is a mobile device, if is then perform another check to see if the URL contains the hashtag '#desktop', if it does, do nothing and keep user on desktop version. If it doesn't then redirect to mobile website:
JS
<script>
if( /Android|webOS|iPhone|iPod|BlackBerry|IEMobile/i.test(navigator.userAgent) ) {
if(window.location.hash == "#desktop"){
// Stay on desktop website
} else {
window.location = "http://www.domain.co.uk/m";
}
}
</script>
Then to complete the loop, add a link on the mobile site that adds the hashtag '#desktop' to the URL ensuring they don't get redirected back to the mobile version automatically:
View desktop site
One solution would be to have the link back to desktop version have a url parameter, and only forward from desktop to mobile when that parameter isn't set.
As for detecting the device, you have to read the user-agent and provide logic. Here's a link to detect iPad and iPhone. Similar user agents apply to others. There is no silver bullet to identify a tablet.
You can identify most specific devices by learning what their user agent returns, but this is always open to being changed, and you would have to do this for every possible tablet.
As for the parameter solution, that seems straight-forward. You would link to http://www.mywebpage.com/MyDesktopHome?forwardToMobile=no. Otherwise you could store that in either the session or cookie, depending on how long you want to persist it.

Facebook Graph API - Page Tab Extra Permissions

I am trying to create a welcome tab for one of my pages, but I would like to be able to access a users likes (permission user_likes).
I can only find documentation on how to do this for a Facebook app or a website integrating Facebook, I can find no documentation on how to do this for an app (tab) inside a facebook page (as a welcome tab).
Is it possible as a page tab to request extra permissions from the user but allow page access without it, or is it a case or me having to make an application as well as a page tab? Could I perhaps have a button that when they click it grants the page extra permissions?
I am currently trying two separate implementations, neither of which I can get to work, PHP and Javascript.
Thanks,
Just using
$loginUrl = $fb->getLoginUrl(
array('canvas' => 1, 'scope' => 'user_likes,user_about_me,user_birthday')
);
echo "<a href='$loginUrl'>Login</a>";
Results in a link, which just redirects the user (within the pages iframe) to a screen with the Facebook logo. I want a permissions dialog!
Using the javascript code
<script>
FB.init({
appId : 'APPID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // enable OAuth 2.0
});
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
</script>
Results in
Unsafe JavaScript attempt to access frame with URL https://www.facebook.com/dialog/oauth?api_key=158609350887973&app_id=158609350887973&client_id=158609350887973&display=popup&locale=en_US&method=permissions.oauth&origin=1&redirect_uri=http%3A%2F%2Fstatic.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%3Fversion%3D3%23cb%3Df2f7aed38%26origin%3Dhttp%253A%252F%url.com%252Ff3634c5da%26relation%3Dopener%26transport%3Dpostmessage%26frame%3Df9748b77&response_type=token%2Csigned_request&scope=email&sdk=joey from frame with URL http://url.com/gs/index.php. Domains, protocols and ports must match.
The javascript also opens the following error popup box
My app config settings
You're seeing the error in your popup window because the redirect_uri in your authorization URL doesn't match what's listed in your Site URL in app config. To address this, you need to enable the "Website" option in app config. Enable it by clicking on the checkbox next to "Website" and then enter http://Site.com (or whatever your real site url is) in the "Site URL" text box. This URL must match the host url you're providing in redirect_uri. Doing this should solve the popup window error.
In terms of the "Unsafe JavaScript attempt to access frame" error, are you using a webkit browser? Webkit throws these errors but for the most part can be ignored. See this for more info: "Unsafe JavaScript attempt to access frame with URL..." error being continuously generated in Chrome webkit inspector
Use the user id in the response object instead of 'me' when you call FB.api
Both methods point to the fact you don't have your website domain settings correct in the app settings.
We do this exact thing on a lot of our tab apps so it's definitely possible.
It looks like you're using the same value for app_id and api_key. These should be different.
Instead of displaying the link ($loginUrl) try to redirect user, for example using php header function or js location.href.
Yes it is possible.
Read: http://www.masteringapi.com/tutorials/how-to-ask-for-extended-permission-in-your-facebook-application/32/

Use user info in PHP after logging in with Javascript

I'm currently writing a facebook app. In my app, the user is identified with the Javascript FB SDK:
FB.init({
appId : appId,
status : true,
cookie : true,
xfbml : true,
});
FB.ui({method: 'oauth'
,client_id: appId
,redirect_uri: 'some_URI'
,scope: 'publish_stream'});`
After the user loggs in, I can get the access token like this:
FB.getLoginStatus(function(response) {
if (response.session) {
alert(response.session.access_token);
My question is, if I could pass it back to the php code in order to use it?
you can send it via ajax request to your php script & use/operate with it as you want
Well, theoretically you could just do a ajax query and send the access token back to a php, e.g.
http://www.mydomain.com/setfbtoken?token=
Correct me if I'm wrong, but the session should be attached to your url as a get parameter (at least it is in PHP), so you could just fetch it off the $_GET parameter.
I think you can use this as in theory you should have the facebook cookie.
The information I posted here Facebook PHP SDK getSession() fails to get session. Cookie problem? might be useful and the functions listed there.

CakePHP Auth Component "login" Method Failure in IE8 + Safari

I have a method in users_controller.php of my CakePHP project which is used to remotely log a user in through an AJAX call on a WordPress site. The method works flawlessly when called through Firefox, but when I attempt to call it either via AJAX or directly from the browser in IE8 or Safari, it simply will not log in. The Auth->login() method returns true as if everything is fine, but it does not log in. Any ideas?
function remoteLogin($key)
{
# this method should only be called via AJAX
$this->layout = 'ajax';
$matching_key = '***';
if($key == $matching_key)
{
# auto-login service account
$data['User']['username'] = '***';
$data['User']['password'] = $this->Auth->password('***');
$this->Auth->login($data);
}
}
Note: I have now confirmed that this method does not work in Opera either. I'm legitimately confused.
You might want to check your cookies and make sure they are being passed as you expect. Fiddler is helpful to see the http traffic as it goes by to figure out these AJAX issues.
Are www.domain.com and domain.com going to the same place?
If so this may be related to a CakePHP / IE issue I ran accross.
Delete any domain level cookies and see if it works.
In IE any domain cookies will take precidence over the subdomain cookies. So if you ever get a cookie going to domain.com and then later go to www.domain.com you can reset your session login, logout all day long but IE will ignore the www.domain.com cookies and continue to use the original domain.com one. I wrote a patch for an old version of Cake that would let you set/force the cookie scope to domain.com even when they are accessing the site as www.domain.com to get around this.
Don't now about IE8, but Safari does block cross-domain ajax, even between "siblings" under the same top domain. E.G. You can't have app.example.com load a div using ajax from helppages.example.com. Forget cookies, I am talking just plain html loaded using ajax.
I think the problem is your domain.
Ex: IE or some browser don't work if your domain like: abc_def.com, ...
Please check your domain and change it like abcdef.com => it'll be ok

Categories