본문 바로가기
DEVEL/PHP

PHP 구글 로그인 연동

by codebyai 2023. 3. 15.
반응형

구글 API 클라이언트 라이브러리를 사용하는 예제

<?php

require_once __DIR__ . '/vendor/autoload.php'; // Google API 클라이언트 라이브러리 로드

session_start();

// Google API 인증 정보를 저장하는 파일 경로
$credentialsPath = __DIR__ . '/google-api-credentials.json';

// Google_Client 객체 생성
$client = new Google_Client();
$client->setApplicationName('Google Login Example');
$client->setScopes([
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'
]);

// Google API 인증 정보를 파일에서 로드
if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
    $client->setAccessToken($accessToken);
}

// 로그인된 사용자의 정보 가져오기
if ($client->getAccessToken()) {
    $oauth2 = new Google_Service_Oauth2($client);
    $userInfo = $oauth2->userinfo->get();

    // 사용자 정보 출력
    echo '<p>Hello, ' . $userInfo->name . '!</p>';
    echo '<p>Your email address is: ' . $userInfo->email . '</p>';

    // 로그아웃 버튼 생성
    echo '<a href="?logout">Logout</a>';

    // 로그아웃 요청 처리
    if (isset($_GET['logout'])) {
        unset($_SESSION['access_token']);
        $client->revokeToken();
        header('Location: ' . filter_var($_SERVER['PHP_SELF'], FILTER_SANITIZE_URL));
    }
} else {
    // 로그인 버튼 생성
    $authUrl = $client->createAuthUrl();
    echo '<a href="' . $authUrl . '">Login</a>';
}

 

구글 인증 서버와 직접 통신하는 예제

<?php
session_start();
$google_redirect_url = 'http://localhost/google-login-api/';
$client_id = 'YOUR_CLIENT_ID';
$client_secret = 'YOUR_CLIENT_SECRET';
$scope = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile';

function curl($url,$parameters){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$parameters);
    $data = curl_exec($ch);
    return $data;
}

function getCallbackUrl(){
    global $google_redirect_url;
    return urlencode($google_redirect_url.'index.php?google=callback');
}

function getLoginUrl(){
    global $client_id,$scope;
    return "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=".getCallbackUrl()."&client_id=".$client_id."&scope=".$scope;
}

function getAccessToken(){
    global $client_id,$client_secret;
    
    if(isset($_GET['code'])){
        // get access token from authorization code
        $url = "https://accounts.google.com/o/oauth2/token";
        $parameters="code=".$_GET['code']."&client_id=".$client_id."&client_secret=".$client_secret."&redirect_uri=".getCallbackUrl()."&grant_type=authorization_code";
        return json_decode(curl($url,$parameters),true)['access_token'];
        
    }else if(isset($_SESSION['access_token'])){
        // get access token from session
        return $_SESSION['access_token'];
        
    }else{
        // redirect to login url
        header("Location: ".getLoginUrl());
        exit;
        
    }
}

function getUserInfo(){
    
   // get user info from google api
   $url="https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=".getAccessToken();
   return json_decode(file_get_contents($url),true);

}

if(isset($_GET['google']) && $_GET['google']=='callback'){
    
   // store access token in session
   $_SESSION['access_token']=getAccessToken();

   // redirect to index page
   header("Location: ".$google_redirect_url."index.php");
   
}else{
    
   // print user info
   print_r(getUserInfo());
   
}

 

 

 

반응형

'DEVEL > PHP' 카테고리의 다른 글

PHP Google 인증 토큰 유효성 체크  (0) 2023.04.11
PHP 유튜브 채널 구독하기  (0) 2023.03.16
PHP CURL POST 요청하기  (0) 2023.03.15
PHP 유튜브 동영상 정보 가져오기  (0) 2023.03.15
PHP 유튜브 시청 기록 가져오기  (0) 2023.03.15