我正在创建一个WordPress插件,当新帖子添加到网站时,它会自动将帖子发布到Facebook。出于同样的原因,用户需要验证他的Facebook帐户。我为此使用的代码是:-
try {
$fp_hybridauth = new Hybrid_Auth( $hybrid_config );
$fp_hybridauth->authenticate( "facebook" ); //this function does the job of authenticating user and it is causing the exception to be thrown
update_option( "session_data", $fp_hybridauth->getSessionData() );
wp_redirect( site_url("/wp-admin/admin.php?page=facebook-publish&tab=api&fbauth=success") );
}
catch( Exception $e ){
echo $e->getMessage();
}
如果用户允许Facebook oAuth对话框中的权限,这段代码可以完美地工作,但如果用户拒绝给予权限,它会抛出一个异常,我似乎无法捕获:-
Fatal error: Uncaught exception 'Exception' with message 'Authentication failed! The user denied your request.' in /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Providers/Facebook.php:86 Stack trace: #0 /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Endpoint.php(182): Hybrid_Providers_Facebook->loginFinish() #1 /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Endpoint.php(58): Hybrid_Endpoint::processAuthDone() #2 /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/index.php(15): Hybrid_Endpoint::process() #3 {main} Next exception 'Exception' with message 'Authentication failed! The user denied your request.' in /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Auth.php:147 Stack trace: #0 /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybrid in /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Auth.php on line 147
Hybrid/Providers/Facebook.php文件中的代码是:-
function loginFinish()
{
// in case we get error_reason=user_denied&error=access_denied
if ( isset( $_REQUEST['error'] ) && $_REQUEST['error'] == "access_denied" ){
throw new Exception( "Authentication failed! The user denied your request.", 5 ); //THIS IS LINE NUMBER 86
}
// try to get the UID of the connected user from fb, should be > 0
if ( ! $this->api->getUser() ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid user id.", 5 );
}
// set user as logged in
$this->setUserConnected();
// store facebook access token
$this->token( "access_token", $this->api->getAccessToken() );
}
我试着用谷歌搜索这个问题,但我找不到任何问题。抱歉,我不能提供我在研究中得到的任何东西。
这个解决方案适合我:
try{
$hybridauth = new Hybrid_Auth($config);
$adapter = $hybridauth->authenticate($service);
}catch(Exception $ex){
var_dump($ex);
return;
}
$user_profile = $adapter->getUserProfile();
异常触发Ok。但是如果我移动这条线$hybridauth = new Hybrid_Auth($config);
在try{}区域之外,那么我无法捕获此异常。这很奇怪,因为这一行运行正常,没有抛出任何异常。
我有同样的问题和解决方案是我忘记了名称空间(我在另一个名称空间内操作),所以catch块的正确代码是:
catch('Exception $e) {}