I can't catch Facebookexceptions in try catch block - php

I'm having an issue catching the proper exception, no matter what i do i get the same response. This is the response i get in the view
Error validating access token: The user has not authorized application FacebookResponseException in FacebookResponseException.php line 89:
The issue arrises after a user de-authorizes my app from Facebook after have created an access_token , what I ant to do is catch the exception and automatically log them out and flush the session: But i can't seem to find the right exception to catch
I've tested with all these: I narrowed the problem to being inside this catch block: I included the catch block, then the full code I'm using in my route's function after.
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=permissions');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthenticationException $e) {
echo 'Facebook Dan1 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthorizationException $e) {
echo 'Facebook Dan2 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookClientException $e) {
echo 'Facebook Dan3 returned an error: ' . $e->getMessage();
exit;
} catch(Exception $e) {
echo 'Facebook Dan4 returned an error: ' . $e->getMessage();
exit;
}
now my full code for this page:
public function getHomeProfile(Request $request, LaravelFacebookSdk $fb)
{
$user = Auth::user();
$token = Session::get('fb_user_access_token');
$twitterToken = Session::get('access_token');
// $fb->setDefaultAccessToken($token);
// $resp = $fb->get('/debug_token?=input_token=$token');
// dd($resp);
$permissionsToRequest = ([
'public_profile',
'publish_actions'
]);
$login_link_for_public_actions = $fb->getLoginUrl($permissionsToRequest, 'http://pms.dev:8000/facebook/publicactions/callback');
if (isset($token)) {
$fb->setDefaultAccessToken($token);
// $debugToken = $fb->get('/debug_token?input_token=' . $token);
// $debugTokenResponse = $debugToken->getGraphNode()->asArray();
// echo "<pre>";
// print_r($debugTokenResponse);
// echo "<pre>";
// die();
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=permissions');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthenticationException $e) {
echo 'Facebook Dan1 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthorizationException $e) {
echo 'Facebook Dan2 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookClientException $e) {
echo 'Facebook Dan3 returned an error: ' . $e->getMessage();
exit;
} catch(Exception $e) {
echo 'Facebook Dan4 returned an error: ' . $e->getMessage();
exit;
}
// Returns a `Facebook\GraphNodes\GraphUser` collection
$facebookuser = $response->getGraphUser();
//$ty= json_decode($facebookuser);
$permissions = $facebookuser['permissions'];
$checked = '';
foreach ($permissions as $p) {
if ($p['permission'] == 'publish_actions' && $p['status'] == 'granted' ) {
$checked = 'checked';
}
}
} else {
$checked = null;
}
if (isset($twitterToken)) {
$twitterChecked = 'checked';
} else {
$twitterChecked = null;
}
$userPlugsCountry = $user->plugsCountry()->setPath($request->url());
$user_plugs_list = Auth::user()->plugs()->lists('id');
if (Auth::check()) {
$statuses = Status::where(function($query) {
return $query->where('user_id', Auth::user()->id)->where('parent_id', NULL)
->orWhereIn('user_id', Auth::user()->plugs()->lists('id'));
})->orderBy('created_at', 'desc')->paginate(7);
}
if (array_key_exists('REQUEST_SCHEME', $_SERVER)) {
$cors_location = $_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"] .
dirname($_SERVER["SCRIPT_NAME"]) . "/cloudinary_cors.html";
} else {
$cors_location = "http://" . $_SERVER["HTTP_HOST"] . "/cloudinary_cors.html";
}
if ($request->ajax()) {
return [
'statuses' => view('ajax.status')->with('user', $user)->with(compact('statuses'))->render(),
'next_page' => $statuses->nextPageUrl(),
'countries' => view('ajax.next_countries')->with('user', $user)->with(compact('userPlugsCountry'))->render(),
'next_countries_page' => $userPlugsCountry->nextPageUrl(),
'prev_countries_page' => $userPlugsCountry->previousPageUrl(),
];
}
return view('profile.home')->with('user', $user)->with('cors_location', $cors_location)->with('statuses',$statuses)->with('userPlugsCountry',$userPlugsCountry)->with('checked', $checked)->with('login_link_for_public_actions',$login_link_for_public_actions)->with('twitterChecked', $twitterChecked);
}

