การดึงข้อมูลจาก google calendar ด้วย php เบื้องต้น

เขียนเมื่อ 7 ปีก่อน โดย Ninenik Narkdee
google calendar

คำสั่ง การ กำหนด รูปแบบ ตัวอย่าง เทคนิค ลูกเล่น การประยุกต์ การใช้งาน เกี่ยวกับ google_calendar

ดูแล้ว 15,311 ครั้ง


สำหรับเนื้อหาต่อไปนี้ จะเป็นแนวทางในการดึงข้อมูลกิจกรรมจาก google calendar
มาใช้งานด้วยภาษา php (เวอร์ชั่น 5.4 ขึ้นไป) ซึ่งจะทำให้เราสามารถนำข้อมูลไปใช้งานหรือประยุกต์เพิ่มเติม
ได้ง่ายขึ้น แต่อย่างไรก็ดี ในขั้นตอนการใช้งานนั้น อาจจะซับซ้อนพอสมควรแต่ก็ไม่ยาก
จนเกินไป โดยสิ่งที่เพิ่มเข้ามา คือมีการ รันไฟล์ php ผ่าน command line , มีการใช้งาน
composer เหล่านี้เป็นต้น
 
ในที่นี้ เราจะทำการทดสอบเรียกใช้งานผ่าน localhost ดังนั้นวิธีการปรับค่าต่างๆ ก็จะใช้เป็น
ผ่าน localhost การนำไปใช้ใน server ต้องปรับค่าเป็นโดนเมน ตามให้ถูกต้อง
 
นี้คือ path ไฟล์บนเครื่องทดสอบ ใช้ xampp เป็นตัวจำลอง server 
 
C: > xampp > htdocs > demo > ggc
 
 

 
 
ดูการติดตั้งและการใช้งาน xampp เพิ่มเติมได้ที่
ติดตั้ง xampp จำลอง server สำหรับนักพัฒนาเว็บด้วย php 
 

ตรวจสอบว่าคำสั่ง php และ composer ติดตั้งและพร้อมใช้งานผ่าน command line หรือไม่

โดยเปิด command line แล้วทำตามตัวอย่างดังรูป 
 
 
 
ใช้คำสั่ง php -v เพื่อเช็คเวอร์ชั่นของ php และ
ตรวจสอบว่าคำสั่ง php พร้อมใช้งานผ่าน command line หรือไม่ 
ใช้คำสั่ง composer -v เพื่อเช็คเวอร์ชั่นของ composer และ
ตรวจสอบว่าคำสั่ง composer พร้อมใช้งานผ่าน command line หรือไม่
ถ้าตรวจสอบแล้ว ข้อความแสดงในรูปแบบคล้ายด้านบน นั้นหมายความว่า คำสั่ง php 
และ คำสั่ง composer พร้อมใช้งานผ่าน command line แล้ว
 
กรณีคำสั่ง php ยังไม่สามารถใช้งานผ่าน command line ให้เราเข้าไปทำการเพิ่ม
path ของ php ในตัวอย่างมี path php อยู่ที่ C: > xampp > php
ก็ให้เพิ่ม C:\xampp\php เข้าไปตามรูป ด้านล่าง กรณีไม่ใช่วันโดว์ 10 สามารถเพิ่มเข้าไปใน path
ในลักษณะ ต่อกันโดยแบ่งด้วยเครื่องหมาย ( ; ) เช่น C:\xampp\php;
 


 
 
ส่วนกรณีคำสั่ง composer ยังไม่พร้อมใช้งาน ให้เราเข้าไปทำการดาวน์โหลดไฟล์ ติดตั้งได้ที่
โดยให้ดาวน์โหลดไฟล์ Composer-Setup.exe แล้วทำการติดตั้ง โดยหลังจากติดตั้งสำเร็จ
ก็จะมีการไปเพิ่มค่าตัวแปร ใน path ให้อัตโนมัติ เหมือนกับคำสั่ง php ตามรูปด้านบน
จะเห็นว่า path ของ composer ถูกเพิ่มต่อจาก php path 
เมื่อได้ทำการติดตั้ง คำสั่ง php และ composer แล้วให้เราปิด และเปิด command line ใหม่
เช็คว่าคำสั่งพร้อมทำงานแล้วหรือไม่ตามวิธีทีข้างต้น และเมื่อคำสั่งพร้อมใช้งาน ให้ทำในขั้นตอนถัดไป
 

