rewrite API call
This commit is contained in:
@@ -24,6 +24,8 @@ function modal_styles()
|
|||||||
wp_enqueue_style(
|
wp_enqueue_style(
|
||||||
"prijs-per-postcode",
|
"prijs-per-postcode",
|
||||||
plugins_url("/assets/postcode_modal.css", __FILE__),
|
plugins_url("/assets/postcode_modal.css", __FILE__),
|
||||||
|
[], // Voeg een lege dependencies array toe (verplicht)
|
||||||
|
filemtime(plugin_dir_path(__FILE__) . "assets/postcode_modal.css"), // Voeg versie toe
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,24 +50,28 @@ function send_postcode_data()
|
|||||||
const sndBtnTxt = sndBtn.querySelector(".btn_text");
|
const sndBtnTxt = sndBtn.querySelector(".btn_text");
|
||||||
const errorMsg = document.querySelector("#error_message_modal_postcode");
|
const errorMsg = document.querySelector("#error_message_modal_postcode");
|
||||||
|
|
||||||
|
// 1. Validatie bij blur (client-side checks)
|
||||||
modalForm.querySelectorAll("input").forEach(input => {
|
modalForm.querySelectorAll("input").forEach(input => {
|
||||||
input.addEventListener("blur", ev => {
|
input.addEventListener("blur", ev => {
|
||||||
errorMsg.innerHTML = ""
|
errorMsg.innerHTML = "";
|
||||||
if(!ev.target.validity.valid && ev.target.value !== "") {
|
if (!ev.target.validity.valid && ev.target.value !== "") {
|
||||||
errorMsg.innerHTML = ev.target.title;
|
errorMsg.innerHTML = ev.target.title;
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
|
|
||||||
|
// 2. Submit Handler
|
||||||
modalForm.addEventListener('submit', async (e) => {
|
modalForm.addEventListener('submit', async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
errorMsg.innerHTML = "";
|
errorMsg.innerHTML = "";
|
||||||
|
|
||||||
|
// UI: Laadstatus
|
||||||
sndBtn.disabled = true;
|
sndBtn.disabled = true;
|
||||||
sndBtnLdr.style.opacity = "1";
|
sndBtnLdr.style.opacity = "1";
|
||||||
sndBtnTxt.style.opacity = "0";
|
sndBtnTxt.style.opacity = "0";
|
||||||
|
|
||||||
const formData = new FormData(e.target);
|
const formData = new FormData(e.target);
|
||||||
const data = Object.fromEntries(formData.entries());
|
const payload = Object.fromEntries(formData.entries());
|
||||||
const json = JSON.stringify(data);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('<?php echo get_rest_url(
|
const resp = await fetch('<?php echo get_rest_url(
|
||||||
@@ -76,44 +82,60 @@ function send_postcode_data()
|
|||||||
credentials: 'same-origin',
|
credentials: 'same-origin',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-WP-Nonce': '<?php echo wp_create_nonce("wp_rest"); ?>'
|
'X-WP-Nonce': '<?php echo wp_create_nonce(
|
||||||
|
"wp_rest",
|
||||||
|
); ?>'
|
||||||
},
|
},
|
||||||
body: json
|
body: JSON.stringify(payload)
|
||||||
});
|
});
|
||||||
|
|
||||||
if(!resp.ok){
|
// Parse altijd eerst de JSON, zelfs bij HTTP fouten
|
||||||
throw new Error(`HTTP Error! status: ${resp.status}` );
|
const data = await resp.json();
|
||||||
}
|
|
||||||
|
// UI: Reset knop
|
||||||
sndBtn.disabled = false;
|
sndBtn.disabled = false;
|
||||||
sndBtnLdr.style.opacity = "0";
|
sndBtnLdr.style.opacity = "0";
|
||||||
sndBtnTxt.style.opacity = "1";
|
sndBtnTxt.style.opacity = "1";
|
||||||
const data = await resp.json();
|
|
||||||
console.log("Data returnd", data);
|
|
||||||
|
|
||||||
if (data.status === "error"){
|
if (data.status === "error") {
|
||||||
const err = data.code;
|
const errorCode = data.code; // Komt nu correct door vanuit PHP
|
||||||
let errmsg
|
const apiMessage = data.message;
|
||||||
|
|
||||||
switch (err) {
|
let userErrorMessage = "Gegevens zijn niet correct.";
|
||||||
case "HUISNUMMER_NOT_FOUND":
|
|
||||||
errmsg = "Adres is niet gevonden.";
|
// Specifieke foutafhandeling
|
||||||
break;
|
if (errorCode === "HUISNUMMER_NOT_FOUND" || apiMessage.includes("not found")) {
|
||||||
case "HUISNUMMER_AMBIGUOUS":
|
userErrorMessage = "Adres is niet gevonden.";
|
||||||
errmsg = "Huisnummertovoeging mist.";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
errmsg = "Gegevens zijn niet correct.";
|
|
||||||
}
|
}
|
||||||
errorMsg.innerHTML = errmsg;
|
else if (errorCode === "HUISNUMMER_AMBIGUOUS") {
|
||||||
|
// Deze komt ALLEEN nog hier als PHP géén 'platte' match kon vinden.
|
||||||
|
// Dat betekent dat de gebruiker verplicht een toevoeging moet geven (bijv. alleen 15A bestaat).
|
||||||
|
const suggestions = data.suggestions || [];
|
||||||
|
if (suggestions.length > 0) {
|
||||||
|
userErrorMessage = `Meerdere opties: ${suggestions.join(", ")}. Voeg een toevoeging toe.`;
|
||||||
|
} else {
|
||||||
|
userErrorMessage = "Huisnummertoevoeging is verplicht.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (errorCode === "CURL_ERROR" || errorCode === "JSON_ERROR") {
|
||||||
|
userErrorMessage = "Serverfout. Probeer het later opnieuw.";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.status === "success"){
|
errorMsg.innerHTML = userErrorMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.status === "success") {
|
||||||
|
// Succes: Modal sluiten en eventueel reload of update
|
||||||
postcodeModal.close();
|
postcodeModal.close();
|
||||||
//location.reload();
|
// Optioneel: location.reload(); of update de pagina content
|
||||||
}
|
}
|
||||||
}catch(err){
|
|
||||||
|
} catch (err) {
|
||||||
console.error("Fetch Failed:", err);
|
console.error("Fetch Failed:", err);
|
||||||
throw err;
|
sndBtn.disabled = false;
|
||||||
|
sndBtnLdr.style.opacity = "0";
|
||||||
|
sndBtnTxt.style.opacity = "1";
|
||||||
|
errorMsg.innerHTML = "Er ging iets mis bij het verbinden.";
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
@@ -180,56 +202,99 @@ function handle_postcode_modal($data)
|
|||||||
$params = $data->get_params();
|
$params = $data->get_params();
|
||||||
$nonce = $data->get_header("X-WP-Nonce");
|
$nonce = $data->get_header("X-WP-Nonce");
|
||||||
|
|
||||||
if (wp_verify_nonce($nonce, "wp_rest")) {
|
// 1. Security
|
||||||
|
if (!wp_verify_nonce($nonce, "wp_rest")) {
|
||||||
|
echo json_encode(["status" => "error", "message" => "nononce"]);
|
||||||
|
exit();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Basis Validatie
|
||||||
if (!verify_postcode($params["postcode"])) {
|
if (!verify_postcode($params["postcode"])) {
|
||||||
$resp = [
|
echo json_encode(["status" => "error", "message" => "postcode"]);
|
||||||
"status" => "error",
|
|
||||||
"message" => "postcode",
|
|
||||||
];
|
|
||||||
echo json_encode($resp);
|
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!verify_huisnummer($params["huisnummer"])) {
|
if (!verify_huisnummer($params["huisnummer"])) {
|
||||||
$resp = [
|
echo json_encode(["status" => "error", "message" => "huisnummer"]);
|
||||||
"status" => "error",
|
|
||||||
"message" => "huisnummer",
|
|
||||||
];
|
|
||||||
echo json_encode($resp);
|
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 3. API Call (Ruwe data)
|
||||||
$result = getStraatnaam($params["postcode"], $params["huisnummer"]);
|
$result = getStraatnaam($params["postcode"], $params["huisnummer"]);
|
||||||
if (isset($result["error"])) {
|
|
||||||
$resp = [
|
// 4. Validatie & Logic
|
||||||
|
$hasError = isset($result["error"]);
|
||||||
|
$errorCode = null;
|
||||||
|
$errorMessage = null;
|
||||||
|
$candidates = [];
|
||||||
|
$straatnaam = null;
|
||||||
|
$woonplaats = null;
|
||||||
|
|
||||||
|
if ($hasError) {
|
||||||
|
$errorCode = $result["error"]["code"] ?? "UNKNOWN_ERROR";
|
||||||
|
$errorMessage = $result["error"]["message"] ?? "Onbekende fout";
|
||||||
|
$candidates = $result["error"]["details"]["candidates"] ?? [];
|
||||||
|
|
||||||
|
// SPECIAL CASE: HUISNUMMER_AMBIGUOUS
|
||||||
|
if ($errorCode === "HUISNUMMER_AMBIGUOUS" && !empty($candidates)) {
|
||||||
|
$plainMatch = null;
|
||||||
|
|
||||||
|
// Zoek naar candidate ZONDER toevoeging
|
||||||
|
foreach ($candidates as $candidate) {
|
||||||
|
if (
|
||||||
|
empty($candidate["huisletter"]) &&
|
||||||
|
empty($candidate["huisnummertoevoeging"])
|
||||||
|
) {
|
||||||
|
$plainMatch = $candidate;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Als we een 'platte' match hebben (bijv. 15), dan is het SUCCES
|
||||||
|
if ($plainMatch) {
|
||||||
|
$hasError = false; // Negeer de error
|
||||||
|
$straatnaam = $plainMatch["straat"];
|
||||||
|
$woonplaats = $plainMatch["woonplaats"];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Normaal succes (geen error in response)
|
||||||
|
if (!empty($result["results"])) {
|
||||||
|
$straatnaam = $result["results"][0]["straat"];
|
||||||
|
$woonplaats = $result["results"][0]["woonplaats"];
|
||||||
|
} else {
|
||||||
|
// Edge case: geen error veld, maar ook geen results
|
||||||
|
$hasError = true;
|
||||||
|
$errorCode = "NO_RESULTS";
|
||||||
|
$errorMessage = "Adres niet gevonden";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Response sturen
|
||||||
|
if ($hasError) {
|
||||||
|
echo json_encode([
|
||||||
"status" => "error",
|
"status" => "error",
|
||||||
"message" => $result["error"],
|
"code" => $errorCode,
|
||||||
|
"message" => $errorMessage,
|
||||||
|
"suggestions" => $result["error"]["details"]["suggestions"] ?? [],
|
||||||
"apirequest" => "openpostcode.nl",
|
"apirequest" => "openpostcode.nl",
|
||||||
];
|
]);
|
||||||
echo json_encode($resp);
|
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 6. Succes: Sessie opslaan & response
|
||||||
$_SESSION["postcode"] = $params["postcode"];
|
$_SESSION["postcode"] = $params["postcode"];
|
||||||
$_SESSION["huisnummer"] = $params["huisnummer"];
|
$_SESSION["huisnummer"] = $params["huisnummer"];
|
||||||
$_SESSION["straatnaam"] = $result["straatnaam"];
|
$_SESSION["straatnaam"] = $straatnaam;
|
||||||
$_SESSION["woonplaats"] = $result["woonplaats"];
|
$_SESSION["woonplaats"] = $woonplaats;
|
||||||
|
|
||||||
$_SESSION["postcode_is_local"] = postcode_in_range($params["postcode"]);
|
$_SESSION["postcode_is_local"] = postcode_in_range($params["postcode"]);
|
||||||
|
|
||||||
$resp = [
|
echo json_encode([
|
||||||
"status" => "success",
|
"status" => "success",
|
||||||
"message" => "all good",
|
"message" => "all good",
|
||||||
"straatnaam" => $result["straatnaam"],
|
"straatnaam" => $straatnaam,
|
||||||
"lokaal_trarief" => postcode_in_range($params["postcode"]),
|
"woonplaats" => $woonplaats,
|
||||||
];
|
"lokaal_tarief" => postcode_in_range($params["postcode"]),
|
||||||
} else {
|
]);
|
||||||
$resp = [
|
|
||||||
"status" => "error",
|
|
||||||
"message" => "nononce",
|
|
||||||
];
|
|
||||||
}
|
|
||||||
echo json_encode($resp);
|
|
||||||
exit();
|
exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -272,27 +337,32 @@ function getStraatnaam($postcode, $huisnummer)
|
|||||||
curl_setopt($ch, CURLOPT_USERAGENT, "PHP/OpenPostcodeClient");
|
curl_setopt($ch, CURLOPT_USERAGENT, "PHP/OpenPostcodeClient");
|
||||||
|
|
||||||
$response = curl_exec($ch);
|
$response = curl_exec($ch);
|
||||||
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||||
|
|
||||||
if (curl_error($ch)) {
|
if (curl_error($ch)) {
|
||||||
curl_close($ch);
|
curl_close($ch);
|
||||||
return ["error" => "cURL error: " . curl_error($ch)];
|
return [
|
||||||
|
"error" => ["code" => "CURL_ERROR", "message" => curl_error($ch)],
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
curl_close($ch);
|
curl_close($ch);
|
||||||
|
|
||||||
|
// Decodeer als associatieve array (true)
|
||||||
$data = json_decode($response, true);
|
$data = json_decode($response, true);
|
||||||
|
|
||||||
if (isset($data["error"])) {
|
// Als JSON decode faalt
|
||||||
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||||
return [
|
return [
|
||||||
"error" => $data["error"]["message"],
|
"error" => [
|
||||||
"code" => $data["error"]["code"],
|
"code" => "JSON_ERROR",
|
||||||
|
"message" => "Invalid JSON response",
|
||||||
|
],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
// Geef de RUWE response terug (inclusief meta, error, results, etc.)
|
||||||
"straatnaam" => $data["results"][0]["straat"],
|
return $data;
|
||||||
"woonplaats" => $data["results"][0]["woonplaats"],
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function postcode_in_range($postcode)
|
function postcode_in_range($postcode)
|
||||||
|
|||||||
Reference in New Issue
Block a user