tp框架下获取AccessToken

时间:2023-01-30 23:05:09
DROP TABLE IF EXISTS `tp_wx_token`;
CREATE TABLE `tp_wx_token` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `appid` varchar(100) DEFAULT NULL,
  `secret` varchar(100) DEFAULT NULL,
  `access_token` varchar(512) DEFAULT NULL,
  `expires_in` int(10) DEFAULT '0',
  `ticket` varchar(512) DEFAULT NULL,
  `ticket_time` int(10) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;


//使用 CURL 传送GET、POST数据,获取结果
function CURLSend($url,$method = 'get', $data = '',$type='') {
    $ch = curl_init(); //初始化
    if(!empty($type))curl_setopt($ch, CURLOPT_REFERER, $type);
    $headers = array('Accept-Charset: utf-8');
    //设置URL和相应的选项
    curl_setopt($ch, CURLOPT_URL, $url); //指定请求的URL
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method)); //提交方式
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //不验证SSL
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //不验证SSL
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //设置HTTP头字段的数组
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible;MSIE5.01;Windows NT 5.0)'); //头的字符串


    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1); //自动设置header中的Referer:信息
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //提交数值
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //是否输出到屏幕上,true不直接输出
    $temp = curl_exec($ch); //执行并获取结果
    curl_close($ch);
    return $temp; //return 返回值
}
function getAccessToken() {   
    $info = M('WxToken')->find(1);
    //判断access_token是否失效
    if ($info['expires_in'] < time()) {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$info['appid'].'&secret='.$info['secret'];
        $tmp = CURLSend($url); //json格式
        $obj = json_decode($tmp);
        if($obj->access_token !=null){
            $data = array('access_token' => $obj->access_token, 'expires_in' => (time() + $obj->expires_in));
            M('WxToken')->where('id=1')->save($data);
            return $obj->access_token;
        }else return 'error';
    } else return $info['access_token'];
}