分享

持久化access_token - 傻瓜式微信开发教程24

 取经悟能 2015-10-10

安装php redis扩展 - 傻瓜式微信开发教程23 - 耗子原创中我们搞定了环境的搭建,
现在我们可以直接使用redis来缓存access_token了.

我们把配置项分离到`config.php`页面,里面存放了一下微信的字段和redis的连接字段等信息:

  1. <?php
  2.     // weixin
  3.     define('token', 'xxx');
  4.     define('aeskey', 'xxx');
  5.     define('appid', 'xxx');
  6.     define('appsecret', 'xxx');
  7.     define('debug', true);

  8.     // redis
  9.     define('redis_host', '127.0.0.1');
  10.     define('redis_port', 6379);
  11.     define('token_key', 'weixinshow001_token');
  12. ?>
复制代码


我们新建一个页面`token_get.php`,首先导入config.php,用来读取相关内容.

  1. require_once('config.php');
复制代码


之后实现`getToken`函数,返回一个数组,
其中有一个`error`字段,如果正确`error`为0,同时附带`msg`字段,
如果`error`不为0,则附带`msg`字段说明错误情况.

游客,如果您要查看本帖隐藏内容请回复


当我们需要在其他地方获取token的时候,使用方式如下:

  1. // 引入获取函数
  2. require_once('token_get.php');
  3. // 获取token信息
  4. $token_info = getToken();
  5. if ($token_info['error'] != 0) {
  6.     // 如果token获取错误,对错误进行处理
  7.     exit("get token error\n" . $token_info['msg']);
  8. }
  9. // 获取到了token
  10. $token = $token_info['token'];
复制代码


调用一次后,我们就可以从后台看到redis缓存的数据了,
下一次就会读取缓存数据,而不会调用api了
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多