PHP获取微信JS-SDK接口设置(access_token、jsapi_ticket、signature)
前端
引入JS文件
<script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
或
<script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
后端
PHP-Main
if (empty(Cache::get('accessToken'))) {
$access_token = $this->getAccessToken($setting['weixin_appid'], $setting['weixin_appsecret']);// 传入微信公众号信息
Cache::set('accessToken', $access_token, 7200);
}
else {
$access_token = Cache::get('accessToken');
}
if (empty(Cache::get('jsapiTicket'))) {
$jsapi_ticket = $this->getJsapiTicket($access_token);// 传入access_token
Cache::set('jsapiTicket', $jsapi_ticket, 7200);
}
else {
$jsapi_ticket = Cache::get('jsapiTicket');
}
if ($jsapi_ticket) {
$timestamp = time();
$nonceStr = $this->createNonceStr();
$http = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$http$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // 调用JSSDK的页面地址
$str = "jsapi_ticket={$jsapi_ticket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}";
$signature = sha1($str);
}
//$access_token、$jsapi_ticket、$signature均已获取
PHP-Function
public function getAccessToken($appid, $secret)
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
$res = $this->curl_get($url);
if ($res['errcode'] != 0) return false;// 获取AccessToken错误
return $res['access_token'];
}
public function getJsapiTicket($access_token)
{
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
$res = $this->curl_get($url);
if ($res['errcode'] != 0) return false;// 获取JsapiTicket错误
return $res['ticket'];
}
public function curl_get($url)
{
$headerArray = array("Content-type:application/json;", "Accept:application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output, true);
return $output;
}
public function curl_post($url, $data)
{
$data = json_encode($data);
$headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return json_decode($output, true);
}
public 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;
}