如何向 Google Sheets 客户端添加访问和刷新令牌?

时间:2021-05-26 06:01:08

标签: javascript php google-sheets google-api google-oauth

我正在尝试编写脚本,在 test.php 中登录到 Google 帐户后,它会重定向到 import.php 以便将值添加到 Google 表格中。 我设法在 test.php 中登录并访问和刷新令牌

<?php
session_start();
$end_point = 'https://accounts.google.com/o/oauth2/auth';
$client_id = '8309**'; 
$redirect_uri = 'http://localhost/import.php';
$scope = 'https://www.googleapis.com/auth/spreadsheets';
$client_secret = 'k2**';

$authUrl = $end_point.'?'.http_build_query([
    'client_id'              => $client_id,
    'redirect_uri'           => $redirect_uri,              
    'scope'                  => $scope,
    'access_type'            => 'offline',
    'include_granted_scopes' => 'true',
    'state'                  => 'state_parameter_passthrough_value',
    'response_type'          => 'code',
]);
echo '<a href = "'.$authUrl.'">Authorize</a></br>';
if (!file_exists('token.json')){   
    if ( isset($_GET['code'])){
        $code = $_GET['code'];   
    }else{
        return;
    } 

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://oauth2.googleapis.com/token");
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'code'          => $code,
        'client_id'     => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri'  => $redirect_uri,
        'grant_type'    => 'authorization_code',
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close ($ch);
    
    file_put_contents('token.json', $response);
}
else{
    $response = file_get_contents('token.json');
    $array = json_decode($response);
    $access_token = $array->access_token;
    $refresh_token = $array->refresh_token;

    // Check if the access token already expired
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/tokeninfo?access_token='.$access_token); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $error_response = curl_exec($ch);
    $array = json_decode($error_response);
   
    if( isset($array->error)){        
        // Generate new Access Token using old Refresh Token
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"https://accounts.google.com/o/oauth2/token");
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'client_id'     => $client_id,
            'client_secret' => $client_secret,
            'refresh_token'  => $refresh_token,
            'grant_type'    => 'refresh_token',
        ]));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close ($ch);
    }  
}
$_SESSION['acs_token'] = $response;

在重定向页面 import.php 中,我正在尝试向 Google 表格添加值。但是我无法正确地将凭证添加到 gapi 客户端。

***
<script>
      function makeApiCall() {
     var params = {
      spreadsheetId: "1qBX_v***",
      range: "CSV-to-Google-Sheet", 
      valueInputOption: 'RAW',
     }
    
    var valueRangeBody = {
      "values": <?php echo '[' . implode(',', $newData) . ']'; ?>
    }; 
    var request = gapi.client.sheets.spreadsheets.values.update(params, valueRangeBody);
    request.then(function(response) {
    }, function(reason) {
      console.error('error2: ' + reason.result.error.message);

    });
 } 
<?php
  $response = file_get_contents('token.json');
  $array = json_decode($response);
?>

var access_token = <?php  echo "'".$array->access_token."'"; ?>;
var refresh_token = <?php  echo "'".$array->refresh_token."'"; ?>;
var GoogleAuth;
  function initClient() {
    var API_KEY = 'A***';  
    var CLIENT_ID = '8***'; 
    var SCOPE = 'https://www.googleapis.com/auth/spreadsheets';
     gapi.client.init({
      'apiKey': API_KEY,
      'clientId': CLIENT_ID,
      'scope': SCOPE,
      'access_token': access_token,
      'refresh_token': refresh_token,
      'discoveryDocs': ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
    }).then(function() {  
            makeApiCall();
    }); 
    
  }  

给我这些错误:

  1. PUT https://content-sheets.googleapis.com/v4/spreadsheets/1qBX_v***/values/CSV-to-Google-Sheet?valueInputOption=RAW&alt=json&key=AIzaSy*** 401 cb=gapi.loaded_0:225

2.import.php?state=state_parameter_passthrough_value&code=4%2F***2Fwww.googleapis.com%2Fauth%2Fspreadsheets:19 error2:请求缺少所需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。见https://developers.google.com/identity/sign-in/web/devconsole-project

我做错了什么? 如何正确地将这些凭据传递给 Google 表格客户端?

0 个答案:

没有答案