其他分享
首页 > 其他分享> > tp5 获取微信分享配置

tp5 获取微信分享配置

作者:互联网

private $appId = '微信appid';
private $appSecret = '微信appSecret ';
//获取分享配置
public function config()
{
	$jsapiTicket = $this->getJsApiTicket();
	
	// 注意 URL 一定要动态获取,不能 hardcode.
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$url = URLdecode($_REQUEST['url']);
	$timestamp = time();
	$nonceStr = $this->createNonceStr();
	// 这里参数的顺序要按照 key 值 ASCII 码升序排序
	$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	$appid = $this->appId;
	$signature = sha1($string);
	$signPackage = array(
		"appId"     	=> $appid,
		"nonceStr"  	=> $nonceStr,
		"timestamp" 	=> $timestamp,
		"url"       	=> $url,
		"signature" 	=> $signature,
		"rawString" 	=> $string,
		"jsapiTicket" 	=> $jsapiTicket,
		"title" 		=> '分享标题',
		"link" 			=> '分享链接',
		"image" 		=> '封面图'
	);
	$this->result($signPackage, 1, '链接配置');
}

//获取jsapi_ticket
private function getJsApiTicket() {
	//jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
	$access_token = $this->getAccessToken();
	if(Session('jsapiTicket')){
	    $jsapiTicket = Session('jsapiTicket');
	}else{
	    $jsapi_ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
	    $jsapi = $this->getJson($jsapi_ticket);
	    $jsapiTicket = $jsapi['ticket'];
	    Session('jsapiTicket', $jsapi['ticket']);
	}
	return $jsapiTicket;
}
 
//获取access_token 
private function getAccessToken() {
	// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
	$appid = $this->appId;
	$secret = $this->appSecret;
	if(Session('access_token')){
		$access_token = Session('access_token');
	}else{
		$re = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
		$arr = $this->getJson($re);
		$access_token = $arr['access_token'];
		Session('access_token', $access_token);
	}
	return $access_token;
}

//获取随机数
private 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;
}

标签:jsapiTicket,微信,jsapi,token,access,tp5,appid,ticket,分享
来源: https://blog.csdn.net/dongsiwei196823/article/details/110387809