Friday, October 28, 2022

[SOLVED] Make API request with cURL PHP

Issue

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?


Solution

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)
]);


Answered By - Honk der Hase
Answer Checked By - Marie Seifert (WPSolving Admin)