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 APIs 客户端库。我无法使用代码中显示的设置和渲染功能

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>
4

2 回答 2

5

我相信问题在于为您提供不完整代码片段的文档(我已经打开了一个关于此的错误)。该特定示例依赖于 Symfony,这就是您遇到的缺少变量/方法的情况。

PHP 快速入门提供了设置此特定示例的完整说明。您还可以从 Github 获取完整的源代码

当然,您不必使用 Symfony,但如果您选择使用原生 PHP 方法,则需要更新对 $request、$app 和示例使用的其他 Symfony 方法的引用。

于 2013-04-29T15:46:08.330 回答
1

更新:

登录/注册链接:

  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

获取用户信息:

查看此代码以从 Google+ API 获取用户信息。

问题是您的应用程序上没有可以在您的应用程序尝试设置会话中的状态时$app调用该方法的对象。set

也就是说,谷歌方面的文档告诉阅读文档的用户,以确保状态值存储在他们的应用程序会话中,以及应该如何存储 google_auth API 的其他必需值。

教程:

查看此链接以获取有关如何配置和使用 Google OAuth API 的更详细教程。

于 2013-04-29T11:30:21.840 回答