Google Calendar API调用配置疑问,已获取OAuth凭证不知如何使用
解决方案
核心逻辑说明
Google Calendar API 2021年之后就不再支持仅用API Key访问非公开日历数据,所有私有日历操作都必须携带OAuth 2.0凭证,凭证需要放在请求头的Authorization字段,格式为Bearer {你的访问令牌(access_token)}。
代码修改示例
你当前的代码缺少授权头配置,修改后的可运行代码如下:
<?php /** * Template Name: API Test Page * */ get_header(); // 替换为你自己的日历ID $calendar_id = '你的日历ID'; // 替换为你通过OAuth流程获取到的有效access_token $access_token = '你获取到的OAuth访问令牌'; $url = "https://www.googleapis.com/calendar/v3/calendars/{$calendar_id}"; // 配置请求参数,添加授权头 $args = [ 'headers' => [ 'Authorization' => "Bearer {$access_token}", 'Accept' => 'application/json' ] ]; $response = wp_remote_get( esc_url_raw( $url ), $args ); // 先判断请求是否出错 if ( is_wp_error( $response ) ) { echo '请求错误:' . $response->get_error_message(); } else { $api_response = json_decode( wp_remote_retrieve_body( $response ), true ); print_r($api_response); } get_footer();
注意事项
- 你拿到的OAuth凭证里包含
access_token和refresh_token,access_token有效期只有1小时,过期后需要用refresh_token交换新的有效访问令牌,不要硬编码长期使用同一个access_token - 申请OAuth凭证时,授权范围必须包含
https://www.googleapis.com/auth/calendar或者https://www.googleapis.com/auth/calendar.readonly,否则会报权限不足错误 - 如果你要访问的是公开可查看的日历,也可以不用OAuth,直接把日历设为公开后,在请求URL后加
?key=你的API密钥即可调用
内容的提问来源于stack exchange,提问作者RRhodes
相关产品推荐
相关产品推荐