ใช้ composer เพื่อติดตั้ง Google Client Library

 
โดยใช้คำสั่งผ่าน command line ในโฟลเดอร์ ggc ที่เราใช้ทดสอบ ซึ่งจะเป็นการ
ไปโหลดส่วนของไฟล์ที่จำเป็นของ Google Client Library ดังรูป
 

 
 

 
 
รอจนทำงานเสร็จ อาจจะใช้เวลาสักพักขึ้นกับความเร็วอินเทอร์เน็ต หลังทำการดาวน์โหลด
และติดตั้งเรียบร้อยแล้ว เราจะได้ไฟล์ และโฟลเดอร์ดังรูป ซึ่งในโฟลเดอร์ vendor จะมีไฟล์
เพิ่มเติมด้านใน โดยเวลาใช้งานเราจะเรียกผ่านไฟล์ autoload.php
 
 

 
 

จากนั้นให้เราสร้างไฟล์ชื่อ calendar.php ไว้ใน path 

C: > xampp > htdocs > demo > ggc ตามรูป
 
 

 
 

โดยใช้โค้ดดังนี้

<?php
require_once __DIR__ . '/vendor/autoload.php';
?>
<!DOCTYPE html>
<html>
  <head>
    <title>Google Calendar API </title>
    <meta charset='utf-8' />
  </head>
  <body>
    <p>Google Calendar API </p>
    
<?php
define('APPLICATION_NAME', '<APP NAME>');
define('CREDENTIALS_PATH', __DIR__ . '/.credentials/calendar.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/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)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * 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');
	$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
	$client->setHttpClient($guzzleClient);  

  // Load previously authorized credentials from a file.
  $credentialsPath = 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);
}

// Get the API client and construct the service object.
$client = 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);
	printf('<br>');
  }
}
?>

  </body>
</html>
 
 
โดยการทำงานสุดท้ายของโค้ดคือการไปดึงกิจกรรมจาก google calendar โดยดึงข้อมูล
กิจกรรมที่จะถึงเร็วๆ นี้ ลักษณะการทำงานคล้ายบทความ
 
การดึงข้อมูลจาก google calendar ด้วย javascript เบื้องต้นอย่างง่าย 
 
แต่ก่อนที่เราจะเรียกใช้งาน ต้องการหนด 
<APP NAME> เป็นชื่อ web application ที่เราสร้าง
และดาวน์โหลด JSON มาเรียกใช้ตามส่วนของโค้ด
 
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
 
เรามาดูส่วนของ 3 โค้ดนี้อย่างละเอียด
 
