Extracting json string with PHP - php

JSON string that i received from the API
{"accessTokenResponse":{"token":"562371e99fda4296a380547cb5bf9fab","token_type":"Bearer","expires_in_seconds":"77476","client_id":"LTcyMDI1NDI0OQ==","responseStatus":{"code":"100000","message":"Service operation completed successfully","messageDetails":"Access token assigned."}}}
Information that i wanted to extract
562371e99fda4296a380547cb5bf9fab //-->The Token
My attempt
<?php
$user = "LTcyMDI1NDI0OQ==";
$password = "MjAzMDI5MTU";
$returnFormat = "json";
$url = "https://sandbox.dhlecommerce.asia/rest/v1/OAuth/AccessToken?clientId=".$user.
"&password=".$password."&returnFormat=".$returnFormat."";
$method = "GET";
$headers = array(
"content-type: application/json",
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
));
$response = curl_exec($curl);
$err = curl_error($curl);
$result = json_decode($response);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $result->token;
}
?>
The output:
Warning: Undefined property: stdClass::$token in C:\xampp\htdocs\Tracking\getToken.php on line 31
Did the JSON string that i received is in bad format?
Why does it says undefined property? Appreciate any helps. thanks!
Post that i've refer to:
How do I extract data from JSON with PHP?

token is in the accessTokenResponse object, so :
echo $result->accessTokenResponse->token;

Related

OpenAI API error: "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth"

I am creating a PHP script to access Open Ai's API, to ask a query and get a response.
I am getting the following error:
You didn't provide an API key. You need to provide your API key in an
Authorization header using Bearer auth (i.e. Authorization: Bearer
YOUR_KEY)
...but I thought I was providing the API key in the first variable?
Here is my code:
$api_key = "sk-U3B.........7MiL";
$query = "How are you?";
$url = "https://api.openai.com/v1/engines/davinci/jobs";
// Set up the API request headers
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer " . $api_key
);
// Set up the API request body
$data = array(
"prompt" => $query,
"max_tokens" => 100,
"temperature" => 0.5
);
// Use WordPress's built-in HTTP API to send the API request
$response = wp_remote_post( $url, array(
'headers' => $headers,
'body' => json_encode( $data )
) );
// Check if the API request was successful
if ( is_wp_error( $response ) ) {
// If the API request failed, display an error message
echo "Error communicating with OpenAI API: " . $response->get_error_message();
} else {
// If the API request was successful, extract the response text
$response_body = json_decode( $response['body'] );
//$response_text = $response_body->choices[0]->text;
var_dump($response_body);
// Display the response text on the web page
echo $response_body;
All Engines endpoints are deprecated.
This is the correct Completions endpoint:
https://api.openai.com/v1/completions
Working example
If you run php test.php in CMD, the OpenAI API will return the following completion:
string(23) "
This is indeed a test"
test.php
<?php
$ch = curl_init();
$url = 'https://api.openai.com/v1/completions';
$api_key = '<OPENAI_API_KEY>';
$post_fields = '{
"model": "text-davinci-003",
"prompt": "Say this is a test",
"max_tokens": 7,
"temperature": 0
}';
$header = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result);
var_dump($response->choices[0]->text);
?>

Cannot get the correct user information from the Slack API

