oauth 401 unauthorized error for heroku app fitbit - php

I've got a heroku app and I am running with Auth0 as the way of logging in via oauth... I have some code more or less the same as from the fitbit api php tutorial - "completeAuthorization.php". It looks a bit like:
$oauth = new OAuth($conskey, $conssec, OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->enableDebug();
}
catch( OAuthException $E )
{
print_r($E);
}
echo 'done new oauth';
$oauth->setToken($_SESSION['access_token'], $_SESSION['access_token_secret']);
echo 'done set token';
// Fitbit API call (get activities for specified date)
//http://api.fitbit.com/1/user/28C9GG/activities/date/2013-12-01.xml
$apiCall2 = 'http://api.fitbit.com/1/user/'.$_SESSION['userid'].'/activities/date/2014-02-25.xml';
echo $apiCall2;
// Performing API call
$oauth->fetch($apiCall2);
//$oauth->fetch($apiCall);
var_dump($oauth->getLastResponse());
I get the user id, and the session secret and token etc. from the Auth0 response from my index.php page, but I save them in a session to keep them on my get activities page.
But when I go to my page that does this after I log in with Auth0, I get this error:
http://api.fitbit.com/1/user/28C9GG/activities/date/2014-02-25.xml Fatal error: Uncaught exception 'OAuthException' with message 'Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)'
I am also only able to get this far on my webserver which has a pecl oauth extension installed, but heroku does not and I have no idea how to get it on Heroku, any ideas on this or why I get the above error?

Here is an example that might be useful:
https://github.com/auth0/Auth0-PHP/tree/master/examples/fitbit
In particular look at callback.php where there is a call to fitbit API
Matias

Related

How to solve User profile request failed in Google social login

When I try to login with google authentication, gives me an error. I have use Hybrid authentication use. It's work on HTTP but not working on HTTPS.
Please see the error:
User profile request failed. Most likely the user is not connected to
the provider and he should authenticate again. Ooophs, we got an
error: User profile request failed! Google returned an error:
exception 'Exception' with message 'The Authorization Service has
return
Code
$hybridauth = new Hybrid_Auth( $setting );
$provider = $hybridauth->authenticate( $this->session->data['provider']);
//get the user profile
$profile = $provider->getUserProfile();
$this->register($this->session->data['provider'], (array)$profile);
The OAuth2Client class has recently been changed in order to be compliant with the RFC6749 specifications.
Check them out here: https://www.rfc-editor.org/rfc/rfc6749#section-2.3.1
I believe this only affected POST requests.
Get the update in this PR: https://github.com/hybridauth/hybridauth/pull/707
I believe this has been merged into the master now as well, so you could just grab a new copy of the code and update locally.

Google Analytics API login required error

I've got a strange problem that I've tried to solve but I've tried a whole day and it just doesn't work, so I hope maybe someone else can help me with this.
I've build a CMS and after you login you see the dashboard.
On this dashboard you can click on a button to connect your account with Google - because I want my customers to be able to connect their Google Analytics account.
Everything works fine, I've got tokens and the refresh token and everything seems to work. Even when I request my user profile data I get it printed on my screen as an array. But when I try to get the accounts that are available to view for the connected user i get this error:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties
key=xxxxxxxxxxxxxxxxxxxxxxxxxx: (401) Login Required'
I just don't understand why I get the message 'Login required'.
Below you can see my script.
require_once('/Google/Client.php');
require_once('/Google/Service/Analytics.php');
// call object
$client = new Google_Client();
$client->setApplicationName("Google Analytics - CMS title");
$client->setClientId('xxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxx');
$client->setRedirectUri('xxxxxxxxxxxxxxxxxxx');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxx');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array(
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/analytics'
));
// decode
$token = $token; // this comes from my database and it's json encoded
// connect
$client->setAccessToken($token);
// call service
$service = new Google_Service_Analytics($client);
// get accounts from analytics
$accounts = $service->management_accounts->listManagementAccounts();
When I try to var_dump $accounts I don't see anything because the error already occurred (Login required)
I think you are going to ask me now if my token is correct but it is because I tested it with other api calls.. it's just not working for this specific analytics request.
I hope someone can help me with this.
Thanks,
Pim vd Molen
UPDATE:
Something really strange just happened. I don't know how this is possible but the error just changed into another error:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management
/accounts?key=xxxxxxxxxxxxxxxxxx: (403) Access Not Configured.
Please use Google Developers Console to activate the API for your project.
I've enabled the Google Analytics service ofcourse, but don't know which one i also need to enable.
The 401 error clearly states that the credentials are wrong. The Token might be valid for retrieving Data, but for retrieving user management information, you need a particular grant when asking for that token, please look here in the table you see the additional value for the scope parameter to set in your OAuth request.
not sure if you have solved this yet, but I've documented the process, with photos here:
https://circlical.squarespace.com/blog/2014/7/18/getting-zend-framework-2-and-googles-api-to-play-nice

Google Analytics API 401 Invalid Credentials

