Попытка получить уведомления pubsub в двух разных файлах с одного сервера - PullRequest
0 голосов
/ 10 июля 2019

У меня есть два разных проекта Google, каждый из которых находится на отдельном электронном письме.

Я создал отдельную тему и подписку в каждом письме, перенаправляя ее на соответствующий веб-крючок.Кроме того, я использую oauth-аутентификацию для каждого электронного письма с двумя разными ключами, по одному на каждый webhook.

Когда я получаю почту из любого места, они должны вызывать соответствующий webhook (оба на одном сервере с другим именем), но я незнаете почему, они вызывают один и тот же webhook.

Я использовал пример быстрого запуска PHP gmail для приложения.

Подробности: https://developers.google.com/gmail/api/quickstart/php

Первый webhook

<?php
    require __DIR__ . '/vendor/autoload.php';

function getClient()
{
$client = new Google_Client();
$client->setApplicationName('APP name1');
$client->setScopes(array("https://mail.google.com/", "https://www.googleapis.com/auth/gmail.compose", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/pubsub"));
$client->setAuthConfig('credentialsapp1.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');

// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token_webhook1.json';
if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client->setAccessToken($accessToken);
}

// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
    // Refresh the token if possible, else fetch a new one.
    if ($client->getRefreshToken()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        $client->setAccessToken($accessToken);

        // Check to see if there was an error.
        if (array_key_exists('error', $accessToken)) {
            throw new Exception(join(', ', $accessToken));
        }
    }
    // Save the token to a file.
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}



$client = getClient();
$service = new Google_Service_Gmail($client);

// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);

if (count($results->getLabels()) == 0) {
  print "No labels found.\n";
} else {
 print "Labels:\n";
  foreach ($results->getLabels() as $label) {
printf("- %s\n", $label->getName());
  }
}


?>

Второй webhook

<?php
require __DIR__ . '/vendor/autoload.php';


function getClient()
{
$client = new Google_Client();
$client->setApplicationName('APP name2');
$client->setScopes(array("https://mail.google.com/", "https://www.googleapis.com/auth/gmail.compose", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/pubsub"));
$client->setAuthConfig('credentialsapp2.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');

// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token_webhook2.json';
if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client->setAccessToken($accessToken);
}

// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
    // Refresh the token if possible, else fetch a new one.
    if ($client->getRefreshToken()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        $client->setAccessToken($accessToken);

        // Check to see if there was an error.
        if (array_key_exists('error', $accessToken)) {
            throw new Exception(join(', ', $accessToken));
        }
    }
    // Save the token to a file.
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);

// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);

if (count($results->getLabels()) == 0) {
  print "No labels found.\n";
} else {
  print "Labels:\n";
  foreach ($results->getLabels() as $label) {
    printf("- %s\n", $label->getName());
  }
}


?>

В скрипте вообще нет ошибок.Ошибка в вызываемом веб-крюке по подписке (pubsub), потому что они вызывают один и тот же веб-крючок при запуске.

Схема

учетная запись gmail1 -> Их собственный проект -> их собственная Тема / Подписка-> Их собственные учетные данные -> Их собственная учетная запись webhook

gmail2 -> Их собственный проект -> Их собственная тема / подписка -> Их собственные учетные данные -> Их собственные webhook

Результат -> Pubsubуведомление отправляется на первый веб-крючок всегда.

...