OK i figured out whet i was doing wrong. I'm using sammyk laravelfacebooksdk https://github.com/SammyK/LaravelFacebookSdk and was only including:
use SammyK\LaravelFacebookSdk\LaravelFacebookSdk;
I didn't realize i also needed to add
use Facebook;
to the namespace.
easy fix, that gave me a lot of trouble.

Related

Do I need to create a variable/object to return when catching an exception?

I have this way of handling exceptions for some time now, but lately has been bothering me.
protected function sendPostmarkBatch($envios_preparados)
{
try {
$client = new PostmarkClient($this->postmarkToken());
$sendResult = $client->sendEmailBatchWithTemplate($envios_preparados);
} catch (PostmarkException $e) {
log_message('error', 'HTTP: ' . $e->httpStatusCode . ' MESSAGE: ' . $e->message . ' ERROR CODE: ' . $e->postmarkApiErrorCode);
$sendResult = new stdClass();
$sendResult->ErrorCode = $e->postmarkApiErrorCode;
} catch (Exception $generalException) {
log_message('error', 'GENERAL EXCEPTION: ' . $generalException);
$sendResult = new stdClass();
$sendResult->ErrorCode = '1';
}
return $sendResult;
}
Is it really necessary to create the object or variable $sendResult at 'catch' to return it or it's already created even if 'try' fails? Is there a better way of doing it?
Thanks!
It's necessary.
I'm not sure if it's suits your logic, but you can do something like this:
protected function sendPostmarkBatch($envios_preparados)
{
$sendResult = new stdClass();
try {
$client = new PostmarkClient($this->postmarkToken());
$sendResult = $client->sendEmailBatchWithTemplate($envios_preparados);
} catch (PostmarkException $e) {
log_message('error', 'HTTP: ' . $e->httpStatusCode . ' MESSAGE: ' . $e->message . ' ERROR CODE: ' . $e->postmarkApiErrorCode);
$sendResult->ErrorCode = $e->postmarkApiErrorCode;
} catch (Exception $generalException) {
log_message('error', 'GENERAL EXCEPTION: ' . $generalException);
$sendResult->ErrorCode = '1';
}
return $sendResult;
}
If $client->sendEmailBatchWithTemplate($envios_preparados) fails, your $sendResult variable won't be overwrited.

Handle Try catch block in laravel

I have to try-catch block for stripe payment to handle error responses, Now I am using laravel to code.
But after catching it gives me 500 internal server error, instead of storing an exception message, it catches the error with 500 Internal Server?
Here is my code:
try {
$customer = \Stripe\Customer::create([
'email' => $email,
'source' => $token,
]);
$customer_id = $customer->id;
$subscription = \Stripe\Subscription::create([
'customer' => $customer_id,
'items' => [['plan' => 'plan_id']], //plan-id is static as there is single plan
]);
$chargeJson = $subscription->jsonSerialize();
}
catch(Stripe_CardError $e) {
$error = $e->getMessage();
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
$error = $e->getMessage();
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
$error = $e->getMessage();
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
$error = $e->getMessage();
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error = $e->getMessage();
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error = $e->getMessage();
}
$resp = array();
if(isset($chargeJson) && !empty($chargeJson['id'])) {
$resp['status'] = 1;
$resp['transactions_log'] = $chargeJson;
$resp['current_period_end'] = $chargeJson['current_period_end'];
$resp['transaction_id'] = $chargeJson['id']; // which is actually subcsription id
} else {
$resp['status'] = 0;
$resp['error'] = $error;
}
return $resp;
I am not sure how to handle it and store it.
I am pretty much sure I have catched the exception but I can't store it and further use it.

Facebook SDK getGraphNode(); as array not working

