微信公众号、小程序获取token

/*=============================公众号=============================*/
function wx_get_access_token()
{
    global $_ZEAI;
    $data = json_decode(@file_get_contents(ZEAI . "cache/wxdata/access_token.json"));
    if ($data->expire_time < ADDTIME || empty($data->expire_time)) {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $_ZEAI['wx_gzh_appid'] . "&secret=" . $_ZEAI['wx_gzh_appsecret'];
        $res = json_decode(get_contents($url));
        //        @AddLog("获取公众号token结果:" . json_encode($res,JSON_UNESCAPED_UNICODE));
        $access_token = $res->access_token;
        if ($access_token) {
            $data->expire_time = ADDTIME + 300;
            $data->access_token = $access_token;
            $fp = fopen(ZEAI . "cache/wxdata/access_token.json", "w+");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    } else {
        $access_token = $data->access_token;
    }
    return $access_token;
}
/*============================= 小程序 ========================*/
function wx_xcx_get_access_token() { global $_ZEAI; $data = json_decode(@file_get_contents(ZEAI . "cache/wxdata/xcx_access_token.json"), true); if (!isset($data['expire_time']) || $data['expire_time'] < ADDTIME || empty($data['expire_time'])) { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"; $res = json_decode(get_contents($url)); // @AddLog("获取小程序token结果:" . json_encode($res,JSON_UNESCAPED_UNICODE)); $access_token = $res->access_token; if ($access_token) { $data['expire_time'] = ADDTIME + 300; $data['access_token'] = $access_token; $fp = fopen(ZEAI . "cache/wxdata/xcx_access_token.json", "w+"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $access_token = $data['access_token']; } return $access_token; }

  

function get_contents($url, $time = 3600)
{
$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);
curl_setopt($ch, CURLOPT_TIMEOUT, $time * 1000);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

 

 

posted @ 2025-12-10 09:28  流浪2024  阅读(5)  评论(0)    收藏  举报