根据微信openid获取用户信息类,缓存access

tech2025-12-30  2

<?php /** * 关注公众号回调事件操作 * 或者根据openid获取用户信息 * * $obj = new Follow(); * $res = $obj->getUserinfo(..); * */ class Follow { private $appid=''; //公众号在微信的appid private $secret =''; //公众号在微信的app secret /*初始化数据*/ public function __construct(){ $this->appid = web_config('appid'); $this->secret = web_config('secret'); } /** * 获取用户信息 */ public function getUserinfo($param) { $access_token = $this->getAccessToken(); $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$param['FromUserName']}&lang=zh_CN"; $userinfo = $this->httpGet($url); $userinfo = json_decode($userinfo); p($userdata); } /** * 获取access_token */ private function getAccessToken() { $data = json_decode($this->get_php_file("access_token.php")); if ($data->expire_time < time()) { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->secret"; $res = json_decode($this->httpGet($url)); $access_token = $res->access_token; if ($access_token) { $data->expire_time = time() + 7000; $data->access_token = $access_token; $this->set_php_file("access_token.php", json_encode($data)); } } else { $access_token = $data->access_token; } return $access_token; } /** * 请求url * @param $url url地址 */ private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } /** * 获取缓存文件 * @param $filename 文件名称 */ private function get_php_file($filename) { return trim(substr(file_get_contents(__DIR__.'/'.$filename), 15)); } /** * 保存缓存文件 * @param $filename 文件名称 * @param $content 保存内容 */ private function set_php_file($filename, $content) { $fp = fopen(__DIR__.'/'.$filename, "w"); fwrite($fp, "<?php exit();?>" . $content); fclose($fp); } }

 

最新回复(0)