define('APPLICATION_NAME', '<APP NAME>');
define('CREDENTIALS_PATH', __DIR__ . '/.credentials/calendar.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
 
- APPLICATION_NAME สำหรับกำหนดชื่อ web application ที่เราในกำหนดใน API Project
- CREDENTIALS_PATH สำหรับเก็บไฟล์ที่ใช้ในการเข้าไปดึงข้อมูล โดย path และไฟล์ด้านใน
จะถูกสร้างตอนเราเรียกใช้คำสั่ง php ผ่าน command line
- CLIENT_SECRET_PATH สำหรับระบุ path ของไฟล์ json ที่เราดาวน์โหลดมากจาก API Project
ในส่วนของ Credentials
 
ดังนั้นส่วนของข้อมูลที่เราต้องสร้างหรือนำมาใช้คือ APPLICATION_NAME  และ  CLIENT_SECRET_PATH
โดยให้เข้าไปที่ https://console.developers.google.com/apis/library
 
1. เลือก API Project ที่ต้องการ
2. เลือกเมนู Credentials ในที่นี้เราจะสร้าง client ID ใหม่ เพื่อจะได้เห็นเพิ่มแต่ต้น
 
 

 
 
3. กรอกข้อมูล โดยประมาณดังนี้ ตามรูป
 
 

 
 
จะเห็นว่าเราใช้การทดสอบบนเครื่อง จึงใช้เป็น localhost 
ส่วน Authorized redirect URIs เราก็กำหนดเป็นไฟล์ php ที่เราใช้ทดสอบ
ในที่นี้คือ  http://localhost/demo/ggc/calendar.php
 
จากนั้นกด save เราก็จะได้ส่วนของรายการ APPLICATION_NAME  และ  CLIENT_SECRET_PATH
เพิ่มนำไปใช้งานแล้ว โดย APPLICATION_NAME คือ CALENDAR-PHP
 
 
 
ส่วน CLIENT_SECRET_PATH ให้เราทำการโหลดไฟล์ JSON ตามรูป แล้ว copy ไปวางในโฟลเดอร์
ที่เราทดสอบ แล้วเปลี่ยนชื่อเป็น client_secret.json 
 
 
 
 
ให้เราเปลี่ยนค่า <APP NAME> เป็นชื่อ web application ที่เราตั้ง ในตัวอย่างคือ CALENDAR-PHP
ก็จะได้เป็น  
 
define('APPLICATION_NAME', 'CALENDAR-PHP');
 
ต่อไปคือการใช้คำสั่ง php รันไฟล์ calendar.php ผ่าน command line ดังนี้
 

 
 
เราก็จะได้ ลิ้งค์ url เพื่อไปรันผ่าน เบราวเซอร์ 
 
 
 
ให้เรา copy ลิ้งค์ไปเปิดใน chrome
(ยังไม่ต้องปิด command line)
ก็จะแสดงการขอสิทธิการเข้าใช้งาน calendar ให้เรากด allow ตามรูป
 
 
จากนั้น เบราวเซอร์ จะส่งค่า code กลับมาที่ไฟล์ ที่เรากำหนดใน Authorized redirect URIs  ซึ่งก็คือ
http://localhost/demo/ggc/calendar.php ให้เรา copy code หลัง url ?code=xxxxxxxxxx
 
 

 
 
นำมาวางใน command line ดังรูป  แล้วกด enter
 
 

 
 
คำสั่ง php จะสร้างไฟลเดอร์ชื่อ .credentials และมีไฟล์ calendar.json ด้านใน 
 
 

 
 
โดยไฟล์ด้านใน ก็คือ access_token ที่ให้เราใช้สำหรับเข้าไปใช้ทำการดึงข้อมูล calendar มาแสดง
 
 

 
 
เท่านี้เราก็สามารถดึงข้อมูลจาก google calendar ผ่านไฟล์ calendar.php ได้แล้ว
แต่ก่อนเรียกใช้งาน ให้เราปิดส่วนของคำสั่ง ที่กำหนดให้รันไฟล์ผ่าน command line ไว้ก่อน
 
 

 
 
เสร็จแล้วก็ทดสอบรันไฟล์ http://localhost/demo/ggc/calendar.php ผ่านเบราวเซอร์
ก็จะได้ข้อมูลกิจกรรมอย่างง่ายดังนี้
 
 
จะเห็นว่าเราสามารถทำการดึงข้อมูลจาก google calendar ด้วย php ได้แล้ว
โดยสามารถนำค่าที่ได้ไปใช้งานได้อย่างง่ายกว่ากรณีการใช้งาน javascript 
สามารถนำไปประยุกต์สร้างไฟล์ json เพื่อใช้ร่วมกับ fullcalendar ได้ และอื่นๆ 
 
เพิ่มเติม กรณีต้องการดึงข้อมูล รายการย้อนหลัง 1 เดือน เราสามารถเปลี่ยนส่วนของโค้ด

  'timeMin' => date('c'),
 
เป็น
 
  'timeMin' => date('c',strtotime('-1 month')),
 
 
ทั้งหมดเป็นแนวทางการใช้ google calendar กับ php หวังว่าจะเป็นแนวทางสำหรับนำไปประยุกต์ใช้งาน
ต่อๆ ไปได้
 


   เพิ่มเติมเนื้อหา ครั้งที่ 1 วันที่ 27-06-2017


การดึงข้อมูลปฏิทินจาก google calendar ถัาดึงจากปฏิทินหลัก จะใช้ค่าว่า primary ซึ่งมีค่าเท่ากับ 
email account ของ gmail หรือก็คือปฏิทินของเรา ส่วนกรณีใช้ดึงข้อมูลจากปฏิทินอื่นๆ ให้เปลี่ยน primary 
เป็น calendarID ที่ต้องการ โดยสามารถดูรายการ calendarID ได้จากตัวอย่างโค้ดหน้านี้
 
 
ตัวอย่างโค้ด

<?php
require_once __DIR__ . '/vendor/autoload.php';
?>
<!DOCTYPE html>
<html>
  <head>
    <title>Google Calendar API </title>
    <meta charset='utf-8' />
  </head>
  <body>
    <p>Google Calendar API </p>
     
<?php
define('APPLICATION_NAME', 'CALENDAR-PHP');
define('CREDENTIALS_PATH', __DIR__ . '/.credentials/calendar.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/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)
));
 
