用户
 找回密码
 入住 CI 中国社区
搜索
查看: 14932|回复: 15
收起左侧

[库 Library] [原创]最新的微信网页(不关注公共平台也可以)Oauth2.0类库

[复制链接]
发表于 2014-7-27 11:22:06 | 显示全部楼层 |阅读模式
本帖最后由 qfly888 于 2014-7-27 11:42 编辑

一、首先在config文件夹下新建文件“wx_oauth.php”(配置文件),包含如下代码:
PHP复制代码
 
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// 用于验证微信接口配置信息的Token,可以任意填写
$config['token'] = '接口配置信息的Token';
 
// appID
$config['appid'] = '你的appid';
 
// appSecret
$config['secret'] = '你的secret';
 
// 回调链接地址
$config['redirect_uri'] = '你需要设置的回掉地址';
 
// 是否以 HTTPS 安全协议访问接口
$config['https_request']        = true;
 
// 授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),
// snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,
// 即使在未关注的情况下,只要用户授权,也能获取其信息)
$config['scope'] = 'snsapi_userinfo';
 
// 语言
$config['lang'] = 'zh_CN'; // zh_CN 简体,zh_TW 繁体,en 英语
 
// 微信公众账户授权地址
$config['mp_authorize_url'] = 'https://api.weixin.qq.com/cgi-bin/token';
// 授权地址
$config['authorize_url'] = 'https://open.weixin.qq.com/connect/oauth2/authorize';
// 获取access token 的地址
$config['access_token_url'] = 'https://api.weixin.qq.com/sns/oauth2/access_token';
// 刷新 token 的地址
$config['refresh_token_url'] = 'https://api.weixin.qq.com/sns/oauth2/refresh_token';
// 获取用户信息地址
$config['userinfo_url'] = 'https://api.weixin.qq.com/sns/userinfo';
// 验证access token
$config['valid_token_url'] = 'https://api.weixin.qq.com/sns/auth';
 
 
复制代码



二、将“wx_oauth.php”(类库文件),代码如下:
PHP复制代码
 
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
 
/**
* Weixin_oauth 类库,主要是远程抓取页面,默认http请求,也可以使用https请求,
* 可以在初始化的时候通过传入可选参数https为true,设置为https请求
*/

class Wx_oauth
{
        const TIMEOUT = 5;                        // 设置超时时间
 
        private $ci;                                // CI对象
        private $ch;                                // curl对象
       
        function __construct()
        {
                $this->ci =& get_instance();
                $this->ci->config->load('wx_oauth');                // 载入配置文件
        }
 
        /**
         * 验证配置接口信息
         * @param array 从微信接口发送来的信息,通过$_GET获得
         */

        public function interface_valid($get_request)
        {
                $signature = $get_request['signature'];
                $timestamp = $get_request['timestamp'];
                $nonce = $get_request['nonce'];        
 
                $token = $this->ci->config->item('token');
                $tmpArr = array($token, $timestamp, $nonce);
                sort($tmpArr);
                $tmpStr = implode( $tmpArr );
                $tmpStr = sha1( $tmpStr );
 
                if( $tmpStr == $signature ){
                        echo $get_request['echostr'];
                        exit;
                }
        }
 
        /**
         * 生成用户授权的地址
         * @param string 自定义需要保持的信息
         * @param bool 是否是通过公众平台方式认真
         */

        public function authorize_addr($state='', $mp=false)
        {
                if ($mp) {
                        $data = array(
                                'appid'=>$this->ci->config->item('appid'),
                                'secret'=>$this->ci->config->item('secret'),
                                'grant_type'=>'client_credential');
                        $url = $this->ci->config->item('mp_authorize_url');
                } else {
                        $data = array(
                                'appid'=>$this->ci->config->item('appid'),
                                'redirect_uri'=>urlencode($this->ci->config->item('redirect_uri')),
                                'response_type'=>'code',
                                'scope'=>$this->ci->config->item('scope'),
                                'state'=>$state,
                                '#wechat_redirect'=>'');
                        $url = $this->ci->config->item('authorize_url');
                }
               
                return $url . $this->create_url($data);
        }
 
        /**
         * 获取 access token
         * @param string 用于换取access token的code,微信提供
         */

        public function access_token($code)
        {
                $data = array(
                        'appid'=>$this->ci->config->item('appid'),
                        'secret'=>$this->ci->config->item('secret'),
                        'code'=>$code,
                        'grant_type'=>'authorization_code');
                // 生成授权url
                $url = $this->ci->config->item('access_token_url');
                return $this->send_request($url, $data);
        }
 
        /**
         * 刷新 access token
         * @param string 用于刷新的token
         */

        public function refresh_token($refresh_token)
        {
                $data = array(
                        'appid'=>$this->ci->config->item('appid'),
                        'refresh_token'=>$refresh_token,
                        'grant_type'=>'refresh_token');
                // 生成授权url
                $url = $this->ci->config->item('refresh_token_url');
                return $this->send_request($url, $data);
        }
 
        /**
         * 获取用户信息
         * @param string access token
         * @param string 用户的open id
         */

        public function userinfo($token, $openid)
        {
                $data = array(
                        'access_token'=>$token,
                        'openid'=>$openid,
                        'lang'=>$this->ci->config->item('lang'));
                // 生成授权url
                $url = $this->ci->config->item('userinfo_url');
                return $this->send_request($url, $data);
        }
 
