通过PHP在Google帐户中无需浏览器身份验证即可从Google+发布信息

时间:2014-03-20 12:01:44

标签: php session authentication google-plus posts

我想通过PHP获取谷歌+帖子,但谷歌要求我通过浏览器登录。 可以通过PHP提供帐户的身份验证,每次我想要收到帖子时都可以在没有登录的情况下获取帖子吗?

代码为:

<?php 
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';

session_start();

$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");


// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
 $client->setClientId('clientid');
 $client->setClientSecret('clientsecret');
 $client->setRedirectUri('http://localhost/OLA/google+/simple.php/b.html');
 $client->setDeveloperKey('apikey');
$plus = new Google_PlusService($client);

if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

if (isset($_GET['code'])) { // login stuff <-------
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die("The session state did not match.");
  }
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if ($client->getAccessToken()) {
  //$me = $plus->people->get('me');
  //print "Your Profile: <pre>" . print_r($me, true) . "</pre>";

  $params = array('maxResults' => 100);
  $activities = $plus->activities->listActivities('me', 'public', $params);
  //print "Your Activities: <pre>" . print_r($activities, true) . "</pre>";

  $params = array(
    'orderBy' => 'recent',
    'maxResults' => '20'//20
  );

    $q = "tag";


  $results = $plus->activities->search($q, $params);
  //code ....

  // The access token may have been updated lazily.
  $_SESSION['token'] = $client->getAccessToken();
} else {
  // This is the part that logs me in via browser <------
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>

1 个答案:

答案 0 :(得分:0)

是的,只需按照您的意愿调用并使用简单的API访问密钥 - 您可以检索公共信息,但是您必须为要检索帖子的用户提供长数字ID,而不是使用字符串'me ”。另请查看最新版本的库:https://github.com/google/google-api-php-client。您需要使用来自项目的API密钥设置您的客户端,该项目已在https://developers.google.com/console上启用了Google+

$client = new Google_Client();
$client->setApplicationName("Post Fetcher");
$client->setDeveloperKey('PUT_YOUR_API_KEY_HERE_OR_IT_WONT_WORK');
$plus = new Google_Service_Plus($client);
$activities = $this->plus->activities
                   ->listActivities("118051310819094153327", "public");