0

Google 캘린더 API를 이해하는 데 몇 가지 문제가 있습니다. 내 일기에 내 이벤트를 삽입하고 싶습니다. 그러나 그것은 효과가 없습니다. 내 일정은 "공개"해야합니까?PHP를 사용하여 Google 캘린더 API에 일정을 삽입하는 방법은 무엇입니까?

$client = new Google_Client(); 
$client->setApplicationName("MASTERSINGE THE BEST"); 
$client->setDeveloperKey("MyDevelopperKey"); 
$client->setClientId('MyIdClient '); 
$client->setClientSecret('MySecret'); 
$client->setAccessType('offline');// Gets us our refreshtoken 
$client->setScopes(array('https://www.googleapis.com/auth/calendar.read')); 

$googleApievent = new Google_Service_Calendar_Event(); 
$googleApievent->setSummary('My event'); 
$googleApievent->setLocation('Paris éào'); 

$start = new Google_Service_Calendar_EventDateTime(); 
$start->setDate('2017-02-16'); 
$start->setTimeZone('Europe/London'); 
$start->setDate('2017-02-16'); 

$end = new Google_Service_Calendar_EventDateTime(); 
$end->setDate('2017-02-17'); 
$end->setTimeZone('Europe/London'); 
$end->setDate('2017-02-17'); 

$googleApievent->setStart($start); 
$googleApievent->setEnd($end); 

$attendee1 = new Google_Service_Calendar_EventAttendee(); 
$attendee1->setEmail('myemail'); 
$attendees = array($attendee1 
); 
$googleApievent->attendees = $attendees;  

$createdEvent = $service->events->insert('primary', $googleApievent);/ 
echo $createdEvent->getId(); 
+0

오류가 발생하거나 출력 되나요? – MrDarkLynx

+0

예 2 개의 오류가 있습니다. 치명적인 오류 : '/var/www/html/mysite/www/vendors/google-api-php-client/src/Google/Http/REST.php에'의 'Google_Service_Exception'예외가 캐치되지 않았습니다. 줄 118 && Google_Service_Exception : { "오류": { "오류": [{ "도메인": "글로벌", "이유": "필수", "메시지": "로그인 필요", "locationType": "헤더" "location": "Authorization"}], "code": 401, "message": "Login Required"}} – MasterSinge

+0

이벤트를 삽입하려면 먼저 로그인/허가해야합니다. – MrDarkLynx

답변

0

내 코드가 약간 길어서 최적화 할 수 있습니까? 1 시간 후에 내 토큰이 새로 고쳐지지 않을지 확실하지 않습니다. x 인증을 요청하지 않고 Google 캘린더 API를 사용할 수 있습니까?

