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

由于国内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'];
  }
}

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

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索oauth
, php版
QQ互联
oauth使用示例、oauth登录ava代码示例、微信分享oauth、微信js分享接口 示例、汉英翻译技巧示例 pdf,以便于您获取更多的相关知识。

时间: 2024-08-04 12:20:38

PHP版QQ互联OAuth示例代码分享_php技巧的相关文章

php调整gif动画图片尺寸示例代码分享_php技巧

类的使用demo: 复制代码 代码如下: <?php require_once "roucheng.php";  $gr = new gifresizer; $gr->temp_dir = "keleyi"; $gr->resize("keleyi.gif","keleyi_resized.gif",500,500); ?> 类的源代码,保存为roucheng.php文件: 复制代码 代码如下: <

修复ShopNC使用QQ 互联时提示100010 错误_php技巧

QQ 互联不允许 URL 有 Hash 存在,而 ShopNC 默认下是 ?act=toqq&op=g 这样的链接回调的,所以会导致设置失败,或者 100010 错误. 1. 建立 /shop/api_qq.php 文件 2. 修改 /shop/api/qq/comm/config.php $_SESSION["callback"] = SHOP_SITE_URL."/api_qq.php"; 3. QQ 互联填写 http://域名/shop/api_qq

php分页函数示例代码分享_php实例

分享一例php分页函数代码,用此函数实现分页代码很不错. 代码,php分页函数. 复制代码 代码如下: <?php/** Created on 2011-07-28* Author : LKK , http://lianq.net* 使用方法:require_once('mypage.php');$result=mysql_query("select * from mytable", $myconn);$total=mysql_num_rows($result);    //取得

使用PHP实现二分查找算法代码分享_php技巧

第一种方法: [二分查找要求]:1.必须采用顺序存储结构 2.必须按关键字大小有序排列. [优缺点]折半查找法的优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难.因此,折半查找方法适用于不经常变动而查找频繁的有序列表. [算法思想]首先,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功:否则利用中间位置记录将表分成前.后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表. 复制代码 代码如下: <?

5种PHP创建数组的实例代码分享_php技巧

看这篇文章之前相信大家都已经看过PHP中文手册关于数组这一节的讲解了,怎么样呢,看懂了多少?至少我第一次阅读文档时是一头雾水,也许是因为在翻译的不够通俗易懂吧^_^!!这里UncleToo根据自己的经验,将数组的各种创建方式用PHP实例代码的方式分享给大家,希望对大家有些帮助(当然,PHP文档还是要多看的) 1.使用array()创建数组 array()创建数组是我们在PHP开发过程中最常用到的一种方式,准确来说array()是一种结构而不是一个函数. 示例1: 复制代码 代码如下: <?php

基于GD2图形库的PHP生成图片缩略图类代码分享_php技巧

要使用PHP生成图片缩略图,要保证你的PHP服务器安装了GD2图形库 使用一个类生成图片的缩略图 1.使用方法 $resizeimage = new resizeimage("图片源文件地址", "200", "100", "0","缩略图地址"); //就只用上面的一句话,就能生成缩略图,其中,源文件和缩略图地址可以相同,200,100分别代表宽和高 2. 缩略图类代码 //使用如下类就可以生成图片缩略图

php处理单文件、多文件上传代码分享_php技巧

php处理  单文件.多文件上传实例代码,供大家参考,具体内容如下  后台处理文件submit_form_process.php  <?php /****************************************************************************** 参数说明: $max_file_size : 上传文件大小限制, 单位BYTE $destination_folder : 上传文件路径 $watermark : 是否附加水印(1为加水印,其他为

php实现文件下载代码分享_php技巧

简单的文件下载只需要使用HTML的连接标记<a>,并将属性href的URL值指定为下载的文件即可.所示: <a href="http://www.jb51.net/download/book.rar">下载文件</a> 如果通过上面的代码实现文件下载,只能处理一些浏览器不能默认识别的MIME类型文件,例如当访问book.rar文件时,浏览器并没有直接打开,而是弹出一个下载提示框,提示用户"下载"还是"打开"等处

PHP发送短信代码分享_php技巧

方法一(比较好,推荐) //PHP发送短信 Monxin专用(PHP代码函数) //本代码基于Monxin 运行 //代码来源:Monxin ./config/functions.php function sms($config,$language,$pdo,$sender,$phone_number,$content){ //demo var_dump(sms(self::$config,self::$language,$pdo,"system","18074507509,