安装php redis扩展 - 傻瓜式微信开发教程23 - 耗子原创中我们搞定了环境的搭建, 现在我们可以直接使用redis来缓存access_token了.
我们把配置项分离到`config.php`页面,里面存放了一下微信的字段和redis的连接字段等信息:
- <?php
- // weixin
- define('token', 'xxx');
- define('aeskey', 'xxx');
- define('appid', 'xxx');
- define('appsecret', 'xxx');
- define('debug', true);
- // redis
- define('redis_host', '127.0.0.1');
- define('redis_port', 6379);
- define('token_key', 'weixinshow001_token');
- ?>
复制代码
我们新建一个页面`token_get.php`,首先导入config.php,用来读取相关内容.
- require_once('config.php');
复制代码
之后实现`getToken`函数,返回一个数组, 其中有一个`error`字段,如果正确`error`为0,同时附带`msg`字段, 如果`error`不为0,则附带`msg`字段说明错误情况.
当我们需要在其他地方获取token的时候,使用方式如下:
- // 引入获取函数
- require_once('token_get.php');
- // 获取token信息
- $token_info = getToken();
- if ($token_info['error'] != 0) {
- // 如果token获取错误,对错误进行处理
- exit("get token error\n" . $token_info['msg']);
- }
- // 获取到了token
- $token = $token_info['token'];
复制代码
调用一次后,我们就可以从后台看到redis缓存的数据了, 下一次就会读取缓存数据,而不会调用api了
|