2016-01-08 39 views
0

我有一个使用twitter,facebook或google登录系统的网站。 我使用oAuth这里是我的代码。如何区分YII2中的oauth社交媒体插件

配置

'authClientCollection' => [ 
       'class' => 'yii\authclient\Collection', 
       'clients' => [ 
       'facebook' => [ 
        'class' => 'yii\authclient\clients\Facebook', 
        'clientId' => 'asdsad', 
        'clientSecret' => 'xzxas', 
       ], 
      'twitter' => [ 
       'class'   => 'yii\authclient\clients\Twitter', 
       'consumerKey' => 'sadsd', 
       'consumerSecret' => 'dasdasd', 
      ], 
      ], 
     ], 

控制器

public function actions() 
    { 
     return [ 
      'error' => [ 
       'class' => 'yii\web\ErrorAction', 
      ], 
      'captcha' => [ 
       'class' => 'yii\captcha\CaptchaAction', 
       'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, 
      ], 
      'auth' => [ 
       'class' => 'yii\authclient\AuthAction', 
       'successCallback' => [$this, 'oAuthSuccess'], 
      ], 
     ]; 
    } 

    public function oAuthSuccess($client) { 
     // get user data from client 
     $userAttributes = $client->getUserAttributes(); 
     echo '<pre>'; 
     print_r($userAttributes); 
     die; 

的问题是,我怎么知道社交媒体的用户使用登录到系统,哪一个?

回答

1
public function oAuthSuccess($client) { 
    // get user data from client 
    $userAttributes = $client->getUserAttributes(); 
    if($client->getName() == 'twitter'){ 
    ........ 
    }else if($client->getName() == 'facebook'){ 
    ......... 
    } 
+0

看起来更简单,虐待尝试.. –

+0

简单,但作品! ! 谢谢你.. –

2

区分您的OAuth用户端可以放一些实例条件为: -

public function oAuthSuccess($client) { 
    $reponse = $client->getUserAttributes(); 

    $session = Yii::$app->session; 

    $token = $client->accessToken->params['access_token']; 

    $session->set('token' ,$token); 
    $id = ArrayHelper::getValue($reponse , 'id'); 
    $session->set('auth_id', $id); 
    //Facebook Oauth 
    if($client instanceof \yii\authclient\clients\Facebook){ 

     //Do Facebook Login 

    } 
    //Google Oauth 
    elseif($client instanceof \yii\authclient\clients\GoogleOAuth){ 
     //Do Google Login Condition 

    } 


} 
+0

三江源病很快试试吧.. –