'Plaid API Error "body could not be parsed as JSON" when creating a link token request

I am receiving a "INVALID_BODY" error with the message "body could not be parsed as JSON" when sending a curl request through php to create a plaid link token.

I have the header and body formatted this way:

$ch=curl_init("https://development.plaid.com/link/token/create");
    $username = array(
        "client_user_id"=>"cus_L7tpXAO0PXsPsh"
    );
    $headers = array(
        'Content-type: application/json'
    );
    
    $data = array( 
        'client_id'=>'ID', 
        'secret'=>'SECRET', 
        'client_name'=>'Plaid App', 
        'user'=>$username,   
        'products'=>'auth', 
        'country_codes'=>'US', 
        'language'=>'en', 
        'webhook'=>'https://webhook.sample.com'
    );
    
    $hstring = http_build_query($headers);
    $string = http_build_query($data);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $token = curl_exec($ch);
    echo $token;
    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
?>

There is probably a very obvious formatting issue but I can't see it as is. Appreciate any suggestions or criticisms. I should also mention building out the POST in Postman also gives invalid body error.



Solution 1:[1]

I was getting the same error, but for a different reason. The problem in your code is how you are sending your country codes and products. They are expected to be arrays of strings despite the documentation seeming to say otherwise. Also, I don't think you're sending the data in JSON either... Try this:

$data =[
    "client_id" => $plaidID,
    "secret" => $plaidSecret,
    "client_name" => $clientName,
    "user" => [
        "client_user_id"  => $userID
    ],
    "products" => ["auth"],
    "country_codes"=>["US"],
    "language" => "en"
];

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"https://".$apiMode.".plaid.com/link/token/create");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");          
curl_setopt($ch,CURLOPT_HTTPHEADER,["content-type: application/json"]);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode((object)$data,JSON_HEX_APOS | JSON_HEX_QUOT ));
$response = curl_exec($ch);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1