1.프로젝트 생성 [생략]

https://console.cloud.google.com/

 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

 

2.OAuth 동의 하기

OAuth 동의 화면

 

위의 사진 처럼 프로젝트를 선택 후 왼쪽 메뉴 탭을 펼쳐서 OAuth 동의 화면을 클릭 한다.

OAuth 동의 화면2

프로젝트에 맞게 내부, 외부를 선택 후 만들기 클릭

 

2-1.앱 등록 하기.

 

항목에 맞게 써주는데 홈페이지 URL은 이때 안 써도 된다.

 

 

범위 추가 또는 삭제 버튼을 클릭 해서 필요한 범위를 체크 해준다.

 

테스트를 할 사용자의 계정을 추가 해준다.

 

 

추가 후 OAuth 동의 화면 메뉴를 클릭 후 앱 게시 버튼을 클릭 해준다.

 

3.OAuth 클라이언트 ID를 생성

 

 

 

사용자 인증 정보 메뉴 클릭 -> +사용자 인증 정보 만들기 클릭 -> OAuth 클라이언트 ID 클릭

 

 

웹 어플리케이션으로 선택 후 이름, URL, 리다이렉트 URL을 설정해준다.

 

4.코드

php 코드

<?php
$google_redirect_url = "등록한 리다이렉트 주소(파일명 제거)";
$client_id = '발급한 클라이언트 ID';
$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.'login_google.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."login_google.php");

}else{
    $res = getUserInfo();
    //여기서 로그인된 정보를 갖고 회원 가입 및 로그인 연동
    exit;
}

 

redirect_url 변수 사용하는 곳을 보면 파일명을 따로 쓰기 때문에 처음 선언시 파일명을 제외한 URL로 입력 시켜야 한다.

또한 getcallbackUrl() 함수를 보면 ?google=callback 이렇게 파라미터를 보내기 때문에 애플리케이션 설정 페이지에서

redirect url을 저장시 기존 파일명에 ?google=callback 파라미터를 보내는 url도 저장시켜야 한다.

예를 들면 저장 시켜야 하는 URL은 2개이다.

-https://localhost:8080/API/login_google.php

-https://localhost:8080/API/ login_google.php?goole=callback 

위의 2개를 저장 시켜야 한다.

 

프론트에서 코드

<a href="/API/login_google.php">구글 로그인</a>

 

'프로그래밍 > API' 카테고리의 다른 글

[API] 네이버 로그인 API 연동  (0) 2024.01.24
YouTube 간단히 연동하기  (0) 2019.06.27

참고 URL :https://developers.naver.com/products/login/api/api.md

 

네이버 로그인 - INTRO

환영합니다 네이버 로그인의 올바른 적용방법을 알아볼까요? 네이버 로그인을 통해 신규 회원을 늘리고, 기존 회원은 간편하게 로그인하게 하려면 제대로 적용하는 것이 중요합니다! 이에 올바

developers.naver.com

 

1. 위의 사이트에 접속 후 애플리케이션을 등록 해준다. (어렵지 않기 때문에 생략)

 

2.프론트

<?
  //네이버 로그인 접근토큰 요청 예제
  $client_id = "YOUR_CLIENT_ID";
  $redirectURI = urlencode("YOUR_CALLBACK_URL");
  $state = "RAMDOM_STATE";
  $apiURL = "https://nid.naver.com/oauth2.0/authorize?response_type=code&client_id=".$client_id."&redirect_uri=".$redirectURI."&state=".$state;
 ?>
  
  <!-- html -->
  <a href="<?=$apiURL?>">네이버 로그인</a>

 

 

이때 callback url은 1번에서 등록한 URL과 동일 해야 한다.(www제거)

 

3.PHP(위에서 적은 콜백 URL 파일)

<?php
  // 네이버 로그인 콜백 예제
  $client_id = "YOUR_CLIENT_ID";
  $client_secret = "YOUR_CLIENT_SECRET";
  $code = $_GET["code"];;
  $state = $_GET["state"];;
  $redirectURI = urlencode("YOUR_CALLBACK_URL");
  $url = "https://nid.naver.com/oauth2.0/token?grant_type=authorization_code&client_id=".$client_id."&client_secret=".$client_secret."&redirect_uri=".$redirectURI."&code=".$code."&state=".$state;
  $is_post = false;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, $is_post);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $headers = array();
  $response = curl_exec ($ch);
  $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  
  if($status_code == 200) {//로그인 성공
    $responseArr = json_decode($response, true);
    //회원프로필 조회
    $token = $responseArr['access_token'];
    $header = "Bearer ".$token;
    $url = "https://openapi.naver.com/v1/nid/me";
    $is_post = false;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, $is_post);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $headers = array();
    $headers[] = "Authorization: ".$header;
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec ($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close ($ch);
    if($status_code == 200) {
    	//여기서 받은 데이터 조회 후 회원 등록 또는 회원 가입 페이지로 이동 시키면 된다.
        echo $response;
    } else {
        echo "Error 내용:".$response;
    }
} else {
    echo "Error 내용:".$response;
}
?>

 

