PHP版QQ互联OAuth示例代码分享


Posted in PHP onJuly 05, 2015

由于国内QQ用户的普遍性,所以现在各大网站都尽可能的提供QQ登陆口,下面我们来看看php版,给大家参考下

/**
 * QQ互联 oauth
 * @author dyllen
 *
 */
class Oauth
{
  //取Authorization Code Url
  const PC_CODE_URL = 'https://graph.qq.com/oauth2.0/authorize';
   
  //取Access Token Url
  const PC_ACCESS_TOKEN_URL = 'https://graph.qq.com/oauth2.0/token';
   
  //取用户 Open Id Url
  const OPEN_ID_URL = 'https://graph.qq.com/oauth2.0/me';
   
  //用户授权之后的回调地址
  public $redirectUri = null;
   
  // App Id
  public $appid = null;
   
  //App Key
  public $appKey = null;
   
  //授权列表
  //字符串,多个用逗号隔开
  public $scope = null;
   
  //授权code
  public $code = null;
   
  //续期access token的凭证
  public $refreshToken = null;
   
  //access token
  public $accessToken = null;
   
  //access token 有效期,单位秒
  public $expiresIn = null;
   
  //state
  public $state = null;
   
  public $openid = null;
   
  //construct
  public function __construct($config=[])
  {
    foreach($config as $key => $value) {
      $this->$key = $value;
    }
  }
   
  /**
   * 得到获取Code的url
   * @throws \InvalidArgumentException
   * @return string
   */
  public function codeUrl()
  {
    if (!$this->redirectUri) {
      throw new \Exception('parameter $redirectUri must be set.');
    }
    $query = [
        'response_type' => 'code',
        'client_id' => $this->appid,
        'redirect_uri' => $this->redirectUri,
        'state' => $this->getState(),
        'scope' => $this->scope,
    ];
   
    return self::PC_CODE_URL . '?' . http_build_query($query);
  }
   
  /**
   * 取access token
   * @throws Exception
   * @return boolean
   */
  public function getAccessToken()
  {
    $params = [
        'grant_type' => 'authorization_code',
        'client_id' => $this->appid,
        'client_secret' => $this->appKey,
        'code' => $this->code,
        'redirect_uri' => $this->redirectUri,
    ];
   
    $url = self::PC_ACCESS_TOKEN_URL . '?' . http_build_query($params);
    $content = $this->getUrl($url);
    parse_str($content, $res);
    if ( !isset($res['access_token']) ) {
      $this->thrwoError($content);
    }
   
    $this->accessToken = $res['access_token'];
    $this->expiresIn = $res['expires_in'];
    $this->refreshToken = $res['refresh_token'];
   
    return true;
  }
   
  /**
   * 刷新access token
   * @throws Exception
   * @return boolean
   */
  public function refreshToken()
  {
    $params = [
        'grant_type' => 'refresh_token',
        'client_id' => $this->appid,
        'client_secret' => $this->appKey,
        'refresh_token' => $this->refreshToken,
    ];
   
    $url = self::PC_ACCESS_TOKEN_URL . '?' . http_build_query($params);
    $content = $this->getUrl($url);
    parse_str($content, $res);
    if ( !isset($res['access_token']) ) {
      $this->thrwoError($content);
    }
   
    $this->accessToken = $res['access_token'];
    $this->expiresIn = $res['expires_in'];
    $this->refreshToken = $res['refresh_token'];
   
    return true;
  }
   
  /**
   * 取用户open id
   * @return string
   */
  public function getOpenid()
  {
    $params = [
        'access_token' => $this->accessToken,
    ];
   
    $url = self::OPEN_ID_URL . '?' . http_build_query($params);
       
    $this->openid = $this->parseOpenid( $this->getUrl($url) );
     
    return $this->openid;
  }
   
  /**
   * get方式取url内容
   * @param string $url
   * @return mixed
   */
  public function getUrl($url)
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
    curl_close($ch);
   
    return $response;
  }
   
  /**
   * post方式取url内容
   * @param string $url
   * @param array $keysArr
   * @param number $flag
   * @return mixed
   */
  public function postUrl($url, $keysArr, $flag = 0)
  {
    $ch = curl_init();
    if(! $flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $keysArr);
    curl_setopt($ch, CURLOPT_URL, $url);
    $ret = curl_exec($ch);
   
    curl_close($ch);
    return $ret;
  }
   
   
  /**
   * 取state
   * @return string
   */
  protected function getState()
  {
    $this->state = md5(uniqid(rand(), true));
    //state暂存在缓存里面
    //自己定义
        //。。。。。。。。。
   
    return $this->state;
  }
   
  /**
   * 验证state
   * @return boolean
   */
  protected function verifyState()
  {
    //。。。。。。。
  }
   
  /**
   * 抛出异常
   * @param string $error
   * @throws \Exception
   */
  protected function thrwoError($error)
  {
    $subError = substr($error, strpos($error, "{"));
    $subError = strstr($subError, "}", true) . "}";
    $error = json_decode($subError, true);
     
    throw new \Exception($error['error_description'], (int)$error['error']);
  }
   
  /**
   * 从获取openid接口的返回数据中解析出openid
   * @param string $str
   * @return string
   */
  protected function parseOpenid($str)
  {
    $subStr = substr($str, strpos($str, "{"));
    $subStr = strstr($subStr, "}", true) . "}";
    $strArr = json_decode($subStr, true);
    if(!isset($strArr['openid'])) {
      $this->thrwoError($str);
    }
     
    return $strArr['openid'];
  }
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

