1️⃣ Tạo project trên Google Cloud

  1. Vào: https://console.cloud.google.com/
  2. Đăng nhập Google
  3. Góc trên → Select a projectNew Project
  4. Đặt tên project (ví dụ: CI3 Google Login)
  5. Create

2️⃣ Bật Google Identity (OAuth)

  1. Vào APIs & Services → Enabled APIs & services
  2. Không cần bật API phức tạp, OAuth 2.0 không cần Google+ API (đã deprecated)
  3. Chuyển sang OAuth consent screen

3️⃣ Cấu hình OAuth Consent Screen (bắt buộc)

Chọn loại

  • User Type:
    • Website thường → External
    • App nội bộ Google Workspace → Internal

Create

Điền thông tin cơ bản

  • App name: Tên website
  • User support email: email của bạn
  • Developer contact email: email của bạn

Scopes

  • Thêm:
    • email
    • profile
      (Google sẽ tự map với userinfo.email & userinfo.profile)

Test users (rất quan trọng)

  • Thêm email Google của bạn
  • Nếu không thêm → login sẽ bị chặn

Save & Continue cho đến xong


4️⃣ Tạo OAuth Client ID

  1. Vào APIs & Services → Credentials
  2. Create Credentials → OAuth client ID
  3. Application type:
    👉 Web application

Điền:

  • Name: CI3 Google Login
  • Authorized JavaScript origins
    Ví dụ: http://localhost http://yourdomain.com
  • Authorized redirect URIs (RẤT QUAN TRỌNG)
    Ví dụ: http://localhost/auth/google_callback https://yourdomain.com/auth/google_callback

Create


5️⃣ Lấy key bạn cần 🎯

Sau khi tạo xong, Google sẽ trả về:

Client ID     = xxxxx.apps.googleusercontent.com
Client Secret = xxxxxxxx

6️⃣ Gắn vào code của bạn (CI3 / PHP)

Ví dụ trong config/constants.php:

define('APP_CLIENT_ID', 'xxxxx.apps.googleusercontent.com');
define('APP_CLIENT_SECRET', 'xxxxxxxx');
define('APP_CLIENT_REDIRECT_URL', 'http://localhost/auth/google_callback');

Hoặc dùng .env nếu bạn có.


7️⃣ Callback Controller mẫu (CI3)

public function google_callback()
{
    $google = new Google();
    if ($this->input->get('code')) {
        $token = $google->fetchAccessTokenWithAuthCode(
            $this->input->get('code')
        );
        if (!isset($token['error'])) {
            $google->setAccessToken($token['access_token']);
            $oauth = new Google_Service_Oauth2($google);
            $user  = $oauth->userinfo->get();
            // $user->email
            // $user->name
            // $user->picture
        }
    }
}

8️⃣ Lỗi thường gặp (tránh mất thời gian)

redirect_uri_mismatch
→ Redirect URI phải giống 100% (http/https, slash, path)

Error 403: access_denied
→ Quên add email vào Test users

❌ Login chạy local không được
→ Redirect URI phải là:

http://localhost/...

chứ không phải 127.0.0.1


9️⃣ Checklist nhanh ✅

  • Tạo Google Cloud Project
  • OAuth Consent Screen
  • OAuth Client ID (Web)
  • Redirect URI khớp code
  • Add email test user