Warm tip: This article is reproduced from stackoverflow.com, please click
google-api-php-client google-calendar-api php push-notification

Google Calendar API returning unauthorized even when domain is properly registered

发布于 2020-04-20 11:07:57

I'm using the google php client library to create a webhook to my domain, but the API keeps returning unauthorized.

I've successfully followed the steps on "registering your domain" on push and my domain is listed on the API console.

Under APIs & Service > Domain verification it lists my domain under "allowed domains".

Yet it's still telling me the domain is unauthorized:

The library function

$channel = new Google_Service_Calendar_Channel();
$channel->setId($channelId);
$channel->setType("web_hook");
$channel->setAddress("https://example.com/notifications");
$service->events->watch($calendarId, $channel);

Error message

{ "error":
  { "errors": [{
    "domain": "global",
    "reason": "push.webhookUrlUnauthorized", 
    "message": "Unauthorized WebHook callback channel: https://example.com/notifications"
    }],
  "code": 401,
  "message": "Unauthorized WebHook callback channel: https://example.com/notifications"
  }
}
Questioner
Boefjim
Viewed
36
DaImTo 2020-02-05 22:09

Google_Service_Calendar_Channel requires that you send a client to authenticate it. Personally i would use service account.

function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope('https://www.googleapis.com/auth/calendar');
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

$client = getServiceAccountClient();
$channel = new Google_Service_Calendar_Channel($client);
$channel->setId($channelId);
$channel->setType("web_hook");
$channel->setAddress("https://example.com/notifications");
$service->events->watch($calendarId, $channel);