如何在PHP中发送Google APIs REST请求(含鉴权示例)
用REST方式调用Google API(PHP环境)
一、基于Guzzle的实现
首先确保已通过Composer安装Guzzle:
composer require guzzlehttp/guzzle
以下是调用Google日历API获取日历列表的完整示例,核心是通过请求头携带鉴权Token:
<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; // 已获取的鉴权信息 $accessToken = '你的access_token'; // Google日历API的日历列表接口URL $apiUrl = 'https://www.googleapis.com/calendar/v3/users/me/calendarList'; try { $client = new Client(); $response = $client->request('GET', $apiUrl, [ // 核心鉴权配置:在请求头中添加Bearer Token 'headers' => [ 'Authorization' => 'Bearer ' . $accessToken, 'Accept' => 'application/json' // 指定返回JSON格式 ], // 可选:添加URL参数实现分页、筛选等需求 'query' => [ 'maxResults' => 10, 'minAccessRole' => 'owner' ] ]); // 解析并输出JSON响应 $result = json_decode($response->getBody(), true); print_r($result); } catch (RequestException $e) { // 处理请求错误(如Token过期、权限不足) if ($e->hasResponse()) { $errorInfo = json_decode($e->getResponse()->getBody(), true); echo '请求错误:' . $errorInfo['error']['message']; } else { echo '请求失败:' . $e->getMessage(); } } ?>
关键说明:
- 所有Google API的REST请求都需要在
Authorization头中携带Bearer {access_token},这是鉴权的核心逻辑 - 若需发送POST/PUT请求(比如创建日历事件),只需修改请求方法,并在
json字段中传递请求体数据
二、自定义REST类实现(基于PHP原生CURL)
如果不想依赖第三方框架,可通过原生CURL实现轻量的REST请求类:
<?php class GoogleApiRestClient { private $accessToken; public function __construct($accessToken) { $this->accessToken = $accessToken; } // GET请求方法 public function get($url, $params = []) { if (!empty($params)) { $url .= '?' . http_build_query($params); } return $this->sendRequest('GET', $url); } // POST请求方法(发送JSON格式请求体) public function post($url, $data = []) { return $this->sendRequest('POST', $url, $data); } private function sendRequest($method, $url, $data = []) { $ch = curl_init(); // 基础请求配置 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $this->accessToken, 'Accept: application/json', 'Content-Type: application/json' ]); // 根据请求方法设置对应选项 if ($method === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } elseif ($method === 'PUT') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } // 执行请求并处理响应 $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); throw new Exception('CURL请求错误:' . $error); } curl_close($ch); $result = json_decode($response, true); // 处理HTTP错误状态码 if ($httpCode >= 400) { throw new Exception('API请求失败:' . $result['error']['message']); } return $result; } } // 使用示例 try { $client = new GoogleApiRestClient('你的access_token'); // 获取日历列表 $calendarList = $client->get('https://www.googleapis.com/calendar/v3/users/me/calendarList', [ 'maxResults' => 5 ]); print_r($calendarList); // 示例:创建日历事件 /* $eventData = [ 'summary' => '测试会议', 'start' => ['dateTime' => '2024-06-01T14:00:00+08:00'], 'end' => ['dateTime' => '2024-06-01T15:00:00+08:00'] ]; $newEvent = $client->post('https://www.googleapis.com/calendar/v3/calendars/primary/events', $eventData); print_r($newEvent); */ } catch (Exception $e) { echo '错误:' . $e->getMessage(); } ?>
补充说明:
client_id和client_secret主要用于获取或刷新access_token(OAuth2授权流程环节),直接调用API时仅需使用access_token- 若
access_token过期,可通过client_id、client_secret和refresh_token调用Google的Token刷新接口获取新的access_token
内容的提问来源于stack exchange,提问作者Datadimension
相关产品推荐
相关产品推荐

