Telegram bot payment shows precheckout timeout error despite successful response

I’m having trouble with my Telegram bot payment system. When users try to make payments through different providers like Sberbank test and Yukassa test, I get a weird issue.

Here’s what happens: My bot receives the pre_checkout_query update and I call answerPreCheckoutQuery method. The API returns {“ok”:true,“result”:true} which means everything should be fine. But then users see “BOT_PRECHECKOUT_TIMEOUT” error in their payment window.

This happens with different payment providers and different user accounts. Even when I test it manually step by step, the same error appears. The bot gets the checkout query, responds correctly, gets success response, but still shows timeout error to users.

Is this something wrong with my bot setup or could it be an issue with Telegram’s payment system?

sounds like telegram’s 10-sec limit is hitting you even tho the response looks fine. I had the same weird issue - my webhook was getting requests okay, but async tasks were blocking the response thread. add logs with timestamps right before you call answerPreCheckoutQuery to check the actual timing. also make sure you’re not accidentally processing the same precheckout twice - that can cause delays.

Been fighting this for months across multiple bots. BOT_PRECHECKOUT_TIMEOUT hits you when there’s ANY delay in your webhook processing - even tiny delays that shouldn’t matter. Here’s what fixed it for me: handle the response immediately. The second your pre_checkout_query webhook gets hit, validate the payment data and fire back answerPreCheckoutQuery. Don’t do anything else first - no database writes, no external API calls, nothing. Do all your heavy stuff (order creation, user notifications) AFTER you’ve sent the response. Also check if you’ve got multiple webhook handlers competing for resources or if your web server’s request queuing is adding delays.

This error got me too when I built Telegram payments last year. Even with successful API calls, you’ll hit timeouts if your webhook processing is slow. Check your webhook endpoint performance first - it’s often not the answerPreCheckoutQuery call that’s the problem, but how long your server takes to receive and start processing the webhook. Network lag between Telegram’s servers and your host can push you over the limit. I moved from shared hosting to a VPS with better connectivity and it fixed everything. Also check if you’ve got middleware or auth layers slowing things down before your payment handler runs.

The Problem:

Estás experimentando el error “BOT_PRECHECKOUT_TIMEOUT” en tu sistema de pagos de Telegram Bot, incluso cuando la API devuelve {“ok”:true,“result”:true}. Esto ocurre con diferentes proveedores de pago y cuentas de usuario, incluso en pruebas manuales paso a paso. El bot recibe la consulta de pago, responde correctamente, recibe una respuesta de éxito, pero aún así muestra el error de tiempo de espera al usuario.

:thinking: Understanding the “Why” (The Root Cause):

El error “BOT_PRECHECKOUT_TIMEOUT” en Telegram no se debe necesariamente a un fallo en tu respuesta answerPreCheckoutQuery. Telegram impone un estricto límite de tiempo de 10 segundos entre la recepción de la consulta pre_checkout_query y la recepción de tu respuesta. Si tu servidor tarda más de 10 segundos en procesar la solicitud y responder, Telegram mostrará este error al usuario, independientemente de que tu código haya procesado correctamente la solicitud y haya respondido con éxito a la API de Telegram. El problema radica en la latencia o tiempo de procesamiento de tu servidor, y no en el código que maneja la respuesta answerPreCheckoutQuery en sí misma. Retrasos ocultos en tu flujo de procesamiento (consultas a bases de datos lentas, llamadas a APIs externas, problemas de red, etc.), pueden provocar que se supere este límite de tiempo.

:gear: Step-by-Step Guide:

Paso 1: Responde Inmediatamente. Lo más importante es responder a pre_checkout_query lo más rápido posible. Tu respuesta a Telegram debe ser inmediata. No realices ninguna otra operación (escrituras en bases de datos, llamadas a APIs externas, etc.) antes de enviar la respuesta answerPreCheckoutQuery a Telegram. Solo valida los datos de pago lo más rápidamente posible en este punto.

Paso 2: Procesa las Operaciones Pesadas Después. Después de que answerPreCheckoutQuery haya sido enviada a Telegram y hayas recibido una confirmación de éxito, puedes realizar el resto del procesamiento: crear el pedido, notificar al usuario, etc. Estas tareas, si son lentas, ya no afectarán el tiempo de respuesta a la consulta de pago.

Paso 3: Optimiza el Rendimiento del Servidor. Si, incluso después de los pasos anteriores, aún experimentas el error, deberás optimizar el rendimiento de tu servidor:

  • Optimiza las consultas a la base de datos. Identifica y optimiza cualquier consulta lenta a tu base de datos. Usa índices adecuados y considera técnicas de almacenamiento en caché para reducir el tiempo de respuesta de las consultas.
  • Reduce las llamadas a APIs externas. Si tu sistema depende de llamadas a otras APIs, asegúrate de que estas sean lo más eficientes posible y que no causen cuellos de botella.
  • Mejora la conectividad de red. Asegúrate de que tu servidor tiene una buena conectividad de red con los servidores de Telegram. Un retraso en la red entre tu servidor y los servidores de Telegram puede contribuir al problema. Considera cambiar a un servidor con una mejor conectividad.
  • Reduce la carga del servidor. Si tu servidor está sobrecargado, esto puede aumentar los tiempos de respuesta. Considera una solución de escalamiento para manejar picos de tráfico.
  • Desactiva el modo de depuración. Si tu servidor está en modo de depuración, esto puede agregar sobrecarga innecesaria y aumentar los tiempos de respuesta. Desactívalo en producción.

Paso 4: Monitorea los Tiempos de Respuesta. Implementa un sistema de monitoreo para rastrear los tiempos de respuesta de tu servidor a las solicitudes pre_checkout_query. Esto te ayudará a identificar las partes de tu sistema que causan el retraso.

:mag: Common Pitfalls & What to Check Next:

  • Configuración incorrecta de webhooks: Verifica que tu webhook de Telegram esté configurado correctamente y que la URL sea accesible para los servidores de Telegram. Prueba con una herramienta como ngrok para exponer tu webhook local temporalmente.
  • Procesamiento duplicado de pre_checkout_query: Asegúrate de que no estás procesando accidentalmente la misma consulta pre_checkout_query dos veces.
  • Middleware o capas de autenticación lentas: Las capas de middleware o autenticación innecesarias en tu servidor pueden agregar latencia adicional. Minimiza estas capas tanto como sea posible.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Had this exact problem for weeks when I started using Telegram payments. It’s a timing issue even though you’re getting success responses. If your server takes longer than 10 seconds to respond to the pre_checkout_query, Telegram throws that timeout error no matter what you send back. Check your actual server response times in the logs, not just the API response. I had some database queries that occasionally ran slow and pushed me over the limit. Fixed it by optimizing the queries and adding caching. Also, call answerPreCheckoutQuery right when you get the update - don’t do heavy processing first. Telegram’s timeout is pretty strict.

This timeout hits even when your code’s perfect because there’s hidden delays in the webhook chain you can’t see.

I hit this exact issue building payment flows. The problem isn’t your answerPreCheckoutQuery call - it’s everything happening before it gets there.

What fixed it? I ditched traditional webhooks completely. Instead of Telegram hitting my server directly, I use Latenode to handle webhook processing. It catches the pre_checkout_query instantly, runs validation or database checks, then fires back the answer in milliseconds.

Latenode runs closer to Telegram’s infrastructure, so you cut most network delays. Plus their visual workflow builder shows exact timing for each step. No more guessing where those extra seconds go.

Set it up to catch the webhook, validate payment data, check your user database, and respond to Telegram - all in one flow that stays under the 10 second limit.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.