2013-04-29 2 views
2
<?php 
    require_once '/google-api-php-client/src/Google_Client.php'; 
    require_once '/google-api-php-client/src/contrib/Google_PlusService.php'; 

    session_start(); 
    // Create a state token to prevent request forgery. 
    // Store it in the session for later validation. 
    $state = md5(rand()); 
    $app['session']->set('state', $state); 
    // Set the client ID, token state, and application name in the HTML while 
    // serving it. 
    return $app['twig']->render('index.html', array(
     'CLIENT_ID' => CLIENT_ID, 
     'STATE' => $state, 
     'APPLICATION_NAME' => APPLICATION_NAME 
    )); 

     // Ensure that this is no request forgery going on, and that the user 
    // sending us this connect request is the user that was supposed to. 
    if ($request->get('state') != ($app['session']->get('state'))) { 
    return new Response('Invalid state parameter', 401); 
    } 


    $code = $request->getContent(); 
    $gPlusId = $request->get['gplus_id']; 
    // Exchange the OAuth 2.0 authorization code for user credentials. 
    $client->authenticate($code); 

    $token = json_decode($client->getAccessToken()); 
    // Verify the token 
    $reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' . 
      $token->access_token; 
    $req = new Google_HttpRequest($reqUrl); 

    $tokenInfo = json_decode(
     $client::getIo()->authenticatedRequest($req)->getResponseBody()); 

    // If there was an error in the token info, abort. 
    if ($tokenInfo->error) { 
    return new Response($tokenInfo->error, 500); 
    } 
    // Make sure the token we got is for the intended user. 
    if ($tokenInfo->userid != $gPlusId) { 
     return new Response(
     "Token's user ID doesn't match given user ID", 401); 
    } 
    // Make sure the token we got is for our app. 
    if ($tokenInfo->audience != CLIENT_ID) { 
    return new Response(
     "Token's client ID does not match app's.", 401); 
    } 

    // Store the token in the session for later use. 
    $app['session']->set('token', json_encode($token)); 
    $response = 'Succesfully connected with token: ' . print_r($token, true); 
    ?> 

이것은 내 code.php입니다.
이 코드는 https://developers.google.com/+/web/signin/server-side-flow에서 가져 왔습니다. 내 응용 프로그램에 Google + 서버 사이드 등록을 추가하고 싶습니다. 그래서 샘플 코드를 실행하기로 결정했습니다. 코드를 실행하는 동안 오류가 발생합니다. 이미 PHP 용 Google API 클라이언트 라이브러리가 포함되어 있습니다. 나는 세트를 사용하고 코드에 표시되는 기능을 렌더링 할 수없는 오전반대로 요청 위조 상태 토큰을 만드는 방법 Google + 서버 쪽 가입에서

this is My index.html 


    <!-- The top of file index.html --> 
    <html itemscope itemtype="http://schema.org/Article"> 
    <head> 
    <!-- BEGIN Pre-requisites --> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> 
    </script> 
    <script type="text/javascript"> 
    (function() { 
     var po = document.createElement('script'); 
     po.type = 'text/javascript'; 
     po.async = true; 
     po.src = 'https://plus.google.com/js/client:plusone.js?onload=start'; 
     var s = document.getElementsByTagName('script')[0]; 
     s.parentNode.insertBefore(po, s); 
    })(); 
    </script> 
    <!-- END Pre-requisites --> 
</head> 
<!-- ... --> 
</html> 

<!-- Add where you want your sign-in button to render --> 
<div id="signinButton"> 
    <span class="g-signin" 
    data-scope="https://www.googleapis.com/auth/plus.login" 
    data-clientid="YOUR_CLIENT_ID" 
    data-redirecturi="postmessage" 
    data-accesstype="offline" 
    data-cookiepolicy="single_host_origin" 
    data-callback="signInCallback"> 
    </span> 
</div> 
<div id="result"></div> 

    <!-- Last part of BODY element in file index.html --> 
    <script type="text/javascript"> 

     function signInCallback(authResult) { 
     if (authResult['code']) { 

     // Hide the sign-in button now that the user is authorized, for example: 
    $('#signinButton').attr('style', 'display: none'); 

    // Send the code to the server 
    $.ajax({ 
     type: 'POST', 
     url: 'plus.php?storeToken', 
     contentType: 'application/octet-stream; charset=utf-8', 
     success: function(result) { 
     // Handle or verify the server response if necessary. 

     // Prints the list of people that the user has allowed the app to know 
     // to the console. 
     console.log(result); 
     if (result['profile'] && result['people']){ 
      $('#results').html('Hello ' + result['profile']['displayName'] + '. You successfully made a server side call to people.get and people.list'); 
     } else { 
      $('#results').html('Failed to make a server-side call. Check your configuration and console.'); 
     } 
     }, 
     processData: false, 
     data: authResult['code'] 
    }); 
    } 
    else if (authResult['error']) { 
     // There was an error. 
     // Possible error codes: 
     // "access_denied" - User denied access to your app 
     // "immediate_failed" - Could not automatially log in the user 
     // console.log('There was an error: ' + authResult['error']); 
    } 
    } 
    </script> 
