I get an authentication error with a json post - php

I am trying to authenticate, the result of my request is returned incorrectly.
Request Model
Method: Post, Endpoint: /api/authenticate, Header Variables:
[{"key":"Content-Type","value":"application/json","enabled":true}],
Body Parameters: username: string, password: string,
authenticationType: string
Sample Request
POST /api/authenticate
Host: mpop-sit.hepsiburada.com
Content-Type: application/json
{
"username": "xyz_dev",
"password": "XYZ_dev123!",
"authenticationType": "INTEGRATOR"
}
Request i sent
$url = 'https://mpop-sit.hepsiburada.com//api/authenticate';
$ch = curl_init($url);
$header = array(
'Content-Type: application/json',
'Authorization: Bearer '. base64_encode('xyz_dev:XYZ_dev123!:INTEGRATOR'),
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
$return=json_decode($result,true);
print_r($return);
This is the result of the query returned and the error I received.
Where do you think I might be making a mistake?
Array ( [timestamp] => 2020-02-07T09:01:47.426+0000 [status] => 500
[error] => Internal Server Error [exception] =>
io.jsonwebtoken.MalformedJwtException [message] => JWT strings must
contain exactly 2 period characters. Found: 0 [path] =>
//api/authenticate )

Do you need the authentication header for this endpoint?
Because what the sample request wants you to send the parameters in the request body like this:
$post = [
'username' => 'xyz_dev',
'password' => 'XYZ_dev123!',
'authenticationType' => 'INTEGRATOR'
];
$url = 'https://mpop-sit.hepsiburada.com//api/authenticate';
$ch = curl_init($url);
$header = array('Content-Type: application/json');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
$return=json_decode($result,true);
print_r($return);
So no need fot the Authentication: Bearer ... header, it would also be created differently.

This should work fine! I get access denied error, so, that means codes works fine.
Note you might need to change http_build_query($fields) to $fields
$url = "https://mpop-sit.hepsiburada.com/api/authenticate/";
$token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$fields = array(
"username" => "xyz_dev",
"password" => "XYZ_dev123!"
);
$header = array(
'Content-Type: application/json',
'Authorization' => 'Bearer ' . $token,
);
//open curl connection
$ch = curl_init();
//set the url, fields, vars
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); // SSL false if not required
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); //False if not required
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute fields
$result = curl_exec($ch);
//return result echo $result; if you need
echo curl_error($ch);
//close curl connection
curl_close($ch);
Please let me know if it works!
UPDATE : if you want to use ssl which is saving you from hacks.
Follow steps in this answer to activate ssl : https://stackoverflow.com/a/59919558/12232340

2 slashes here, so it does not work:
$url = 'https://mpop-sit.hepsiburada.com//api/authenticate';

Related

Openfigi php request -> Request body must be a JSON array

I am trying to use the openfigi api with php. I keep getting this error message: "Request body must be a JSON array.". Any ideas on how to solve this? I have tried several solutions.
$curlUrl = 'https://api.openfigi.com/v2/mapping';
$data = array('idType' => 'ID_WERTPAPIER', 'idValue' => '851399', 'exchCode' => 'US');
$j = json_encode($data);
//$apiToken = 'X-OPENFIGI-APIKEY: xxx';
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Content-Type: application/json';
//$httpHeadersArray[] = $apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $j);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeadersArray);
$res = curl_exec($ch);
echo "<pre>";
print_r($res);
echo "</pre>";
had the same problem, but solved it.
This is my working code:
// The url you wish to send the POST request to
$url = 'https://api.openfigi.com/v2/mapping/';
// Create a new cURL resource
$ch = curl_init($url);
// The data to send to the API
$postData = array(
array(
"idType" => "ID_ISIN",
"idValue" => "US4592001014"
)
);
// Setup cURL
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => json_encode($postData)
));
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
print_r(json_encode($postData));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
print_r($responseData);

How can i get the length of a curl Post body