/*if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}*/
 
/**
 * 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');
    $guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
    $client->setHttpClient($guzzleClient);  
 
  // Load previously authorized credentials from a file.
  $credentialsPath = 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);
}
 
// Get the API client and construct the service object.
$client = 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',strtotime('-1 month')),
);
$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);
    printf('<br>');
  }
}
 
echo "<hr>";
echo "รายการ calendarID";
echo "<hr>";
$calendarList = $service->calendarList->listCalendarList();
 
while(true) {
  foreach ($calendarList->getItems() as $calendarListEntry) {
    echo $calendarListEntry->getSummary();
  }
  echo "<pre>";
  print_r($calendarList->getItems());
  echo "</pre>";
  $pageToken = $calendarList->getNextPageToken();
  if ($pageToken) {
    $optParams = array('pageToken' => $pageToken);
    $calendarList = $service->calendarList->listCalendarList($optParams);
  } else {
    break;
  }
}
?>
 
  </body>
</html>


กด Like หรือ Share เป็นกำลังใจ ให้มีบทความใหม่ๆ เรื่อยๆ น่ะครับ







เนื้อหาที่เกี่ยวข้อง






เนื้อหาพิเศษ เฉพาะสำหรับสมาชิก

กรุณาล็อกอิน เพื่ออ่านเนื้อหาบทความ

ยังไม่เป็นสมาชิก

สมาชิกล็อกอิน



( หรือ เข้าใช้งานผ่าน Social Login )




URL สำหรับอ้างอิง





คำแนะนำ และการใช้งาน

สมาชิก กรุณา ล็อกอินเข้าระบบ เพื่อตั้งคำถามใหม่ หรือ ตอบคำถาม สมาชิกใหม่ สมัครสมาชิกได้ที่ สมัครสมาชิก


  • ถาม-ตอบ กรุณา ล็อกอินเข้าระบบ
  • เปลี่ยน


    ( หรือ เข้าใช้งานผ่าน Social Login )







เว็บไซต์ของเราให้บริการเนื้อหาบทความสำหรับนักพัฒนา โดยพึ่งพารายได้เล็กน้อยจากการแสดงโฆษณา โปรดสนับสนุนเว็บไซต์ของเราด้วยการปิดการใช้งานตัวปิดกั้นโฆษณา (Disable Ads Blocker) ขอบคุณครับ