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": "[email protected]"
},
"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" => "[email protected]"];
$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?
CodePudding user response:
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)
]);
CodePudding user response:
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": "[email protected]"
},
"signup_method": "link"
}',
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;