本文最后更新于 1228 天前,其中的信息可能已经有所发展或是发生改变。
前言
这两天在写TP5实现第三方平台的登录,碰巧想写博客,就直接分享出来了,代码简单粗暴。
配置信息
private $qq_app_id='';//QQ互联里的应用ID
private $qq_app_key='';//QQ互联里的应用KEY
private $qq_app_redirect_uri='http://user.berfen.com/index/login/qq_callback.html';//回调地址
跳转到QQ登录
public function qq_login(){
$url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=".$this->qq_app_id."&redirect_uri=".$this->qq_app_redirect_uri."&scope=get_user_info&state=text";
session('qq', 'login', 'login');
$this->redirect($url);
}
授权成功,处理信息
public function qq_callback(){
//获取code
$code = $_GET['code'];
//Authorization Code获取Access Token
$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=".$this->qq_app_id."&redirect_uri=".$this->qq_app_redirect_uri."&client_secret=".$this->qq_app_key."&code=".$code."";
$response = file_get_contents($token_url);
//获取的Access Token,得到对应用户身份的OpenID和unionid。
$params = array();
//parse_str() 函数把查询字符串('a=x&b=y')解析到变量中。
parse_str($response,$params);
//获取用户openID和unionid
$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token']."&unionid=1";
$str = file_get_contents($graph_url);
// --->找到了字符串:callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} )
// strpos() 函数查找字符串在另一字符串中第一次出现的位置,从0开始
if(strpos($str,"callback")!==false)
{
$lpos = strpos($str,"(");
// strrpos() 函数查找字符串在另一字符串中最后一次出现的位置。
$rpos = strrpos($str,")");
//substr(string,start,length) 截取字符串某一位置
$str = substr($str,$lpos+1,$rpos-$lpos-1);
}
// json_decode() 函数用于对 JSON 格式-->{"a":1,"b":2,"c":3,"d":4,"e":5}<--的字符串进行解码,并转换为 PHP 变量,默认返回对象
$user_qq_id = json_decode($str);//这里就是用户的openID和unionid
/*//调用OpenAPI接口,得到json数据,要转换为数组
$qq_user_data = "https://graph.qq.com/user/get_user_info?access_token=".$params['access_token']."&oauth_consumer_key=".$this->qq_app_id."&openid=".$user_qq_id->openid."";
//加上true,得到数组,否则默认得到对象
$res = json_decode(file_get_contents($qq_user_data),true);
Debug::dump($res);//输出获取的QQ用户信息
}