/wp-json/sendu/v1/status-change * * El payload esperado es JSON con, al menos, los siguientes campos: * - order_id: identificador numérico de la orden en WooCommerce (sin prefijo WC) * - state: cadena de estado que envía Sendu, por ejemplo "entregado". * * Cuando se reciba un estado "entregado" se marca automáticamente la orden * como "completed" en WooCommerce. Se pueden añadir otros mapeos si se desea. */ add_action('rest_api_init', function () { register_rest_route('sendu/v1', '/status-change', array( 'methods' => 'POST', 'callback' => 'sendu_webhook_status_change', 'permission_callback' => 'sendu_webhook_permission', )); }); /** * Autenticación del webhook (desde v5.2). * * Sendu debe firmar el cuerpo crudo de la petición con HMAC-SHA256 usando como * clave el `x_user_token` de la tienda (el mismo que Sendu ya conoce) y enviar * el resultado en hexadecimal en el header `X-Sendu-Signature`. * Sin token configurado o sin firma válida, la petición se rechaza. * * @param WP_REST_Request $request * @return true|WP_Error */ function sendu_webhook_permission(WP_REST_Request $request) { $settings = get_option('woocommerce_sendu_settings', array()); $token = isset($settings['x_user_token']) ? (string) $settings['x_user_token'] : ''; $given = (string) $request->get_header('x_sendu_signature'); if ('' === $token || '' === $given) { return new WP_Error('sendu_unauthorized', 'unauthorized', array('status' => 401)); } $expected = hash_hmac('sha256', $request->get_body(), $token); if (!hash_equals($expected, strtolower(trim($given)))) { return new WP_Error('sendu_unauthorized', 'unauthorized', array('status' => 401)); } return true; } /** * Callback que procesa el webhook. * * @param WP_REST_Request $request * @return WP_REST_Response */ function sendu_webhook_status_change(WP_REST_Request $request) { $body = $request->get_body(); $data = json_decode($body, true); if (!is_array($data)) { return new WP_REST_Response([ 'status' => 'error', 'message' => 'invalid-json' ], 400); } $order_id = isset($data['order_id']) ? intval($data['order_id']) : 0; $state = isset($data['state']) ? sanitize_text_field($data['state']) : ''; if (!$order_id || '' === $state) { return new WP_REST_Response([ 'status' => 'error', 'message' => 'missing-fields' ], 400); } // Normalizar a minúsculas para comparaciones cómodas $state_lc = strtolower($state); // Mapear estados Sendu -> estados WC. Solo "entregado" por ahora. if ('entregado' === $state_lc) { $order = wc_get_order($order_id); if ($order && 'completed' !== $order->get_status()) { $order->update_status('completed', 'Actualización recibida desde webhook Sendu: ' . $state); return new WP_REST_Response([ 'status' => 'updated', 'message' => 'order marked as completed' ], 200); } else if ($order && 'completed' === $order->get_status()) { return new WP_REST_Response([ 'status' => 'no-action', 'message' => 'order already completed' ], 200); } } return new WP_REST_Response([ 'status' => 'no-action', 'message' => 'no matching action for state or order not found' ], 200); }