TwitterOAuth: Invalid oauth_verifier parameter - php

I am at the stage of the OAuth flow where I get the OAuth verifier and have to use it to get the permanent token, however I encounter the error "Invalid oauth_verifier parameter".
// I get a valid oauth verifier
$oauth_verifier = filter_input(INPUT_GET, "oauth_verifier");
// I am able to run var_dump($connection) and the response seems valid
$connection = new TwitterOAuth(
$config["consumer_key"],
$config["consumer_secret"],
$_SESSION["oauth_token"],
$_SESSION["oauth_token_secret"]
);
// I believe this is where the problem lies, if I try var_dump($token) nothing shows but my original error message
$token = $connection->oauth(
"oauth/access_token", [
"oauth_verifier" => $oauth_verifier
]
);
$twitter = new TwitterOAuth(
$config["consumer_key"],
$config["consumer_secret"],
$token["oauth_token"],
$token["oauth_token_secret"]
);
The full error message is:
Fatal error: Uncaught Abraham\TwitterOAuth\TwitterOAuthException: Invalid request token. in C:\xampp\htdocs\twitteroauth-master\src\TwitterOAuth.php:158 Stack trace: #0 C:\xampp\htdocs\twitter_callback.php(34): Abraham\TwitterOAuth\TwitterOAuth->oauth('oauth/access_to...', Array) #1 {main} thrown in C:\xampp\htdocs\twitteroauth-master\src\TwitterOAuth.php on line 158

If you are running this on a local server then check your url_callback, its not be in form of google tiny url, it must be in the form of "http://localhost:80/file_name" OR "http://localhots:8080/file_name". If you still have this problem then write your throw statement in try catch block.
e.g.
try {
throw new TwitterOAuthException($result);
}
catch(Exception $e) {
}
If you are running on server in spite of always check your url_callback should not be in the form of google tiny url because new twitter oauth didn't verify your google tiny url.

Related

Fatal error: Uncaught Google_Auth_Exception: Invalid token format in ...google\apiclient\src\Google\Auth\OAuth2.php:189 Stack trace: #0

I am tying to integrate google sign in service (OAuth 2.0) within a web application without success.
I bump into this issue after using a "token" in a json file (token.json for simplicity).
Fatal error: Uncaught Google_Auth_Exception: Invalid token format in [DIR]\phpgmailapi\vendor\google\apiclient\src\Google\Auth\OAuth2.php:189 Stack trace: #0
the script:
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_encode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
token.json looks like this:
{"access_token" : "XXXXXXXXXX"}
Assuming the error comes from invalid format I tried also save it as a string by editing the json file or calling the string from the array.
$client->setAccessToken($accessToken['access_token']);
yet, no success.
The setAccessToken isn't seem to be messed with (located in OAuth2.php)
public function setAccessToken($token)
{
$token = json_decode($token, true);
if ($token == null) {
throw new Google_Auth_Exception('Could not json decode the token');
}
if (! isset($token['access_token'])) {
throw new Google_Auth_Exception("Invalid token format");
}
$this->token = $token;
}
I wonder what leads to this bug in the system.

Facebook Graph Query with PHP

