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

 更新时间:2015年07月05日 15:52:53   投稿:hebedich  
这篇文章主要介绍了PHP版QQ互联OAuth示例代码分享,十分的详细使用,有需要的小伙伴可以参考下。

由于国内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解决和避免form表单重复提交的几种方法

    php解决和避免form表单重复提交的几种方法

    在PHP提交表单的时候,可能遇到网速等导致页面突然加载变慢,用户重复地点击提交按钮,将在数据库产生多条数据,导致不可控情况。那么如何避免和解决这种问题呢?下面来一起看看。
    2016-08-08
  • 实例讲解PHP面向对象之多态

    实例讲解PHP面向对象之多态

    这篇文章主要介绍了实例讲解PHP面向对象之多态,本文用实例讲解什么情况下使用PHP的多态、多态的好处等内容,可以充分帮你理解多态,需要的朋友可以参考下
    2014-08-08
  • php array_chunk()函数用法与注意事项

    php array_chunk()函数用法与注意事项

    这篇文章主要介绍了php array_chunk()函数用法与注意事项,结合实例形式分析了php数组分割函数array_chunk()相关功能、用法及操作注意事项,需要的朋友可以参考下
    2019-07-07
  • php中生成随机密码的自定义函数代码

    php中生成随机密码的自定义函数代码

    这篇文章主要分享下php中生成随机密码的方法,原理就是把一些要生成的字符预置一个的字符串包括数字拼音之类的以及一些特殊字符,这样我们再随机取字符组成我们想要的随机密码了
    2013-10-10
  • PHP中使用file_get_contents抓取网页中文乱码问题解决方法

    PHP中使用file_get_contents抓取网页中文乱码问题解决方法

    这篇文章主要介绍了PHP中使用file_get_contents抓取网页中文乱码问题解决方法,可以通过使用curl配置gzip选项来解决,具有一定的参考借鉴价值,需要的朋友可以参考下
    2014-12-12
  • PHP解决中文乱码

    PHP解决中文乱码

    在php中,中文乱码非常头疼,很麻烦,所以根据在编程的经验,总结以下方法(以utf_8为例),下面跟着小编一起来看下吧
    2017-04-04
  • php中文字符串截取多种方法汇总

    php中文字符串截取多种方法汇总

    这篇文章主要为大家详细介绍了php中文字符串截取多种方法,具有一定的参考价值,感兴趣的朋友可以参考一下
    2016-10-10
  • PHP获取Exif缩略图的方法

    PHP获取Exif缩略图的方法

    这篇文章主要介绍了PHP获取Exif缩略图的方法,实例分析了php针对图片的读取及返回MIME类型的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • PHP基于curl后台远程登录正方教务系统的方法

    PHP基于curl后台远程登录正方教务系统的方法

    这篇文章主要介绍了PHP基于curl后台远程登录正方教务系统的方法,结合实例形式分析了php使用curl及cookie实现远程登陆的操作技巧,需要的朋友可以参考下
    2016-10-10
  • RSA实现JS前端加密与PHP后端解密功能示例

    RSA实现JS前端加密与PHP后端解密功能示例

    这篇文章主要介绍了RSA实现JS前端加密与PHP后端解密功能,结合实例形式分析了rsa前端js加密与后端php解密相关操作技巧,需要的朋友可以参考下
    2019-08-08

最新评论