问题描述
我尝试使用来访问Google Analytics数据。我成功获取授权代码并将其更改为授权令牌。但是,当我尝试从Analytics API获取任何数据时,我收到了 401无效凭证错误。
我使用的代码来自:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once'lib / API / Google_Client.php';
require_once'lib / API / contrib / Google_AnalyticsService.php';
session_start();
$ client = new Google_Client();
$ client-> setApplicationName(APP name);
$ client-> setClientId('xxx.apps.googleusercontent.com');
$ client-> setClientSecret('mysecret');
$ client-> setRedirectUri('http://example.com');
$ client-> setDeveloperKey('mykey');
$ client-> setScopes('https://www.googleapis.com/auth/analytics');
$ service = new Google_AnalyticsService($ client);
if(isset($ _ GET ['logout'])){
session_destroy();
if(isset($ _ GET ['code'])){
$ 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']);
// $ client-> refreshToken('refresh-token');
print_r(json_decode($ _ SESSION ['token']));
if($ client-> isAccessTokenExpired()){
session_destroy();
header('Location:http://example.com');
$ b $ if($ client-> getAccessToken()){
$ props = $ service-> management_webproperties-> listManagementWebproperties(〜b
$ b)所有);
print< h1>网站资源< / h1>< pre> 。 print_r($ props,true)。 < /预> 中;
$ accounts = $ service-> management_accounts-> listManagementAccounts();
print< h1>帐户< / h1>< pre> 。 print_r($ accounts,true)。 < /预> 中;
$ segments = $ service-> management_segments-> listManagementSegments();
print< h1>分段< / h1>< pre> 。 print_r($ segments,true)。 < /预> 中;
$ goals = $ service-> management_goals-> listManagementGoals(〜all,〜all,〜all);
print< h1>分段< / h1>< pre> 。 print_r($目标,true)。 < /预> 中;
$ _SESSION ['token'] = $ client-> getAccessToken();
} else {
$ authUrl = $ client-> createAuthUrl();
print< a class ='login'href ='$ authUrl'>连接我!< / a>;
}
?>
我重新验证了我的凭据。我的访问令牌看起来像这样:
对象
(
[access_token] => ya29。 blablabla
[token_type] => Bearer
[expires_in] => 3600
[refresh_token] => 1 / Eblablabla
[created] => 1413873721
)
当我尝试从GA帐户获取webproperties时,出现401错误:
Google_ServiceException对象
(
[errors:protected] => Array
(
[0 ] =>数组
(
[domain] =>全局
[reason] => authError
[message] =>无效凭证
[locationType ] => header
[location] =>授权
)
)
[message:protected] => ://www.googleapis.com/analytics/v3/management/accounts/~all/we bproperties?key = AIzaSyCDOiczVHVPiXhynaTkLkQ-Jp2Kr8kngS0:(401)Invalid Credentials
[string:Exception:private] =>
[code:protected] => 401
[file:protected] => ... lib // API / io / Google_REST.php
[line:protected] => 66
[trace:Exception:private] =>数组
(
[0] =>数组
(
[file] => ... / lib / API / io / Google_REST.php
[ line] => 36
[function] => decodeHttpResponse
[class] => Google_REST
[type] => ::
[args] => Array
(
[0] => Google_HttpRequest Object
(
[batchHeaders:Google_HttpRequest:private] => Array
(
[Content- Type] => application / http
[Content-Transfer-Encoding] => binary
[MIME-Version] => 1.0
[Content-Length] =>
)
[url:protected] => https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties?key=AIzaSyCDOiczVHVPiXhynaTkLkQ-Jp2Kr8kngS0
[requestMethod:protected] => GET
[requestHeaders:protected] => Array
(
[authorization] =>承载者ya29.xxx
)
[postBody:protected] =>
[userAgent:protected] => APP名称google-api-php-client / 0.6.5
[responseHttpCode:protected] => 401
[responseHeaders:protected] => Array
(
[vary] => Origin
Referer
X-Origin
[www-authenticate] =>承载领域=https:// accounts .google.com / AuthSubRequest,error = invalid_token
[content-type] => application / json; charset = UTF-8
[date] => 2014年10月21日,星期二14:00 :46 GMT
[expires] => 2014年10月21日14:00:46 GMT
[cache-control] => private,max-age = 0
[x- SAMEORIGIN
[x-xss-protection] => 1; mode = block
[server-content-type-options] => nosniff
[x-frame-options] =& ] = > GSE
[alternate-protocol] => 443:quic,p = 0.01
[transfer-encoding] =>分块
)
[responseBody:protected] => {error:{errors:[{domain:global,reason:authError,message:证书无效,locationType:header,location Authorization}],code:401,message:Invalid Credentials}}
[accessKey] =>
)
)
)
[1] => Array
(
[file] => ... / lib / API / service / Google_ServiceResource.php
[line] => 186
[function] =>执行
[class] => Google_REST
[type] => ::
[args] => Array
(
[0] => Google_HttpRequest Object
(
[batchHeaders:Google_HttpRequest:private] => Array
(
[Content-Type] => application / http
[Content-Transfer -Encoding] => binary
[MIME-Version] => 1.0
[Content-Length] =>
)
[url:protected] => https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties?key=AIzaSyCDOiczVHVPiXhynaTkLkQ-Jp2Kr8kngS0
[requestMethod:protected] => GET
[requestHeaders:protected] => Array
(
[authorization] =>承载者ya29.xxx
)
[postBody:protected] =>
[userAgent:protected] => APP名称google-api-php-client / 0.6.5
[responseHttpCode:protected] => 401
[responseHeaders:protected] => Array
(
[vary] => Origin
Referer
X-Origin
[www-authenticate] =>承载领域=https:// accounts .google.com / AuthSubRequest,error = invalid_token
[content-type] => application / json; charset = UTF-8
[date] => 2014年10月21日,星期二14:00 :46 GMT
[expires] => 2014年10月21日14:00:46 GMT
[cache-control] => private,max-age = 0
[x- SAMEORIGIN
[x-xss-protection] => 1; mode = block
[server-content-type-options] => nosniff
[x-frame-options] =& ] = > GSE
[alternate-protocol] => 443:quic,p = 0.01
[transfer-encoding] =>分块
)
[responseBody:protected] => {error:{errors:[{domain:global,reason:authError,message:证书无效,locationType:header,location Authorization}],code:401,message:Invalid Credentials}}
[accessKey] =>
)
)
)
[2] => Array
(
[file] => ... / lib / API / contrib / Google_AnalyticsService.php
[line] => 1010
[function] => __call
[class] => Google_ServiceResource
[type] => - >
[args] => Array
(
[0] => ;列表
[1] =>数组
(
[0] =>数组
(
[accountId] =>〜全部
)
)
)
)
[3] => Array
(
[file] => ... / oatuhCallback.php
[line] => 46
[function] => listManagementWebproperties
[ class] => Google_ManagementWebpropertiesServiceResource
[type] => - >
[args] => Array
(
[0] =>〜all
)
)
)
[前一个例外:private] =>
)
我做错了什么?
我自己找到答案。
使用Google API时,您必须始终创建公开访问密钥,为您提供开发人员密钥。这是您的正确开发者关键。我遵循一些论坛的指示,并得到了我的开发人员密钥的错误方向。
不幸的是,这在Googles OAuth集成指令中没有提及。
I'm trying to use Oauth2 to access Analytics data. I successfully get authorization code from and change it for authorization token. But when I try to get any data from Analytics API I get 401 Invalid Credentials error.
The code I'm using is from PHP client library:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once 'lib/API/Google_Client.php';
require_once 'lib/API/contrib/Google_AnalyticsService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("APP name");
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('mysecret');
$client->setRedirectUri('http://example.com');
$client->setDeveloperKey('mykey');
$client->setScopes('https://www.googleapis.com/auth/analytics');
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) {
session_destroy();
}
if (isset($_GET['code'])) {
$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']);
// $client->refreshToken('refresh-token');
print_r(json_decode($_SESSION['token']));
if ($client->isAccessTokenExpired()) {
session_destroy();
header('Location: http://example.com');
}
}
if ($client->getAccessToken()) {
$props = $service->management_webproperties->listManagementWebproperties("~all");
print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";
$accounts = $service->management_accounts->listManagementAccounts();
print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
$segments = $service->management_segments->listManagementSegments();
print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";
$goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
print "<h1>Segments</h1><pre>" . print_r($goals, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
I tripplechecked my credentials. My access token looks something like this:
Object
(
[access_token] => ya29.blablabla
[token_type] => Bearer
[expires_in] => 3600
[refresh_token] => 1/Eblablabla
[created] => 1413873721
)
When I try to get webproperties from GA account I get 401 error:
Google_ServiceException Object
(
[errors:protected] => Array
(
[0] => Array
(
[domain] => global
[reason] => authError
[message] => Invalid Credentials
[locationType] => header
[location] => Authorization
)
)
[message:protected] => Error calling GET https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties?key=AIzaSyCDOiczVHVPiXhynaTkLkQ-Jp2Kr8kngS0: (401) Invalid Credentials
[string:Exception:private] =>
[code:protected] => 401
[file:protected] => ...lib//API/io/Google_REST.php
[line:protected] => 66
[trace:Exception:private] => Array
(
[0] => Array
(
[file] => .../lib/API/io/Google_REST.php
[line] => 36
[function] => decodeHttpResponse
[class] => Google_REST
[type] => ::
[args] => Array
(
[0] => Google_HttpRequest Object
(
[batchHeaders:Google_HttpRequest:private] => Array
(
[Content-Type] => application/http
[Content-Transfer-Encoding] => binary
[MIME-Version] => 1.0
[Content-Length] =>
)
[url:protected] => https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties?key=AIzaSyCDOiczVHVPiXhynaTkLkQ-Jp2Kr8kngS0
[requestMethod:protected] => GET
[requestHeaders:protected] => Array
(
[authorization] => Bearer ya29.xxx
)
[postBody:protected] =>
[userAgent:protected] => APP name google-api-php-client/0.6.5
[responseHttpCode:protected] => 401
[responseHeaders:protected] => Array
(
[vary] => Origin
Referer
X-Origin
[www-authenticate] => Bearer realm="https://accounts.google.com/AuthSubRequest", error=invalid_token
[content-type] => application/json; charset=UTF-8
[date] => Tue, 21 Oct 2014 14:00:46 GMT
[expires] => Tue, 21 Oct 2014 14:00:46 GMT
[cache-control] => private, max-age=0
[x-content-type-options] => nosniff
[x-frame-options] => SAMEORIGIN
[x-xss-protection] => 1; mode=block
[server] => GSE
[alternate-protocol] => 443:quic,p=0.01
[transfer-encoding] => chunked
)
[responseBody:protected] => {"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid Credentials","locationType":"header","location":"Authorization"}],"code":401,"message":"Invalid Credentials"}}
[accessKey] =>
)
)
)
[1] => Array
(
[file] => .../lib/API/service/Google_ServiceResource.php
[line] => 186
[function] => execute
[class] => Google_REST
[type] => ::
[args] => Array
(
[0] => Google_HttpRequest Object
(
[batchHeaders:Google_HttpRequest:private] => Array
(
[Content-Type] => application/http
[Content-Transfer-Encoding] => binary
[MIME-Version] => 1.0
[Content-Length] =>
)
[url:protected] => https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties?key=AIzaSyCDOiczVHVPiXhynaTkLkQ-Jp2Kr8kngS0
[requestMethod:protected] => GET
[requestHeaders:protected] => Array
(
[authorization] => Bearer ya29.xxx
)
[postBody:protected] =>
[userAgent:protected] => APP name google-api-php-client/0.6.5
[responseHttpCode:protected] => 401
[responseHeaders:protected] => Array
(
[vary] => Origin
Referer
X-Origin
[www-authenticate] => Bearer realm="https://accounts.google.com/AuthSubRequest", error=invalid_token
[content-type] => application/json; charset=UTF-8
[date] => Tue, 21 Oct 2014 14:00:46 GMT
[expires] => Tue, 21 Oct 2014 14:00:46 GMT
[cache-control] => private, max-age=0
[x-content-type-options] => nosniff
[x-frame-options] => SAMEORIGIN
[x-xss-protection] => 1; mode=block
[server] => GSE
[alternate-protocol] => 443:quic,p=0.01
[transfer-encoding] => chunked
)
[responseBody:protected] => {"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid Credentials","locationType":"header","location":"Authorization"}],"code":401,"message":"Invalid Credentials"}}
[accessKey] =>
)
)
)
[2] => Array
(
[file] => .../lib/API/contrib/Google_AnalyticsService.php
[line] => 1010
[function] => __call
[class] => Google_ServiceResource
[type] => ->
[args] => Array
(
[0] => list
[1] => Array
(
[0] => Array
(
[accountId] => ~all
)
)
)
)
[3] => Array
(
[file] => .../oatuhCallback.php
[line] => 46
[function] => listManagementWebproperties
[class] => Google_ManagementWebpropertiesServiceResource
[type] => ->
[args] => Array
(
[0] => ~all
)
)
)
[previous:Exception:private] =>
)
What am I doing wrong?
I found answer myself.
When using Google API you ALWAYS have to create Public access key which gives you developer key. That is your right developer key. I followed instructions from some forum and got wrong directions for getting my developer key.
Unfortunately this is not mentioned in Googles OAuth integration instructions.
这篇关于Google API 401无效凭证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!