We're creating a Slack-app, and have gotten most of the things up and running. However, we can't seem to get information about the user. Here is our code so far:
The following code triggers our function. We are sure that the user ID is the correct one, and have tried with several:
$uid = getUser("U1234567890");
print_r($uid);
This is our function:
/* Get User Profile */
public function getUser($userId) {
$method = "GET";
$endpoint = "https://slack.com/api/users.info";
$token = ###;
$data = array(
"user" => $userId
);
$data = http_build_query($data);
$response = $this->call_slack_api($token, $method, $endpoint, $data);
return $response;
}
Finally our function to call the API:
/* Call the Slack API */
private function call_slack_api($token, $method, $endpoint, $data = "") {
$curl = curl_init();
$headers = array(
"Accept: application/x-www-form-urlencoded",
"Content-type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
);
$options = array(
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_URL => $endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
if (isset($data)) {
$options[CURLOPT_POSTFIELDS] = $data;
}
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
$this->response_code = $info['http_code'];
curl_close($curl);
return $response;
}
This results in the following error message:
{"ok":false,"error":"user_not_found"}
We feel like we've tried everything, and Googled a lot. Anyone who can help us out?
Thank you!

JSON response TypeError - 'The "data" argument must be of type string'

The API I'm trying to fetch an access token gives me the following instructions (you can check for yourself at https://developers.finove.com.br/authentication):
Use your 'ClientId' and 'ClientSecret' to fetch an access token and the API authentication follows standard Oauth 2.0 protocols.
The API only accepts requests in JSON, so all requests must include the header 'Content-Type: application/json'.
The Parameters goes on thebody:
clientId and clientSecret as a string
The Response 200 will contain the acess Token as followed:
{
accessToken: "eyJhbGciOiJSUz..."
}
Right, so I using the following function to POST a JSON request to the API, get the response and fetch the 'acessToken' value.
<?php
// ignore the $order because its not used in the function, just passed
private function finove_auth($order){
$authurl = 'https://api.finove.com.br/api/auth/authenticate';
$client_id = $this->apiId;
$client_secret = $this->apiSecret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $authurl);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'clientId' => $client_id,
'clientSecret' => $client_secret,
));
$data = curl_exec($ch);
if ( curl_errno( $ch ) ){
// for printing on console and allowing me to check whats happening
echo 'Error: ' . curl_error( $ch );
return $this->finove_payment_processing( $order );
}
else {
curl_close($ch);
$auth_string = json_decode($data, true);
print_r($auth_string); // to check the response on the console
$this->finove_payment_processing( $order );
}
}
But something not working. On the console its returning me two things. Firts its
Fixed malformed JSON. Original:
and second is:
array(7) {
["name"]=>
string(9) "TypeError"
["message"]=>
string(112) "The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined"
["errors"]=>
array(0) {
}
["table"]=>
string(0) ""
["constraint"]=>
string(0) ""
["paramName"]=>
string(0) ""
["stack"]=>
string(585) "TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
at Hmac.update (internal/crypto/hash.js:84:11)
at ApiKeyService.verify (/usr/src/app/dist/api/services/ApiKeyService.js:15:18)
at AuthController.<anonymous> (/usr/src/app/dist/api/controllers/AuthController.js:17:48)
at Generator.next (<anonymous>)
at fulfilled (/usr/src/app/node_modules/tslib/tslib.js:114:62)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:95:5)"
}
Can't figure it out what I'm doing wrong but it seens that the clientId and ClientSecret are not beeing send as they should.
The following code works:
<?php
private function finove_auth(){
// Get the id and secret values
$clientId = $this->finoveID;
$clientSecret = $this->finoveSecret;
$url = "https://api.finove.com.br/api/auth/authenticate";
// encode to json
$data = array("clientId" => "$clientId", "clientSecret" => "$clientSecret");
$data_string = json_encode($data);
// begin the request
$curl = curl_init();
curl_setopt_array($curl, [ // request properties
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
],
]);
$response = curl_exec($curl); // execute the request
$err = curl_error($curl); // get error if occur
curl_close($curl); // close the request
if ($err) {
print_r("cURL Error #:" . $err); // print error to log
} else {
print_r($response); // print value to log
}
}
It seens that the problem was that I was not putting the infos inside a array and using Json_decode() properly. Using the Insomnia app: https://insomnia.rest to check the JSON response from the API really helped aswell.

Retrieve Json Data Using CURL PHP

Using CURL here we retrieve data and print then save to file after that insert it into database.
$curl = curl_init();
$options=array(
CURLOPT_URL=>"http://api.abc.com/v1/products/search.json?q=ball",
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_ENCODING =>"",
CURLOPT_FOLLOWLOCATION =>true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT=>30,
CURLOPT_HTTP_VERSION=>CURL_HTTP_VERSION_1_0,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS=>"",
CURLOPT_HTTPHEADER=> array(
"authorization: AsiMemberAuth client_id=50041351&client_secret=55700485cc39f1",
"cache-control: no-cache"
),
CURLOPT_HEADER=> true
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err){
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The Result json is fine. now i want to save it in json file?
to save a string to a file in php, you can use file_put_contents()
file_put_contents doc
file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int
You can update your code as follows:
if ($err){
echo "cURL Error #:" . $err;
} else {
echo $response;
//Write response to file
file_put_contents("my_file.json", $response)
}

Type of 'json' response is boolean in PHP

I am using the following:
<?php
$url = '...';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => "GET"
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = json_decode($response, true);
echo gettype($response); /$response/ THIS RETURNS INTEGER FOR SOME REASON!
?>
So the $response I am getting is of type integer, and I am unable to read the elements of this JSON.
Also note that when I echo the response, 1 is printed after it.
Check the manual for the possible return values. You need to at least use CURLOPT_RETURNTRANSFER.
Returns TRUE on success or FALSE on failure. However, if the
CURLOPT_RETURNTRANSFER option is set, it will return the result on
success, FALSE on failure.
<?php
$url = '...';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true // <<<< add this
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
var_dump(json_last_error_msg());
}
'$result' is not defined in your code, double check it?
Perhaps the line "$response = json_decode($response, true);" needs to be changed.
A default value for undefined variable is NULL/False

Categories