自己重写的一个php QQ第三方登陆SDK程序代码,官方的不敢恭维了所以自己再写了一个,主要是考虑到QQ的PHP SDK写的真是太烂了,纯属是普及API知识,而不是到手就可以部署的类库,反正自己都写了一个了,就拿出来分享下.
什么也不多说,直接上代码,代码如下:
- <?php
-
-
-
-
-
-
-
-
-
-
-
- class Qq_sdk{
-
-
-
-
-
- private $app_id = 你的APP ID;
-
- private $app_secret = ‘你的APP_secret’;
-
- private $redirect = 你的回调地址;
-
-
-
- function __construct()
-
- {
-
-
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- function get_access_token($code)
-
- {
-
-
-
- $token_url = ‘https:
-
- . ‘client_id=’ . $this->app_id . ‘&redirect_uri=’ . urlencode($this->redirect)
-
- . ‘&client_secret=’ . $this->app_secret . ‘&code=’ . $code;
-
- $token = array();
-
-
-
- parse_str($this->_curl_get_content($token_url), $token);
-
-
-
- return $token;
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- function get_open_id($token)
-
- {
-
- $str = $this->_curl_get_content(‘https:
-
- if (strpos($str, “callback”) !== false)
-
- {
-
- $lpos = strpos($str, “(“);
-
- $rpos = strrpos($str, “)”);
-
- $str = substr($str, $lpos + 1, $rpos – $lpos -1);
-
- }
-
- $user = json_decode($str, TRUE);
-
-
-
- return $user;
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- function get_user_info($token, $open_id)
-
- {
-
-
-
-
-
- $user_info_url = ‘https:
- r_info?’
-
- . ‘access_token=’ . $token
-
- . ‘&oauth_consumer_key=’ . $this->app_id
-
- . ‘&openid=’ . $open_id
-
- . ‘&format=json’;
-
-
-
- $info = json_decode($this->_curl_get_content($user_info_url), TRUE);
-
-
-
- return $info;
-
- }
-
- private function _curl_get_content($url)
-
- {
-
- $ch = curl_init();
-
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
-
- curl_setopt($ch, CURLOPT_URL, $url);
-
-
-
- curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 3);
-
- $result = curl_exec($ch);
-
- curl_close($ch);
- return $result;
- }
- }
-
- ?>
使用方法:在你网站上放置超链接,地址为:https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=你的APP_ID&redirect_uri=你的回调地址.
在回调地址上调用我上面这个qq_sdk即可.
demo代码如下:
- if(emptyempty($_GET['code']))
- {
- exit(‘参数非法’);
- }
- include(‘qq_sdk’);
-
- $qq_sdk = new Qq_sdk();
-
- $token = $qq_sdk->get_access_token($_GET['code']);
-
- print_r($token);
- $open_id = $qq_sdk->get_open_id($token['access_token']);
-
- print_r($open_id);
-
- $user_info = $qq_sdk->get_user_info($token['access_token'], $open_id['openid']);
-
- print_r($user_info);
|