Permite emitir credenciales (token hasheado + IP/CIDR opcional) desde
/app/pagos-externos para que aplicaciones de terceros pidan cobros a
través de Bold/dLocal/PayPal sin acceso a nada más del sistema:
- POST /api/v1/pagos-externos/solicitar genera el link de cobro real
usando solo las pasarelas habilitadas para ese servicio.
- Los webhooks existentes de Bold/dLocal/PayPal (firma obligatoria,
idempotentes) ahora también resuelven referencias "extpay-…" sin
tocar el flujo de contratos ("contrato-{id}").
- Al confirmarse el pago se notifica por webhook firmado (HMAC) y/o
Telegram, configurable por servicio.
- CRUD de servicios protegido con SoloAdmin; token y callback_secret
solo se muestran una vez, en DB se guardan hasheados.
107 lines
4.0 KiB
Go
107 lines
4.0 KiB
Go
package controllers
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
|
"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
|
|
)
|
|
|
|
// PaypalWebhook recibe las notificaciones de PayPal y confirma el pago del
|
|
// contrato asociado.
|
|
// Ruta: POST /webhooks/paypal
|
|
//
|
|
// La firma se verifica siempre contra la API de PayPal: sin eso cualquiera
|
|
// podría enviar un "pago completado" falso y renovar un contrato sin pagar.
|
|
func PaypalWebhook(c *fiber.Ctx) error {
|
|
rawBody := c.Body()
|
|
|
|
cfg, err := models.GetPaypalConfig()
|
|
if err != nil {
|
|
log.Println("[PAYPAL] Webhook: sin configuración activa")
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"ok": true})
|
|
}
|
|
|
|
headers := map[string]string{
|
|
"paypal-auth-algo": c.Get("Paypal-Auth-Algo"),
|
|
"paypal-cert-url": c.Get("Paypal-Cert-Url"),
|
|
"paypal-transmission-id": c.Get("Paypal-Transmission-Id"),
|
|
"paypal-transmission-sig": c.Get("Paypal-Transmission-Sig"),
|
|
"paypal-transmission-time": c.Get("Paypal-Transmission-Time"),
|
|
}
|
|
if headers["paypal-transmission-id"] == "" || headers["paypal-transmission-sig"] == "" {
|
|
log.Printf("[PAYPAL] Webhook rechazado: sin cabeceras de firma (IP %s)", c.IP())
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"ok": false, "error": "firma requerida"})
|
|
}
|
|
|
|
valido, err := services.PaypalVerificarWebhook(cfg, headers, rawBody)
|
|
if err != nil {
|
|
log.Printf("[PAYPAL] Webhook: no se pudo verificar la firma: %v", err)
|
|
return c.Status(fiber.StatusServiceUnavailable).JSON(fiber.Map{"ok": false})
|
|
}
|
|
if !valido {
|
|
log.Printf("[PAYPAL] Webhook rechazado: firma inválida (IP %s)", c.IP())
|
|
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"ok": false, "error": "firma inválida"})
|
|
}
|
|
|
|
evento, err := services.ParsePaypalWebhook(rawBody)
|
|
if err != nil {
|
|
log.Printf("[PAYPAL] Webhook: %v", err)
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"ok": true})
|
|
}
|
|
|
|
log.Printf("[PAYPAL] Webhook %s — evento=%s ref=%s recurso=%s",
|
|
evento.ID, evento.EventType, evento.Referencia, evento.ResourceID)
|
|
|
|
switch evento.EventType {
|
|
case "CHECKOUT.ORDER.APPROVED":
|
|
// El cliente aprobó el pago pero todavía no se cobró: hay que capturarlo.
|
|
if evento.ResourceID != "" {
|
|
if ok, err := services.PaypalCapturarOrden(cfg, evento.ResourceID); err != nil {
|
|
log.Printf("[PAYPAL] Error capturando la orden %s: %v", evento.ResourceID, err)
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"ok": true})
|
|
} else if !ok {
|
|
log.Printf("[PAYPAL] La orden %s no quedó capturada todavía", evento.ResourceID)
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"ok": true})
|
|
}
|
|
}
|
|
case "PAYMENT.CAPTURE.COMPLETED":
|
|
// El cobro ya se hizo efectivo: no hay nada que capturar.
|
|
default:
|
|
// Otros eventos (reembolsos, disputas, etc.) solo se registran.
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"ok": true})
|
|
}
|
|
|
|
marcarContratoPagadoPorReferencia(evento.Referencia, evento.ResourceID, "paypal")
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"ok": true})
|
|
}
|
|
|
|
// marcarContratoPagadoPorReferencia confirma el pago del contrato codificado en
|
|
// una referencia con formato "contrato-{id}", o de una solicitud de pago
|
|
// externo con formato "extpay-…".
|
|
func marcarContratoPagadoPorReferencia(referencia, transaccionID, pasarela string) {
|
|
if referencia == "" {
|
|
log.Printf("[%s] Pago confirmado pero sin referencia de contrato: requiere conciliación manual", pasarela)
|
|
return
|
|
}
|
|
if services.ConfirmarPagoExternoPorReferencia(referencia, transaccionID, pasarela) {
|
|
return
|
|
}
|
|
var contratoID uint
|
|
if _, err := fmt.Sscanf(referencia, "contrato-%d", &contratoID); err != nil || contratoID == 0 {
|
|
log.Printf("[%s] Referencia '%s' no corresponde a un contrato", pasarela, referencia)
|
|
return
|
|
}
|
|
ok, err := models.MarcarContratoPagado(contratoID)
|
|
if err != nil {
|
|
log.Printf("[%s] Error marcando contrato %d como pagado: %v", pasarela, contratoID, err)
|
|
return
|
|
}
|
|
log.Printf("[%s] Contrato %d marcado como pagado (nuevo=%v)", pasarela, contratoID, ok)
|
|
if ok {
|
|
go services.EnviarCorreoConfirmacionPago(contratoID, pasarela)
|
|
}
|
|
}
|