Icharle | Don't forget your first thoughts - oauth
type: channel
link: https://icharle.com/tag/oauth/
items: 基于ThinkPHP3.2.3实现第三方QQ登录

基于ThinkPHP3.2.3实现第三方QQ登录
type: item
date: 2017-11-03T01:26:00+08:00
description: 杂说 最近在弄一个需要验证用户真实性的网页，开始是想到用微信登录的(毕竟现在用微信的人数很多，用起来比较方便吧),但是咧，没有获取到微信登录的权限，需要给钱才能用到微信登录这个功能，所以最后还是直接使用QQ登录好了，能够验证用户真实性就OK吧。 SDK引入 官方的SDK很长，而且不适合引入到TP框架里边，因此，这里用到的SDK结合官方SDK进行了改写(参考网上的列子结合自己的理解重新整合了一份SDK)。 方法：先在Vendor文件夹中新建一个文件夹QQ,并且在里边新建一个qqAuth.class.php文件，并将下面代码贴入其中。 <?php namespace Vendor\QQ; class qqAuth { private static $data; //APP ID private $app_id=""; //APP KEY private $app_key=""; //回调地址 private $callBackUrl=""; //Authorization Code private $code=""; //access Token private $accessToken=""; public function __construct($appid,$appkey,$callback){ $this->app_id=$appid; $this->app_key=$appkey; $this->callBackUrl=$callback; //检查用户数据 if(empty($_SESSION['QC_userData'])){ self::$data = array(); }else{ self::$data = $_SESSION['QC_userData']; } } //获取Authorization Code public function getAuthCode(){ $url="https://graph.qq.com/oauth2.0/authorize"; $param['response_type']="code"; $param['client_id']=$this->app_id; $param['redirect_uri']=$this->callBackUrl; //-------生成唯一随机串防CSRF攻击 $state = md5(uniqid(rand(), TRUE)); $_SESSION['state']=$state; $param['state']=$state; $param['scope']="get_user_info"; //其它权限 $param =http_build_query($param,'','&'); $url=$url."?".$param; header("Location:".$url); } //通过Authorization Code获取Access Token private function getAccessToken(){ $url="https://graph.qq.com/oauth2.0/token"; $param['grant_type']="authorization_code"; $param['client_id']=$this->app_id; $param['client_secret']=$this->app_key; $param['code']=$_GET['code']; $param['redirect_uri']=$this->callBackUrl; $param =http_build_query($param,'','&'); $url=$url."?".$param; return $this->getUrl($url); } //获取openid public function getOpenID(){ $rzt=$this->getAccessToken(); parse_str($rzt,$data); $this->accessToken=$data['access_token']; $url="https://graph.qq.com/oauth2.0/me"; $param['access_token']=$this->accessToken; $param =http_build_query($param,'','&'); $url=$url."?".$param; $response=$this->getUrl($url); //--------检测错误是否发生 if(strpos($response, "callback") !== false){ $lpos = strpos…