/*
表结构
CREATE TABLE `wx_menuset` (
`menusetid` int(11) NOT NULL AUTO_INCREMENT,
`appid` varchar(100) DEFAULT NULL,
`appsecret` varchar(100) DEFAULT NULL,
`accesstoken` varchar(250) DEFAULT NULL,
`lasttime` int(10) DEFAULT NULL,
PRIMARY KEY (`menusetid`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
menusetid 主键ID
appid 微信平台 AppId
appsecret 微信平台 AppSecret
accesstoken 通过 appid 和 appsecret 获取到的 access_token 串值
lasttime 最后更新 access_token 的时间
# 首次使用,需手动在表内添加一条记录 填入menusetid和appid和appsecret字段即可 ( accesstoken字段留空 )
*/
function accessToken(){
$sql = ‘SELECT menusetid,appid,appsecret,accesstoken,lasttime FROM wx_menuset ORDER BY lasttime DESC LIMIT 1‘;
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
if(isset($row[‘lasttime‘])){
if($row[‘lasttime‘]+7000>time() && $row[‘accesstoken‘]!=‘‘){
return $row[‘accesstoken‘];
}else{
$appid = $row[‘appid‘];
$appsecret = $row[‘appsecret‘];
$url = ‘https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=‘.$appid.‘&secret=‘.$appsecret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$jsoninfo = json_decode($output, true);
$access_token = $jsoninfo["access_token"];
$sql = sprintf(‘UPDATE wx_menuset SET accesstoken = \‘%s\‘,lasttime = \‘%d\‘ WHERE menusetid = %d‘,$access_token,time(),$row[‘menusetid‘]);
$res = mysql_query($sql);
if($res){
return $access_token;
}else{
return false;
}
}
}else{
return false;
}
}