'프로그래밍 > API' 카테고리의 다른 글

[API]구글 로그인 API  (0) 2024.01.26
YouTube 간단히 연동하기  (0) 2019.06.27

 

1.Google 프로젝트 생성

 

https://console.developers.google.com

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

1-1)로그인해서 접속시 프로젝트가 없는 경우는 프로젝트를 생성해야 합니다.

아래 사진과 같이 맨 오른쪽에 만들기 버튼이 있습니다. 

 

1-2)아래 사진처럼 프로젝트 이름을 알맞게 쓰고 만들기 버튼을 클릭해서 만들어 줍니다.

1-3)만들기 버튼을 누르시면 아래 사진과 같이 나오는데 빨간색 버튼의 'API 및 서비스 사용 설정'을 클릭해 줍니다.

1-4)아래 사진의 YouTube Data API v3를 선택합니다.

 

1-5)사용 설정을 누릅니다.

 

1-6)그 다음으로는 사용자 정보를 만들어야합니다.

다른 글들을 보니 OAuth 클라이언트 ID를 사용해서 인증을 해서 데이터를 갖고오는 경우가 많은데 

저는 간단히 하기 위해 API키만 발급받겠습니다.

 

1-7)API 키를 받으시면 아래 화면처럼 나오는데 나중에 API키를 사용할겁니다.

 

2.유튜브 필요 데이터 얻기

 

2-1) 유튜브 채널 키 얻기

 

https://developers.google.com/youtube/v3/docs/channels/list 여기로 접속합니다.

 

접속하시면 아래로 쭉 내리시면 아래 화면이 나옵니다

2개의 데이터를 넣어주셔야합니다.

-part : contentDetails

-id : 보여줄 유튜브 채널의 id

 

보여줄 채널에 접속하시면 아래 화면처럼 url에 id가 있습니다.

두개의 데이터를 넣고 아래의 EXECUTE를 눌러주면 아래화면 처럼 나옵니다.

이렇게 데이터가 나오면 uploads의 값을 복사합니다.

 

그런다음 https://developers.google.com/youtube/v3/docs/playlistItems/list 여기에 접속합니다.

 

마찬가지로 2개의 데이터를 입력해야합니다.

-part : snippet 

-playlistId : 위에서 얻은 uploads 값을 써줍니다.

 

쓰고 EXECUTE 버튼을 누르시면 아래와 같이 채널에 있는 데이터가 나오는걸 확인할수 있습니다.

 

그럼 이제 아까 얻은 API 키와 playlistId 로 데이터를 호출해보겠습니다.

https://www.googleapis.com/youtube/v3/playlistItemspart=snippet&playlistId={playlistId}&key={API Key}

 

위에의 URL을 호출하시면 됩니다.

 

my_upload.js

function GetList() {
    $.ajax({
        url: encodeURI('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=' + playlistId +'&key='+key),
        type: 'Get',
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            $('#video-container').html('');

            var playlistItems = result.items;
            if (playlistItems) {
                $('#listConcent').html('');
                var content = '';
                $.each(playlistItems, function (index, item) {
                    if (index < 4) {
                        var title = item.snippet.title.replace(/"/gi, "'");
                        var videoId = item.snippet.resourceId.videoId;
                        var img = item.snippet.thumbnails.default.url;

                        if (index == 0) {
                            $('#firstTitle').text(title);
                            $('#videoContent').append("<iframe width='380' height='218' src='https://www.youtube.com/embed/" + videoId + "' frameborder='0' allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>");
                        }
                        content += "<li class='list' onclick=javascript:ChangeVideo(\"" + title.replace(/ /gi, '&nbsp;') + "\",'" + videoId + "');>";
                        content += "<div class='thumbnail'><a href='#' name='listVideo'><img width='185' height='120' src='" + img + "'></a></div>";
                        content += "<h3 class='list-title'><a href='#' name='listTitle'>" + title + "</a></h3>";
                        content += "</li>";
                        //displayResult(item.snippet);
                    }
                });
                $('#listConcent').append(content);
            } else {
                $('#video-container').html('Sorry you have no uploaded videos');
            }

        },
        error: function (error) {
            //alert(error);
        }
    });
}


