前端直接读取接口getApiTicketAction并传入url。
vue里url获取
var urls = window.location.href.split('#')[0]; //当前网页的URL,不包含#及其后面部分
php端
//拿tokeng
public function gettonken()
{
$site = xn_cfg('base');
$appid = $site['wxchat_appid'];
$appsecret = $site['wxchat_secret'];
$token = Db::name('wxtoken')->where('id',2)->find();
$minute=floor((time()-$token['create_time'])%86400/60);
$access_token=$token['token'];
if ($minute>100){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
$weixin = file_get_contents($url);
$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
$array = get_object_vars($jsondecode);//转换成数组
$access_token = $array['access_token'];//输出token
$expires_in=$array['expires_in'];//输出token
Db::name('wxtoken')->where('id',2)->update(['token'=>$access_token,'create_time'=>time()]);
}
return $access_token;
}
//拿Ticket
public function getJsApiTicket()
{
$site = xn_cfg('base');
$appid = $site['wxchat_appid'];
$appsecret = $site['wxchat_secret'];
$token = Db::name('wxtoken')->where('id',3)->find();
$minute=floor((time()-$token['create_time'])%86400/60);
$access_token=$token['token'];
if ($minute>100){
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$this->gettonken();
$weixin = file_get_contents($url);
$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
$array = get_object_vars($jsondecode);//转换成数组
$access_token = $array['ticket'];//输出token
$expires_in=$array['expires_in'];//输出token
Db::name('wxtoken')->where('id',3)->update(['token'=>$access_token,'create_time'=>time()]);
}
return $access_token;
}
public function getApiTicketAction(Request $request)
{
$site = xn_cfg('base');
$param = $request->param();
$url =$param['url'];
$appid = $site['wxchat_appid'];
$jsapiTicket = $this->getJsApiTicket();
$timestamp = time();
$nonceStr = $this->createNonceStr(); //构造一个随机数,用来生成签名的一部分
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; //签名算法先按照ascII码排序
$signature = sha1($string); //对排序好的字符串加密
$signPackage = array(
"appId" => $appid,
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"signature" => $signature,
);
return success($signPackage);
}
private function createNonceStr($length = 16) { //生成随机16个字符的字符串
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}