        /**
         * 检验access token 是否有效
         * @param string access token
         * @param string 用户的open id
         */

        public function valid($token, $openid)
        {
                $data = array(
                        'access_token'=>$token,
                        'openid'=>$openid);
                // 生成授权url
                $url = $this->ci->config->item('valid_token_url');
                return $this->send_request($url, $data);
        }
 
        /**
         * 发送curl请求,并获取请求结果
         * @param string 请求地址
         * @param array 如果是post请求则需要传入请求参数
         * @param string 请求方法,get 或者 post, 默认为get
         * @param bool 是否以https协议请求
         */

        private function send_request($request, $params, $method='get', $https=true)
        {
                // 以get方式提交
                if ($method == 'get') {
                        $request = $request . $this->create_url($params);
                }
 
                $this->ch = curl_init($request);
                curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);// 设置不显示结果,储存入变量
                curl_setopt($this->ch, CURLOPT_TIMEOUT, self::TIMEOUT); // 设置超时限制防止死循环
 
                // 判断是否以https方式访问
                if ($https) {
                        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
                }
 
                if ($method == 'post') {        // 以post方式提交
                        curl_setopt($this->ch, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params); // Post提交的数据包
                }
               
                $tmpInfo = curl_exec($this->ch); // 执行操作
                if (curl_errno($this->ch)) {
                        echo 'Errno:'.curl_error($this->ch);//捕抓异常
                }
                curl_close($this->ch); // 关闭CURL会话
 
                return $tmpInfo; // 返回数据
        }
 
        /**
         * 生成url
         */

        private function create_url($data)
        {
                $temp = '?';
                foreach ($data as $key => $item) {
                        $temp = $temp . $key . '=' . $item . '&';
                }
                return substr($temp, 0, -1);
        }
}
 
/**
 * End fo wx_oauth.php file
 */

 
复制代码


文件中注释的已经很清楚了,所以不用我细说了吧,下面是我测试的controller:
PHP复制代码
 
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class Site extends CI_Controller {
        public function __construct()
        {
                parent::__construct();
                $this->load->helper('url');
                $this->load->library('wx_oauth');
        }
 
        public function index()
        {
                $addr = $this->wx_oauth->authorize_addr();
                echo anchor($addr, 'authorize!!!');
        }
 
        public function callback()
        {
                $code = $_GET['code'];
                $response = $this->wx_oauth->access_token($code);
                echo '<pre>';
                print_r($r = json_decode($response));
                echo '</pre>';
                echo anchor('site/refresh/'.$r->refresh_token, 'refresh'),'<br>';
                echo anchor('site/info/'.$r->access_token.'/'.$r->openid, 'user info'),'<br>';
                echo anchor('site/valid/'.$r->access_token.'/'.$r->openid, 'valid access');
 
        }
 
        public function refresh($refresh_token)
        {
                $response = $this->wx_oauth->refresh_token($refresh_token);
                echo '<pre>';
                print_r(json_decode($response));
                echo '</pre>';
        }
 
        public function info($access_token, $openid)
        {
                header("Content-type: text/html; charset=gbk");
                $response = $this->wx_oauth->userinfo($access_token, $openid);
                echo '<pre>';
                print_r(json_decode($response));
                echo '</pre>';
        }
        public function valid($access_token, $openid)
        {
                $response = $this->wx_oauth->valid($access_token, $openid);
                echo '<pre>';
                print_r(json_decode($response));
                echo '</pre>';
        }
}
 
/* End of file site.php */
/* Location: ./application/controllers/site.php */
 
 
复制代码




测试微信接口,需要时用微信访问网页。
首先要到微信官网申请个测试账号,然后就可以用了,当然了,如果获得微信认证就更好了。


发表于 2014-10-8 13:32:43 | 显示全部楼层
江流 发表于 2014-10-8 12:15
这里的 defined('BASEPATH')) 中,BASEPATH是指什么?

这个不用你关心,只要放到 CI 里,这个就可以工作。

发表于 2016-4-9 00:13:30 | 显示全部楼层
hzh 发表于 2016-4-8 23:16
就是这个微信授权登录   我不知道怎么用这位姐姐的代码啊!

那你得问问楼主
发表于 2016-4-6 23:03:11 | 显示全部楼层
Hex 发表于 2014-10-8 13:32
这个不用你关心,只要放到 CI 里,这个就可以工作。

大神  教我使用这个好么?
发表于 2014-9-28 09:52:15 | 显示全部楼层
很好,迟些试试。
发表于 2014-10-8 12:15:54 | 显示全部楼层
这里的 defined('BASEPATH')) 中,BASEPATH是指什么?
发表于 2015-1-11 18:57:26 | 显示全部楼层
请问 你这个需要微信服务号通过认证吗?
发表于 2015-4-22 09:13:35 | 显示全部楼层
楼主,你好。你确定以上代码实现了授权获取未关注的用户信息吗?我看了下,代码里面也没什么特别的地方啊
发表于 2015-10-21 20:01:51 | 显示全部楼层
江流 发表于 2014-10-8 12:15
**** 作者被禁止或删除 内容自动屏蔽 ****

请查看根目录index.php
发表于 2015-11-21 16:35:14 | 显示全部楼层
代码哪儿下载?上面没有index.php
发表于 2016-4-4 01:34:33 | 显示全部楼层
姐姐   开口配置信息的Token  怎么获取啊!

本版积分规则