按照微信公众号第三方平台的文档,测试到获取令牌时发现无法获取到,提示{“errcode”:41002,”errmsg”:”appid missing”},如下图:
后通过网上搜索,发现文档中要求是将一个json格式的字符串post过去,而非数组。
故代码应改为:
$url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
$data['component_appid'] = $this->appid;
$data['component_appsecret'] = $this->appSecret;
$data['component_verify_ticket'] = $this->ticket();
$data = json_encode($data);
$result = http($url,$data);
http函数的代码为:
function http($url, $POSTFIELDS=null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
if($POSTFIELDS){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
}
$response = curl_exec ($ch);
curl_close ($ch);
if(empty($response)){
return '-100000';
}
return json_decode($response,true);
}
此时,就可以获取到了。获取到后,令牌的有效期是2小时,故应该将此令牌进行缓存,官方建议的缓存时间是1小时50分钟。