zoukankan      html  css  js  c++  java
  • Redis存储AccessToken

    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扩展函数,功能强大!

  • 相关阅读:
    QML中的states用法
    mako的namespace(四)
    Dynamics CRM2013 按钮自定义开发工具 Ribbon Workbench 介绍
    CRM 导入导出附件上传大小限制控制
    插件(plugin)调试技巧及注意事项
    Dynamics CRM2013 自定义开发工具 Dynamics XRM Tools 介绍
    传递正能量,拒绝负能量!加油
    让人无语的编程环境
    转NET(C#):线程本地存储(ThreadLocal Storage)之ThreadStatic, LocalDataStoreSlot和ThreadLocal<T>
    转javaThreadLocal
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/9119150.html
Copyright © 2011-2022 走看看