微信公众号开发 ThinkPHP3.2获取access_token和jsapi_ticket以及全局缓存

梦想不抛弃苦心追求的人,只要不停止追求,你们会沐浴在梦想的光辉之中。再美好的梦想与目标,再完美的计划和方案,如果不能尽快在行动中落实,最终只能是纸上谈兵,空想一番。只要瞄准了大方向,坚持不懈地做下去,才能够扫除挡在梦想前面的障碍,实现美好的人生蓝图。微信公众号开发 ThinkPHP3.2获取access_token和jsapi_ticket以及全局缓存,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

首先,微信公众号开发有2个access_token,分别为基础接口的access_token和网页授权oauth2.0的access_token,在此就先讲基础接口的access_token。根据微信公众号开发文档,先获取到基础接口的access_token,再由这个access_token获取到jsapi_ticket,然后这两个玩意的有效期为7200秒,在接口权限中写明access_token每天调用上限2000次,jsapi_ticket每天调用上限1000000次,因此需要开发者对这两个玩意进行file或者Cache全局缓存。

1、使用TP3.2框架,在Application/Home模块下的Controller控制器目录,新建控制器CommonController.class.php

<?php
namespace Home\Controller;
use Think\Controller;

class CommonController extends Controller {
    public function _initialize()
    {
        $jssdk = new JSSDK(C('appID'),C('appSecret'));

        $appID = C('appID');
        $appSecret = C('appSecret');
        $accessToken = $jssdk->getAccessToken();
        $signPackage = $jssdk->GetSignPackage();

        $this->assign('appID',$appID);
        $this->assign('appSecret',$appSecret);
        $this->assign('accessToken',$accessToken);
        $this->assign('signPackage',$signPackage);
    }
}

/**
 * 微信方法
*/
class JSSDK {
    private $appId;
    private $appSecret;

    public function __construct($appId, $appSecret) {
      $this->appId = $appId;
      $this->appSecret = $appSecret;
    }
    
    public function getSignPackage() {
      $jsapiTicket = $this->getJsApiTicket();
      $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
      $timestamp = time();
      $nonceStr = $this->createNonceStr();
      // 这里参数的顺序要按照 key 值 ASCII 码升序排序
      $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
      $signature = sha1($string);
      $signPackage = array(
        "appId"     => $this->appId,
        "nonceStr"  => $nonceStr,
        "timestamp" => $timestamp,
        "url"       => $url,
        "signature" => $signature,
        "rawString" => $string
      );
      return $signPackage; 
    }

    private function createNonceStr($length = 16) {
      $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $str = "";
      for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
      }
      return $str;
    }

    private function getJsApiTicket() {
      // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
      $data = json_decode(file_get_contents("jsapi_ticket.json"));
      if ($data->expire_time < time()) {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $res = json_decode($this->httpGet($url));
        $ticket = $res->ticket;
        if ($ticket) {
          $data->expire_time = time() + 7000;
          $data->jsapi_ticket = $ticket;
          $fp = fopen("jsapi_ticket.json", "w");
          fwrite($fp, json_encode($data));
          fclose($fp);
        }
      } else {
        $ticket = $data->jsapi_ticket;
      }
      return $ticket;
    }

    public 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;
    }
    
    private function httpGet($url) {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_TIMEOUT, 500);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
      curl_setopt($curl, CURLOPT_URL, $url);
      $res = curl_exec($curl);
      curl_close($curl);
      return $res;
    }
}

2、在Application/Common模块下的Config目录,新建配置文件config.php

<?php
return array(
    //'配置项'=>'配置值'
    'TOKEN'=>'weixin',
    'appID'=>'你的微信公众号appID',
    'appSecret'=>'你的微信公众号appSecret',

    'DB_TYPE' => 'mysql',
    'DB_HOST' => '127.0.0.1',
    'DB_NAME' => '你的数据库名',
    'DB_USER' => '你的数据库用户名',
    'DB_PWD' => '你的数据库密码',
    'DB_PORT' => 3306,
    
    '__PUBLIC__' =>  __ROOT__.'/Public',// 站点公共目录
);

3、在Application/Home模块下的Controller控制器目录,新建控制器IndexController.class.php

<?php
namespace Home\Controller;
// use Think\Controller;

class IndexController extends CommonController {
    public function index(){        
        $this->display();
    }
}

4、在Application/Home模块下的View视图目录,新建Index/index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Document</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
</head>
<body>
  <b>基础接口accessToken:{$accessToken}</b>
  <p>微信公众号appId:{$signPackage.appId}</p>
  <p>时间戳:{$signPackage.timestamp}</p>
  <p>随机字符串:{$signPackage.nonceStr}</p>
  <p>签名:{$signPackage.signature}</p>
</body>
</html>

5、访问http://你的域名/index.php/Home/Index/index/index

微信公众号开发 ThinkPHP3.2获取access_token和jsapi_ticket以及全局缓存

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/151221.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!