PHP 相关文章推荐
php执行sql语句的写法
Mar 10 PHP
关于php curl获取301或302转向的网址问题的解决方法
Jun 02 PHP
通过5个php实例细致说明传值与传引用的区别
Aug 08 PHP
php获取淘宝分类id示例
Jan 16 PHP
php smarty模板引擎的6个小技巧
Apr 24 PHP
yii2.0之GridView自定义按钮和链接用法
Dec 15 PHP
PHP整合七牛实现上传文件
Jul 03 PHP
PHP的Yii框架中YiiBase入口类的扩展写法示例
Mar 17 PHP
PHP+jquery+CSS制作头像登录窗(仿QQ登陆)
Oct 20 PHP
Laravel 的数据库迁移的方法
Jul 31 PHP
Laravel框架控制器的request与response用法示例
Sep 30 PHP
Yii框架学习笔记之应用组件操作示例
Nov 13 PHP
PHP 获取ip地址代码汇总
Jul 05 #PHP
PHP中$_SERVER使用说明
Jul 05 #PHP
php实现短信发送代码
Jul 05 #PHP
phpMyAdmin安装并配置允许空密码登录
Jul 04 #PHP
Ubuntu下安装PHP的mongodb扩展操作命令
Jul 04 #PHP
Cygwin中安装PHP方法步骤
Jul 04 #PHP
php使用Session和文件统计在线人数
Jul 04 #PHP
You might like
一首老MP3,致敬WAR3经典
2021/03/08 魔兽争霸
PHP个人网站架设连环讲(一)
2006/10/09 PHP
介绍php设计模式中的工厂模式
2008/06/12 PHP
PHP中使用asort进行中文排序失效的问题处理
2014/08/18 PHP
php实现将base64格式图片保存在指定目录的方法
2016/10/13 PHP
php实现保存周期为1天的购物车类
2017/07/07 PHP
centos7上编译安装php7以php-fpm方式连接apache
2018/11/08 PHP
JQuery 学习笔记 选择器之三
2009/07/23 Javascript
javascript中IE浏览器不支持NEW DATE()带参数的解决方法
2012/03/01 Javascript
JavaScript快速检测浏览器对CSS3特性的支持情况
2012/09/26 Javascript
JS刷新当前页面的几种方法总结
2013/12/24 Javascript
JavaScript运行机制之事件循环(Event Loop)详解
2014/10/10 Javascript
jQuery超赞的评分插件(8款)
2015/08/20 Javascript
基于JQuery的$.ajax方法进行异步请求导致页面闪烁的解决办法
2016/05/10 Javascript
AngularJS基础 ng-mousemove 指令简单示例
2016/08/02 Javascript
微信小程序 PHP生成带参数二维码
2017/02/21 Javascript
Linux使用Node.js建立访问静态网页的服务实例详解
2017/03/21 Javascript
jQuery简单绑定单个事件的方法示例
2017/06/10 jQuery
JavaScript仿微信(电话)联系人列表滑动字母索引实例讲解(推荐)
2017/08/16 Javascript
原生JS实现多个小球碰撞反弹效果示例
2018/01/31 Javascript
vue打包的时候自动将px转成rem的操作方法
2018/06/20 Javascript
vue+element实现表格新增、编辑、删除功能
2019/05/28 Javascript
[01:38]完美世界DOTA2联赛PWL S3 集锦第四期
2020/12/21 DOTA
利用Python的Django框架中的ORM建立查询API
2015/04/20 Python
python粘包问题及socket套接字编程详解
2019/06/29 Python
对django中foreignkey的简单使用详解
2019/07/28 Python
pytorch之ImageFolder使用详解
2020/01/06 Python
使用Python+Appuim 清理微信的方法
2021/01/26 Python
JINS眼镜官方网站:日本最大的眼镜邮购
2016/10/14 全球购物
Monnier Freres中文官网:法国领先的奢侈品配饰在线零售商
2017/11/01 全球购物
巴西化妆品商店:Lojas Rede
2019/07/26 全球购物
英国索普公园票务和酒店套餐:Thorpe Breaks
2019/09/14 全球购物
社区巾帼文明岗事迹材料
2014/06/03 职场文书
党的群众路线教育实践活动学习笔记
2014/11/05 职场文书
2015年银行客户经理工作总结
2015/04/01 职场文书
2015年禁毒工作总结
2015/04/30 职场文书