403 Google日历的禁止错误

时间:2018-02-06 14:18:46

标签: php http google-api google-calendar-api google-oauth

我一直在尝试使用日历api访问我的Google日历。在我的开发机器上,我能够访问数据并在日历上显示事件,但是当我将其推送到生产服务器时,在授予对日历的访问权限后,我会收到以下错误。

禁止

  

您无权访问/secondavechurch/calendar2.php   这个服务器。

     

此外,尝试时遇到403 Forbidden错误   使用ErrorDocument来处理请求。

我创建了一个服务帐户,并有权访问日历以查看是否存在问题,但仍然会出现同样的错误。

这是我的代码

require_once __DIR__ . '/vendor/autoload.php';

  date_default_timezone_set('America/New_York');

  $REDIRECT_URI = 'http://' . $_SERVER['HTTP_HOST'] .'/calendar2.php';
  $KEY_LOCATION = __DIR__ . '/client_secret.json';
  $SERVICE_ACCOUNT_NAME = 'xxxxxx.iam.gserviceaccount.com';
  $TOKEN_FILE   = "token.txt";

  $SCOPES = array(
      Google_Service_Calendar::CALENDAR_READONLY
  );

  $client = new Google_Client();
  $client->setApplicationName("Second Ave Church Calendar");
  $client->setAuthConfig($KEY_LOCATION);
  $service = new Google_Service_Calendar($client);
  // Incremental authorization
  $client->setIncludeGrantedScopes(true);

  // Allow access to Google API when the user is not present. 
  $client->setAccessType('offline');
  $client->setApprovalPrompt ("force");
  $client->setRedirectUri($REDIRECT_URI);
  $client->setScopes($SCOPES);

  if (isset($_GET['code']) && !empty($_GET['code'])) {
      try {
          // Exchange the one-time authorization code for an access token
          $accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);

          // Save the access token and refresh token in local filesystem
          file_put_contents($TOKEN_FILE, json_encode($accessToken));

          $_SESSION['accessToken'] = $accessToken;
          header('Location: ' . filter_var($REDIRECT_URI, FILTER_SANITIZE_URL));
          exit();
      }
      catch (\Google_Service_Exception $e) {
          print_r($e);
      }
  }

  if (!isset($_SESSION['accessToken'])) {

      $token = @file_get_contents($TOKEN_FILE);

      if ($token == null) {

          // Generate a URL to request access from Google's OAuth 2.0 server:
          $authUrl = $client->createAuthUrl();

          // Redirect the user to Google's OAuth server
          header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
          exit();

      } else {

          $_SESSION['accessToken'] = json_decode($token, true);

      }
  }

  $client->setAccessToken($_SESSION['accessToken']);

  /* Refresh token when expired */
  if ($client->isAccessTokenExpired()) {

      // the new access token comes with a refresh token as well
      $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
      file_put_contents($TOKEN_FILE, json_encode($client->getAccessToken()));
  }
  $currentEvents = date('Y-m-d', strtotime(date('Y-m-1'))) . 'T00:00:00-23:59';
  $currentMonth = date('F');
  $currentYear = date('Y');
  $endDay = get_number_of_days_in_month(date('m'), $currentYear);
  $endOfMonth = date('Y-m-d', strtotime(date('Y-m-' . $endDay ))) . 'T00:00:00-23:59';


  $calendarId = 'wayko621@gmail.com';
$optParams = array(
  'maxResults' => 100,
  'orderBy' => 'startTime',
   'singleEvents' => TRUE,
  'timeMin' => $currentEvents,
  'timeMax' => $endOfMonth

);
 $results = $service->events->listEvents($calendarId, $optParams);

if (count($results->getItems()) == 0) {
  $Heading =  "No upcoming events found.\n";
} else {
  $Heading =  $currentMonth . " events:\n";

  echo "<div class='calendar'><h2> " . $Heading . "</h2></div>";
  foreach ($results->getItems() as $event) {
    $start = $event->start->dateTime;
    $description = $event->getDescription();
    $formattedDate = date_format(new DateTime($start),"F j, Y - G:i A");
    if (empty($description)){
        $description = "No Description";
    }
    if (empty($start)) {
      $start = 'All Day Event';
    }

   echo "<div class='calendar'><h1>" .$event->getSummary() . "</h1>  <h3 class='getdates'>" . $formattedDate . " </h3><br /><span class='description'>" . $description . "</span></div>";
  }
}
 function get_number_of_days_in_month($month, $year) {
    // Using first day of the month, it doesn't really matter
    $date = $year."-".$month."-1";
    return date("t", strtotime($date));
}

