I am working on a Facebook canvas application which is technically supposed to load a page from YII 2. I am using Facebook PHP SDK. However my current problem is that whenever I try to load the canvas, I get error 400
(Unable to verify your data submission). On Facebook settings, I have the correct domain name on allowed domain.
Below is my source code and error:
$fb = new \Facebook\Facebook([
'app_id'=>$appId ,
'app_secret'=>$appSecret,
'default_graph_version'=>'v2.5']);$helper = $fb->getCanvasHelper();
$permissions = ['email','user_likes','user_friends'];
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'We are unable to log you in. Sorry.: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
$_SESSION['facebook_access_token']= $accessToken;
$oAuth2Client = $fb->getOAuth2Client();
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token']=$longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
if ($e->getCode() == 190) {
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/fb-app/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
echo "<script>window.top.location.href='https://apps.facebook.com/fb-app/'</script>";
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$model->fbvisitor(['name'=>$profile['name'],'email'=>$profile['email'],'id'=>$profile['id']]);
return $this->actionFacebook();
} else {
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/fb-app/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
Below is the error:
Bad Request (#400) Unable to verify your data submission.
The above error occurred while the Web server was processing your request.
Please contact us if you think this is a server error. Thank you
Following a comment shared by @CBroe I have figured out how to disable CSRF protection for that specific action. Add a beforeAction on the Controller and disable CSRFcheck as follows:
Public function beforeAction($action)
{
if ($this->action->id == 'action-name') {
Yii::$app->controller->enableCsrfValidation = false;
}
return true;
}