Webhooks y entrega

Recibir Webhooks

En HIOBuy Developer Center → Webhooks , seleccione la misma App y URL HTTPS. Antes de habilitar retirada, adapte todos los receptores y suscriba los cuatro eventos siguientes; las suscripciones previas no se amplían solas. No requiere almacén ni registro directo en HIOAsk. inquiry.webhook_configured=true comprueba uno de los tres eventos básicos created/updated/closed, no capacidad de retirada/multimedia, suscripciones completas o entrega correcta.

Event
ask.message.createdRespuesta publicada del agente; incluye data.message.
ask.message.recalledRespuesta retirada; guardar el registro definitivo incluso antes de creación.
ask.conversation.updatedCambió la instantánea pública de estado/asignación.
ask.conversation.closedConversación cerrada; consulte la valoración.

Guarde en el servidor el secreto mostrado una sola vez, distinto de la clave API. La envoltura contiene id, type, created_at, livemode, app_id, data. app_id es la App HIOBuy; data.conversation.external_app_id lo gestiona HIOBuy. Los eventos de prueba llevan livemode=false.

{
  "id": "evt_example_001",
  "type": "ask.message.created",
  "created_at": "2026-11-13T13:01:01.000Z",
  "livemode": true,
  "app_id": "app_example",
  "data": {
    "conversation": {
      "id": "11111111-1111-4111-8111-111111111111",
      "external_app_id": "hiobuy:app_example",
      "external_conversation_id": "customer-42-1688-673124809943-1",
      "external_user_id": "customer-42",
      "language": "en",
      "context": {
        "type": "product",
        "product_url": "https://detail.1688.com/offer/673124809943.html",
        "product_id": "673124809943",
        "product_title": "Knitted shoulder bag"
      },
      "target_language": "en",
      "status": "waiting_customer",
      "created_at": "2026-11-13T13:00:00.000Z",
      "updated_at": "2026-11-13T13:00:00.000Z"
    },
    "message": {
      "id": "22222222-2222-4222-8222-222222222222",
      "conversation_id": "11111111-1111-4111-8111-111111111111",
      "client_message_id": "22222222-2222-4222-8222-222222222222",
      "sender_type": "staff",
      "type": "text",
      "content": "We can help you confirm neutral packaging with the supplier.",
      "language": "en",
      "status": "accepted",
      "translation_status": "translated",
      "created_at": "2026-11-13T13:01:00.000Z",
      "attachments": []
    }
  }
}

Verificar entrega

Verifique HioBuy-Signature: t=<unix_seconds>,v1=<hex_hmac_sha256> con HMAC-SHA256(secret, timestamp + ”.” + rawBody). Use bytes originales, comparación de tiempo constante y tolerancia ±300 segundos antes de analizar JSON. Rechace firmas o App incorrectas. El ejemplo recibe un Buffer limitado; nunca registre el secreto.

import { createHmac, timingSafeEqual } from "node:crypto";
 
export function verifyHioBuyWebhook(rawBody, signature, secret, expectedAppId) {
  if (!Buffer.isBuffer(rawBody) || rawBody.length > 256 * 1024) throw new Error("Invalid body");
  const match = /^t=([0-9]{1,12}),v1=([a-f0-9]{64})$/.exec(signature ?? "");
  if (!match || Math.abs(Date.now() / 1000 - Number(match[1])) > 300) {
    throw new Error("Invalid signature timestamp");
  }
  const expected = createHmac("sha256", secret).update(match[1] + ".").update(rawBody).digest();
  const actual = Buffer.from(match[2], "hex");
  if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
    throw new Error("Invalid signature");
  }
  const event = JSON.parse(rawBody.toString("utf8"));
  if (event.app_id !== expectedAppId || typeof event.id !== "string") throw new Error("Invalid event App");
  if (!["ask.message.created", "ask.message.recalled", "ask.conversation.updated", "ask.conversation.closed"].includes(event.type)) {
    throw new Error("Unsupported event");
  }
  return event;
}

La entrega es al menos una vez y puede retrasarse o desordenarse. Deduzca duplicados por id de forma duradera, guarde aceptación y mensajes en una transacción y después devuelva 2xx. Rechace un ID con otro contenido. Un evento antiguo no debe reabrir una conversación cerrada. Si no puede persistir, responda no-2xx y consulte reintentos en el portal.

Al cargar, reconectar y periódicamente con espera progresiva, actualice la primera página y las páginas cargadas/visibles. Retirar no cambia created_at ni mueve el mensaje a la primera página. El cursor solo carga entradas anteriores; no hay flujo since/updated_since. Combine por App + conversación + mensaje; un recalled_at guardado prevalece sobre respuestas antiguas normales. Lea estado y valoración actuales; no reabra conversaciones cerradas por eventos antiguos. Conserve borradores e ID estables tras envíos inciertos.

