Google+ API 时刻上未经授权的 401.insert with PHP.


Unauthorized 401 on Google+ API moments.insert with PHP

我想创建一个小机器人,它可以在特定条件下将 G+ 时刻推送到 G+ 页面。想用PHP尝试一下。所以我有:在Google Console中注册了Web应用程序,打开了Google+ API,我的Apache服务器上的小PHP脚本以及结果中的401 Unathorized。我正在使用来自 https://github.com/google/google-api-php-client 的google-api-php-client

我通过互联网搜索了答案,但一无所获。到处都有自己幸福的结局,所有人都在工作,但我都尝试了——只有 401 来找我。

我的脚本:

<?
header("Content-Type: text/html; charset=utf-8");
session_start();
ini_set("display_errors", 1);
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.php';
$client = new Google_Client();
$client->setClientId("MY_CLIENT_ID");
$client->setClientSecret("MY_CLIENT_SECRET");
$client->setRedirectUri("REDIRECT_URL");
$client->setAccessType('offline');
$client->addScope("https://www.googleapis.com/auth/plus.login");
$client->addScope("https://www.googleapis.com/auth/plus.me");
$client->addScope("https://www.googleapis.com/auth/userinfo.profile");
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$requestVisibleActions = array('http://schemas.google.com/AddActivity');
$client->setRequestVisibleActions($requestVisibleActions);
if (!isset($_GET['code'])) {
    if (isset($_SESSION['access_token'])) {
        $client->setAccessToken($_SESSION['access_token']);
        $moment_body = new Google_Service_Plus_Moment();
        $plus = new Google_Service_Plus($client);
        $moment_body->setType("http://schemas.google.com/AddActivity");
        $item_scope = new Google_Service_Plus_ItemScope();
        $item_scope->setId("target-id-214wdefsadf1");
        $item_scope->setType("http://schemas.google.com/AddActivity");
        $item_scope->setName("The Google+ Platform");
        $item_scope->setDescription("A page that describes just how awesome Google+ is!");
        $item_scope->setImage("https://developers.google.com/+/plugins/snippet/examples/thing.png");
        $moment_body->setTarget($item_scope);
        $momentResult = $plus->moments->insert('me', 'vault', $moment_body);
    } else {
        $authUrl = $client->createAuthUrl();
        header("Location: ".$authUrl);
        exit;
    }
} else {
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    header("Location: REDIRECT_URL");
    exit;
}

因此,脚本会根据客户端中注册的范围成功请求所有需要的访问权限,获取令牌,将其写入会话,但是当它尝试插入新时刻时,它会Google_Service_Exception在/var/www/rico/Google/Http/REST.php:79 中收到消息"调用 POST https://www.googleapis.com/plus/v1/people/me/moments/vault 时出错":79

怎么了?我尝试了一些放在堆栈流上的解决方案,但它们没有帮助。我还检查了我的身份验证 - 似乎还可以,有正确的request_visible_actions和其他......我不知道怎么了...

你可能错过了一些东西。 也许您的示例假设您正在为您设置的一些值放置实际值。 但是,您需要设置应用程序名称和开发人员密钥。 如果您没有确定设置开发人员密钥,则许多 api 调用将返回未授权。

$client->setApplicationName($plApp->authenticationData->applicationName);
$client->setDeveloperKey($authData->apiKey);

我想你实际上是在下面设置这些。 返回网址必须与在 Google 开发者网站上为特定应用设置的返回网址一致

$client->setClientId($authData->clientId);
$client->setClientSecret($authData->clientSecret);
$client->setRedirectUri($returnUrl);