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

6人阅读 评论(0) 收藏 举报
分类:

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


查看评论

将小写数字金额转成大写金额

procedure TfmBMZC.BitBtn2Click(Sender: TObject); //金额转换const  chNum : array[0..9] of string = (零,壹,贰...
  • tlovexyj
  • tlovexyj
  • 2001-04-26 13:40:00
  • 810

微信&java 开发6 全局缓存access_token与jsapi_ticket

access_token与jsapi_ticket 需要全局缓存为什么我就不说了,既然来看了就应该知道了 我用的是spring容器加载完毕后监听器,就是容器加载完毕调用 ApplicationLis...
  • cnm_1314
  • cnm_1314
  • 2016-05-12 13:40:53
  • 7304

微信公众号开发(二)获取AccessToken、jsapi_ticket

Access Token在微信公众平台接口开发中,Access Token占据了一个很重要的地位,相当于进入各种接口的钥匙,拿到这个钥匙才有调用其他各种特殊接口的权限。 access_token是公...
  • lwpoor123
  • lwpoor123
  • 2017-12-07 16:42:38
  • 1061

微信公众号开发:access_token和jsapi_ticket的缓存和数据库存储方案

微信JS—SDK开放接口给我们的开发提供了很大的便利,以及更多的可能,鼓舞了我们做web app的信心。初看接口,感觉不是很简单,特别是还有demo做实例;由于太缺乏经验,后面自己做的过程中还是花费了...
  • hzqtx12345
  • hzqtx12345
  • 2015-05-30 15:03:09
  • 6454

采用java单例模式实现微信AccessToken和Jsapi_ticket缓存支持

一、单例模式介绍 java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例、饿汉式单例、登记式单例。   单例模式有以下特点:   1、单例类只能有一个实例。...
  • honghailiang888
  • honghailiang888
  • 2016-02-22 09:58:17
  • 2635

微信公众号开发获取access_token和jsapiticket

Java实现HTTP的GET请求示例: import java.io.BufferedReader; import java.io.InputStream; import java.io.InputS...
  • qq_33765907
  • qq_33765907
  • 2017-11-06 15:08:36
  • 324

nodejs微信开发access_token jsapi_ticket signature的获得

//express_demo.js 文件 var express = require('express'); var request = require('request'); //请求页面的服务 ...
  • dongmelon
  • dongmelon
  • 2017-03-09 16:55:44
  • 1614

微信接口开发缓存全局token,ticket

在服务启动监听器里定时请求,缓存到静态的变量中,time=7000秒public class StartupListener extends ContextLoaderListener impleme...
  • xu982604405
  • xu982604405
  • 2015-04-17 16:03:00
  • 1982

weinx公众号--AccessToken和JsapiTicket的获取方法及长期保存 (整合)

创建 AccessToken实体类 和 JsapiTicket 实体类 ,用来长久保存 token 和 ticket 值  package com.play.bean; /**  * 微信通用接...
  • u014799292
  • u014799292
  • 2016-03-02 11:51:52
  • 2491

微信测试号开发之四 获取access_token和jsapi_ticket

access_token:公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。acces...
  • qq_37936542
  • qq_37936542
  • 2017-11-16 11:48:46
  • 1341
    个人资料
    持之以恒
    等级:
    访问量: 5067
    积分: 435
    排名: 11万+
    文章存档
    最新评论