Reputation: 665
I tried to understand how this works since more than a day, and I'm totally confused right now.
Here is my (very simple) goal: make a GET request on a URL when I receive a new email.
How do I set up the rest ? I don't understand what to do now..
Upvotes: 1
Views: 500
Reputation: 3329
Thanks to the reply from @antoine-nedelec I was also create a watcher in Laravel.
I installed the package google/apiclient (composer require google/apiclient
)
However I to implement some modifications, as otherwise this did not work for me:
https://mail.google.com/
) or I would have received an error Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
Precondition check failed.
error).Of course this code has just dd
for seeing an output. For production you could handle the exception and just ignore the $messagesResponse
.
<?php
use Google_Client;
use Google_Service_Gmail;
use Google_Service_Gmail_WatchRequest;
define('MY_EMAIL', '[email protected]');
define('PROJECT', 'pivotal-destruction-123456');
define('TOPIC', 'my_topic');
function watch()
{
$client = new Google_Client();
$client->setAuthConfig(resource_path('mycredentials.json'));
$client->setSubject(MY_EMAIL);
$client->addScope("https://mail.google.com/");
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
$service = new Google_Service_Gmail($client);
try {
$watch = new Google_Service_Gmail_WatchRequest($client);
$watch->setTopicName("projects/" . PROJECT . "/topics/" . TOPIC);
$messagesResponse = $service->users->watch(MY_EMAIL, $watch);
} catch(\Exception $e) {
dd("EXCEPTION", $e);
}
dd("WATCHED!!!", $messagesResponse);
}
BTW I tried to log the output from the webhook, but first missed to disable the CSRF check (VerifyCsrfToken.php
), so did not get any notifications.
Upvotes: 0
Reputation: 665
I did a Symfony4 command, executed everyday like a cron:
class WatchGoogleClient extends Command {
private $kernel;
private $gmailService;
public function __construct(GmailService $gmailService, Kernel $kernel)
{
parent::__construct();
$this->gmailService = $gmailService;
$this->kernel = $kernel;
}
protected function configure()
{
$this->setName('app:watch-google-client')
->setDescription('watch-google-client')
->setHelp('Reset the google watch timer');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// This getClient function is basically what is given by the google API tutorial
$client = $this->gmailService->getClient($this->kernel);
$service = new \Google_Service_Gmail($client);
$watchreq = new \Google_Service_Gmail_WatchRequest();
$watchreq->setLabelIds(array('INBOX'));
$watchreq->setTopicName('YOUR_TOPIC_NAME');
$msg = $service->users->watch('me', $watchreq);
var_dump($msg);
// DO WHAT YOU WANT WITH THIS RESPONSE BUT THE WATCH REQUEST IS SET
}
}
Upvotes: 2