Reputation: 530
I have follow some steps from Google's document about how to use Google Service API with PHP function.
I have done it so far by including Library and even the secret key. Finaly I reach to the last step but it asked me to get login. Exactly I want to retrieve my own message without asking for login because I have my own password and gmail's account already.
What is the problem with my code? could you tell me?
public function retrieving_message()
{
$client_id = '10521XXXX456-XXXXX.apps.googleusercontent.com'; //Client ID
$client_email = '[email protected]'; //Email Address
$key_file_location = 'API Project-0f1afd2a0615.p12'; //key.p12
$this->load->library('google');
$client = new Google_Client();
// Replace this with your application name.
$client->setApplicationName("API Project");
// Replace this with the service you are using.
// We only need permissions to compose and send emails
// $client->addScope("https://www.googleapis.com/auth/gmail.readonly");
$service = new Google_Service_Gmail($client);
$this->listMessages($service, '[email protected]');
}
Code to get Message :
function listMessages($service, $userId) {
$pageToken = NULL;
$messages = array();
$opt_param = array();
do {
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
}
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
foreach ($messages as $message) {
print 'Message with ID: ' . $message->getId() . '<br/>';
}
return $messages;
}
Out Put :
An error occurred: Error calling GET https://www.googleapis.com/gmail/v1/users/hostplus.cam%40gmail.com/messages: (401) Login Required
Upvotes: 1
Views: 383
Reputation: 61
This code my help you:
$client->setApplicationName('API Project');
$client->setScopes(implode(' ', array(Google_Service_Gmail::GMAIL_READONLY)));
$client->setAuthConfigFile('key/client_secret.json');
$client->setAccessType('offline');
You have to generate new json file but don't choose web or service, please check installed.
Upvotes: 1