使用Google API获取谷歌相册的内容

首先要申请一个谷歌 Oauth2 应用的 ID 和密钥,然后用浏览器访问下面的地址获取授权码 code

https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=http://localhost&response_type=code&client_id={ClientID}&scope=https://www.googleapis.com/auth/photoslibrary+https://www.googleapis.com/auth/drive&access_type=offline

获取到 code 以后,请求谷歌服务器换取 refresh_token

define('Client_ID', 'client_id');
define('Client_Secrec', 'client_secrec');

function getRefreshToken($code) {
    $params = ['grant_type' => 'authorization_code', 'code' => $code, 'client_id' => Client_ID, 'client_secret' => Client_Secrec, 'redirect_uri' => 'http://localhost'];
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v4/token');
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

用 refresh_token 获取 access_token

function getAccessToken($refresh_token) {
    $params = ['grant_type' => 'refresh_token', 'client_id' => 'client_id', 'client_secret' => 'client_secre', 'refresh_token' => $refresh_token];
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v4/token');
    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}