其他分享
首页 > 其他分享> > 获取微信accesstoken并文件缓存方式

获取微信accesstoken并文件缓存方式

作者:互联网

function getAccessToken()
	{
		$appid = 'wx53cxxxxxx';
		$secret = 'f46xxxxxxxxxxxddda2';
		
		$accessTokenFile = './accessToken.txt';
		if (file_exists($accessTokenFile)) {//文件存在
			$time = time();
			$tokenFileJson = file_get_contents($accessTokenFile);
			$fileArrData = json_decode($tokenFileJson,true);
			$fileExpireTime = isset($fileArrData['expireTime'])?$fileArrData['expireTime']:0;
			if ($fileExpireTime > $time) {//请求token未过期
				$accessToken = isset($fileArrData['accessToken'])?$fileArrData['accessToken']:'';
				return $accessToken;
			}else{
				$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
				$jsonData = file_get_contents($url);
				$arrData = json_decode($jsonData,true);
				file_put_contents('./getToken.txt','【'.date("Y-m-d H:i:s").'】'.$jsonData.PHP_EOL,FILE_APPEND);
				if (isset($arrData['errcode'])) {
					exit($arrData['errmsg']);
				}else{
					$expireTime = time() + 5000;//过期时间
					$accessToken = isset($arrData['access_token'])?$arrData['access_token']:'';
					file_put_contents($accessTokenFile,json_encode(array('accessToken'=>$accessToken,'expireTime'=>$expireTime)));
					return $accessToken;
				}
			}
		}else{//文件不存在
			$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
			$jsonData = file_get_contents($url);
			$arrData = json_decode($jsonData,true);
			file_put_contents('./getToken.txt','['.date("Y-m-d H:i:s").']'.$jsonData.PHP_EOL,FILE_APPEND);
			if (isset($arrData['errcode'])) {
				exit($arrData['errmsg']);
			}else{
				$expireTime = time() + 5000;//过期时间
				$accessToken = isset($arrData['access_token'])?$arrData['access_token']:'';
				file_put_contents($accessTokenFile,json_encode(array('accessToken'=>$accessToken,'expireTime'=>$expireTime)));
				return $accessToken;
			}
		}
		

		
	}

  

标签:缓存,accesstoken,accessToken,微信,expireTime,token,contents,file,arrData
来源: https://www.cnblogs.com/dreamboycx/p/13576264.html