So I am trying to fetch images posted with a certain hashtag in facebook. I am using the facebook php api. This is my code:
FacebookSession::setDefaultApplication('my-api-key', 'secret');
$session=FacebookSession::newAppSession();
try {
$session->validate();
} catch (FacebookRequestException $ex) {
var_dump($ex);
echo $ex->getMessage();
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
echo $ex->getMessage();
}
$request = new FacebookRequest(
$session,
'GET',
'/gatos'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
var_dump($graphObject);
I know that the request I am executing is not for pulling hashtags, but anyways, I am getting the following error:
Fatal error: Uncaught exception 'Facebook\FacebookAuthorizationException' with message 'Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api' in /var/www/experiments/gatopull/vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequestException.php:104 Stack trace: #0 /var/www/experiments/gatopull/vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequest.php(280): Facebook\FacebookRequestException::create('{"error":{"mess...', Object(stdClass), 400) #1 /var/www/experiments/gatopull/config/facebook_api.php(36): Facebook\FacebookRequest->execute() #2 /var/www/experiments/gatopull/config/apicontroller.php(2): require_once('/var/www/experi...') #3 /var/www/experiments/gatopull/index.php(3): require_once('/var/www/experi...') #4 {main} thrown in /var/www/experiments/gatopull/vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequestException.php on line 104
My questions are:
Do I need a user access-token to search hashtags, or is it
sufficient with the client token?
I know the request I need to do with curl or by url, but how do I make this request with the fb api? Here is the url request:
https://graph.facebook.com/search?q=hashtag&type=post&limit=999&access_token=myaccesstoken
Is there any php library to do this with more social networks?
thanks!

fitbit php auth doesn't work

After 10 hours of trying various fitbit php libraries I'm turning to stackoverflow for help.
This doesn't work: https://github.com/heyitspavel/fitbitphp
Using
$profile = $fitbit->getProfile();
with that library returns
Fatal error: Uncaught exception 'FitBitException' with message 'Your Fitbit request failed. Code: 400' in /var/www/api/fitbitphp.php:324 Stack trace: #0 /var/www/api/addFitbit.php(22): FitBitPHP->getProfile() #1 {main} thrown in /var/www/api/fitbitphp.php on line 324
This the library on the fitbit website, seems like a lot of people have a problem with this.
public function getProfile()
{
$headers = $this->getHeaders();
try {
$this->oauth->fetch($this->baseApiUrl . "user/" . $this->userId . "/profile." . $this->responseFormat, null, OAUTH_HTTP_METHOD_GET, $headers);
} catch (Exception $E) {
}
$response = $this->oauth->getLastResponse();
$responseInfo = $this->oauth->getLastResponseInfo();
if (!strcmp($responseInfo['http_code'], '200')) {
$response = $this->parseResponse($response);
if ($response)
return $response;
else
throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
} else {
throw new FitBitException($responseInfo['http_code'], 'Your Fitbit request failed. Code: ' . $responseInfo['http_code']);
}
}
I tried this here as well but it doesn't return the user token or session id https://github.com/nostra999/fitbit-api
Perhaps missed out the init step, as described in the lib README file (https://github.com/heyitspavel/fitbitphp/blob/master/README.md)
Simple working usage is:
<?php
define('FITBIT_KEY', '777'); // The application key registered
define('FITBIT_SECRET', '777'); // The application secret registered
$fitbit = new FitBitPHP(FITBIT_KEY, FITBIT_SECRET);
$fitbit->initSession('http://localhost:8080/fibit'); // callback URL
$fitbit->getProfile();
Also from the Fitbit API Documentation:
https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors#APIResponseFormatAndErrors-Response
400 Bad Request Any case where either endpoint doesn't exist, resource
path parameters are invalid, POST request parameters are invalid or no
Authentication header provided. This doesn't include invalid specific
resource ids
If this does not help, please provide the full code that you run, not just
$profile = $fitbit->getProfile();

How to store authenticated users access token from Instagram using PHP API

I'm creating a simple page to display my current photos from my Instragram account. I'm using cosenary's Instagram PHP API (instagram.class.php) from https://github.com/cosenary/Instagram-PHP-API
Upon successful login the success page displayed correctly. But when I refresh the page again, it displayed this error message:
Fatal error: Uncaught exception 'Exception' with message 'Error: _makeCall() | users/self/media/recent - This method requires an authenticated users access token.' in /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php:432
Stack trace: #0 /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php(148): Instagram->_makeCall('users/self/medi...', true, Array) #1 /home/teammond/public_html/projects/amacc/it321/final/success/index.php(40): Instagram->getUserMedia() #2 {main} thrown in /home/teammond/public_html/projects/amacc/it321/final/instagram.class.php on line 432
I tried placing what I think were the tokens in PHP sessions but still to no avail.
This the PHP code from my success page (redirect_uri):
<?php
session_start();
require_once '../instagram.class.php';
// initialize class
$instagram = new Instagram(array(
'apiKey' => '010d47aaccf945559ae9ded9d0aa7459',
'apiSecret' => '{omitted}',
'apiCallback' => 'http://projects.teammondestars.com/amacc/it321/final/success'
));
// receive OAuth code parameter
$code = $_GET['code'];
if (!isset($_SESSION['oauth'])) {
$_SESSION['oauth'] = $code;
}
// check whether the user has granted access
if (isset($_SESSION['oauth'])) {
// receive OAuth token object
$data = $instagram->getOAuthToken($_SESSION['oauth'], true);
$username = $username = $data->user->username;
// store user access token
$instagram->setAccessToken($data);
if (!isset($_SESSION['token'])) {
$_SESSION['token'] = $instagram->getAccessToken();
}
// now you have access to all authenticated user methods
$result = $instagram->getUserMedia();
} else {
// check whether an error occurred
if (isset($_GET['error'])) {
echo 'An error occurred: ' . $_GET['error_description'];
}
}
?>

Cannot catch an Exception while authenticating user with HybridAuth

I'm creating a WordPress plugin that automatically publishes the post to Facebook when a new post is added to the site. For the same reason user needs to authenticate his Facebook account. The code I use for this purpose is:-
try {
$fp_hybridauth = new Hybrid_Auth( $hybrid_config );
$fp_hybridauth->authenticate( "facebook" ); //this function does the job of authenticating user and it is causing the exception to be thrown
update_option( "session_data", $fp_hybridauth->getSessionData() );
wp_redirect( site_url("/wp-admin/admin.php?page=facebook-publish&tab=api&fbauth=success") );
}
catch( Exception $e ){
echo $e->getMessage();
}
This code works perfectly if user permits the permission in Facebook oAuth dialog, but if user denies to give permission, it throws an exception that I can't seem to catch:-
Fatal error: Uncaught exception 'Exception' with message 'Authentication failed! The user denied your request.' in /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Providers/Facebook.php:86 Stack trace: #0 /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Endpoint.php(182): Hybrid_Providers_Facebook->loginFinish() #1 /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Endpoint.php(58): Hybrid_Endpoint::processAuthDone() #2 /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/index.php(15): Hybrid_Endpoint::process() #3 {main} Next exception 'Exception' with message 'Authentication failed! The user denied your request.' in /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Auth.php:147 Stack trace: #0 /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybrid in /home/pramodjodhani/public_html/dev/wp-content/plugins/facebook-publish/lib/class/hybridauth/Hybrid/Auth.php on line 147
The code that is written in the Hybrid/Providers/Facebook.php file is:-
function loginFinish()
{
// in case we get error_reason=user_denied&error=access_denied
if ( isset( $_REQUEST['error'] ) && $_REQUEST['error'] == "access_denied" ){
throw new Exception( "Authentication failed! The user denied your request.", 5 ); //THIS IS LINE NUMBER 86
}
// try to get the UID of the connected user from fb, should be > 0
if ( ! $this->api->getUser() ){
throw new Exception( "Authentication failed! {$this->providerId} returned an invalid user id.", 5 );
}
// set user as logged in
$this->setUserConnected();
// store facebook access token
$this->token( "access_token", $this->api->getAccessToken() );
}
I tried Googling and searching for the issue but I couldn't find anything wrong with this. Sorry I can't provide anything that I got in my research.
This solution works for me:
try{
$hybridauth = new Hybrid_Auth($config);
$adapter = $hybridauth->authenticate($service);
}catch(Exception $ex){
var_dump($ex);
return;
}
$user_profile = $adapter->getUserProfile();
Exception fires Ok.
But if I move line
$hybridauth = new Hybrid_Auth($config);
outside the try{} area then I can't catch this exeption. This is quite wierd because this line works Ok and doesn't throw any exeption.
I had the same problem and solution was that i forgot about namespace (i was operating inside another one), so the correct code for catch block is:
catch(\Exception $e) {}

Categories