구글 달력과 Laravel 사이트 통합

25824 단어 laravelphpgoogleapis
우리는 구글 API를 통해 구글 달력을 클라이언트 사이트(Laravel)에 통합하는 작업을 곧 끝낼 것이다.나는 내가 우리의 해결 방안을 쓸 것이라고 생각한다. 다음에 이렇게 해야 할 사람을 도울 수 있기를 바란다.

소개


고객은 무료 또는 저비용 공간을 제공하는 장소를 활동 공간이 필요한 청년 조직과 연결시키기를 원한다.
장관은 사이트에 개인 자료와 달력을 첨부하여 언제 사용할 수 있는지 표시한다.갤러리에 예약을 이 달력에 추가하고 링크된 구글 달력에 자동으로 추가할 수 있도록 요구하고, 반대로도 마찬가지다.

개요



이미지 출처: https://developers.google.com/identity/protocols/OAuth2
장관이 링크된 구글 달력에서 데이터를 추출하기 위해서는 이 사이트의 달력 방문에 동의해야 한다.
위 그림에서 보듯이 허가된 장소는 사이트에 권한 수여 코드를 제공하고 이 사이트는 구글 API로 방문 영패를 교환할 수 있다.이 접속 영패는 장관이 이미 접속에 동의한 서비스와 상호작용을 하는 데만 사용할 수 있다.이런 상황에서 구글 달력이다.

항목 만들기


첫 번째 단계는 고객들이 구글 계정으로 프로젝트를 설정하도록 하는 것이다.구글에서 온 이 빠른 입문 안내서는 좋은 연습을 제공했다. https://developers.google.com/google-apps/calendar/quickstart/php
프레젠테이션도 시작하고 실행할 것이지만, 나는 이 단계를 건너뛸 것이다.
프로젝트 설정이 완료되면 클라이언트는 이 프로젝트를 통해 구글 달력 API에 접근할 수 있도록 증빙서류를 설정해야 한다.

자격 증명 추가


자격 증명을 만드는 데 사용할 마법사가 있습니다.이것은 분명하지 않기 때문에 여기는 우리가 설정한 화면 캡처이다.주의: 클라이언트 데이터가 아닌 가상 콘텐츠를 사용했습니다.
첫 번째 단계는 어떤 API를 사용할 것인지, 어떻게 접근할 것인지 묻습니다.

두 번째 단계는 화이트리스트 URL과 oAuth 콜백 경로 설정입니다.

3단계 설치 장관이 제출한 동의서의 설치.

네 번째 단계에서는 클라이언트 ID 및 자격 증명을 제공합니다.

마지막 화면에서 다운로드를 클릭하면 client_id.json 파일이 제공됩니다. 이 파일은clients 프로젝트를 통해 API에 접근하는 사이트 키입니다.이것은 서버에 저장된 개인 위치여야 한다.
{  
   "web":{  
      "client_id":"[hash-string].apps.googleusercontent.com",
      "project_id":"calendar-integration-[project-id]",
      "auth_uri":"https://accounts.google.com/o/oauth2/auth",
      "token_uri":"https://accounts.google.com/o/oauth2/token",
      "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
      "client_secret":"[hash-string]",
      "redirect_uris":[  
         "https://www.example.com/oauth2callback"
      ],
      "javascript_origins":[  
         "https://www.example.com"
      ]
   }
}

Google API 클라이언트 필요


이것은 Laravel 사이트이기 때문에 우리는 이미 Composer 설정을 가지고 있기 때문에 우선 구글 API 클라이언트가 필요하다.composer require google/apiclient:^2.0이것은 Google API와 통신할 수 있는 PHP 라이브러리를 제공하고 모든 API와 OAuth2에 일련의 도움말 함수를 제공합니다.
더 많은 정보는 여기에서 찾을 수 있습니다: https://github.com/google/google-api-php-client

권한 부여


동의를 구하다


이 사이트의 첫 번째 단계는 장관이 구글 달력에 접근하는 것에 동의하도록 하는 방식이다.
이를 위해 링크를 만들어 구글에 보내면 구글이 동의 화면을 표시할 것이다.
이를 위해 우리는 google/apiclient 제공된 구글 클라이언트를 초기화하고 응용 프로그램에 특정한 설정을 설정할 것이다.
<?php

namespace App\Helpers;

