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;
}
上一篇:树莓派0 ubuntu无显示器ssh登录终端


下一篇:Substance风格实例大全javaswing皮肤风格大全(原)