官方文档
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/getStableAccessToken.html

获取 Access token

$data['grant_type'] = 'client_credential';$data['appid'] = $appid;$data['secret'] = $appsecret;$url = 'https://api.weixin.qq.com/cgi-bin/token?' . http_build_query($data);$res = json_decode(file_get_contents($url), true);
$access_token_str = Db::name('config')->value('access_token');$access_token_arr = json_decode($access_token_str, true);$access_token = $access_token_arr['access_token'];if ($access_token_arr['expires_in'] < time()) {$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=***&secret=***";$response = json_decode(file_get_contents($url), true);$access_token = $response['access_token'];$data['access_token'] = $access_token;$data['expires_in'] = time() + 7000;Db::name('config')->where('id', 1)->setField('access_token', json_encode($data));}return json(['code' => 200, 'token' => $access_token]);

获取 Stable Access token

/** * 发送post请求 * @param string $url 请求地址 * @param array $post_data post键值对数据 * @return string */function send_post($url, $post_data) {$postData = http_build_query($post_data);$options = array('http' => array('method' => 'POST','header' => 'Content-type:application/x-www-form-urlencoded','content' => $postData,'timeout' => 15 * 60 // 超时时间(单位:s)));$context = stream_context_create($options);$result = file_get_contents($url, false, $context);return $result;}//使用方法$data['grant_type'] = 'client_credential';$data['appid'] = $appid;$data['secret'] = $appsecret;$url = 'https://api.weixin.qq.com/cgi-bin/stable_token';$response = json_decode(send_post($url, json_encode($data)), true);$access_token = $res['access_token'];