La clave determina la App. No envíe X-External-App-Id ni conecte directamente con HIOAsk. Guarde claves y secretos en el servidor, fuera del navegador, URL y registros. Verifique además que el cliente autenticado sea dueño de la conversación; el aislamiento de App no sustituye esta autorización.

Errores y recuperación

HTTPCode
400MISSING_IDEMPOTENCY_KEY / INVALID_CURSOR / VALIDATION_ERROR
401INVALID_API_KEY
403SUPPLIER_INQUIRY_NOT_ENABLED / INSUFFICIENT_SCOPE / INQUIRY_SANDBOX_UNAVAILABLE
404CONVERSATION_NOT_FOUND
409IDEMPOTENCY_KEY_REUSED / CONVERSATION_CONFLICT / CLIENT_MESSAGE_ID_CONFLICT
409CONVERSATION_CLOSED / PRODUCT_CARD_NOT_FIRST / RATING_ALREADY_SUBMITTED
410RATING_WINDOW_CLOSED / HIOASK_V1_RETIRED
429RATE_LIMIT_EXCEEDED / DAILY_QUOTA_EXCEEDED
502HIOASK_INTEGRATION_REJECTED
503HIOASK_BINDING_NOT_READY / HIOASK_UNAVAILABLE

401: revise la clave; 403: capacidad, scopes y producción; 409: recupere el recurso o reintente igual; 429: respete Retry-After. Para 502/503 use reintentos limitados; HIOASK_BINDING_NOT_READY requiere configuración HIOBuy. Un rechazo de permisos remoto, incluidos medios desactivados, se mapea actualmente a 502 HIOASK_INTEGRATION_REJECTED y no demuestra clave inválida.

/v1/supplier-inquiries y subrutas devuelven 410 HIOASK_V1_RETIRED. questions, answers tipadas y supplier_inquiry.* están retirados. Use /v1/ask/* y ask.*, incluido ask.message.recalled en integraciones compatibles. Se conserva V1 sin conversión automática.

Retirada y eventos fuera de orden

ask.message.recalled incluye el mismo ID, recalled_at, content vacío y ningún medio. Guarde un registro definitivo por App + conversación + mensaje, incluso si llega antes de la creación. En la transacción de aceptación quite texto, adjuntos y cachés públicos. Los duplicados no tienen efecto; un created tardío, una respuesta API antigua o recargar nunca deben restaurar contenido. Mantenga el created_at original. No se garantiza borrar copias ya leídas o descargadas.

Tras adaptar todos los receptores y el historial, confirme la activación con HIOBuy. Las demás integraciones mantienen su comportamiento. No hay API pública de retirada; solo afecta a respuestas admisibles del agente, no a mensajes del cliente ni notas internas.

{
  "id": "evt_example_recall_001",
  "type": "ask.message.recalled",
  "created_at": "2026-11-13T13:01:15.000Z",
  "livemode": true,
  "app_id": "app_example",
  "data": {
    "conversation": {
      "id": "11111111-1111-4111-8111-111111111111",
      "external_app_id": "hiobuy:app_example",
      "external_conversation_id": "customer-42-1688-673124809943-1",
      "external_user_id": "customer-42",
      "language": "en",
      "context": {
        "type": "product",
        "product_url": "https://detail.1688.com/offer/673124809943.html",
        "product_id": "673124809943",
        "product_title": "Knitted shoulder bag"
      },
      "target_language": "en",
      "status": "waiting_customer",
      "created_at": "2026-11-13T13:00:00.000Z",
      "updated_at": "2026-11-13T13:00:00.000Z"
    },
    "message": {
      "id": "22222222-2222-4222-8222-222222222222",
      "conversation_id": "11111111-1111-4111-8111-111111111111",
      "client_message_id": "22222222-2222-4222-8222-222222222222",
      "sender_type": "staff",
      "type": "text",
      "content": "",
      "language": "en",
      "status": "accepted",
      "translation_status": "translated",
      "created_at": "2026-11-13T13:01:00.000Z",
      "attachments": [],
      "recalled_at": "2026-11-13T13:01:15.000Z"
    }
  }
}

Referencias a mensajes

Las integraciones habilitadas reciben reply_to_message_id en el ask.message.created existente. Guarde el ID, no un extracto copiado, y resuelva por App + conversación. Si el destino tiene recalled_at, todas las referencias muestran retirada, aunque llegue antes de la creación o de la respuesta asociada. Una respuesta retirada oculta también su referencia. Respuestas API antiguas y reintentos no restauran texto ni medios; firmas y deduplicación siguen iguales. No vuelva a receptores incompatibles mientras existan estos eventos o historial en uso.

Get Support

Need integration help? Contact Developer Support at support@hiobuy.com · Response within 1–2 business days

Email support