一、获取流程
1、获取 access_token
2、通过access_token换取 jsapi_ticket
3、签名算法
签名生成规则如下:参与签名的字段包括noncestr(随机字符串), 有效的jsapi_ticket, timestamp(时间戳), url(当前网页的url,不包含#及其后面部分) 。对所有待签名参数按照字段名的ascii 码从小到大排序(字典序)后,使用url键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1。这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,字段名和字段值都采用原始值,不进行url 转义。
二、具体实现方式
1、获取access_token
/**
* [getaccesstoken description] 获取access_token
* @return [type] [description] */private function getaccesstoken() {
$data = $this->getfile($this->accesstokenfile); if(time() - $data['time'] > 0){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
$re = $this->httpget($url);
$access_token = $re['access_token'];
if(isset($access_token)){
$data['access_token'] = $access_token;
$data['time'] = time() + 7200;
$this->setfile($this->accesstokenfile,json_encode($data));
}
}else{
$access_token = $data['access_token'];
} return $access_token;
}
access_token 的有效时间是7200s,故可以采用文件存储的方法进行保存,避免多次请求;
2、获取jsapi_ticket
/**
* [getjsapiticket description] 获取jsapi_ticket
* @return [type] [description] */private function getjsapiticket() {
$access_token = $this->getaccesstoken();
$jsapi_ticket = $this->getfile($this->jsapiticketfile); if(time() - $jsapi_ticket['time'] > 0) {
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
$re = $this->httpget($url);
$this->prearr($re);
$jsapi_ticket = $re['ticket'];
if(isset($jsapi_ticket)){
$data['jsapi_ticket'] = $jsapi_ticket;
$data['time'] = time() + 7200;
$this->setfile($this->jsapiticketfile, json_encode($data));
}
}else{
$jsapi_ticket = $jsapi_ticket['jsapi_ticket'];
} return $jsapi_ticket;
}
通过access_token进行交换,得到jsapi_ticket,有效期也是7200s;
3、生成签名
/**
* [getsignpackage description] 获取签名
* @return [type] [description] */public function getsignpackage(){
$jsapi_ticket = $this->getjsapiticket(); // 注意 url 一定要动态获取,不能 hardcode.
$protocol = (!empty($_server['https']) && $_server['https'] !== 'off' || $_server['server_port'] == 443) ? "https://" : "http://";
$url = "$protocol$_server[http_host]$_server[request_uri]";
$noncestr = $this->createnoncestr();
$timestamp = time();
$string1 = "jsapi_ticket={$jsapi_ticket}&noncestr={$noncestr}×tamp={$timestamp}&url={$url}";
$signature = sha1($string1);
$signpackage = array(
'appid' => $this->appid,
'noncestr' => $noncestr,
'timestamp' => $timestamp,
'signature' => $signature,
);
return $signpackage;
}
签名算法,
使用url键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1:
对string1进行sha1签名,得到signature:
注意事项:
1.签名用的noncestr和timestamp必须与wx.config中的noncestr和timestamp相同。
2.签名用的url必须是调用js接口页面的完整url。
3.出于安全考虑,开发者必须在服务器端实现签名的逻辑
以上就是关于微信开发中获取jsapi_ticket的详细内容。