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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cai181191/article/details/79979431

首先,微信公众号开发有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


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页