I am trying to log in to a remote website which requires me to post username password and login via post. I am using the Curl Option
curl_setopt($ch, CURLOPT_POSTFIELDS , $postData);
and assign my info like this
$postData['email'] = 'smart#acme.com';
$postData['password'] = 'Secret';
$postData['Submit']='Login';
But the remote server complains about
HTTP Error 411. The request must be chunked or have a content length.
So how can i tell the content length of my postData ?
To get the length of PostData, you can use PHP's function count to get it.
Try:
#Get the length
$postData_len = count($postData);
#Set Curl Header with Content Length
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: '.$postData_len));
The above code with calculate the length of the postData array and then set the Curl header, if you're looking for 1 line of code, try this:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: '.count($postData)));
Not sure this will work for you or not? but you need something like this with strlen() to set Content-Length.
$postData= array("email" => "smart#acme.com", "password" => "Secret","Submit"=>"Login");
$data_string = json_encode($postData);
$ch = curl_init('http://api.remote.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$ch = curl_init();
$data['email'] = 'smart#acme.com';
$data['password'] = 'Secret';
$data['Submit']='Login';
curl_setopt($ch, CURLOPT_URL, '****/upload.php');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
the header of the request is
[CONTENT_LENGTH] => 357
[CONTENT_TYPE] => multipart/form-data; boundary=------------------------aac448045c2fe517
however if we pass the args through string like this
$ch = curl_init();
$data['email'] = 'smart#acme.com';
$data['password'] = 'Secret';
$data['Submit']='Login';
echo strlen(http_build_query($data));
curl_setopt($ch, CURLOPT_URL, '*/upload.php');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_exec($ch);
and the header of this request is
[CONTENT_LENGTH] => 51
[CONTENT_TYPE] => application/x-www-form-urlencoded
so it is better to use application/x-www-form-urlencoded than multipart/form-data for it is easy to calculate content-length

Curl request works in Rested chrome extension but not in php

everyone, i am requesting data from some other website but I am unable to request through curl it shows error 500 but when I do the same request through chrome RESTED extension it shows me output
$url = "XXXXXXXXXXX";
// what post fields?
$fields = array(
'roll_number' => '123456',
'full_name' => 'aaaaaa',
'mother_name' => 'bbbbbbb',
'_token' => 'xxxxxxxxxxxxxxxx'
);
// build the urlencoded data
$postvars = http_build_query($fields);
// open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Request should be by post method and data should be JSON encoded or URL encoded I have tried both but none of them worked
Not sure if this is the cause, but shouldn't your HTTPHEADER be application/json? Also, you're not encoding the data as JSON - you might need to change $postvars = http_build_query($fields); to $postvars = json_encode($fields);
I'd also take a look at https://lornajane.net/posts/2011/posting-json-data-with-php-curl

Calling Watson API from PHP code

I am trying to call Natural Language Understanding Watson API from my PHP code using curl. I have successfully tried curl from terminal. It gives some result on executing this command:
curl -u "my_username":"my_password" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream.&features=sentiment,keywords"
However when I try to use curl in php using this code:
<?php
$url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&text=I%20still%20have%20a%20dream%2C%20a%20dream%20deeply%20rooted%20in%20the%20American%20dream%20%E2%80%93%20one%20day%20this%20nation%20will%20rise%20up%20and%20live%20up%20to%20its%20creed%2C%20%22We%20hold%20these%20truths%20to%20be%20self%20evident%3A%20that%20all%20men%20are%20created%20equal.&features=sentiment,keywords";
$post_args = array(
'version' => '2017-02-27',
'url' => 'https://davidwalsh.name/curl-post',
'features' => 'sentiment,keywords'
);
$headers = array(
'Content-Type:application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "my_username:my_password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_args));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;
?>
I get this result:
{
"error": "unsupported media type",
"code": 415
}
What should be done?
I can't believe I was stuck here due to a blank space.
Replacing this:
$headers = array(
'Content-Type:application/json'
);
with
$headers = array(
'Content-Type: application/json'
);
worked. Note the blank space between : and application/json.

PHP CURL Using POST Raw JSON Data

I am working with PHP curl for post, for some reason I couldn't post the form successfully.
$ch = curl_init();
$headers = [
'x-api-key: XXXXXX',
'Content-Type: text/plain'
];
$postData = array (
'data1: value1',
'data2: value2'
);
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
When I try using the same in post it works, but not with PHP.
var_dump($server_output) ==> string(67) ""require data1 and data2 or check the post parameters""
var_dump(curl_error($ch)) ==> string(0) ""
If you wanna use Content-type: application/json and raw data, seem your data should be in json format
$ch = curl_init();
$headers = [
'x-api-key: XXXXXX',
'Content-Type: application/json'
];
$postData = [
'data1' => 'value1',
'data2' => 'value2'
];
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
If you want an arranged and explained format, see the code below.
// Set The API URL
$url = 'http://www.example.com/api';
// Create a new cURL resource
$ch = curl_init($url);
// Setup request to send json via POST`
$payload = json_encode(array(
'data1' => 'value1',
'data2' => 'value2'
)
);
// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-api-key: XXXXXX', 'Content-Type: application/json'));
// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the POST request
$result = curl_exec($ch);
// Get the POST request header status
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// If header status is not Created or not OK, return error message
if ( $status !== 201 || $status !== 200 ) {
die("Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
}
// Close cURL resource
curl_close($ch);
// if you need to process the response from the API further
$response = json_decode($result, true);
I hope this helps someone

Categories