Not getting expected PHP cURL response - php

I have the following PHP code:
<?php
$data = array("client_id" => "sipgate-app-web", "grant_type" => "password", "username" => "my_username", "password" => "my_password");
$data_string = json_encode($data);
$ch = curl_init('https://api.sipgate.com/login/sipgate-apps/protocol/openid-connect/token');
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/x-www-form-urlencoded',
'Accept: application/json'
));
$result = curl_exec($ch);
echo $result;
?>
Unfortunately, I'm not getting the expected response. The response I'm receiving is:
{"error":"invalid_request","error_description":"Missing form
parameter: grant_type"}
When using an online cURL tool like https://onlinecurl.com with the same data (URL, header, data) as in my cURL PHP code, I'm getting the right response. This means, there's something wrong with my PHP code. I'm not getting any error in the PHP error log.
The manual says I have to use the following cURL code:
curl \
--request POST \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Accept: application/json' \
--data-urlencode "client_id=sipgate-app-web" \
--data-urlencode "grant_type=password" \
--data-urlencode "username=my_username" \
--data-urlencode "password=my_password" \
https://api.sipgate.com/login/sipgate-apps/protocol/openid-connect/token
Since I'm new to cURL, after googling a lot, I have no idea what I'm doing wrong.
Can anybody help me?
EDIT: You can test my PHP code above as it is. You should get the following response, if the code is working:
{"error":"invalid_grant","error_description":"Invalid user
credentials"}

As per the manual, your request needs to have the Content-Type of application/x-www-form-urlencoded which looks like this:
key1=value1&key2=value2
Thus you need to convert your array into such a string either manually or with http_build_query, like so:
$data_string = http_build_query( $data );

I am consuming one of the API using following PHP CURL, Give this a try and pass your credentials i.e username and password in "your username" and "your password".
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sipgate.com/login/sipgate-apps/protocol/openid-
connect/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>"{\r\n\client_id:\"sipgate-app-
web\",\r\n\tgrant_type\"password\",\r\n\tusername:\"your
username\",\r\n\tpassword:\"your password\"\r\n}",
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
} ?>

Related

Make API request with cURL PHP

I am trying to connect to an API, which should be done with cURL.
This is what the documentation is telling me to send (with my own data though, this is just and example).
curl --request POST \
--url https://api.reepay.com/v1/subscription \
--header 'Accept: application/json' \
-u 'priv_11111111111111111111111111111111:' \
--header 'Content-Type: application/json' \
--data '{"plan":"plan-AAAAA",
"handle": "subscription-101",
"create_customer": {
"handle": "customer-007",
"email": "joe#example.com"
},
"signup_method":"link"}'
What I have tried is this, but I get and error:
$postdata = array();
$postdata['plan'] = 'plan-AAAAA';
$postdata['handle'] = 'subscription-101';
$postdata['create_customer'] = ["handle" => "customer-007", "email" => "joe#example.com"];
$postdata['signup_method'] = 'link';
$cc = curl_init();
curl_setopt($cc,CURLOPT_POST,1);
curl_setopt($cc,CURLOPT_RETURNTRANSFER,1);
curl_setopt($cc,CURLOPT_URL, "https://api.reepay.com/v1/subscription");
curl_setopt($cc,CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($cc);
echo $result;
This is the error I get:
{"error":"Unsupported Media Type","path":"/v1/subscription","timestamp":"2022-10-22T11:42:11.733+00:00","http_status":415,"http_reason":"Unsupported Media Type"}
Can anyone help me make the correct request?
The example says, that application/json is accepted, but you are posting application/x-www-form-urlencoded. You'll need to json_encode the postdata and put it into the body + set the appropriate content-type.
To be nice, also set 'Content-Length'...
$json_data = json_encode($postdata);
curl_setopt($cc, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($cc, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: '.strlen($json_data)
]);
Based on the error you get, I guess you need to set the content-type header as JSON.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.reepay.com/v1/subscription',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"plan": "plan-AAAAA",
"handle": "subscription-101",
"create_customer": {
"handle": "customer-007",
"email": "joe#example.com"
},
"signup_method": "link"
}',
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
This should work:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.reepay.com/v1/subscription');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
]);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'priv_11111111111111111111111111111111:');
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"plan":"plan-AAAAA",\n "handle": "subscription-101",\n "create_customer": {\n "handle": "customer-007",\n "email": "joe#example.com"\n },\n "signup_method":"link"}');
$response = curl_exec($ch);
curl_close($ch);

How do I make an api call in PHP