<?php 
     public function calendarAction() 
     { 
      define('APPLICATION_NAME', 'RK THE BEST'); 
      define('CREDENTIALS_PATH', __DIR__ . '/credentials/calendar-php-quickstart.json'); 
      define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json'); 
     define('SCOPES', implode(' ', array(
       \Google_Service_Calendar::CALENDAR) 
     )); 

     /** 
     * 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'); 
      $client->setApprovalPrompt ("force"); 


      // Load previously authorized credentials from a file. 
      $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); 

      if(file_exists($credentialsPath)) { 
       $accessToken = json_decode(file_get_contents($credentialsPath), true); 

       echo "WIN :)"; 

       if (isset($_GET['code'])){ 

        $credentials = $client->authenticate($_GET['code']); 
        $code = trim($_GET['code']); 
        $authCode = $code; 
        $client->setAccessToken($accessToken); 


        // Refresh the token if it's expired. 
        if ($client->isAccessTokenExpired()) { 
         // save refresh token to some variable 
         $refreshTokenSaved = $client->getRefreshToken(); 

         // update access token 
         $client->fetchAccessTokenWithRefreshToken($refreshTokenSaved); 

         // pass access token to some variable 
         $accessTokenUpdated = $client->getAccessToken(); 

         // append refresh token 
         $accessTokenUpdated['refresh_token'] = $refreshTokenSaved; 

         // save to file 
         file_put_contents($credentialsPath, json_encode($accessTokenUpdated)); 
        } 

         // Service creation 
         $service = new \Google_Service_Calendar($client); 
         $calendarList = $service->calendarList->listCalendarList(); 

         $googleApievent = new \Google_Service_Calendar_Event(); 
         $googleApievent->setSummary('google api'); 
         $googleApievent->setLocation('google api'); 

         $start = new \Google_Service_Calendar_EventDateTime(); 
         $start->setDate('2017-02-20'); 
         $start->setTimeZone('Europe/London'); 
         $start->setDate('2017-02-20'); 

         $end = new \Google_Service_Calendar_EventDateTime(); 
         $end->setDate('2017-02-17'); 
         $end->setTimeZone('Europe/London'); 
         $end->setDate('2017-02-17'); 

         $googleApievent->setStart($start); 
         $googleApievent->setEnd($end); 

         $calendarId = "primary"; 

         $createdEvent = $service->events->insert($calendarId, $googleApievent); 
         echo $createdEvent->getId();   

         while (true) { 
          foreach ($calendarList->getItems() as $calendarListEntry) { 
           echo $calendarListEntry->getSummary() . "\n"; 
           // get events 
           $events = $service->events->listEvents($calendarListEntry->id); 

           foreach ($events->getItems() as $event) { 
            echo "<br/>" . $event->getSummary() . ""; 
            echo " ID : " . $event->getId() . "<br/>"; 
            echo "***********************" . "<br/> "; 
           } 
          } 
          $pageToken = $calendarList->getNextPageToken(); 

          if ($pageToken) { 
           $optParams = array('pageToken' => $pageToken); 
           $calendarList = $service->calendarList->listCalendarList($optParams); 
          } else { 
           break; 
          } 
         } 

        } 

      }else { 

       // Request authorization from the user. 
       $authUrl = $client->createAuthUrl(); 

       printf("Open the following link in your browser:\n<a href='%s' > ici </a>\n", $authUrl); 
       print 'Enter verification code: '; 

       /****TOKEN***********************/ 
       if(!empty($_GET['code'])) { 
        $code = trim($_GET['code']); 
        $authCode = $code; 

        // 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); 
        } 

        $token = $client->getAccessToken(); 

        if($client->isAccessTokenExpired()){ // if token expired 
         // refresh the token 
         $test=$client->refreshToken($token); 

        } 
        $accessToken = $client->getAccessToken(); 
        file_put_contents($credentialsPath, json_encode($accessToken)); 
        printf("Credentials saved to %s\n", $credentialsPath); 
        $client->authenticate($code); 


        if (isset($_GET['code'])) { 
         $client->authenticate($_GET['code']); 
         $_SESSION['token'] = $client->getAccessToken(); 
         $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; 
        } 


        if (isset($_SESSION['token'])) { 
         $client->setAccessToken($_SESSION['token']); 
         print "LogOut"; 
         $service = new \Google_Service_Calendar($client); 
         $calendarList = $service->calendarList->listCalendarList(); 

         $googleApievent = new \Google_Service_Calendar_Event(); 
         $googleApievent->setSummary('wake up'); 
         $googleApievent->setLocation('wake up'); 

         $start = new \Google_Service_Calendar_EventDateTime(); 
         $start->setDate('2017-02-16'); 
         $start->setTimeZone('Europe/London'); 
         $start->setDate('2017-02-16'); 

         $end = new \Google_Service_Calendar_EventDateTime(); 
         $end->setDate('2017-02-17'); 
         $end->setTimeZone('Europe/London'); 
         $end->setDate('2017-02-17'); 

         $googleApievent->setStart($start); 
         $googleApievent->setEnd($end); 

         $calendarId = "primary"; 

         $createdEvent = $service->events->insert($calendarId, $googleApievent); 
         echo $createdEvent->getId();     


         while (true) { 
          foreach ($calendarList->getItems() as $calendarListEntry) { 
           echo $calendarListEntry->getSummary() . "\n"; 
           // get events 
           $events = $service->events->listEvents($calendarListEntry->id); 

           foreach ($events->getItems() as $event) { 
            echo "<br/>" . $event->getSummary() . ""; 
            echo " ID : " . $event->getId() . "<br/>"; 
            echo "***********************" . "<br/> "; 
           } 
          } 
          $pageToken = $calendarList->getNextPageToken(); 

          if ($pageToken) { 
           $optParams = array('pageToken' => $pageToken); 
           $calendarList = $service->calendarList->listCalendarList($optParams); 
          } else { 
           break; 
          } 
         } 
        } 

       } 
       return $client; 
      } 

     } 
    } 
0

마지막으로 나는 서비스 계정으로 Google 캘린더 API를 사용하며 잘 작동합니다.

session_start(); 
    putenv('GOOGLE_APPLICATION_CREDENTIALS=' .get_include_path().'/yourPath/client_secret.json'); 
    define('SCOPES', implode(' ', array(
      Google_Service_Calendar::CALENDAR) 
    )); 

    $client = new Google_Client(); 
    $client->useApplicationDefaultCredentials(); 
    $client->setScopes(SCOPES); 
    $client->setApplicationName("MasterSinge"); 

    $service = new Google_Service_Calendar($client); 

    $calendarList = $service->calendarList->listCalendarList(); 

    $googleApievent = new Google_Service_Calendar_Event(); 
    $googleApievent->setSummary('TEST!!!!!!!!!!!'); 
    $googleApievent->setDescription('TEST : <b>Bloublou !!!!!!!!!!!</b>'); /*ajout d'un lien*/ 
    $googleApievent->setLocation('TEST !!!!!!!!!!!'); 

    $start = new Google_Service_Calendar_EventDateTime(); 
    $start->setDate('2017-02-23'); 
    $start->setTimeZone('Europe/London'); 
    $start->setDate('2017-02-23'); 

    $end = new Google_Service_Calendar_EventDateTime(); 
    $end->setDate('2017-02-23'); 
    $end->setTimeZone('Europe/London'); 
    $end->setDate('2017-02-23'); 

    $googleApievent->setStart($start); 
    $googleApievent->setEnd($end); 

    $calendarId = "[email protected]"; 

    $createdEvent = $service->events->insert($calendarId, $googleApievent); 
    echo $createdEvent->getId(); 


    foreach ($calendarList->getItems() as $calendarListEntry) { 
      echo $calendarListEntry->getSummary() . "\n"; 
      // get events 
      $events = $service->events->listEvents($calendarListEntry->id); 



      foreach ($events->getItems() as $event) { 
       echo "<br/>" . $event->getSummary() . ""; 
       echo " ID : " . $event->getId() . "<br/>"; 
       echo "***********************" . "<br/> "; 
      } 
     } 
    $pageToken = $calendarList->getNextPageToken();