PHP API access - continue after oauth2 authentication - php

This is rather a basic question. I'm just getting started with using API calls. I'm trying to use the Dropbox API.
My app has the following code:
<?php
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
$appInfo = dbx\AppInfo::loadFromJsonFile("app-info.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "CharmsBox/1.0");
$authorizeUrl = $webAuth->start();
print "<p>Authorize the App now</p>";
print '
<p class="ui-widget">Auth Key: <input id="authkey">
<a id="btnAuth" class="btn btn-primary btn-large" href="#" tabindex="2">
<span class="glyphicon glyphicon-flash" aria-hidden="true"></span>Authenticate
</a>
</p>';
?>
In another tab, I enter the username and password to authenticate. Dropbox gives the auth code. I'm now supposed to use this code to generate user id and access token as below:
list($accessToken, $userId) = $webAuth->finish($authCode);
echo "Authorization complete.\n";
echo "- User ID: $userId\n";
echo "- Access Token: $accessToken\n";
However since my php code has already finished execution, I'm unable to run the above code. I tried using the following in another php script, and using GET request:
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
$appInfo = dbx\AppInfo::loadFromJsonFile("app-info.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "CharmsBox/1.0");
if (isset($_GET['authcode'])) {
list($accessToken, $userId) = $webAuth->finish($authCode);
echo "Authorization complete.\n";
echo "- User ID: $userId\n";
echo "- Access Token: $accessToken\n";
return;
} else {
print "Unauthenticated call of script!";
return;
}
However that gives me the following error code:
Fatal error: Uncaught exception 'InvalidArgumentException' with message ''code' must not be null' in /var/www/virtual/mydomain/split/htdocs/dropbox-sdk/Dropbox/Checker.php
The original example script at Dropbox looks like this:
echo "1. Go to: $authorizeUrl\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
echo "Enter the authorization code here: ";
$authCode = \trim(\fgets(STDIN));
list($accessToken, $userId) = $webAuth->finish($authCode);
echo "Authorization complete.\n";
echo "- User ID: $userId\n";
echo "- Access Token: $accessToken\n";
How can I continue with authentication with the generated accesscode? Specifically, how can I accept a web based input instead of STDIN and continue authentication?

In a web app, you probably want to use dbx\WebAuth, rather than dbx\WebAuthNoRedirect. Check out the web file browser example in the SDK.

Related

code has expired (within the last hour) dropbox

Hi everyone i am new in dropbox api (php version).
i am getting authCode using authorizeUrl, its working good for only one time if i reload page error message shows on
'HTTP status 400 {"error_description": "code has expired (within the last hour)", "error": "invalid_grant"}
how to get permanent authCode from dropbox.
$appInfo = dbx\AppInfo::loadFromJsonFile("api-key.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = "****************************************";
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);
Found the solution in this error
some steps to solve this problem
go to Apps page Dropbox apps
add your site or localhost link to OAuth 2 Redirect URIs
next to generate access token, then copy the access token and use it .
finally remove this lines
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
and paste directly in your access token into
$accessToken =
"VTEp2cvkQ8************************************";
it's working perfectly

Google PHP client won't authenticate code, invalid_request

I'm using Google PHP Client 4ae272683e18888362e1f935b813e345b99e23b8 pulled Aug 9 from github. I feel like my code is too simple to be wrong.
require_once ('Google/Client.php');
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->authenticate($_POST['code']);
I get this invalid_request error:
Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_request'' in /Users/dfabulich/test/Google/Auth/OAuth2.php:125
Stack trace:
#0 /Users/dfabulich/test/Google/Client.php(135): Google_Auth_OAuth2->authenticate('4/58wTCTNiQNIdR...')
#1 /Users/dfabulich/test/google-login.php(24): Google_Client->authenticate('4/58wTCTNiQNIdR...')
#2 {main}
client_secret.json is the exact file I downloaded from the Google API Developers Console. The file definitely exists, because if I use the wrong file name, I get a very clear error, "Invalid client secret JSON file." I've visually inspected the file and it looks fine.
I edited Google/Auth/OAuth2.php to log the post body as json; it looks like this (but I've HIDDEN the client secret below):
{"code":"4\/58wTCTNiQNIdRfb8DgQBYk518URV.Elrb71kFKHAYEnp6UAPFm0HWWGd6jwI","grant_type":"authorization_code","redirect_uri":"","client_id":"807284957448-3katmu7oqd1277ql9eo258dadkbkqruq.apps.googleusercontent.com","client_secret":"HIDDEN"}
What could I possibly be doing wrong?!
I was using the Google+ Sign-in API, so I also needed to add a setRedirectUri("postmessage") line. This code works.
require_once ('Google/Client.php');
$client = new Google_Client();
$client->setRedirectUri('postmessage');
$client->setAuthConfigFile('client_secret.json');
$client->authenticate($_POST['code']);
I cant tell you why your code doesn't work I have never tried using setAuthConfigFile This is the code i use
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
My tutorial can be found at Google Oauth2 php

Newly Generated Dropbox Token Expires Instantly

I am having this weird issue here in which the instant I get a token via Dropbox and try to test it, an exception is thrown with this message:
HTTP status 401 {"error": "The given OAuth 2 access token doesn't
exist or has expired."}
Why would a Dropbox token expire as soon as I generate it?
Let me show you the flow of my app:
User sees this screen:
Which has the following relevant PHP code:
require "../../includes/dropbox-sdk/Dropbox/autoload.php";
require "../../includes/config.php";
session_start();
session_regenerate_id();
$appInfo = Dropbox\AppInfo::loadFromJsonFile("../../includes/dropbox-sdk/Dropbox/app-info.json");
$webAuth = new Dropbox\WebAuthNoRedirect($appInfo, "Mignori-Box/1.0");
$authorizeUrl = $webAuth->start();
So okay, we generate a Dropbox authorization URL with the official SDK, which seems to be working fine, the user sees this screen:
They click allow, Dropbox gives them an Authorization token, then they paste it into my site, and submit it. This is the code that processes the form:
try
{
$accessToken = $_POST['authorization_code'];
$dbxClient = new Dropbox\Client($accessToken, "Mignori-Box/1.0");
$accountInfo = $dbxClient->getAccountInfo();
}catch(Exception $e)
{
echo "<div class=\"alert alert-danger\">";
echo "<strong>An error has occurred.</strong><br>" . $e -> getMessage();
echo "</div>";
}
But no matter how recent the token is, when the user submits the token the catch is called and the warning displayed. Even if the token was generated literally seconds ago, this happens.
Can someone please enlighten me as to what's wrong?
I was forgetting the step to convert the authorization code into an access token.
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
In other words, I was indeed using the wrong token. Haha. Last snippet of code should be:
try
{
list($accessToken, $dropboxUserId) = $webAuth->finish($_POST['authorization_code']);
$dbxClient = new Dropbox\Client($accessToken, "Mignori-Box/1.0");
$accountInfo = $dbxClient->getAccountInfo();
}catch(Exception $e)
{
echo "<div class=\"alert alert-danger\">";
echo "<strong>An error has occurred.</strong><br>" . $e -> getMessage();
echo "</div>";
}

Call to undefined method Google_Client in Google Analytics while using HelloAnalyticsApi

I am using Core reporting API for reporting. I have installed Google PHP API client master on my localhost server and made a file HelloAnalyticsAPi.php in src folder Where I include
Google/Client.php
,
Google/Service/Analytics.php
files. And use the below details
$client->setClientId('XXXXXXXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXXXXXXX');
$client->setRedirectUri('http://localhost/analytics/src/HelloAnalyticsApi.php');
$client->setDeveloperKey('XXXXXXXXXXX');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setUseObjects(true);
I have fatal error on setUseObjects. Error is Fatal error: Call to undefined method Google_Client::setUseObjects(). I have done some authorization on my google analytics backend also.
Please let me know the whole process for getting report on my server. Because I am not able to understand the developers guide of google analytics which they have given.
The problem you are having is that you have the wrong client lib. The Hello Analytics API tutorial was created using the old lib on Code.google - google-api-php-client Not the newer version on github.
Update:
Because of the fact that the tutorial still hasn't been updated I have made a tutorial that may help. Google Oauth2 php. The code below is ripped directly from it. The tutorial will be kept up to date you may want to check that for any changes.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>

Dropbox API - Call to undefined function readline()

I have the following code
<?php
// Include DropBox API
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
// Settings for DropBox
$appInfo = dbx\AppInfo::loadFromJsonFile("config.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authCode = \trim(\readline("A-WALID-KEY-HERE"));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
?>
Bud i get this error when i run the code.
Call to undefined function readline()
What am I doing wrong?
It sounds from your comment like you're trying to run this as a web app. If so, you're going to run into trouble. This looks like the command-line app example code, which is why it uses readline (which reads input from the command-line).
You might want to start from the web-file-browser example that ships with the SDK. This is meant to be run as a web app and should show you to how to do (among other things) authentication in the browser.
I had the same problem with the same code. You have forgotten to add this:
$authorizeUrl = $webAuth->start();
just right after this line:
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
What you have to do is to use the created link stored in the variable $authorizeUrl to get the authorization code.
After doing this you need to use the authorization code to generate a token. For this comment the part of your code like that:
<?php
// Include DropBox API
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
// Settings for DropBox
//$appInfo = dbx\AppInfo::loadFromJsonFile("config.json");
//$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
//**$authorizeUrl = $webAuth->start();**
$authCode = \trim(\readline("**A-WALID-KEY-HERE**"));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
?>
Once you get the token save it somewhere safe and comment also the rest of the lines. Then you can access dropbox with no problem. For example:
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();

Categories