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.
Related
There is a div on UIWebView which is hidden and on DIV, there is some kind of string which also contains some JSON response as well.
NSString *response = [webView stringByEvaluatingJavaScriptFromString:#"document.getElementById('response').textContent"];
There is JSON response start with the key "FinalizeResult"
and the response string is
response = Illuminate\Http\JsonResponse Object
(
[jsonOptions:protected] => 0
[data:protected] => {"FinalizeResult":{"ResponseCode":0,"ResponseDescription":"Request processed successfully","UniqueID":"18278712782","version":"2.0","Account":"MyAcount","Amount":"102.000","ApprovalCode":"21782","Balance":"102.000","CardBrand":"Visa","CardNumber":"411111******1111","CardToken":"21212122121","Fees":"0","OrderID":"166221"}}
[callback:protected] =>
[encodingOptions:protected] => 15
[headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
(
[computedCacheControl:protected] => Array
(
[no-cache] => 1
)
[cookies:protected] => Array
(
)
[headerNames:protected] => Array
(
[cache-control] => Cache-Control
[date] => Date
[content-type] => Content-Type
)
[headers:protected] => Array
(
[cache-control] => Array
(
[0] => no-cache
)
[date] => Array
(
[0] => Mon, 04 Dec 2017 10:30:52 GMT
)
[content-type] => Array
(
[0] => application/json
)
)
[cacheControl:protected] => Array
(
)
)
)
How can we get this JSON response?
I am trying to figure out if I am missing something.
my first code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlParam->asXML());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
this works properly,
Second Code:
$client = new Client($url, array(
'maxredirects' => 0,
'timeout' => 30,
'adapter' => 'Zend\Http\Client\Adapter\Curl'));
$client->setMethod("POST");
$client->setRawBody($xmlParam->asXML());
$client->setEncType('text/xml');
$response = $client->send();
this one is the problem,
ERROR from second set of code
Zend\Http\Response Object (
[recommendedReasonPhrases:protected] => Array
(
[100] => Continue
[101] => Switching Protocols
[102] => Processing
[200] => OK
[201] => Created
[202] => Accepted
[203] => Non-Authoritative Information
[204] => No Content
[205] => Reset Content
[206] => Partial Content
[207] => Multi-status
[208] => Already Reported
[300] => Multiple Choices
[301] => Moved Permanently
[302] => Found
[303] => See Other
[304] => Not Modified
[305] => Use Proxy
[306] => Switch Proxy
[307] => Temporary Redirect
[400] => Bad Request
[401] => Unauthorized
[402] => Payment Required
[403] => Forbidden
[404] => Not Found
[405] => Method Not Allowed
[406] => Not Acceptable
[407] => Proxy Authentication Required
[408] => Request Time-out
[409] => Conflict
[410] => Gone
[411] => Length Required
[412] => Precondition Failed
[413] => Request Entity Too Large
[414] => Request-URI Too Large
[415] => Unsupported Media Type
[416] => Requested range not satisfiable
[417] => Expectation Failed
[418] => I'm a teapot
[422] => Unprocessable Entity
[423] => Locked
[424] => Failed Dependency
[425] => Unordered Collection
[426] => Upgrade Required
[428] => Precondition Required
[429] => Too Many Requests
[431] => Request Header Fields Too Large
[500] => Internal Server Error
[501] => Not Implemented
[502] => Bad Gateway
[503] => Service Unavailable
[504] => Gateway Time-out
[505] => HTTP Version not supported
[506] => Variant Also Negotiates
[507] => Insufficient Storage
[508] => Loop Detected
[511] => Network Authentication Required
)
[statusCode:protected] => 200
[reasonPhrase:protected] => OK
[version:protected] => 1.1
[headers:protected] => Zend\Http\Headers Object
(
[pluginClassLoader:protected] =>
[headersKeys:protected] => Array
(
[0] => cachecontrol
[1] => pragma
[2] => contenttype
[3] => contentencoding
[4] => vary
[5] => server
[6] => xaspnetversion
[7] => xpoweredby
[8] => xframeoptions
[9] => xcontenttypeoptions
[10] => contentsecuritypolicy
[11] => date
[12] => connection
)
[headers:protected] => Array
(
[0] => Array
(
[name] => Cache-Control
[line] => Cache-Control: no-cache
)
[1] => Array
(
[name] => Pragma
[line] => Pragma: no-cache
)
[2] => Array
(
[name] => Content-Type
[line] => Content-Type: text/xml; charset=utf-8
)
[3] => Array
(
[name] => Content-Encoding
[line] => Content-Encoding: gzip
)
[4] => Array
(
[name] => Vary
[line] => Vary: Accept-Encoding
)
[5] => Array
(
[name] => Server
[line] => Server: Microsoft-IIS/8.5
)
[6] => Array
(
[name] => X-AspNet-Version
[line] => X-AspNet-Version: 4.0.30319
)
[7] => Array
(
[name] => X-Powered-By
[line] => X-Powered-By: ASP.NET
)
[8] => Array
(
[name] => X-Frame-Options
[line] => X-Frame-Options: DENY
)
[9] => Array
(
[name] => X-Content-Type-Options
[line] => X-Content-Type-Options: nosniff
)
[10] => Array
(
[name] => Content-Security-Policy
[line] => Content-Security-Policy: frame-ancestors 'none';
)
[11] => Array
(
[name] => Date
[line] => Date: Tue, 17 Jan 2017 12:09:01 GMT
)
[12] => Array
(
[name] => Connection
[line] => Connection: close
)
)
)
[metadata:protected] => Array
(
)
[content:protected] => ���`I�%&/m�{J�J��t��`$ؐ#������iG#)�*��eVe]f#�흼��{���{���;�N'���?\fdl��J�ɞ!���?~|?"��ez��MQ-?�hw��Q�/�լX^|�Ѻ=�>���8����uެ�e���i���e{t����տ�������^�GO�z��������������'oξ|���k��/��.�ߧZ�YY���:�g�y��m�-�l�z�U���v���=M��U]]�|��
#B� ���i���
This is not an error it is a Zend\Http\Response object which is returned by the Client object when you call the send method
you can see from the output you have posted that it returned successfully (Http 200 Response).
[statusCode:protected] => 200
and returned some zipped content
[content:protected] => ���...
You just need to call:
$response->getBody();
which will return the decoded content body of the response
See https://framework.zend.com/manual/2.4/en/modules/zend.http.response.html for more details
I've changed around the path structure for HybridAuth quite a bit, all of the HybridAuth files are in a login directory.
require_once('login/Auth.php');
$auth = new Hybrid_Auth(self::$settings['auth']);
Where self::$settings['auth'] is this json file
{
"debug": 1,
"database": {
"driver": "mysql",
"host": "localhost",
"port": 3306,
"name": "ws_db",
"username": "root",
"password": "",
"charset": "utf8"
},
"auth": {
"base_url": "http://localhost/login/process",
"providers": {
"Twitter": {
"enabled": true
},
"Google": {
"enabled": true,
"keys": {
"id": "",
"secret": ""
}
},
"Facebook": {
"enabled": true,
"keys": {
"id": "",
"secret": ""
},
"trustForwarded": false
},
"Steam": {
"enabled": true
}
},
"debug_mode": true,
"debug_file": "auth.txt"
}
}
I have not yet acquired keys for the providers I intended to use (is that possibly why this is happening?). I tried to login with Steam to test that it was working since it was the only provider that didn't require me to get keys.
$_SESSION['user'] = $auth->authenticate('Steam');
I was correctly redirected to a Steam login page however upon clicking Login I received the above error.
Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in login\Auth.php:153 Stack trace: #0 login\Auth.php(39): Hybrid_Auth::initialize(Array) #1 index.php(83): Hybrid_Auth->__construct(Array) #2 index.php(6): Site::main() #3 {main} thrown in login\Auth.php on line 153
I thought it possibly had something to do with this line:
Hybrid_Logger::debug( "Hybrid_Auth initialize. dump used config: ", serialize( $config ) );
because that is the only line that I see serializing something but commenting that out didn't seem to work. Line 83 in my index.php is the initialization of Hybrid_Auth.
$auth = new Hybrid_Auth(self::$settings['auth']);
I can't seem to figure out what is going wrong with this though. Since that line of code is run when attempting to login and only causes a problem when returning from the Steam authorization page.
Here is the information that was output into auth.txt, I removed some information.
(
[message:protected] => Serialization of 'SimpleXMLElement' is not allowed
[string:Exception:private] =>
[code:protected] => 0
[file:protected] => login\Storage.php
[line:protected] => 73
[trace:Exception:private] => Array
(
[0] => Array
(
[file] => login\Storage.php
[line] => 73
[function] => serialize
[args] => Array
(
[0] => Hybrid_User Object
(
[providerId] => Steam
[timestamp] => 1431707732
[profile] => Hybrid_User_Profile Object
(
[identifier] => ***************
[webSiteURL] =>
[profileURL] => http://steamcommunity.com/id/******/
[photoURL] =>
[displayName] => Renari
[description] => <span>profile information was here</span>
[firstName] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[lastName] =>
[gender] =>
[language] =>
[age] =>
[birthDay] =>
[birthMonth] =>
[birthYear] =>
[email] =>
[emailVerified] =>
[phone] =>
[address] =>
[country] =>
[region] => location information was here
[city] =>
[zip] =>
)
)
)
)
[1] => Array
(
[file] => login\Providers\Steam.php
[line] => 37
[function] => set
[class] => Hybrid_Storage
[type] => ->
[args] => Array
(
[0] => hauth_session.Steam.user
[1] => Hybrid_User Object
(
[providerId] => Steam
[timestamp] => 1431707732
[profile] => Hybrid_User_Profile Object
(
[identifier] => ***************
[webSiteURL] =>
[profileURL] => http://steamcommunity.com/id/******/
[photoURL] =>
[displayName] => ******
[description] => <span>profile information was here</span>
[firstName] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[lastName] =>
[gender] =>
[language] =>
[age] =>
[birthDay] =>
[birthMonth] =>
[birthYear] =>
[email] =>
[emailVerified] =>
[phone] =>
[address] =>
[country] =>
[region] => location information was here
[city] =>
[zip] =>
)
)
)
)
[2] => Array
(
[file] => login\Endpoint.php
[line] => 182
[function] => loginFinish
[class] => Hybrid_Providers_Steam
[type] => ->
[args] => Array
(
)
)
[3] => Array
(
[file] => login\Endpoint.php
[line] => 55
[function] => processAuthDone
[class] => Hybrid_Endpoint
[type] => ->
[args] => Array
(
)
)
[4] => Array
(
[file] => login\Endpoint.php
[line] => 71
[function] => __construct
[class] => Hybrid_Endpoint
[type] => ->
[args] => Array
(
[0] =>
)
)
[5] => Array
(
[file] => index.php
[line] => 90
[function] => process
[class] => Hybrid_Endpoint
[type] => ::
[args] => Array
(
)
)
[6] => Array
(
[file] => index.php
[line] => 6
[function] => main
[class] => Site
[type] => ::
[args] => Array
(
)
)
)
[previous:Exception:private] =>
)
This was an issue with the Steam provider and was fixed in a commit you can download the fixed steam provider from the github repo.
Trying to send a post request to create a 'task' using Closeio's api. I'm getting a 200, and the 'task' isn't being posted to the website. The message is returning "OK". I've tried reformatting the params/options all day. What am I doing wrong? any ideas?
Here's the post request:
url = 'https://app.close.io/api/v1/task'
params = {
"lead_id" => 'lead_xxxxx....',
"assigned_to" => 'user_yyyyyyyyy.....',
"text" => "This customer has been referred",
"due_date" => Date.today.to_s,
"is_complete" => false
}
response = HTTParty.post( url , {
:body => params.to_json,
:basic_auth => {
:username => [API_KEY],
:password => ' '
},
:headers => {
'Content-Type' => 'application/json'
}
})
response:
#response=#<Net::HTTPOK 200 OK readbody=true>, #headers={"content-type"=>["application/json; charset=UTF-8"], "date"=>["Sat, 14 Mar 2015 20:19:38 GMT"], "server"=>["ElasticWWW"], "set-cookie"=>["session=; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/"], "strict-transport-security"=>["max-age=31536000; includeSubDomains"], "vary"=>["Accept"], "x-frame-options"=>["SAMEORIGIN"], "content-length"=>["73861"], "connection"=>["Close"]}>
Below is the data I'm getting from wsdl response... I need to get the separate value for example how to get the firstname from this array...Please anyone help me...
GetReportResponse Object ( [GetReportResult] => MBPeopleSearchRs_Type Object ( [MsgRsHdr] => MsgRsHdr_Type Object ( [RqUID] => {4DB2AD23-228A-465F-938D-BE072CED61C4} [Status] => Status_Type Object ( [StatusCode] => 0 [ServerStatusCode] => [Severity] => Info [StatusDesc] => OK [AdditionalStatus] => ) ) [Subject] => Subject Object ( [RefNum] => [PersonInfo] => PersonInfo_Type Object ( [PersonName] => PersonName_Type Object ( [LastName] => JANARDHANAN [FirstName] => SENTHINBABU [FullName] => [MiddleName] => [TitlePrefix] => [NameSuffix] => [Nickname] => [LegalName] => [MaidenName] => [OfficialTitle] => [Source] => MB [EffDt] => 2013-05-24 ) [ContactInfo] => ContactInfo_Type Object ( [ContactPref] => [PhoneNum] => [ContactName] => [EmailAddr] => [URL] => [PostAddr] => PostAddr_Type Object ( [PreDirection] => [Addr2] => [PostDirection] => N [Addr3] => [StreetType] => AVE [Addr4] => [StreetName] => LEXINGTON [Apt] => APT 4203 [StreetNum] => 4150 [Addr1] => [City] => SAINT PAUL [StateProv] => MN [PostalCode] => 55126-6131 [County] => RAMSEY
I suggest using a framework for this. CXF is a good choice if you write Java.
http://cxf.apache.org/
edit: since you work with php, take a look here: PHP SOAP client Tutorial/Recommendation?