I am trying to create a facebook canvas app. I am using facebook php-sdk and cakephp.
This is my login function:-
public function login() {
$app_id = "xxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxx";
$canvas_page = "https://apps.facebook.com/xxxxxxx";
$scope = 'email,publish_actions';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$fbid = $user_profile['id'];
pr($user_profile);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
'redirect_uri' => $canvas_page
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
}
This seems to work if the user is already authenticated. But for new user, instead of showing the oauth dialog, it throws this error:-
"Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains."
I am testing it on localhost. so my canvas url is http://localhost/xxxxx/
Can someone help me out here ?
I finally found the solution:-
Two steps:-
a) Changed redirect_uri to http://localhost/xxxxxx
b) Added a check to see if get params has code and set header to canvas page.
Correct Code:-
public function login() {
$app_id = "xxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxxxx";
$canvas_page = "https://apps.facebook.com/xxxxxxx";
$scope = 'email,publish_actions';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
if (isset($_GET['code'])) {
header("Location: " . $canvas_page);
exit;
}
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$fbid = $user_profile['id'];
pr($user_profile);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => $scope,
));
print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
}
}