当我使用 PHP 从 HTML 表单提交数据时,我试图向 API 发出 POST 请求。 虽然发出了请求,但服务器返回 422 - Unprocessable Entity 错误并且不允许发出 POST 请求。
这是我的php代码:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$dataMarcacao = trim($_POST["dataMarcacao"]);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$centro = ucfirst(trim($_POST["centro-inspecoes"]));
$matricula = trim($_POST["matricula"]);
$telefone = trim($_POST["telefone"]);
$tipoInspecao = trim($_POST["tipo-inspecao"]);
$tipoViatura = trim($_POST["tipo-viatura"]);
$comentario = trim($_POST["comentario"]);
if($centro == "Paredes"){
$centroID = 0;
$tag = 25;
}
elseif ($centro == "Braga"){
$centroID = 1;
$tag = 26;
}
$curl = curl_init();
$fields = array(
'base' => array(
'first_name' => $name,
'email' => $email,
'cellphone' => $telefone,
'extras' => array(
array(
'field_id' => 30,
'format' => 'text',
'value' => $matricula
),
array(
'field_id' => 31,
'format' => 'text',
'value' => 'Dou o meu consentimento para o tratamento de dados pessoais para efeitos de comunicações por parte da Insparedes, S.A. e aceito ser contactado pela mesma entidade.'
),
array(
'field_id' => 32,
'format' => 'date',
'value' => $dataMarcacao
),
array(
'field_id' => 33,
'format' => 'options',
'value' => [$centroID]
),
),
'tags' => [$tag]
)
);
$formValues = json_encode($fields);
print_r ($formValues);
curl_setopt_array($curl, array(
CURLOPT_URL => "api.egoiapp.com/lists/7/contacts",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $formValues,
CURLOPT_HTTPHEADER => array(
"Apikey: <API KEY>"//api key removed for security reasons, in my code it's fine
"Content-Type: application/json"
),
));
echo "<br>";
echo $curl;
echo "<br>";
$response = curl_exec($curl);
curl_close($curl);
echo $response;
这是表单提交后的打印结果:422 error
我不确定问题是什么,有什么想法吗?