I'm wracking my brain trying to figure out how to use the Google API PHP Client to access Google Analytics. Specifically, I want to upload cost data from other campaigns. My code does work to get information from GA, I can view traffic data for profiles, but I cannot figure out how to upload.
Here's the code that I'm using for auth:
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("GA-Tester");
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://www.site.com/indext.php');
$client->setDeveloperKey('xxx');
$analyticsService = new Google_AnalyticsService($client);
$dailyUploads = $analyticsService->management_dailyUploads;
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
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']);
}
if (!$client->getAccessToken()) {
header ('Location:http://www.site.com/indext.php');
} else {...
This code does work for requesting data. I can get a list of accounts, profiles, download traffic data for a specific profile, etc. No errors or issues.
When I try to upload my CSV file containing cost data I get a '401 Invalid Credentials' error. Here's the code that sends the file:
$send = $dailyUploads->upload(
$accountId,
$webPropertyId,
$customDataSourceId,
$start_date,
1,
'cost',
array(
"reset" => true,
"data" => $cont,
"mimeType" => "application/octet-stream",
"uploadType" => "media"));
I've double checked all of my variables that I'm passing, they're sending the correct information.
So here's my question. If all of my GET requests work without issue, why would my POST request throw an error? I can't tell if this is an error with my code, or with settings in the API console. Can anyone steer me in the right direction?
EDIT:
Here's the error code generated (minus identifiable bits).
Fatal error: Uncaught exception 'Google_ServiceException' with message
'Error calling POST https://www.googleapis.com/upload/analytics/v3/man
agement/accounts/1234567/webproperties/UA-1234567-1/customDataSources/
xXxXxX/dailyUploads/2013-01-17/uploads?appendNumber=1&type=cost&reset=
true&uploadType=media&key=xXxXxX: (401) Invalid Credentials' in /../pub
lic_html/proj/google-api-php-client/src/io/Google_REST.php:66 Stack tra
ce: #0 /../public_html/proj/google-api-php-client/src/io/Google_REST.ph
p(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 /
../public_html/proj/google-api-php-client/src/service/Google_ServiceRes
ource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 /..
/public_html/proj/google-api-php-client/src/contrib/Google_AnalyticsSer
vice.php(82): Google_ServiceResource->__call('upload', Array) #3 /../pu
blic_html/proj/dailyUpload_send.php(60): Google_ManagementDailyUploadsS
erviceResource->upload('1234567', 'UA-1234567-1', 'xXxXxXxXxXxXxXx...',
' in /../public_html/proj/google-api-php-client/src/io/Google_REST.php
on line 66
I just successfully uploaded cost data for the first time. In trading comments with Nicholas Pickering I came across the documentation for Management API Authorization which states that:
You will get a 401 status code if your access_token has expired or if you are using the wrong scope for the API.
The default for scope is read only, which is why all of my GET requests were working without difficulty, but I couldn't complete any POST requests through the API. I can't remember how I found it, but the way to accomplish this within the PHP client library is to append the following line to the client declaration:
$client->setScopes('https://www.googleapis.com/auth/analytics');
As soon as I added that line to my project, I was able to successfully upload cost data. I'm really glad to have cleared this hurdle. I still have a long way to go to complete my project, but at least I know that it's going to work.
I kept geting this error until I went to Google Console -> APIs & auth ->
APIs and turned on this API usage.

Twitter OAuth Fetch 404 Error

I am working with Twitter OAuth in PHP framework and having an issue with getting through Twitter OAuth process. Everything seems to go through just fine and tokens match up all the way up to the last step that fetches user information.
The code is as follows:
...
$oauth->setToken($oauth_token, $session->twitter_secret);
$access_token_info = $oauth->getAccessToken(conf::get('TWITTER_OAUTH_ACCESS_URL'));
$session->twitter_state = 2;
$session->twitter_token = $access_token_info['oauth_token'];
$session->twitter_secret = $access_token_info['oauth_token_secret'];
$session->twitter_id = $access_token_info['user_id'];
$oauth->setToken($session->twitter_token, $session->twitter_secret);
if ($oauth->fetch(conf::get('TWITTER_API_URL').'/account/verify_credentials.json'))
{
...
}
Here is the exception error output:
500 exception 'OAuthException' with message 'Invalid auth/bad request (got a 404, expected HTTP/1.1 20X or a redirect)' in /var/www/webapp/app/controllers/default/auth.controller.php:135
Stack trace:
#0 /var/www/webapp/app/controllers/default/auth.controller.php(135): OAuth->fetch('https://api.twi...')
Now I am at a loss as to why there is a 404 error being thrown. It also does not make sense that the error happens after all authentication steps have been passed.
Thanks for any help in advance.
Looks like the solution is described over here:
Getting error with oauth
Seems that Twitter API needs to have a version number now.

LinkedIn Api - Uncaught exception 'OAuthException'

I'm currently attempting to install a login button for LinkedIn onto my website. I'm trying to go step by step as the developers section shows. After I wrote the code to get a request token and checked it using print_r.
define("my consumer key");
define("my consumer secret");
$oauth = new OAuth(my consumer key, my consumer secret);
//The first item of business is getting a request token
$request_token_response = $oauth->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken');
if($request_token_response === FALSE) {
throw new Exception("Failed fetching request token, response was:"
. $oauth->getLastResponse());
} else {
$request_token = $request_token_response;
}
print "Request Token:\n";
printf(" - oauth_token = %s\n", $request_token['oauth_token']);
printf(" - oauth_token_secret = %s\n", $request_token['oauth_token_secret']);
print "\n";
I got "Fatal error:Uncaught exception 'OAuthException'...Peer certificate cannot be authenticated with known CA certificates". The line that was called for the error is below
$request_token_response = $oauth->getRequestToken('https://api.linkedin.com/uas/oauth/requestToken');
I am not understanding what that error is trying to tell me so that I can fix the problem. I would appreciate and tips or guidance to help me better understand what this error message is trying to convey and how to fix it.
It seems that the library is trying to verify the SSL certificate and it cannot do so. You could disable ssl checks via the method OAuth::disableSSLChecks. I assume you are using the following pecl extension http://www.php.net/manual/en/class.oauth.php. If not the client library you are using should have a method to disable the SSL certificate verification.
....
...
$oauth = new OAuth(my consumer key, my consumer secret);
$oauth->disableSSLChecks();
..
...
Ideally you would do it right after instantiation

Categories