// Initialise the client.
$client = new Google_Client();
// Set the application name, this is included in the User-Agent HTTP header.
$client->setApplicationName('Calendar integration');
// Set the authentication credentials we downloaded from Google.
$client->setAuthConfig('[private-path]/client_id.json');
// Setting offline here means we can pull data from the venue's calendar when they are not actively using the site.
$client->setAccessType("offline");
// This will include any other scopes (Google APIs) previously granted by the venue
$client->setIncludeGrantedScopes(true);
// Set this to force to consent form to display.
$client->setApprovalPrompt('force');
// Add the Google Calendar scope to the request.
$client->addScope(Google_Service_Calendar::CALENDAR);
// Set the redirect URL back to the site to handle the OAuth2 response. This handles both the success and failure journeys.
$client->setRedirectUri(URL::to('/') . '/oauth2callback');

참고 위의 코드 블록은 Google API와의 모든 상호 작용에 사용됩니다.우리는 그것을 헬퍼 클래스에 넣습니다. 그러면 어디에서도 복사할 필요가 없습니다.
일단 구글 클라이언트 설정이 생기면 내장createAuthUrl() 방법으로 구글로 돌아가는 링크를 사용하여 장관이 그들의 구글 달력에 동의하도록 할 수 있다.
<?php
// Set state allows us to match the consent to a specific venues
$client->setState($venue->id);
// The Google Client gives us a method for creating the 
$client->createAuthUrl();
장관이 링크를 눌렀을 때, 그들은 구글로 방향을 바꾸었고, 이 사이트의 구글 달력 방문에 동의할 것을 요구받았다.

처리 응답


구글은 회의장을 이곳에서 지정한 URL$client->setRedirectUri(URL::to('/') . '/oauth2callback');에 있는 사이트로 다시 정할 것이다.장관이 구글 달력 방문에 동의하거나 방문을 거부하면 이 노선을 사용한다.
<?php
/**
 * Google OAuth2 route
 */
Route::get('oauth2callback', [
    'as' => 'oauth',
    'uses' => 'OAuthController@index'
]);
이 라우팅은 GET 요청을 /oauth2callback 디렉터에서 index 메서드를 사용하는 경우를 나타냅니다.
Laravels 라우팅에 대한 자세한 내용은 다음을 참조하십시오. https://laravel.com/docs/5.5/routing
이 방법은 다음과 같이 보입니다.
<?php

public function index(Request $request)
    {
        // Get all the request parameters
        $input = $request->all();

        // Attempt to load the venue from the state we set in $client->setState($venue->id);
        $venue = Venue::findOrFail($input['state']);

        // If the user cancels the process then they should be send back to
        // the venue with a message.
        if (isset($input['error']) &&  $input['error'] == 'access_denied') {
            \Session::flash('global-error', 'Authentication was cancelled. Your calendar has not been integrated.');
            return redirect()->route('venues.show', ['slug' => $venue->slug]);

        } elseif (isset($input['code'])) {
            // Else we have an auth code we can use to generate an access token

            // This is the helper we added to setup the Google Client with our             
            // application settings
            $gcHelper = new GoogleCalendarHelper($venue);

            // This helper method calls fetchAccessTokenWithAuthCode() provided by 
            // the Google Client and returns the access and refresh tokens or 
            // throws an exception
            $accessToken = $gcHelper->getAccessTokenFromAuthCode($input['code']);

            // We store the access and refresh tokens against the venue and set the 
            // integration to active.
            $venue->update([
                'gcalendar_credentials' => json_encode($accessToken),
                'gcalendar_integration_active' => true,
            ]);

            \Session::flash('global-success', 'Google Calendar integration enabled.');
            return redirect()->route('venues.show', ['slug' => $venue->slug]);
        }
    }

현재 우리는 OAuthController 되돌아오는 방문 영패 방문 장소의 구글 달력을 사용할 수 있다.이 방법은 방문 영패뿐만 아니라 다른 몇 자리도 되돌려줍니다.
{  
   "access_token":"[hash-string]",
   "token_type":"Bearer",
   "expires_in":3600,
   "created":1510917377,
   "refresh_token":"[hash-string]"
}
이 반환은 데이터베이스에 저장하기 위해 json에 인코딩되었습니다.
fetchAccessTokenWithAuthCode() 에서 보듯이 이 영패는 한 시간만 사용할 수 있습니다.방문 영패가 만료되었을 때, 우리는 expires_in 을 사용하여 새로운 방문 영패를 요청해야 한다.

액세스 토큰을 새로 고칩니다.


