php unable to decode json object - php

I have this json object that I want to get the access_token but its refusing i have no idea why . This is the response I want the access_token
{
"access_token": "Alhq74lVl5GAOVAZrprOGSS1Gj73",
"expires_in": "3599"
}
This is the code
function generateToke() {
// $url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
$credentials = base64_encode('qniogqzdbIskIQt9nxgxG1wSBkzgUqN0:XUjxWzQY3WTndqHh');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); //setting a custom header
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$result = json_decode($curl_response);
$token = $result->access_token;
echo $token;
}
getting the same error
the above code is still displaying to me the json but i want to get only the Alhq74lVl5GAOVAZrprOGSS1Gj73

You're not accessing the access_token property of the resulting object, you try to access a property that is named in the not defined variable $access_token;.
So just remove the $-sign and it shoudl work:
$token = $result->access_token;
Furthermore you're missing a curl option to return the content:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
Without this option set to true you're not retrieving the response from the curl_exec call.

Change:
$token = $result->$access_token;
To (without the $ on access_token):
$token = $result->access_token;
It's not working because PHP has a feature called variable variables which you've accidentally used. PHP is trying to get the property of whatever the value of $access_token is. E.g. if a variable called $access_token was set to helloworld, PHP would run $result->helloworld and replace $access_token with it's value.

Related

Why does my cURL fails? I'm trying to verify user identity on an API

Here are the codes:
<?php
class General{
#to verify user password with api
public static function verifyUser($user,$pswd){
#url
$url = 'https://api.hp.upm.edu.my/cron/request/verify.php';
# initiate cur
$ch = curl_init($url);
# create json data
$jsonData = array(
'jtoken' => "test123",
'id' => "$user",
'pass'=> "$pswd"
);
#Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
#Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
#Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
#Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#Execute the request
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
?>
The passed data are username and password, identified by $user and $pswd respectively
The problem is, the end result should return something.
But I found it empty, after checking.
So, what I learned so far are:
I checked the user and password, they are all intact
when I print $ch during "initiate cur", it prints something
when I printed $ch
However, when I printed $result after curl_exec, it is empty.
What do I do? Where is my mistake? Is it the problem of the api url or soemthing else? Please, I need your help
Edit:
Someone suggested that using json_decode will help with this. But, I have already implemented json_decode, after $result is returned.
$result = General::verifyUser($_POST['user'], $_POST['pass']);
$obj = json_decode($result, true);
Above is the method call that passes the username and password to the "General" class.
I have printed curl_error for $ch and it says:
"Could not resolve host: api.hp.upm.edu.my"

Got this from a API using curl

Trying to add some kind of value to each data point so I can send the response (numbers only) to an existing table . I've been searching online and no CURL API response seems to be this simple so I can find an answer. (sorry new to this, don't know the "lingo")
This is the response I've been able to echo on screen.
"{"price": 2049.27, "change_point": -5.76, "change_percentage": -0.28, "total_vol": "1.27M"}"
rest of php below
<html>
<?php
$url = 'https://realstonks.p.rapidapi.com/';
$collection_name = $_REQUEST["stock_name"];
$request_url = $url . '/' . $collection_name;
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'X-RapidAPI-Host: www.xyz.com',
'X-RapidAPI-Key: xxxxxxxxxxxxxxxxxxx',
'Content-Type: application/json']);
$response = curl_exec($curl);
curl_close($curl);
//Uncomment bellow to show data on screen
echo $response . PHP_EOL;
enter code here
//var_dump(json_decode($json));
//var_dump(json_decode($json, true));
// Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
?>
I'm not much into PHP but here to here. If I'm not mistaken it, I think you want to store $response in <td> element. This resource can help https://www.daniweb.com/programming/web-development/threads/428730/how-to-display-php-variable-in-html

How can I access the property of an object in PHP from the result of a separate PHP file?

I'll try to keep this short and to the point. I'm setting up an API which requires using POST to generate an 'authorization token', which I can then use in combination with GET to retrieve data. The results are in JSON format, of course. I have an auth.php file which works and gives the token, among other object properties. My question is how do I use the token in a separate GET.php file to retrieve the data I need?
Is there a way to access Object properties from the end result of my auth.php file?
Here is the code which isn't working in my GET.php file:
if (isset($_POST['TOKEN'])) {
$api_key = '11111111111111111111111111111';
$utoken = $_POST['TOKEN'];
$url = 'https://api.rmaster.com/api/daltonwholesale/catalogattributes?company='.$company.'&catseq='.$catseq.'&api_key='.$api_key;
$company = '99';
$catseq = '98838';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($ch);
if (!$result) {die("Connection Failure");}
curl_close($ch);
echo $result;
} else {
echo $_POST['TOKEN'];
}
?>```

curl how to format a curl request with an api key in php

hi am new to curl but need it for a particular project could you help me format this code to work i would like to get the results and print out the raw JSON on the page here is the code i am using
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "curl -u api key: https://api.companieshouse.gov.uk/search/companies");
$x = curl_exec($curl);
curl_close($curl);
print($x);
this is a link to the api page i am trying to use
https://developer.companieshouse.gov.uk/api/docs/search/companies/companysearch.html
this is the example they give on the page
curl -uYOUR_APIKEY_FOLLOWED_BY_A_COLON:
https://api.companieshouse.gov.uk/search/companies
these are the parameters for the call if possible i would like to set them as well
q (required)
items_per_page (optional)
start_index (optional)
I simplified your request.you can try this by using below code.
$params = array("q"=>"<Some Value>","items_per_page"=>"<Some Value>","start_index"=>"<Some Value>");
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERPWD, "api key:");
curl_setopt($curl, CURLOPT_URL, "https://api.companieshouse.gov.uk/search/companies?".http_build_query($params));
$x = curl_exec($curl);
curl_close($curl);
print($x);
Thanks for this opportunity to learn more of curl :-)
I tested the code below, it works. Of course you must be registered on the site and you must have got your API key. You will then provide it as username/password, but without username (this is written here on the site).
$searchvalue= 'Test';
$curl = curl_init("https://api.companieshouse.gov.uk/search/companies?q=$searchvalue");
curl_setopt($curl, CURLOPT_USERPWD, "your_api_key_provided_by_the_site");
// curl_setopt($curl, CURLOPT_HEADER, true); // when debugging : to show returning header
$rest = #curl_exec($curl);
print_r($rest);
if(curl_errno($curl))
{
echo 'Curl error : ' . curl_error($curl);
}
#curl_close($curl);

How to use GET on an external URL

I am using an API that returns JSON from a GET request
Eg.
https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}
Returns
{
"call_duration": 4,
"total_amount": "0.00400"
}
How can I call this page from within a script and save call_duation and total_amount as separate variables?
Something like the following?:
$call_duration =
$_GET[https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}, 'call_duration'];
$_GET[] contains the get parameters that are passed to your code - they don't generate a GET request.
You could use curl to make your request:
$ch = curl_init("https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$result = json_decode($output);
If PHP has allow_url_fopen enabled you can simply do
json_decode(file_get_contents('https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}'))
Otherwise you'll have to resort to using something like Curl to get the request going. $_GET is a superglobal array which doesn't actually do anything. It only contains what the script was started with. It does not make any requests itself.
Use curl to get the JSON, then json_decode to decode it into PHP variables
$auth_id = 'your auth id here';
$call_uuid = 'your call_uuid here';
// initialise curl, set URL and options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.domain.com/v1/Account/{$auth_id}/Call/{$call_uuid}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// get the response and decode it
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$call_duration = $response['call_duration'];
$total_amount = $response['total_amount'];

Categories