AccessToken 2小时有效。

就不要每次都调取了,这样会造成浪费。

或者存入Session中,设置过期时间。

或者存入Redis中,设置过期时间。

过期之后,进行重新获取。

<?php

class WeixinAction extends CommonAction{
public $red;
const TOKEN_EXPIRES = 1000; public function _initialize(){
parent::_initialize();
vendor('Func.Red');
$this->red = Red::create();
} // 获取access_token
public function get_access_token() {
// 查询缓存中是否存在
$k = "access_token_".C('APPID');
if ($this->getCacheTtl($k)) {
return $this->getCache($k);
} vendor('Func.Http');
// 获取Token
$request_url = "https://api.weixin.qq.com/cgi-bin/token?";
$request_url .= "grant_type=client_credential&appid=".C('APPID')."&secret=".C('APP_SECRET'); $data = json_decode(Http::doGet($request_url,30),true); $this->setCache($k,$data['access_token'],$data['expires_in'] - self::TOKEN_EXPIRES); return $data['access_token'];
} // 存
protected function setCache($k, $v, $expires = -1)
{
if ($expires == -1) {
return $this->red->set($k, $v);
} else {
return $this->red->setex($k, $expires, $v);
}
} // 取
public function getCache($k) {
return $this->red->get($k);
} // 查看剩余时间
public function getCacheTtl($k)
{
$ttl = $this->red->ttl($k);
if ($ttl != '-2') {
return $ttl;
} else {
return false;
}
} // 查看是否存在
public function cacheExists($k)
{
return $this->red->exists($k);
} }

想得到AccessToken需要知道AppID和AppSecret。这两个数据,可以配置起来。

然后需要初始化Redis。

然后需要几个独立的Redis函数。

存储,获取,判断是否过期。

判断Redis中是否存在,且未过期。

如果有,直接获取。

如果没有,通过HttpGet请求,得到AccessToken。存入Redis中,并返回。

Redis很强大,只要保证key值不重复,就可以存储任何数据。

这里key值通过AppID进行唯一标示,防止有别的access_token也要存储。

PHP的redis扩展函数,功能强大!

最新文章

  1. webform中Session和Cookie对象的用法
  2. 准备开发一款开源NES模拟器
  3. linux中vi编辑器的使用
  4. Yii2-Redis使用小记 - Cache(转)
  5. Effective C++ -----条款23:宁以non-member、non-friend替换member函数
  6. 20160113 JS中CheckBox如何控制全选
  7. atom初体验
  8. 用scikit-learn实现朴素贝叶斯分类器 转
  9. codeforce 621B Wet Shark and Bishops
  10. How to effectively work with multiple files in Vim?
  11. iOS开发-OC语言 (七)继承、多态、类别
  12. Idea Maven 建本地仓库-导入本地JAR包
  13. php正则判断字符串是否含有中文
  14. go-mysql: database/sql 接口适配
  15. MyEclipse设置Console输出到文件
  16. apk的api级别不要低于26
  17. 学习python第三天
  18. python全栈开发 * 10知识点汇总 * 180612
  19. jq 绑定事件和解绑事件
  20. 详解C#7.0新特性

热门文章

  1. crm开发(基于ssh)(五)
  2. uva 11825 巧妙地子集枚举方法
  3. Mac环境下Android Studio配置Git以及最基本使用
  4. wget 官方jdk
  5. ARM汇编指令集1
  6. 团队作业:第五周 Alpha版本测试与发布
  7. react_webpack.prod.config
  8. week05《Java程序设计》第五次学习总结
  9. [转载] FFMPEG结构体分析:AVFrame
  10. input光标位置不居中问题