public function ticket(){
if(request() -> isAjax()){
//包装curl的方法
function get_curl_contents($url, $method ='GET', $data = array()) {
if ($method == 'POST') {
//使用crul模拟
$ch = curl_init();
//允许请求以文件流的形式返回
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch); //执行发送
curl_close($ch);
}else {
if (ini_get('allow_<a href="/tags.php/fopen/" target="_blank">fopen</a>_url') == '1') {
$result = file_get_contents($url);
}else {
//使用crul模拟
$ch = curl_init();
//允许请求以文件流的形式返回
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//禁用https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch); //执行发送
curl_close($ch);
}
}
return $result;
}
//创建随机字符串
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;
}
function wx_get_jsapi_ticket() {
$path = ROOT_PATH.'public/jsapi_ticket.txt';
$jsonStr = file_get_contents($path);
$jsonArr = json_decode($jsonStr, true);
$res = $jsonArr;
if($jsonArr['create_time'] + $jsonArr['expires_in'] > time()){
$url = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", getAccess_token());
$res = get_curl_contents($url);
$res = json_decode($res, true);
$res['create_time'] = time();
file_put_contents($path, json_encode($res));
}
return $res['ticket'];
}
$wx = array();
//生成签名的时间戳
$wx['timestamp'] = time();
//生成签名的随机串
$wx['noncestr'] = createNonceStr();
//jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。
$wx['jsapi_ticket'] = wx_get_jsapi_ticket();
//分享的地址,注意:这里是指当前网页的URL,不包含#及其后面部分,曾经的我就在这里被坑了,所以小伙伴们要小心了
$wx['url'] = "http://www.grandvisual.com.cn/dist/";
$string = sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s", $wx['jsapi_ticket'], $wx['noncestr'], $wx['timestamp'], $wx['url']);
$wx['appId'] = config('wechat.APP_ID');//appid
$wx['signature'] = sha1($string);//生成签名
$wx['coupon_id'] = $this -> shareDiscounted();//优惠券id
return j('000', $wx);
}
}
微信公众号分享php代码(tp5)
最新推荐文章于 2021-09-26 16:14:33 发布