Google 클라이언트는 현재 액세스 토큰이 만료되었는지 확인하는 방법을 제공합니다.우리는 위의 JSON 값refresh_token$venue->gcalendar_credentials에 전달한 다음 영패가 만료될 때 영패를 갱신합니다.
<?php
// Refresh the token if it's expired.
$client->setAccessToken($venue->gcalendar_credentials);
if ($client->isAccessTokenExpired()) {
    $accessToken = $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    $venue->update([
        'gcalendar_credentials' => json_encode($accessToken),
    ]);
}
우리는 다시 그것을 데이터베이스에 저장하여 장소와 대응한다.도움말 클래스에 추가되었습니다. 구글 클라이언트를 초기화합니다.

구글 달력에서 예약 추출


현재 우리는 효과적인 방문 영패를 가지고 있으며, 우리는 경기장의 구글 달력에서 조회 활동을 시작할 수 있다.
<?php

// Load up the helper to initialise the Google Client
$gcHelper = new GoogleCalendarHelper($venue);

// Use the Google Client calendar service. This gives us methods for interacting 
// with the Google Calendar API
$service = $gcHelper->getCalendarService();

// Set over what timeframe we want to grab calendar events
// Dates must be an RFC3339 timestamp with mandatory time zone offset, e.g.,
// 2011-06-03T10:00:00-07:00
$optParams = array(
    'orderBy' => 'startTime',
    'singleEvents' => true,
    'timeMin' => '2011-06-03T10:00:00-07:00',
    'timeMax' => '2011-06-03T10:00:00-23:00',
);

// Poll this venue's Google Calendar
$googleBookings = $service->events->listEvents($calendarId, $optParams);

// Check if we have any events returned
if (count($googleBookings->getItems()) > 0) {
구글 달력에서 이벤트 목록을 얻으면 데이터베이스에 저장해 사이트에 예약으로 표시합니다.

구글 캘린더로 예약 보내기


한 장관이 사이트에 예약을 추가하면 구글 달력에 자동으로 예약이 만들어진다.
<?php

// Set the start time and date for pushing to Google.
$tz = new DateTimeZone('Europe/London');
$startTime = Carbon::create(
    2017,
    11,
    25,
    10,
    0,
    0,
    $tz
);

// Use the Google date handling provided by the Google Client
$googleStartTime = new Google_Service_Calendar_EventDateTime();
$googleStartTime->setTimeZone($tz);
$googleStartTime->setDateTime($endTime->format('c'));

// Create the calendar event and give a default title.
$event = new Google_Service_Calendar_Event();
$event->setStart($googleStartTime);
// Same process to create end time as we use for the start time above. Code 
// omitted for brevity.
$event->setEnd($googleEndTime);
$event->setSummary('Booking automatically created from Calendar Example');

// Use the Google Client calendar service to push 
$service = $gcHelper->getCalendarService();
$createdEvent = $service->events->insert($calendarId, $event);

// Save the newly created event id against the booking.
if (!empty($createdEvent->id)) {
만약 setAccessToken()에 id가 있다면, 우리는 이 예약을 구글 달력에 새로운 이벤트로 미루는 데 성공했다.
이 id는 구글 달력에서 이벤트를 삭제하는 데 사용됩니다. 예를 들어 $createdEvent.

Gotchas 회사


토큰을 새로 고치다


우리의 경험$service->events->delete($calendarId,$eventId);에 따르면 갱신 영패를 신분 검증 영패와 함께 되찾아야 한다.대량의 SO 글을 읽은 후에도 사용자들이 auth 영패가 만료될 때마다 구글 달력에 동의하도록 해야 할 것 같지만, 우리의 상황은 그렇지 않다.

시간대


우리가 경기장의 구글 달력에서 이벤트를 만들 때 시간대를 $client->setApprovalPrompt('force'); 로 설정한 것을 알 수 있을 것이다.API는 기본적으로 미국 시간대 중 하나를 사용합니다.이것은 우리가 영국에 있는 것에 적합하지 않다.

생성된 이벤트


API를 통해 이벤트를 만들 때 필드는 캘린더에 포함해야 합니다.이것은 누군가가 당신을 행사에 초대하는 방식과 같으니, 당신은 행사가 달력에 들어가기 전에 받아들여야 합니다.

총결산


한마디로 Google API 사용은 간단합니다Europe/London.OAuth는 가장 까다로운 부분이다. 이것은 주로 SO와 다른 사이트에서 인증/방문/리셋 영패가 어떻게 작동하는지에 대한 서로 충돌하는 정보 때문이다.
구글 문서 자체는 최상의 상황에 적합하지만 언제 틀렸는지에 대한 정보는 존재하지 않는다.
어떤 의견도 환영합니다

좋은 웹페이지 즐겨찾기