• 微信 token ticket jsapi_ticket access_token 获取 getAccessToken get_jsapi_ticket方法


     获取jsapi_ticket

    function get_jsapi_ticket()//依赖getAccessToken、https_request
    {
        //从memcache中获取
        $mmc = memcache_init(); if($mmc == false){ logger("mc init failed
    "); }
    
        $last_time = memcache_get($mmc,"jsapi_last_time");
        $jsapi_ticket = memcache_get($mmc,"ticket");
        if(time() > ($last_time + 7200) || empty($jsapi_ticket)){
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".getAccessToken()."&type=jsapi";
            $result = https_request($url);
            
            memcache_set($mmc,"jsapi_ticket", $result["ticket"]);
            memcache_set($mmc,"jsapi_last_time", time());
            
            if(empty($result["ticket"])){ echo 'jsapi_ticket null'; die;}
            return $result["ticket"]; 
        }
        return $jsapi_ticket;
    }

    memcache缓存存储用户信息7000秒

    <?php
    function getAccessToken($appid,$appsecret) 
    {
        $mem = new CacheMemcache();
        $acc = $mem->get('access_token_'.$appid);
        if (!$acc) 
        {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
            $result = https_request($url);
            $jsoninfo = json_decode($result, true);
            $access_token = $jsoninfo['access_token'];
            if ($access_token) 
            {
                $expire = time() + 7000;
                $mem = new CacheMemcache();
                $mem->set('access_token_'.$appid,$access_token,$expire);
            }
        }
        else 
        {
            $access_token = $acc;
        }
        return $access_token;
    }
    ?>

    文件存储access_token

     function getAccessToken() {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("access_token.json"));
        if ($data->expire_time < time()) {
          $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
          $res = json_decode($this->httpGet($url));
          $access_token = $res->access_token;
          if ($access_token) {
            $data->expire_time = time() + 7000;
            $data->access_token = $access_token;
            $fp = fopen("access_token.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
          }
        } else {
          $access_token = $data->access_token;
        }
        return $access_token;
      }
  • 相关阅读:
    Java & PHP RSA 互通密钥、签名、验签、加密、解密
    Spring Cloud:Security OAuth2 自定义异常响应
    Spring Cloud:统一异常处理
    Spring Cloud:多环境配置、eureka 安全认证、容器宿主机IP注册
    Hexo + GitEE 搭建、备份、恢复、多终端
    Spring:AOP面向切面编程
    如何找到适合自己的文档工具?
    比较好玩的工具类合集推荐!!!
    C++11 如何使代码仅执行一次?
    CMake 常用操作有哪些?
  • 原文地址:https://www.cnblogs.com/shaoing/p/6080328.html
Copyright © 2020-2023  润新知