function ChangeVideo(title,id) {
    $('#firstTitle').text(title);
    $('#videoContent').html('');
    $('#videoContent').append("<iframe width='380' height='218' src='https://www.youtube.com/embed/" + id + "' frameborder='0' allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>");
}

 

youtube.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>YouTube</title>
<style>
/*================================================================================

* Reset

=================================================================================*/
html { font-size: 14px; font-weight: 300; letter-spacing: -0.025em;}
body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, textarea, p, blockquote, th, td, input, select, textarea, button { margin: 0; padding: 0; box-sizing: border-box; }
fieldset, img { border: 0 none; }
dl, ul, ol, menu, li { list-style: none; }
blockquote, q { quotes: none; }
blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; }
input, select, textarea, button { vertical-align: middle; }
input::-ms-clear {
    display:none;
}
input::-webkit-contacts-auto-fill-button {
    visibility:hidden;
    display:none !important;
    pointer-events:none;
    position:absolute;
    right:0;
}
button { border: 0 none; border-radius: 0; background-color: transparent; cursor: pointer; }
body { word-wrap: break-word; word-break: keep-all; }
body, th, td, input, select, textarea, button { font-size: 14px; font-weight: 300; line-height: 1.6; font-family: 'Noto Sans KR', 'Malgun Gothic', '맑은 고딕', 'Apple SD Gothic Neo', '돋움', 'dotum', sans-serif; color: #232323; }
a { color: #232323; text-decoration: none; -webkit-transition: all 0.4s ease-in; transition: all 0.4s ease-in; }
a:active, a:hover, a.line { text-decoration: underline; }
a:active { background-color: transparent; }
address, caption, cite, code, dfn, em, var { font-style: normal; font-weight: 300; }
table { border-collapse: collapse !important; }
html[data-useragent*=mac] body * { font-family: 'Apple SD Gothic NEO', helvetica, sans-serif!important }
::-moz-selection {
    background:#042f6c;
    color:#fff;
}
::selection { background: #042f6c; color: #fff; }
strong, b { font-weight: 600; }
h1, h2, h3, h4, h5 { font-weight: 600; }
figure { margin: 0; }
hr { margin: 10px 0; border: 0; height: 1px; background-color: #e1e1e1; }
.skip { display: none; }
.hide_txt{display:inline-block!important;overflow:hidden!important;position:absolute!important;width:1px;height:1px;margin:0!important;padding:0!important;font-size:1px;line-height:0;clip:rect(1px 1px 1px 1px)}

	.video-wrap { max-width: 380px; margin:  50px auto; }
	.video-wrap .main-video { width: 100%; border-bottom: 1px solid #ddd; }
	.video-wrap .video-stream { width: 100%; height: 218px; background: #333; }
	.video-wrap .video-info { width: 100%; padding: 15px 0; }
	.video-wrap .video-info .main-video-title { width: 100%; min-height: 30px; word-break: break-all; white-space: pre-wrap;  }
	.video-wrap .video-info .main-video-title, .video-wrap .video-list .list-title a { font-size: 1.1rem; color: #111; font-weight: 400; }
	.video-wrap .video-info .main-video-count, .video-wrap .video-list .list-video-count { font-size: 0.9rem; color: #999; }
	.video-wrap .video-list { padding-top: 15px; }
	.video-wrap .video-list .list-wrap:after { display: block; clear: both; content: ''; }
	.video-wrap .video-list .list { width: calc(100%/2); height: 200px; float: left; padding: 15px 0; }
	.video-wrap .video-list .list:nth-child(odd) { padding-right: 5px; }
	.video-wrap .video-list .list:nth-child(even) { padding-left: 5px; }
	.video-wrap .video-list .list .thumbnail { width: 100%; height: 120px; margin-bottom: 8px; background: #333; }
	.video-wrap .video-list .list .list-title { width: 100%; height: 50px; word-break: break-all; white-space: inherit; overflow: hidden;  }
	.video-wrap .video-list .list .list-video-count { margin-top: 5px; }
	
</style>
	
</head>

<body>
    <div class="video-wrap">
        <div class="main-video">
            <div class="video-stream" id="videoContent">
                <!--비디오 영역-->
            </div>
            <div class="video-info" id="videoBody">
                <h2 class="main-video-title" id="firstTitle"></h2>
            </div>
        </div>
        <!-- 비디오 리스트 -->
        <div class="video-list">
            <ul class="list-wrap" id="listConcent" name="listConcent">
               
            </ul>
        </div>

    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="my_uploads.js"></script>
    <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>

 

 

'프로그래밍 > API' 카테고리의 다른 글

[API]구글 로그인 API  (0) 2024.01.26
[API] 네이버 로그인 API 연동  (0) 2024.01.24

+ Recent posts