2016-12-09 156 views
0

谷歌日曆無法正常工作,出現錯誤「致命錯誤:未知的異常'InvalidArgumentException'在E:\ Extrawork \ wamp \ www \ alpha \ application \ modules \ myaccount \控制器\谷歌的API的\ src \谷歌\ Client.php

有人可以幫我請和謝謝?谷歌日曆不能正常工作

public function google_api(){ 
     error_reporting(E_ALL); 
     require_once('google-api/vendor/autoload.php'); 


     define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart'); 
     define('CREDENTIALS_PATH', '~/credential/credential.json'); 
     define('CLIENT_SECRET_PATH', __DIR__ . '\google-api\client_secret.json'); 

     // If modifying these scopes, delete your previously saved credentials 
     // at ~/.credentials/calendar-php-quickstart.json 
     define('SCOPES', implode(' ', array(
      Google_Service_Calendar::CALENDAR_READONLY) 
     )); 

     // Get the API client and construct the service object. 
     $client = $this->getClient(); 
     $service = new Google_Service_Calendar($client); 

     // Print the next 10 events on the user's calendar. 
     $calendarId = 'primary'; 
     $optParams = array(
      'maxResults' => 10, 
      'orderBy' => 'startTime', 
      'singleEvents' => TRUE, 
      'timeMin' => date('c'), 
     ); 
     $results = $service->events->listEvents($calendarId, $optParams); 

     if (count($results->getItems()) == 0) { 
      print "No upcoming events found.\n"; 
     } else { 
      print "Upcoming events:\n"; 
      foreach ($results->getItems() as $event) { 
      $start = $event->start->dateTime; 
      if (empty($start)) { 
       $start = $event->start->date; 
      } 
      printf("%s (%s)\n", $event->getSummary(), $start); 
      } 
     } 
     if (php_sapi_name() != 'cli') { 
      throw new Exception('This application must be run on the command line.'); 
     } 

    } 

    // Code Start 
    /** 
    * Returns an authorized API client. 
    * @return Google_Client the authorized client object 
    */ 
    function getClient() { 
     $client = new Google_Client(); 
     $client->setApplicationName(APPLICATION_NAME); 
     $client->setScopes(SCOPES); 
     $client->setAuthConfig(CLIENT_SECRET_PATH); 

     $client->setAccessType('offline'); 

     // Load previously authorized credentials from a file. 
     $credentialsPath = $this->expandHomeDirectory(CREDENTIALS_PATH); 
     if (file_exists($credentialsPath)) { 
     $accessToken = json_decode(file_get_contents($credentialsPath), true); 
     } 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); 

     // Store the credentials to disk. 
     if(!file_exists(dirname($credentialsPath))) { 
      mkdir(dirname($credentialsPath), 0700, true); 
     } 
     file_put_contents($credentialsPath, json_encode($accessToken)); 
     printf("Credentials saved to %s\n", $credentialsPath); 
     } 
     $client->setAccessToken($accessToken); 

     // Refresh the token if it's expired. 
     if ($client->isAccessTokenExpired()) { 
     $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); 
     file_put_contents($credentialsPath, json_encode($client->getAccessToken())); 
     } 
     return $client; 
    } 

    /** 
    * Expands the home directory alias '~' to the full path. 
    * @param string $path the path to expand. 
    * @return string the expanded path. 
    */ 
    function expandHomeDirectory($path) { 
     $homeDirectory = getenv('HOME'); 
     if (empty($homeDirectory)) { 
     $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH'); 
     } 
     return str_replace('~', realpath($homeDirectory), $path); 
    } 
    // Code End 

`

回答

0

問題是憑證文件夾中的credential.json文件以前未生成。我在我的網絡瀏覽器中收到了一個字符串,如下所示 https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=XXXXXXX&redirect_uri=XXXXX&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly&approval_prompt=auto 我在我的Web瀏覽器中打開此URL時收到了代碼。我抄的代碼和替換$ AUTHCODE =修剪(與fgets(STDIN))以$ AUTHCODE =修剪(CODE_I_GOT)。 此過程已生成credential.json文件,之後我能夠成功運行我的代碼

0

你可以參考這個related GitHub issue其中指出,可能的原因API拋出一個「無效代碼」異常的原因是,訪問令牌格式不匹配在新生成的格式API。

此代碼還可以幫助:

  • while getting contents, I used serialize function

    • Example: $accessToken = serialize (file_get_contents($credentialsPath));
  • while inserting contents, I used deserialize function

    • Example: $accessToken = derialize(file_put_contents($credentialsPath, $accessToken););

嘗試在在讀$accessToken能夠解決您的問題所有的地方寫$accessTokenunserialize()所有地方插入serialize()

+0

感謝您的回覆,但我確實已經嘗試過,我發現沒有成功。我不知道,但我相信有什麼毛病「CREDENTIALS_PATH」。 –