I tested an API using postman. Using, postman, I managed to generate a token.
From postman, I managed to get all the data of a user using the following with the following details via a GET request:
https://example.example.co.za/api/consumers/get?id=567675675&email=example#sample.com
Under Authorization type, I selected "Bearer token" and pasted the Token in its respective field.
When I click send, I get a success response with the user data.
In PHP, how can I do the same api call (using the id,email and token) inside a php function?
I tried this:
curl_setopt_array($curl, array(
CURLOPT_URL => "example.example.co.za/api/consumers/get?email=example#sample.com&id=567675675",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Authorization: Bearer jhgukfytjfytdytfjgjyfytfjkugfyfdhtklhkugjf",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Type: application/x-www-form-urlencoded",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
return $response;
But when I view the page, instead of the user data, I see this:
How do I make the API call inside a function to get the same result that I have on postman in PHP?
You need to follow the location
CURLOPT_FOLLOWLOCATION => true
https://www.php.net/manual/de/function.curl-setopt.php
Please find a proper CURL call here.
$url = "https://example.example.co.za/api/consumers/get?id=567675675&email=example#sample.com";
$curl = curl_init();
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'APIKEY: 111111111111111111111',
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);

PHP cURL - authorization token missing

I am trying to cURL apptweak (ref - https://apptweak.io/api )
curl -H 'X-Apptweak-Key: your-api-key' https://api.apptweak.com/ios/applications/284882215.json
I have my key and can curl from the terminal. In PHP, I get "authorization token missing".
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.apptweak.com/ios/applications/284882215.json&country=US&language=en',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
X-Apptweak-Key => 'MY-KEY-IS-HERE'
)
));
$resp = curl_exec($curl);
print $resp;
curl_close($curl);
Is X-Apptweak-Key => 'MY-KEY-IS-HERE' being a POST field the issue here?
What is wrong?
you can add X-Apptweak-Key between single quotes it's a key
CURLOPT_POSTFIELDS => array(
'X-Apptweak-Key' => 'MY-KEY-IS-HERE'
)
or you can try this:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic MY-KEY-IS-HERE'));
or you can use:
curl_setopt($ch, CURLOPT_USERPWD, "X-Apptweak-Key:MY-KEY-IS-HERE");

PHP cURL JSON Object formatting issues

I'm running into an issue with formatting using the curl_setopt functions in PHP. I'm basically trying to re-create the cURL request below, but my code returns a bad request from the server. I'm pretty sure it has to do with poor formatting, but I can't figure out where I went wrong.
//This code returns the data back successfully
curl -H "Content-Type: application/json" -d '{"bio_ids": ["1234567"]}' http://localhost:9292/program
<?php //This code returns a bad request from the server
$bio = array('bio_ids'=>'1234567');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:9292/program',
CURLOPT_POST => 1, // -d
CURLOPT_POSTFIELDS => $bio,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
));
$resp = curl_exec($curl);
curl_close($curl);
?>
There are two issues:
You need to make sure that the structure of $bio matches what you are expected to pass, so the $bio declaration needs to be:
$bio = array('bio_ids' => array('1234567'));
Secondly you need to json_encode this data structure before sending it to the server:
CURLOPT_POSTFIELDS => json_encode($bio),
<?php //This code returns a bad request from the server
$bio = array('bio_ids'=>'1234567');
$bio = json_encode($bio);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:9292/program',
CURLOPT_POST => 1, // -d
CURLOPT_POSTFIELDS => $bio,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
));
$resp = curl_exec($curl);
curl_close($curl);
?>

Image upload in PHP error - type required

I'm trying for days to upload an image through PHP and OAuth2 to App.net.
Below is the PHP I'm using - it results in this error:
"error_message":"Bad Request: 'type': Required."
<?php
function sendPost()
{
$postData = array(
'type' => 'com.example.upload',
);
$ch = curl_init('https://alpha-api.app.net/stream/0/files');
$headers = array('Authorization: Bearer '.'0123456789',
'Content-Disposition: form-data; name="content"; filename="http://www.example.com/pics/test.jpg";type=image/jpeg',
'Content-Type: image/jpeg',
);
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postData
));
$response = curl_exec($ch);
}
sendPost();
?>
This is their cURL example from the API documentation:
curl -k -H 'Authorization: BEARER ...' https://alpha-api.app.net/stream/0/files -X POST -F 'type=com.example.test' -F "content=#filename.png;type=image/png" -F "derived_key1=#derived_file1.png;type=image/png" -F "derived_key2=#derived_file2.png;type=image/png;filename=overridden.png"
What type is required and what do I need to change to make it work?
Any feedback is really appreciated. Thank you.
You need to do these following changes
$headers = array(
'Authorization: Bearer '.'0123456789'
);
$postData = array('type' => 'com.example.upload', 'content' => '#/roor/test.png');
Also use this as you are using https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);

Categories