GMAIL REST API using service account - Empty or missing scope not allowed
<p>I a trying to get the latest emails from my <code>GMAIL</code> inbox via the <em>GMAIL REST API v2</em> and using a <a href="https://developers.google.com/api-client-library/php/auth/service-accounts" rel="nofollow">service account key (a solution for server to server communication)</a>. However, I get the following error: </p>

<pre><code>{ "error": "invalid_scope", "error_description": "Empty or missing scope not allowed." }
</code></pre>

<p>Below is my PHP code. I have used composer to install the <a href="https://github.com/google/google-api-php-client" rel="nofollow">google API PHP client</a>.</p>

<p>Has anyone encountered and solved this issue?</p>

<pre><code>&lt;?php

require_once 'vendor/autoload.php';
$scopes = array('https://www.googleapis.com/auth/gmail.readonly');
$client = new Google_Client();
$client-&gt;setAuthConfig('serviceaccount-xxxxxxxxx.json');

try{
  $service = new Google_Service_Gmail($client);
  $opt_param['maxResults'] = 5; // Return Only 5 Messages
  $opt_param['labelIds'] = 'INBOX'; // Only show messages in Inbox
  $messages = $service-&gt;users_messages-&gt;listUsersMessages('me',$opt_param);
  $list = $messages-&gt;getMessages();
  var_dump($list);
} catch (Exception $e) {
  print($e-&gt;getMessage());
}
?&gt;
</code></pre>