So i started learning facebook sdk and i wanted to get attening_count/list from my event page as an array, but i'm unable to get it working. It only displays me id, name etc.
if (isset($_SESSION['access_tok'])) {
echo 'Out!<br>';
try {
$response = $fb->get('me/accounts?fields=', $_SESSION['access_tok']);
$page = $response->getGraphEdge();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
foreach($page as $pages)
{
$name = $pages['name'];
$cc = $pages['access_token'];
if($name == 'Testing')
{
try {
$response1 = $fb->get('/eventid', $cc);
$page1 = $response1->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$page1 ['id'];
}
else
{
}
}
}

No handler in dropbox sdk?

I'm trying to get an example from the dropbox sdk to work.
Here is some of the code that is in index.php in the root.
$req = $_SERVER['SCRIPT_NAME'];
if ($req === "/") {
//a bunch of code and elseif:s
}else{
echo renderHtmlPage("Bad URL", "No handler for $req");
exit;
}
I get the following output:
Bad URL
No handler for /index.php
How come req is set to index and how could it be set to / for example?
Full code
$dbxClient = getClient();
if ($dbxClient === false) {
header("Location: /dropbox-auth-start");
exit;
}
$path = "/";
if (isset($_GET['path'])) $path = $_GET['path'];
if (isset($_GET['dl'])) {
passFileToBrowser($dbxClient, $path);
}
else {
$entry = $dbxClient->getMetadataWithChildren($path);
if ($entry['is_dir']) {
echo renderFolder($entry);
}
else {
echo renderFile($entry);
}
}
}
else if ($req === "/dropbox-auth-start") {
$authorizeUrl = getWebAuth()->start();
header("Location: $authorizeUrl");
}
else if ($req === "/dropbox-auth-finish") {
try {
list($accessToken, $userId, $urlState) = getWebAuth()->finish($_GET);
assert($urlState === null);
unset($_SESSION['dropbox-auth-csrf-token']);
}
catch (dbx\WebAuthException_BadRequest $ex) {
error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
// Respond with an HTTP 400 and display error page...
exit;
}
catch (dbx\WebAuthException_BadState $ex) {
// Auth session expired. Restart the auth process.
header('Location: /dropbox-auth-start');
exit;
}
catch (dbx\WebAuthException_Csrf $ex) {
error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage());
// Respond with HTTP 403 and display error page...
exit;
}
catch (dbx\WebAuthException_NotApproved $ex) {
echo renderHtmlPage("Not Authorized?", "Why not, bro?");
exit;
}
catch (dbx\WebAuthException_Provider $ex) {
error_log("/dropbox-auth-finish: unknown error: " . $ex->getMessage());
exit;
}
catch (dbx\Exception $ex) {
error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage());
exit;
}
// NOTE: A real web app would store the access token in a database.
$_SESSION['access-token'] = $accessToken;
echo renderHtmlPage("Authorized!", "Auth complete, <a href='/'>click here</a> to browse");
}
else if ($req === "/unlink") {
// "Forget" the access token.
unset($_SESSION['access-token']);
header("Location: /");
}
else if ($req === "/upload") {
if (empty($_FILES['file']['name'])) {
echo renderHtmlPage("Error", "Please choose a file to upload");
exit;
}
if (!empty($_FILES['file']['error'])) {
echo renderHtmlPage("Error", "Error ".$_FILES['file']['error']." uploading file. See <a href='http://php.net/manual/en/features.file-upload.errors.php'>the docs</a> for details");
exit;
}
$dbxClient = getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$_FILES['file']['name'];
$fp = fopen($_FILES['file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
$str = print_r($result, TRUE);
echo renderHtmlPage("Uploading File", "Result: <pre>$str</pre>");
}

detect exception - if

If i have this:
function valid($valor) {
foreach($valor as $valor){
if (!empty($valor)) {
if (preg_match("/[^A-Za-z0-9-áàçéúâôóã ]|(\d+)/", $valor)) {
$error = "invalid";
throw new Exception($error);
}
}
}
}
and
if (isset($_POST['myform'])){
if ($val_->valid($form1['new'])) {
echo "ok";
}
else
echo "bad";
}
but i got: Fatal error: Uncaught exception 'Exception
What i want is basically something like that (pseudo code):
if (exception true) {
echo "problem";
}
else
echo "ok";
How can i do that ?
You have to handle the exception.
try {
...
//statements
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
EDIT:
try{
if ($val_->valid($form1['new'])) {
echo "ok";
}
}catch(Exception $e){
echo "bad";
}

Categories