phpapicurlsafe-browsing

Safe Browsing Lookup API (v4) Invalid JSON payload received


I have a php script which tries to use google Safe Browsing Lookup API (v4), but I'm getting error "Invalid JSON payload received. Unknown name \"\": Root element must be a message..."

Here is my code:

<?php

$data = '{
  "client": {
    "clientId": "TestClient",
    "clientVersion": "1.0"
  },
  "threatInfo": {
    "threatTypes":      ["MALWARE", "SOCIAL_ENGINEERING"],
    "platformTypes":    ["LINUX"],
    "threatEntryTypes": ["URL"],
    "threatEntries": [
      {"url": "http://www.google.com"}
    ]
  }
}';


$apikey = "my_secret_api_key";
$url_send ="https://safebrowsing.googleapis.com/v4/threatMatches:find?key=".$apikey."";

$str_data = json_encode($data);

function sendPostData($url, $post){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", 'Content-Length: ' . strlen($post)));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}

$jaahas = sendPostData($url_send, $str_data);

echo "<pre>";
var_dump($jaahas);

?>

Is there something wrong with the json-data array formatting or what might be the problem?


Solution

  • You're running json_encode on data which is already encoded.

    ie. change this line:

    $jaahas = sendPostData($url_send, $str_data);
    

    to

    $jaahas = sendPostData($url_send, $data);