Gmail Push Notification with PHP

While reading the Gmail API docs, I noticed that the Gmail API provides a way to push notification to the backend endpoint address. The idea is to call process () in our backend when the user receives a new email (avoiding the pull method).

I created a new signature ( Cloud Pub / Sub API ) and I tested posting a new post from the Cloud Platform Console. The API works as expected. But now I don't know how to notify the Gmail API to start viewing the INBOX user changes. We can use watch()

it stop()

in Python too, but what about PHP?

enter image description here

+3


source to share


2 answers


The Google Discovery APIs are simple rest APIs. You can use them in any language capable of generating an HTTP message and an HTTP Get.

Google is very good at making things easier for developers, so they created several open source client libraries to help developers. The PHP API Client Library Google API is one such library. it handles most of the hard work for you.



I checked PHP Quickstart first , then go to User.watch after you have your authentication flow running.

+2


source


Sample code using HTTP POST:

// Google API
$client = getClient();

// Variables
$user = 'me';
$access_token = $client->getAccessToken()['access_token'];
$topic_name = 'projects/xxxx/topics/xxxx';

// POST request    
$ch = curl_init('https://www.googleapis.com/gmail/v1/users/' . $user . '/watch');

curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer ' . $access_token,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode(array(
        'topicName' => $topic_name,
        'labelIds' => ["INBOX"]
    ))
));

      



Be sure to grant publish rights before serviceAccount:gmail-api-push@system.gserviceaccount.com

.

enter image description here

0


source







All Articles