感谢您对此的帮助

更新: 更改了calendar2.php的权限 得到500内部服务器错误

这是错误日志

[05-Feb-2018 14:55:51 America/New_York] PHP Fatal error:  Call to undefined function GuzzleHttp\Handler\curl_reset() in .../secondavechurch/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 78
[05-Feb-2018 14:56:03 America/New_York] PHP Fatal error:  Call to undefined function GuzzleHttp\Handler\curl_reset() in .../secondavechurch/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 78
[05-Feb-2018 16:20:46 America/Detroit] PHP Fatal error:  Uncaught exception 'InvalidArgumentException' with message 'file does not exist' in .../secondavechurch/vendor/google/apiclient/src/Google/Client.php:839
Stack trace:
#0 .../secondavechurch/vendor/google/apiclient/src/Google/Client.php(824): Google_Client->setAuthConfig('CLIENT_SECRET_P...')
#1 .../secondavechurch/oauth2callback.php(13): Google_Client->setAuthConfigFile('CLIENT_SECRET_P...')
#2 {main}
  thrown in .../secondavechurch/vendor/google/apiclient/src/Google/Client.php on line 839

进一步更新:

这是我在配置错误页面后得到的错误

/secondavechurch/calendar2.php?code=4/aajajkajkdnanfnoaono&scope=https://www.googleapis.com/auth/calendar.readonly
Error Code: 403

进一步更新:

将代码更改为以下内容:

require_once __DIR__.'/vendor/autoload.php';

putenv('GOOGLE_APPLICATION_CREDENTIALS=servicea.json');
  $SCOPES = array(
      Google_Service_Calendar::CALENDAR_READONLY
  );
  $REDIRECT_URI = 'http://' . $_SERVER['HTTP_HOST'] .'/secondavechurch/calendar3.php';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
  $client->setAccessType('offline');
  $client->setApprovalPrompt ("force");
  $client->setRedirectUri($REDIRECT_URI);
  $client->setScopes($SCOPES);
 $service = new Google_Service_Calendar($client);

 $currentEvents = date('Y-m-d', strtotime(date('Y-m-1'))) . 'T00:00:00-23:59';
  $currentMonth = date('F');
  $currentYear = date('Y');
  $endDay = get_number_of_days_in_month(date('m'), $currentYear);
  $endOfMonth = date('Y-m-d', strtotime(date('Y-m-' . $endDay ))) . 'T00:00:00-23:59';

 $calendarId = 'wayko621@gmail.com';
 $optParams = array(
  'maxResults' => 100,
  'orderBy' => 'startTime',
   'singleEvents' => TRUE,
  'timeMin' => $currentEvents,
  'timeMax' => $endOfMonth

);
 $results = $service->events->listEvents($calendarId, $optParams);

 if (count($results->getItems()) == 0) {
  $Heading =  "No upcoming events found.\n";
} else {
  $Heading =  $currentMonth . " events:\n";

  echo "<div class='calendar'><h2> " . $Heading . "</h2></div>";
  foreach ($results->getItems() as $event) {
    $start = $event->start->dateTime;
    $description = $event->getDescription();
    $formattedDate = date_format(new DateTime($start),"F j, Y - G:i A");
    if (empty($description)){
        $description = "No Description";
    }
    if (empty($start)) {
      $start = 'All Day Event';
    }

   echo "<div class='calendar'><h1>" .$event->getSummary() . "</h1>  <h3 class='getdates'>" . $formattedDate . " </h3><br /><span class='description'>" . $description . "</span></div>";
  }
}

 function get_number_of_days_in_month($month, $year) {
    // Using first day of the month, it doesn't really matter
    $date = $year."-".$month."-1";
    return date("t", strtotime($date));
}

开发获得数据生产没有得到任何东西。没有出现错误,但是当我转到开发人员工具时,它显示500错误。错误日志没有错误。也许我可以在php中使用try catch来查看它是否会出现任何错误。

2 个答案:

答案 0 :(得分:0)

此错误与Google日历无关。

  

此外,尝试使用ErrorDocument处理请求时遇到403 Forbidden错误。

403是Web服务器错误。它基本上是一个文件系统错误。 Web服务器无权访问该文件。

我不确定您在哪里运行此功能,但您需要确保Web服务器可以访问相关文件。

/secondavechurch/calendar2.php

答案 1 :(得分:0)

因此,似乎在服务器端的Composer存在问题。 curl_reset没有在CurlFactory.php上工作。 我评论了这条线,它起作用了。