第三方登录后端校验用户真实性(包含微信、QQ、微博)

      移动端第三方登录,往往最后会传递unionid给后端,作为第三方用户的唯一标识,但后端不能轻易相信前端传过来的就是真实的第三方用户,所以需要对第三方用户的真实性进行校验,需要第三方登录的access_token,其中微信多一个openid。

      相关官方文档:微信QQ微博

      封装方法如下:(php语言 tp5框架 需要继承Curl工具类 返回值为第三方用户唯一id 不为空则校验通过)

/**
 * 第三方登录access_token校验 获取unionid
 * @param int $third_logintype 第三方登录类型 1:微信 2:QQ 3:微博
 * @param string $access_token 第三方登录access_token
 * @param string $openid 微信登录openid
 * @return string|bool
 */
function thirdLoginCheck($third_logintype,$access_token,$openid=''){
    $res = null;
    $def = false;
    switch ($third_logintype) {
        case 1: //微信
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
            $res = Curl::post($url,[]);
            break;
        case 2: //QQ
            $url = 'https://graph.qq.com/oauth2.0/me?access_token='.$access_token.'&unionid=1';
            $res = Curl::post($url,['access_token' => $access_token,'unionid' => 1]);
            break;
        case 3: //微博
            $url = 'https://api.weibo.com/oauth2/get_token_info?access_token='.$access_token;
            $res = Curl::post($url,['access_token'=> $access_token]);
            break;
    }
    if(is_string($res)) { //判断返回值
        if($third_logintype==2) $res = substr($res,9,-3);
        $res = json_decode($res, true);
        if(is_array($res)){
            switch ($third_logintype) {
                case 1: //微信
                case 2: //QQ
                    if (isset($res['unionid'])) $def = $res['unionid'];
                    break;
                case 3: //微博
                    if (isset($res['uid'])) $def = $res['uid'];
                    break;
            }
        }
    }
    return $def;
}

      

发布了120 篇原创文章 · 获赞 433 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/msllws/article/details/104743450