ไม่มีชื่อบทความ
การตั้งค่า Google Cloud และ Calendar API
1. สร้าง Google Cloud Project
- เข้าสู่หน้า Google Cloud Console
- คลิก Create Project
- ตั้งชื่อโปรเจกต์ เช่น
time-clock-app - จดจำ Project ID ไว้ใช้งานภายหลัง
2. เปิดใช้ Calendar API
- ในหน้าโปรเจกต์ที่สร้างแล้ว เข้าเมนู APIs & Services → Library
- ค้นหา Google Calendar API
- กด Enable เพื่อเปิดใช้งาน
3. สร้าง Service Account
เหตุผลที่เลือกใช้ Service Account:
- ไม่ต้องขออนุญาตผ่าน OAuth Consent Screen ทีละผู้ใช้
- ใช้ได้กับระบบ server-to-server โดยตรง
- ควบคุมสิทธิ์การเข้าถึง Calendar ได้ละเอียด
ขั้นตอนสร้าง Service Account
- ไปที่ IAM & Admin → Service Accounts
- กด Create Service Account
- กรอกชื่อ เช่น
calendar-access-sa - ในขั้นตอน Grant Access:
- กดข้าม ไม่ต้องกำหนด Role ในตอนนี้
- เมื่อสร้างเสร็จ กดที่ Service Account → Keys → Add Key → Create New Key
- เลือกประเภทไฟล์: JSON
- ดาวน์โหลดไฟล์
.json - เก็บไว้ในโปรเจกต์ที่โฟลเดอร์
/config/google-service-account.json
ข้อควรระวัง: อย่า commit ไฟล์ .json นี้ขึ้น Git (เพิ่มเข้า .gitignore)
4. แชร์สิทธิ์ Calendar ให้ Service Account
- เข้า Google Calendar
- สร้าง Calendar ใหม่ (หรือใช้ Calendar เดิม)
- ไปที่ Settings ของ Calendar นั้น
- ในหัวข้อ Share with specific people or groups:
- กด Add People and Groups
- ใส่ Email ของ Service Account (เช่น
calendar-access-sa@your-project-id.iam.gserviceaccount.com) - ตั้งสิทธิ์เป็น Make changes to events
5. ตั้งค่า .env.example
สร้างไฟล์ .env.example ที่ root ของโปรเจกต์ พร้อมระบุตัวแปรต่อไปนี้:
GOOGLE_PROJECT_ID=your-google-project-id
GOOGLE_CALENDAR_ID=your-calendar-id@group.calendar.google.com
GOOGLE_CLIENT_EMAIL=service-account-email@your-project-id.iam.gserviceaccount.com
GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
ข้อสำคัญเกี่ยวกับ GOOGLE_PRIVATE_KEY:
- ต้องใช้
"..."(double quotes) ครอบรอบ - ต้องแทนบรรทัดใหม่ด้วย
\n(สอง backslash ตามด้วย n) - ตัวอย่างการแปลง:
- หา
\nแทนทุกจุดที่เป็นบรรทัดใหม่เดิม (ใช้ Notepad++ หรือ VSCode Replace)
- หา
ตัวอย่าง:
GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEv...\n...END PRIVATE KEY-----\n"
6. อ้างอิงเอกสารล่าสุด
- Google Calendar API Overview
- Using OAuth 2.0 for Server to Server Applications
- Service Accounts | Google Cloud Documentation
หมายเหตุ: การตั้งค่าให้ครบตามนี้จะสามารถเชื่อมต่อ Calendar API จาก server-side ของ Next.js ได้อย่างปลอดภัย