首页 > 解决方案 > Grant access on spreadsheet using Google Sheets API

问题描述

I have Google Sheets API set up and working (I can read and update existing spreadsheets if it's shared to my credentials) and I need to export some data from my website to google sheet. In order to keep users off seeing other people's sheets, I need to create a new spreadsheet when user wants to export data. I managed to create new spreadsheet like this:

public function init(){
    $user = Socialite::driver('google')->stateless()->user();
    $token = [
        'access_token'  => $user->token,
        'refresh_token' => $user->refreshToken,
        'expires_in'    => $user->expiresIn
    ];

    $client = new \Google_Client();
    $client->setApplicationName('Sheets');
    $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
    $client->setAccessType('offline');
    $client->setAuthConfig('../credentials.json');
    $client->setAccessToken($token);

    $service = new Google_Service_Sheets($client);
    $serviceDrive = new Google_Service_Drive($client);

    $spreadsheet = new Google_Service_Sheets_Spreadsheet([
        'properties' => [
            'title' => 'Testing Sheet'
        ]
    ]);
    $spreadsheet = $service->spreadsheets->create($spreadsheet, [
        'fields' => 'spreadsheetId'
    ]);

    $this->insertPermission($serviceDrive, $spreadsheet->spreadsheetId, $user->email, 'user', 'owner');
}

When I dd($spreadsheet) I can see that it's actually created and I can retrieve its id. But the thing is, if I try to open it, I get a notification that I need to get access as I don't have it. I searched for a solution a lot and tried several ways. I tried to pass a role like this:

$spreadsheet = $service->spreadsheets->create($spreadsheet, [
    'fields' => 'spreadsheetId',
    'role' => 'owner'
    'email' => 'useremail@gmail.com'
]);

Also tried to insert permission using this method:

function insertPermission($service, $fileId, $value, $type, $role) {
    $newPermission = new Google_Service_Drive_Permission();
    $newPermission->setEmailAddress($value);
    $newPermission->setType($type);
    $newPermission->setRole($role);
    try {
      return $service->permissions->create($fileId, $newPermission);
    } catch (Exception $e) {
      print "An error occurred: " . $e->getMessage();
    }
    return NULL;
  }

But this method gives me an error when calling create() function which says "code": 403, "message": "Insufficient Permission: Request had insufficient authentication scopes.". Is there a way to give to authenticated user an access to newly created spreadsheet and where is my mistake?

标签: phpapigoogle-sheets

解决方案


  • You are trying to give permission with the Drive API
  • Your code only contains $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
  • To use both the Sheets and the Drive API with the same client, assign to the client BOTH respective scopes

推荐阅读