使用Google PHP客户端在Google+中插入时刻

时间:2013-07-30 15:19:02

标签: php google-api google-plus

我正在尝试在Google+个人资料中插入一些活动应用,如本文档页面所示: https://developers.google.com/+/api/latest/moments/insert

我成功获得了所需的访问令牌,但似乎moment-> insert方法没有做任何事情。

如果成功,我希望在此页面上看到一些内容,一旦获得访问权限,但没有任何反应 https://plus.google.com/u/0/apps/activities

这是我的代码

<?php
require_once '../google-api-php-client/Google_Client.php';
require_once '../google-api-php-client/contrib/Google_PlusService.php';

session_start();

$client = new Google_Client();
$client->setClientId('xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://www.myregisteredcallbackurl.com');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login'));
$client->setApprovalPrompt('force');

$plus = new Google_PlusService($client);

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

if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['token'])) {
    echo '<a href="http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?logout">Logout</a><br><br>'.PHP_EOL.PHP_EOL;
    $client->setAccessToken($_SESSION['token']);

    $moment = new Google_Moment();
    $moment->setType('http://schemas.google.com/AddActivity');
    $itemScope = new Google_ItemScope();
    $itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
    $moment->setTarget($itemScope);
    $plus->moments->insert('me', 'vault', $moment);
}

if ($client->getAccessToken()) {
    $_SESSION['token'] = $client->getAccessToken();
} else {
    $authUrl = $client->createAuthUrl();
    echo '<a href="' . $authUrl . '">Connect</a><br>';
}

1 个答案:

答案 0 :(得分:1)

您需要向范围添加requestvisibleactions权限。最简单的方法是从传统的OAuth 2.0流程切换到new Google+ Sign-In flow - Google+小组提供a PHP sample for Google+ Sign-In。如果您想继续使用较旧的OAuth流,则需要将request_visible_actions = [应用活动类型]附加到您的授权网址。

相关问题:

在您的代码中,您非常接近,以下似乎对我有用:

$client = new Google_Client();
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('http://example.com/callback.php');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login'));
$client->setRequestVisibleActions(array('https://schemas.google.com/AddActivity'));

$plus = new Google_PlusService($client);

要查看您撰写的应用活动,请访问app activity log