+0

무엇이 오류입니까? ??? –

+0

안녕하세요 문제는 code.php에 있습니다. Google API 클라이언트 library.and에서 정의 된 set 및 render 함수를 사용하고 있습니다. 라이브러리의 전체를 탐색합니다. 설정 및 렌더링 기능이 많이 있습니다. 그래서 어느 것을 사용해야하는지 모르겠습니다. – user2330998

+0

안녕하세요. index.html에는 오류가 없습니다. 주요 문제는 설정되어 있으며 렌더링 함수는 Google API 클라이언트 라이브러리에 정의되어 있으며이 두 함수는 다른 2 클래스로 정의되어 있습니다. 그래서 클래스의 객체를 만들어야합니다.하지만 어떤 클래스를 만들지는 모르겠습니다. 이 두 함수는 Google API 클라이언트 라이브러리의 여러 파일에 정의되어 있기 때문에 – user2330998

답변

5

불완전한 코드 스 니펫을 제공하는 문서에 문제가 있다고 생각합니다 (버그를 열었습니다). 이 샘플은 Symfony에 의존합니다. Symfony는 누락 된 변수/메소드가있는 것입니다.

PHP Quickstart은이 특정 샘플 설정을위한 전체 지침을 제공합니다. get the full source code from Github도 가능합니다.

물론 Symfony를 사용할 필요는 없지만 네이티브 PHP 메소드를 사용하기로 결정한 경우 샘플에서 사용하는 $ request, $ app 및 기타 Symfony 메소드에 대한 참조를 업데이트해야합니다.

+0

안녕하세요. Github 코드를 이미 보았습니다. 수행하려고 시도하고있는 것은 무엇입니까? 내 애플리케이션에 Google+ 가입 버튼을 포함하려면 인증을 서버에서 수행해야하며 사용자 정보도 수집해야합니다. – user2330998

+0

빠른 시작 코드는이를 처리해야합니다. 82 행에서 시작하는/connect 메소드에는 서버가 보유 할 수있는 새로 고침 토큰과 액세스 토큰 모두에 대해 one-time-code를 교환하는 논리가 들어 있습니다. Google+ 로그인 버튼이있는 서버 측 토큰은 클라이언트와 서버 간의 하이브리드 흐름입니다. 서버 쪽에서는 완벽하지 않습니다. 완전히 서버 측 흐름을 원한다면 Google PHP 클라이언트 라이브러리를 사용하여 원시 OAuth를 사용하고 리디렉션 URI가있는 오프라인 액세스 유형을 사용해야합니다. Google+ 로그인 버튼은 항상 postmessage의 redirect_uri를 사용합니다. – BrettJ

1

UPDATE :

로그인 절차/가입 링크 :

  1. http://www.w3resource.com/API/google-plus/tutorial.php
  2. http://rscavilla.blogspot.in/2011/06/using-oauth-20-with-php-to-authenticate.html

사용자 정보를 얻으려면 :

Look at this code to get the user-info from the Google+ API.

문제는 앱이 세션에서 상태를 설정하려고 할 때 set 메서드를 호출 할 수있는 응용 프로그램에 $app 개체가 있어야합니다.

Google 측의 문서는 상태 값이 애플리케이션 세션에 저장되고 google_auth API에 필요한 다른 값이 저장되는 방식을 확인하기 위해 문서를 읽는 사용자에게 알려줍니다.

자습서 :

구성하고 구글의 OAuth API를 사용하는 방법에 대한 자세한 튜토리얼 this link로 살펴 보자.

+0

안녕하세요.이 서버 쪽 가입은 google + – user2330998

+0

입니다. 안녕하세요. RakeshS입니다. 내 애플리케이션에 대해 Google + 서버 쪽 가입을 찾고 있습니다. – user2330998

+0

아무도 도와주세요. 나는 도움을 찾고있다 – user2330998