Files
mail-comment/functions.php
2026-01-06 11:36:41 -05:00

63 lines
2.4 KiB
PHP

<?php
/**
* Registrar el endpoint del Webhook en la API REST de WordPress
* Reemplaza tudominio en register_rest_route por la palabra que quieras, pero recuerda cambiarlo en el archivo .env tambien
*/
add_action('rest_api_init', function () {
register_rest_route('tudominio/v1', '/recibir-comentario', array(
'methods' => 'POST',
'callback' => 'procesar_webhook_comentario',
'permission_callback' => '__return_true', // La validación se hace dentro del callback
));
});
function procesar_webhook_comentario(WP_REST_Request $request) {
// 1. Obtener datos del JSON enviado por Python
$params = $request->get_json_params();
$token_recibido = $params['auth_token'] ?? '';
$token_esperado = 'mi_clave_secreta_123'; // Debe coincidir con WEBHOOK_SECRET_TOKEN
// 2. Validar Token de Seguridad
if ($token_recibido !== $token_esperado) {
return new WP_Error('forbidden', 'No autorizado', array('status' => 403));
}
// 3. Extraer y sanear datos
$target_url = esc_url_raw($params['target_page']);
$author_name = sanitize_text_field($params['author_name']);
$comment_body = wp_kses($params['comment_content'], array(
'b' => array(), 'i' => array(), 'u' => array(),
'em' => array(), 'strong' => array(), 'blockquote' => array(), 'p' => array(), 'br' => array()
));
// 4. Buscar el ID del post/página mediante la URL
$post_id = url_to_postid($target_url);
if ($post_id === 0) {
return new WP_REST_Response(array('error' => 'URL de destino no encontrada en este sitio'), 404);
}
// 5. Insertar el comentario
$comment_data = array(
'comment_post_ID' => $post_id,
'comment_author' => $author_name,
'comment_author_email' => 'webhook@tudominio.com', // Email genérico para identificar origen
'comment_content' => $comment_body,
'comment_type' => 'comment',
'comment_parent' => 0,
'comment_approved' => 0, // 0 = Pendiente de moderación, 1 = Aprobado automáticamente
);
$comment_id = wp_insert_comment($comment_data);
if ($comment_id) {
return new WP_REST_Response(array(
'success' => true,
'message' => 'Comentario recibido y enviado a moderación',
'comment_id' => $comment_id
), 200);
} else {
return new WP_Error('db_error', 'No se pudo insertar el comentario', array('status' => 500));
}
}