How to handle error when PHP request to API fails - php

I have the following request to an API:
$url = "{{correctURLishere}}";
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
The This should bring back the value from they key "title" in this json response. But instead, the error I get is
file_get_contents(url): failed to open stream: HTTP request failed!
HTTP/1.1 402
I know the error is because I am only allowed 150 requests a day and have exceeded this amount but can someone help me to echo "No more requests allowed" instead of the error?
I have tried the following but it wont work:
if(json_decode(file_get_contents($url), true)) {
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
Could anyone tell me how to help with the error? Thanks

try to use try catch section, for example
try{
if(json_decode(file_get_contents($url), true)) {
$response = json_decode(file_get_contents($url), true);
$name = $response["title"];
}
}catch(Exception $e){
print_r($e);
echo '<br>';
echo $e->getMessage();
}
for your referrence: https://www.php.net/manual/en/language.exceptions.php

Related

get facebook page contents from access token

I am trying to get facebook page contents using graph api in codeigniter. when I use access token in controller with a get function, I get the contents. But when I try to use graph url in view file, It's showing an error -- " Invalid OAuth access token"
In my controller, I tried this--
$response2 = $this->get('/me?fields=id,name,posts{actions,comments,message}',$accessToken);
echo "<pre>";
print_r($response2);
the get function is--
public function get($params, $accessToken){
try {
$response = $this->fb->get($params, $accessToken);
return json_decode($response->getBody());
} catch(Facebook\Exceptions\FacebookResponseException $e) {
return $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
return $e->getMessage();
}
}
Here I got the result .
but If I try to use it another view file--
<?php
foreach ($h->result() as $row) {
if ($row->social_network == 'facebook') {
$token = $row->token;
$id = $row->pid;
print_r($id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v15.0/$id?fields=posts%7Bmessage%2Ccomments%2Cactions%7D&access_token=$token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
$result = json_decode($result);
print_r($result);
}
}
?>
Here I am getting the access token from database that I previously stored. Here It shows me an error--
Invalid OAuth access token - Cannot parse access token
How do I make It work?

PHP Notice: Trying to get property 'id' of non-object. How to resolve?

I am using cURL and PHP to make a request to a test API to return a list of users but I get the following error:
PHP Notice: Trying to get property 'id' of non-object
Not sure where I am going wrong.
Here is my code
<?php
// I am using the JSONPlaceholder website as a test API
$url = 'https://jsonplaceholder.typicode.com/users';
// Initial a new cURL session
$request = curl_init($url);
// Return request as string
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
// Run cURL / execute http request
$response = curl_exec($request);
// Close the cURL resource
curl_close($request);
if ($response === false) {
print "Could not make successful request\n";
} else {
$response = json_decode($response);
print $response->id . "\n";
print $response->name . "\n";
print $response->username . "\n";
}
?>
you have to loop through the response:
if ($response === false) {
print "Could not make successful request\n";
} else {
$response = json_decode($response);
foreach ($response as $item) {
print $item->id . "\n";
print $item->name . "\n";
print $item->username . "\n";
}
}

file_get_contents failed to open stream: Connection timed out

I am currently having issues with my going into an infinite loading state and hitting a 505 Gateway when using file_get_contents for reading the response of an API and parsing the JSON.
Here is the code:
<?php
try {
while(true) {
$url = 'http://floodcrm.net/api.php?key=MY_API_KEY_GOES_HERE&method=get_invite';
$jsonData = file_get_contents($url);
$json = json_decode($jsonData,true);
echo $json['code'];
if(#file_get_contents($url))
{
break;
}
sleep(2);
}
}catch (Exception $e) {
echo $e->getMessage();
}
?>
It can work fine, but after a while the site will just die again.
Really hope I can have some help with this.

PHP Accessing a local API for JSON data

Trying to access data from a local API that outputs in JSON data, but I just keep getting:
file_get_contents(/var/www/html/api/api.php?action=stats&user=testplayer): failed to open stream: No such file or directory
Code:
<?php
error_reporting(-1);
ini_set("display_errors", 1);
include 'functions.php';
if(isset($_GET['action']))
{
header('Content-Type: application/json');
try
{
switch($_GET['action'])
{
case 'stats':
if(!isset($_GET['user']))
throw new Exception('Insufficient information : Username');
$user = $_GET['user'];
$url = htmlspecialchars_decode("/var/www/html/api/api.php?action=stats&user=$user");
$response = file_get_contents("$url");
$data = json_decode($response);
echo $data;
break;
}
}
catch(Exception $e)
{
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(array('result' => 'error', 'cause' => $e->getMessage()));
}
}
?>
Is it not possible to pass ? and &s through file_get_contents?
You can't process the php code if you are reading the file contents.
update the $url like this:
$url = htmlspecialchars_decode($_SERVER["SERVER_NAME"] . "/api/api.php?action=stats&user=$user") ;
This will make the request to your apache server instead of reading the file contents.

Retrieve Error Message with array

I have using a version of GoCardless's API in PHP to process payments on my website. However when their API returns an error I would like to display the user more effective errors.
I have got half way there but I was wondering if there is anyway I could do the following:
If I have the following error:
Array ( [error] => Array ( [0] => The resource has already been confirmed ) )
Is there anyway to extract just the The resource has already been confirmed part with PHP?
My Code:
try{
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
}catch(GoCardless_ApiException $e){
$err = 1;
print '<h2>Payment Error</h2>
<p>Server Returned : <code>' . $e->getMessage() . '</code></p>';
}
Thanks.
UPDATE 1:
Code that triggers the exception:
$http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_response_code < 200 || $http_response_code > 300) {
// Create a string
$message = print_r(json_decode($result, true), true);
// Throw an exception with the error message
throw new GoCardless_ApiException($message, $http_response_code);
}
UPDATE 2 :-> print_r($e->getMessage()) Output:
Array ( [error] => Array ( [0] => The resource has already been confirmed ) )
The method $e->getMessage() appears to return an array with an index 'error' wich is an array again that contains the message text. If you ask me this is bad API design
However you can access the message text like this:
try{
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
}catch(GoCardless_ApiException $e){
$err = 1;
$message = $e->getMessage();
$error = $message['error'];
print '<h2>Payment Error</h2>
<p>Server Returned : <code><' . $error[0] . "</code></p>";
}
If you look into the GoCardless_ApiException class code you'll see that there's a getResponse() method that you could use to access the error element of the response array...
$try{
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
}catch(GoCardless_ApiException $e){
$err = 1;
$response = $e->getResponse();
print '<h2>Payment Error</h2>
<p>Server Returned : <code>' . $response['error'][0] . "</code></p>";
}
I discovered the problem, the output from $e->getMessage() was a plain string, NOT an array.
So I edited the Request.php file to the following:
$http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_response_code < 200 || $http_response_code > 300) {
// Create a string <<-- THE PROBLEM -->>
// $message = print_r(json_decode($result, true), true);
$message_test = json_decode($result, true);
// Throw an exception with the error message
// OLD - throw new GoCardless_ApiException($message, $http_response_code);
throw new GoCardless_ApiException($message_test[error][0], $http_response_code);
}
and then my php file :
try{
$confirmed_resource = GoCardless::confirm_resource($confirm_params);
}catch(GoCardless_ApiException $e){
$err = 1;
$message = $e->getMessage();
print '<h2>Payment Error</h2>
<p>Server Returned : <code>' . $message . "</code></p>";
}
and the page outputs:
Payment Error
Server Returned : The resource has already been confirmed

Categories