Tasays

微博授权登陆


需要实现第三方微博登陆:
首先当然是申请微博开放平台啦 http://open.weibo.com/

申请流程不再赘述

下载新浪提供的第三方类库到TP vendor目录下

1.Common/下function.php添加函数引入第三方类库

//微博登陆

function saet($appkey,$appscr,$url){
        Vendor('wb.log.Saet');
        return new SaeTOAuthV2($appkey,$appscr);
    }

2. config中配置appkey appscr,redirect_url(回调地址)

'appkey'=>'xxxxxxx',
'redirect_url'=>'xxxxxxxx',
'appscr'=>'xxxxxxxxxx',

3. 设置设置登陆

<a href="weblogin"></a> 

//微博登陆
public function wblogin(){
    $appkey = C('appkey');
    $appscr =C('appscr');
    $url =C('redirect_url');
    //实例化微博登陆类
    $sate  = saet($appkey,$appscr);
    //获取登陆地址
    $auto = $sate->getAuthorizeURL($url);
    header('Location:'.$auto);
}

4. 获取token

 //获取token

public function gettoken(){
    if(!$_SESSION['expire_time']<time()){
        return $_SESSION['token'];
    }else{
        $appkey = C('appkey');
        $appscr =C('appscr');
        $url =C('redirect_url');
        $code = I('get.code');
        $saet = saet($appkey,$appscr);
        $keys['code'] = $code;
        $keys['redirect_uri'] = $url;
        $token = $saet->getAccessToken($keys);
        $_SESSION['token'] = $token;
        $_SESSION['expire_time'] = time()+157679999;
        return $token;
    }
}

5. 登陆根据token中信息获取用户信息(业务需要)

//微博登陆回调
public function callback(){
    if(IS_GET){
      $token = $this->gettoken();
      //uid获取用户
      $uid = $token['uid'];
      $user = D('user');
      $res = $user->where("uid = $uid")->find();
      if(isset($res)){
        //没有的话新增用户
        $data['uid']= $uid;
        $data['createtime'] = time();
        if( $id = $user->add($data)){

            $_SESSION['username']['username'] = $uid;
            $_SESSION['username']['id'] = $id;
            $this->redirect('index/index');
        }else{
            $this->error('错误');
        }
      }else{
        //有的话直接登陆
        $_SESSION['username']['username'] = $uid;
        $_SESSION['username']['id'] = $res['userid'];
        $this->redirect('index/index');
      }
    }
}