Heim > Backend-Entwicklung > PHP-Tutorial > PHP简单封装QQ oauth 2.0登录及api

PHP简单封装QQ oauth 2.0登录及api

WBOY
Freigeben: 2016-06-23 13:11:35
Original
1249 Leute haben es durchsucht

qq.php

<?php/** * QQ API client for PHP */class qqPHP{    public $api_url='https://graph.qq.com/';    public function __construct($appid, $appkey, $access_token=NULL){        $this->appid=$appid;        $this->appkey=$appkey;        $this->access_token=$access_token;    }    //生成授权网址    public function login_url($callback_url, $scope=''){        $params=array(            'client_id'=>$this->appid,            'redirect_uri'=>$callback_url,            'response_type'=>'code',            'scope'=>$scope        );        return 'https://graph.qq.com/oauth2.0/authorize?'.http_build_query($params);    }    //获取access token    public function access_token($callback_url, $code){        $params=array(            'grant_type'=>'authorization_code',            'client_id'=>$this->appid,            'client_secret'=>$this->appkey,            'code'=>$code,            'state'=>'',            'redirect_uri'=>$callback_url        );        $url='https://graph.qq.com/oauth2.0/token?'.http_build_query($params);        $result_str=$this->http($url);        $json_r=array();        if($result_str!='')parse_str($result_str, $json_r);        return $json_r;    }    /**    //使用refresh token获取新的access token,QQ暂时不支持    public function access_token_refresh($refresh_token){    }    **/    //获取登录用户的openid    public function get_openid(){        $params=array(            'access_token'=>$this->access_token        );        $url='https://graph.qq.com/oauth2.0/me?'.http_build_query($params);        $result_str=$this->http($url);        $json_r=array();        if($result_str!=''){            preg_match('/callback\(\s+(.*?)\s+\)/i', $result_str, $result_a);            $json_r=json_decode($result_a[1], true);        }        return $json_r;    }    //根据openid获取用户信息    public function get_user_info($openid){        $params=array(            'openid'=>$openid        );        return $this->api('user/get_user_info', $params);    }    //发布分享    public function add_share($openid, $title, $url, $site, $fromurl, $images='', $summary=''){        $params=array(            'openid'=>$openid,            'title'=>$title,            'url'=>$url,            'site'=>$site,            'fromurl'=>$fromurl,            'images'=>$images,            'summary'=>$summary        );        return $this->api('share/add_share', $params, 'POST');    }    //调用接口    /**    //示例:根据openid获取用户信息    $result=$qq->api('user/get_user_info', array('openid'=>$openid), 'GET');    **/    public function api($url, $params=array(), $method='GET'){        $url=$this->api_url.$url;        $params['access_token']=$this->access_token;        $params['oauth_consumer_key']=$this->appid;        $params['format']='json';        if($method=='GET'){            $result_str=$this->http($url.'?'.http_build_query($params));        }else{            $result_str=$this->http($url, http_build_query($params), 'POST');        }        $result=array();        if($result_str!='')$result=json_decode($result_str, true);        return $result;    }    //提交请求    private function http($url, $postfields='', $method='GET', $headers=array()){        $ci=curl_init();        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);         curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);        curl_setopt($ci, CURLOPT_TIMEOUT, 30);        if($method=='POST'){            curl_setopt($ci, CURLOPT_POST, TRUE);            if($postfields!='')curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);        }        $headers[]='User-Agent: QQ.PHP(piscdong.com)';        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);        curl_setopt($ci, CURLOPT_URL, $url);        $response=curl_exec($ci);        curl_close($ci);        return $response;    }}
Nach dem Login kopieren

配置文件 config.php

<?php//配置文件header('Content-Type: text/html; charset=UTF-8');$qq_k=''; //QQ应用APP ID$qq_s=''; //QQ应用APP KEY$callback_url='http://yoururl/callback.php'; //授权回调网址$scope='get_user_info,add_share'; //权限列表,具体权限请查看官方的api文档
Nach dem Login kopieren

示例文件 demo.php

<?phpsession_start(); //此示例中要使用sessionrequire_once('config.php');require_once('qq.php');$qq_t=isset($_SESSION['qq_t'])?$_SESSION['qq_t']:'';//检查是否已登录if($qq_t!=''){    $qq=new qqPHP($qq_k, $qq_s, $qq_t);    $qq_oid=$qq->get_openid();    $openid=$qq_oid['openid']; //获取登录用户open id    //获取登录用户信息    $result=$qq->get_user_info($openid);    var_dump($result);    /**    //发布分享    $title='开源中国'; //分享页面标题    $url='http://www.oschina.net/'; //分享页面网址    $site=''; //QQ应用名称    $fromurl='';  //QQ应用网址    $result=$qq->add_share($openid, $title, $url, $site, $fromurl);    var_dump($result);    **/    /**    //其他功能请根据官方文档自行添加    //示例:根据openid获取用户信息    $result=$qq->api('user/get_user_info', array('openid'=>$openid), 'GET');    var_dump($result);    **/}else{    //生成登录链接    $qq=new qqPHP($qq_k, $qq_s);    $login_url=$qq->login_url($callback_url, $scope);    echo '<a href="',$login_url,'">点击进入授权页面</a>';}
Nach dem Login kopieren

回调文件 callback.php

<?php//授权回调页面,即配置文件中的$callback_urlsession_start(); //此示例中要使用sessionrequire_once('config.php');require_once('qq.php');if(isset($_GET['code']) && trim($_GET['code'])!=''){    $qq=new qqPHP($qq_k, $qq_s);    $result=$qq->access_token($callback_url, $_GET['code']);}if(isset($result['access_token']) && $result['access_token']!=''){    echo '授权完成,请记录<br/>access token:<input size="50" value="',$result['access_token'],'">';    //保存登录信息,此示例中使用session保存    $_SESSION['qq_t']=$result['access_token']; //access token}else{    echo '授权失败';}echo '<br/><a href="demo.php">返回</a>';
Nach dem Login kopieren
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage