weixin-note PHP调用微信接口

总结一下微信接口如何调用

关于Token的获取
来自官方的说明:access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。
点击查看原文
官方有关接口频率的限制:公众号调用接口并不是无限制的。为了防止公众号的程序错误而引发微信服务器负载异常,默认情况下,每个公众号调用接口都不能超过一定限制,当超过一定限制时,调用对应接口会收到的错误返回码。

怎么做?

微信现在的Token是2个小时更新一次,而每天调用微信服务的次数是有限制的(虽然基本上是够用的),所以考虑把得到的Token值缓存在Memcache中,有效期为2个小时不到,这样能减少Token的生成次数。
实例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function getAccessToken($host = "127.0.0.1", $port = 11211)
{

//获取access_token值的接口
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
$memObj = new Memcache;
$memObj->connect($host, $port);
$access_token = $memObj->get("access_token");//获取token值
$token_time = $memObj->get("tokenTime"); //获取token值的生命期
if($access_token && $token_time) //token值和token值的生命期 都存在 都获取到
{
$timeNow = time();
$remainTime = $timeNow - $token_time;
if(6900 < $remainTime) //总的有效期是7200秒 如果离token的到期时间不足300秒 则更新token值
{
$res = $this->https_request($url);//GET 请求
$res = json_decode($res, TRUE); //解码json数据成数组
$this->access_token = $res['access_token'];
$memObj->set("access_token", $this->access_token, 0, 7200);
$memObj->set("tokenTime" , time(), 0, 0); //tokenTime值永远有效 用来存储token值存入的时间
}
else
{
$this->access_token = $access_token;
}
}
//code...