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) {}
Related
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.
Currently I installed openfire in my server and started to use it. I tried to create a user in openfire using Restapi . And I got output as I expected.
Now i tried to create a user with the username "abcdef" which is already existed. I want a message that says "username already exists" but instead I get an exception.
The exception:
Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error response [url] http://myip:9090/plugins/restapi/v1/users [status code] 409 [reason phrase] Conflict' in /var/www/html/open_fire_internal/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:88
The message from the exception:
Client error response [url] http://myip:9090/plugins/restapi/v1/users [status code] 409 [reason phrase] Conflict
Stack trace:
#0 [...]/vendor/guzzlehttp/guzzle/src/Subscriber/HttpError.php(33): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Message\Request), Object(GuzzleHttp\Message\Response))
#1 [...]/vendor/guzzlehttp/guzzle/src/Event/Emitter.php(109): GuzzleHttp\Subscriber\HttpError->onComplete(Object(GuzzleHttp\Event\CompleteEvent), 'complete')
#2 [...]/vendor/guzzlehttp/guzzle/src/RequestFsm.php(91): GuzzleHttp\Event\Emitter->emit('complete', Object(GuzzleHttp\Event\CompleteEvent))
#3 [...]/vendor/guzzlehttp/guzzle/src/RequestFsm.php(132): GuzzleHttp\RequestFsm->__invoke(Object(GuzzleHttp\Transaction))in /var/www/html/open_fire_internal/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 88
So can anyone help me to overcome from this issue?
First check whether the user is exists or not than add them
$user = $api->getuser($username);
if(!$user)
{
$result = $api->addUser('Username', 'Password', 'Real Name', 'email#email.tld', array('Group 1'));
// Check result if command is succesful
if($result) {
// Display result, and check if it's an error or correct response
echo ($result['result']) ? 'Success: ' : 'Error: ';
echo $result['message'];
} else {
// Something went wrong, probably connection issues
}
}
else
{
echo 'user already exists';
}
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!
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'];
}
}
?>
I'm using the Facebook PHP API, and around 1 time in 40 it dumps this exception on my webapp:
Uncaught CurlException: 56: SSL read:
error:00000000:lib(0):func(0):reason(0),
errno 104 thrown in ... on line 638
I'm not looking for a solution to what's causing the exception (already working on that), but for now I'd like to change it from dumping the exception on the page to either telling the user to refresh the page or refreshing the page automatically.
The exception is being thrown in this file: https://github.com/facebook/php-sdk/blob/master/src/facebook.php
This is the code I'd like to temporarily change to a refresh / refresh instruction:
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
self::errorLog('Invalid or no certificate authority found, using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
You could use TRY .. CATCH to catch CurlException, or FacebookApiException there.
Or use set_exception_handler to catch any uncaught exception.
As strauberry said, you can stop throwing the exception. If the exception needs to be throw there, you can put the code that call this inside a try-catch and deal with the exception as you want.
Another option is to use the function set_exception_handler. This function will be called when an exception is thrown but nothing catch it.
You throw the Exception $e in the last line which causes the dumping. Instead you could do something like
echo "ERROR: " . $e->getMessage();