How to handle the exception in OpenFire Restapi in php? - php

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';
}

Related

Mailchimp addListMember returns client error 400 bad request when already existing [duplicate]

This question already has answers here:
Guzzlehttp - How get the body of a response from Guzzle 6?
(3 answers)
Handle Guzzle exception and get HTTP body
(10 answers)
Closed 1 year ago.
I'm working on adding a basic Mailchimp subscribe form to a website using their MailchimpMarketing\ApiClient() composer resource. Adding a user seems to work fine, but when trying to add somebody who already exists, i'd expect just a nice json response so that I can catch that error and display it to the user, but instead I get the following GuzzleHttp\Exception\ClientException:
Client error: `POST https://us10.api.mailchimp.com/3.0/lists/xxxxxxxxxx/members` resulted in a `400 Bad Request` response:
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Member Exists","status" (truncated...)
The documentation doesnt really seem to explain much, I had to find the right way to catch that error from stack overflow too as Mailchimps documentation was.. lacking! Here is the code:
try {
$response = $mailchimp->lists->addListMember($this->settings_helper->get('mailchimp_list_id'), [
"email_address" => $form->get_field_value('email'),
"status" => "subscribed",
"merge_fields" => [
"FNAME" => $first_name,
"LNAME" => $last_name
]
]);
if ($response->getId()) {
$this->add_json_success($this->settings_helper->get('mailchimp_success_message'));
}
} catch (MailchimpMarketing\ApiException $e) {
$errors[] = $e->getMessage();
} catch (ClientErrorResponseException $e) {
$errors[] = $e->getMessage();
} catch (GuzzleHttp\Exception\ClientException $e) {
$errors[] = $e->getMessage();
}
Here is the mailchimp documentation I used: https://mailchimp.com/developer/api/marketing/list-members/add-member-to-list/
I could just catch the error code of 400 and output a custom error but i'm sure that I must be doing soemthing wrong to get such an unhelpful response from the Mailchimp API?
Many thanks, andy and all help is appreciated.
I had the same issue, so I ended up directing the error message to see what the whole error was by changing your last catch clause to the following:
catch (GuzzleHttp\Exception\ClientException $e) {
echo '<pre>' . var_export($e->getResponse()->getBody()->getContents()).'</pre>';
$errors[] = $e->getMessage();
}
This revealed the following crappy error, which was up to this point truncated:
{
"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title":"Invalid Resource",
"status":400,
"detail":"Isabell_Murazik#example.com looks fake or invalid, please enter a real email address.",
"instance":"fcc1d762-2475-40a6-bc7f-4ac7f3fb7902"
}
So, my issue was that #example.com looks fake or invalid...
Trying a different email, even a #test.com worked.
I cannot promise you this will be your issue as well, but checking the error details is definitely a good first step!
I also struggled with this.
To display the various key values use your own variation on this
catch (\GuzzleHttp\Exception\BadResponseException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
$decoded = json_decode($responseBodyAsString);
echo $decoded->title;
}

TwitterOAuth: Invalid oauth_verifier parameter

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.

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