feat(webhook): align chatwoot ingress routes
This commit is contained in:
@@ -396,7 +396,7 @@ func Bootstrap(env string) (*App, error) {
|
||||
|
||||
// Create Telegram webhook handler (Gin HTTP handler for Telegram webhook endpoint)
|
||||
telWebhook := telegramchannel.NewWebhookHandler(tgProvider)
|
||||
telegramWebhookHandler := webhook.NewTelegramWebhookHandler(tgProvider, telWebhook)
|
||||
telegramWebhookHandler := webhook.NewTelegramWebhookHandler(tgProvider, telWebhook, db)
|
||||
|
||||
// Step 8c: Wire WhatsApp channel provider (Cloud API / 360dialog)
|
||||
// Reference: Chatwoot registers WhatsApp channel providers in config/initializers/channels.rb
|
||||
|
||||
@@ -3,17 +3,18 @@ package webhook
|
||||
// LineWebhookHandler processes incoming LINE webhook HTTP requests via Gin.
|
||||
// Reference: Facebook webhook adapter pattern (facebook_webhook.go)
|
||||
//
|
||||
// URL pattern: /webhooks/line/:inbox_id
|
||||
// URL pattern: /webhooks/line/:line_channel_id
|
||||
// Method: POST (LINE Messaging API sends events as JSON)
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
linechannel "github.com/gochat/gochat/internal/channel/line"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
channelmodel "github.com/gochat/gochat/internal/model/channel"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -40,18 +41,20 @@ func NewLineWebhookHandler(lineWebhook *linechannel.WebhookHandler, pipeline *li
|
||||
|
||||
// HandleLineWebhook processes an incoming LINE webhook Gin request.
|
||||
func (h *LineWebhookHandler) HandleLineWebhook(c *gin.Context) {
|
||||
inboxIDStr := c.Param("inbox_id")
|
||||
inboxID, err := strconv.ParseUint(inboxIDStr, 10, 32)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("LINE webhook: invalid inbox_id %s", inboxIDStr)
|
||||
lineChannelID := c.Param("line_channel_id")
|
||||
if lineChannelID == "" {
|
||||
lineChannelID = c.Param("channel_id")
|
||||
}
|
||||
if lineChannelID == "" {
|
||||
applogger.L().Warn("LINE webhook: missing line_channel_id in path")
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
|
||||
// Lookup inbox from database
|
||||
inbox, err := h.lookupInbox(uint(inboxID))
|
||||
inbox, err := h.lookupInboxByLineChannelID(lineChannelID)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("LINE webhook: inbox lookup failed for id %d: %v", inboxID, err)
|
||||
applogger.L().Warnf("LINE webhook: inbox lookup failed for channel_id %s: %v", lineChannelID, err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
@@ -59,7 +62,7 @@ func (h *LineWebhookHandler) HandleLineWebhook(c *gin.Context) {
|
||||
// Read request body
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("LINE webhook: failed to read body for inbox %d: %v", inboxID, err)
|
||||
applogger.L().Errorf("LINE webhook: failed to read body for inbox %d: %v", inbox.ID, err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
@@ -75,7 +78,7 @@ func (h *LineWebhookHandler) HandleLineWebhook(c *gin.Context) {
|
||||
|
||||
if channelSecret != "" && signature != "" {
|
||||
if !h.service.VerifySignature(channelSecret, string(body), signature) {
|
||||
applogger.L().Warnf("LINE webhook: invalid signature for inbox=%d", inboxID)
|
||||
applogger.L().Warnf("LINE webhook: invalid signature for inbox=%d", inbox.ID)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid signature"})
|
||||
return
|
||||
}
|
||||
@@ -84,7 +87,7 @@ func (h *LineWebhookHandler) HandleLineWebhook(c *gin.Context) {
|
||||
// Parse webhook event
|
||||
var webhookEvent linechannel.WebhookEvent
|
||||
if err := json.Unmarshal(body, &webhookEvent); err != nil {
|
||||
applogger.L().Errorf("LINE webhook: failed to parse JSON for inbox %d: %v", inboxID, err)
|
||||
applogger.L().Errorf("LINE webhook: failed to parse JSON for inbox %d: %v", inbox.ID, err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
@@ -93,7 +96,7 @@ func (h *LineWebhookHandler) HandleLineWebhook(c *gin.Context) {
|
||||
for _, event := range webhookEvent.Events {
|
||||
incomingMsg, err := h.pipeline.ProcessEvent(c.Request.Context(), inbox, event)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("LINE webhook: process event failed for inbox %d: %v", inboxID, err)
|
||||
applogger.L().Errorf("LINE webhook: process event failed for inbox %d: %v", inbox.ID, err)
|
||||
continue
|
||||
}
|
||||
if incomingMsg != nil {
|
||||
@@ -119,6 +122,25 @@ func (h *LineWebhookHandler) lookupInbox(inboxID uint) (*model.Inbox, error) {
|
||||
return &inbox, nil
|
||||
}
|
||||
|
||||
// lookupInboxByLineChannelID fetches an Inbox through the LINE channel record.
|
||||
// Chatwoot exposes /webhooks/line/:line_channel_id and resolves the channel from that URL segment.
|
||||
func (h *LineWebhookHandler) lookupInboxByLineChannelID(lineChannelID string) (*model.Inbox, error) {
|
||||
if h.db == nil {
|
||||
return nil, fmt.Errorf("line webhook database is not configured")
|
||||
}
|
||||
|
||||
var channel channelmodel.ChannelLINE
|
||||
if err := h.db.Where("channel_id = ?", lineChannelID).First(&channel).Error; err != nil {
|
||||
return nil, fmt.Errorf("line channel not found for channel_id=%s: %w", lineChannelID, err)
|
||||
}
|
||||
|
||||
var inbox model.Inbox
|
||||
if err := h.db.Where("id = ? AND channel_type = ?", channel.InboxID, "line").First(&inbox).Error; err != nil {
|
||||
return nil, fmt.Errorf("line inbox not found for channel inbox_id=%d: %w", channel.InboxID, err)
|
||||
}
|
||||
return &inbox, nil
|
||||
}
|
||||
|
||||
// parseChannelConfig parses the JSON-encoded ChannelConfig string into a map.
|
||||
func (h *LineWebhookHandler) parseChannelConfig(inbox *model.Inbox) map[string]interface{} {
|
||||
if inbox.ChannelConfig == "" {
|
||||
@@ -130,4 +152,4 @@ func (h *LineWebhookHandler) parseChannelConfig(inbox *model.Inbox) map[string]i
|
||||
return map[string]interface{}{}
|
||||
}
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package webhook
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
@@ -10,7 +11,9 @@ import (
|
||||
channelprovider "github.com/gochat/gochat/internal/channel/provider"
|
||||
telegramchannel "github.com/gochat/gochat/internal/channel/telegram"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
channelmodel "github.com/gochat/gochat/internal/model/channel"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// TelegramWebhookHandler processes incoming Telegram webhook HTTP requests via Gin.
|
||||
@@ -32,17 +35,19 @@ import (
|
||||
type TelegramWebhookHandler struct {
|
||||
provider *channelprovider.TelegramProvider
|
||||
telWebhook *telegramchannel.WebhookHandler
|
||||
// inboxRepo would be injected here for inbox lookup in production
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewTelegramWebhookHandler creates a Telegram webhook handler for Gin integration.
|
||||
func NewTelegramWebhookHandler(
|
||||
provider *channelprovider.TelegramProvider,
|
||||
telWebhook *telegramchannel.WebhookHandler,
|
||||
db *gorm.DB,
|
||||
) *TelegramWebhookHandler {
|
||||
return &TelegramWebhookHandler{
|
||||
provider: provider,
|
||||
telWebhook: telWebhook,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,18 +128,20 @@ func (h *TelegramWebhookHandler) HandleTelegramWebhook(c *gin.Context) {
|
||||
// In production: queries GORM for Inbox with channel_type=telegram matching the bot_token.
|
||||
// Reference: Chatwoot: Inbox.find_by(channel: telegram, bot_token: token)
|
||||
func (h *TelegramWebhookHandler) lookupInbox(botToken string) (*model.Inbox, error) {
|
||||
// TODO: Implement with GORM repository
|
||||
// Placeholder — production would use:
|
||||
// var ch channelmodel.ChannelTelegram
|
||||
// db.Where("bot_token = ?", botToken).First(&ch)
|
||||
// var inbox model.Inbox
|
||||
// db.Where("id = ?", ch.InboxID).First(&inbox)
|
||||
//
|
||||
// For now, return a placeholder inbox
|
||||
inbox := &model.Inbox{
|
||||
ChannelType: "telegram",
|
||||
if h.db == nil {
|
||||
return nil, fmt.Errorf("telegram webhook database is not configured")
|
||||
}
|
||||
return inbox, nil
|
||||
|
||||
var channel channelmodel.ChannelTelegram
|
||||
if err := h.db.Where("bot_token = ?", botToken).First(&channel).Error; err != nil {
|
||||
return nil, fmt.Errorf("telegram channel not found for bot_token: %w", err)
|
||||
}
|
||||
|
||||
var inbox model.Inbox
|
||||
if err := h.db.Where("id = ? AND channel_type = ?", channel.InboxID, "telegram").First(&inbox).Error; err != nil {
|
||||
return nil, fmt.Errorf("telegram inbox not found for channel inbox_id=%d: %w", channel.InboxID, err)
|
||||
}
|
||||
return &inbox, nil
|
||||
}
|
||||
|
||||
// maskBotToken masks a bot token for safe logging (show first 8 chars only).
|
||||
@@ -143,4 +150,4 @@ func maskBotToken(token string) string {
|
||||
return token[:8] + "..."
|
||||
}
|
||||
return token
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,15 @@ package webhook
|
||||
// Reference: Facebook webhook adapter pattern (facebook_webhook.go)
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
tiktokchannel "github.com/gochat/gochat/internal/channel/tiktok"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
channelmodel "github.com/gochat/gochat/internal/model/channel"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -36,18 +38,29 @@ func NewTikTokWebhookHandler(tiktokWebhook *tiktokchannel.WebhookHandler, pipeli
|
||||
|
||||
// HandleTikTokWebhook processes incoming TikTok webhook HTTP requests.
|
||||
func (h *TikTokWebhookHandler) HandleTikTokWebhook(c *gin.Context) {
|
||||
inboxIDStr := c.Param("inbox_id")
|
||||
inboxID, err := strconv.ParseUint(inboxIDStr, 10, 32)
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("TikTok webhook: invalid inbox_id %s", inboxIDStr)
|
||||
applogger.L().Errorf("TikTok webhook: failed to read body: %v", err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
c.Request.Body.Close()
|
||||
c.Request.Body = io.NopCloser(bytes.NewReader(body))
|
||||
|
||||
businessID := c.Param("business_id")
|
||||
if businessID == "" {
|
||||
businessID = extractTikTokBusinessID(body)
|
||||
}
|
||||
if businessID == "" {
|
||||
applogger.L().Warn("TikTok webhook: missing business_id in path and payload")
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
|
||||
// Lookup inbox from database
|
||||
inbox, err := h.lookupInbox(uint(inboxID))
|
||||
inbox, err := h.lookupInboxByBusinessID(businessID)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("TikTok webhook: inbox lookup failed for id %d: %v", inboxID, err)
|
||||
applogger.L().Warnf("TikTok webhook: inbox lookup failed for business_id %s: %v", businessID, err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
@@ -55,14 +68,14 @@ func (h *TikTokWebhookHandler) HandleTikTokWebhook(c *gin.Context) {
|
||||
// Parse the webhook event using the channel-level handler
|
||||
event, err := h.tiktokWebhook.HandleWebhookRequest(c.Request)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("TikTok webhook: parse request failed for inbox %d: %v", inboxID, err)
|
||||
applogger.L().Errorf("TikTok webhook: parse request failed for inbox %d: %v", inbox.ID, err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
|
||||
return
|
||||
}
|
||||
|
||||
// Process the event via the pipeline
|
||||
if err := h.pipeline.ProcessUpdate(c.Request.Context(), inbox, *event); err != nil {
|
||||
applogger.L().Errorf("TikTok webhook: process event failed for inbox %d: %v", inboxID, err)
|
||||
applogger.L().Errorf("TikTok webhook: process event failed for inbox %d: %v", inbox.ID, err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
@@ -72,13 +85,6 @@ func (h *TikTokWebhookHandler) HandleTikTokWebhook(c *gin.Context) {
|
||||
|
||||
// HandleTikTokVerification handles TikTok webhook verification (challenge-response).
|
||||
func (h *TikTokWebhookHandler) HandleTikTokVerification(c *gin.Context) {
|
||||
inboxIDStr := c.Param("inbox_id")
|
||||
inboxID, err := strconv.ParseUint(inboxIDStr, 10, 32)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid inbox_id"})
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "failed to read body"})
|
||||
@@ -94,7 +100,7 @@ func (h *TikTokWebhookHandler) HandleTikTokVerification(c *gin.Context) {
|
||||
}
|
||||
|
||||
challenge, _ := verifyReq["challenge"].(string)
|
||||
applogger.L().Infof("TikTok webhook verification: inbox=%d challenge=%s", inboxID, challenge)
|
||||
applogger.L().Infof("TikTok webhook verification: business_id=%s challenge=%s", c.Param("business_id"), challenge)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"challenge": challenge})
|
||||
}
|
||||
@@ -108,6 +114,53 @@ func (h *TikTokWebhookHandler) lookupInbox(inboxID uint) (*model.Inbox, error) {
|
||||
return &inbox, nil
|
||||
}
|
||||
|
||||
// lookupInboxByBusinessID fetches an Inbox through the TikTok channel record.
|
||||
func (h *TikTokWebhookHandler) lookupInboxByBusinessID(businessID string) (*model.Inbox, error) {
|
||||
if h.db == nil {
|
||||
return nil, fmt.Errorf("tiktok webhook database is not configured")
|
||||
}
|
||||
|
||||
var channel channelmodel.ChannelTikTok
|
||||
if err := h.db.Where("tiktok_business_id = ?", businessID).First(&channel).Error; err != nil {
|
||||
return nil, fmt.Errorf("tiktok channel not found for business_id=%s: %w", businessID, err)
|
||||
}
|
||||
|
||||
var inbox model.Inbox
|
||||
if err := h.db.Where("id = ? AND channel_type = ?", channel.InboxID, "tiktok").First(&inbox).Error; err != nil {
|
||||
return nil, fmt.Errorf("tiktok inbox not found for channel inbox_id=%d: %w", channel.InboxID, err)
|
||||
}
|
||||
return &inbox, nil
|
||||
}
|
||||
|
||||
func extractTikTokBusinessID(body []byte) string {
|
||||
var payload struct {
|
||||
BizID string `json:"biz_id"`
|
||||
BusinessID string `json:"business_id"`
|
||||
TikTokBusinessID string `json:"tiktok_business_id"`
|
||||
Data struct {
|
||||
BizID string `json:"biz_id"`
|
||||
BusinessID string `json:"business_id"`
|
||||
TikTokBusinessID string `json:"tiktok_business_id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, candidate := range []string{
|
||||
payload.BizID,
|
||||
payload.BusinessID,
|
||||
payload.TikTokBusinessID,
|
||||
payload.Data.BizID,
|
||||
payload.Data.BusinessID,
|
||||
payload.Data.TikTokBusinessID,
|
||||
} {
|
||||
if candidate != "" {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseChannelConfig parses the JSON-encoded ChannelConfig string into a map.
|
||||
func (h *TikTokWebhookHandler) parseChannelConfig(inbox *model.Inbox) map[string]interface{} {
|
||||
if inbox.ChannelConfig == "" {
|
||||
@@ -119,4 +172,4 @@ func (h *TikTokWebhookHandler) parseChannelConfig(inbox *model.Inbox) map[string
|
||||
return map[string]interface{}{}
|
||||
}
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,17 +4,19 @@ package webhook
|
||||
// Reference: Facebook webhook adapter pattern (facebook_webhook.go)
|
||||
//
|
||||
// URL patterns:
|
||||
// /webhooks/twilio/sms/:inbox_id — inbound SMS/MMS
|
||||
// /webhooks/twilio/status/:inbox_id — delivery status callbacks
|
||||
// /webhooks/sms/:phone_number — Chatwoot-compatible inbound SMS/MMS
|
||||
// /webhooks/twilio/sms/:phone_number — legacy inbound SMS/MMS
|
||||
// /webhooks/twilio/status/:phone_number — delivery status callbacks
|
||||
//
|
||||
// Method: POST (Twilio sends form-encoded data, not JSON)
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
twiliochannel "github.com/gochat/gochat/internal/channel/twilio"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
channelmodel "github.com/gochat/gochat/internal/model/channel"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -37,18 +39,17 @@ func NewTwilioWebhookHandler(twilioWebhook *twiliochannel.WebhookHandler, db *go
|
||||
|
||||
// HandleTwilioInboundSMS processes an incoming Twilio SMS webhook Gin request.
|
||||
func (h *TwilioWebhookHandler) HandleTwilioInboundSMS(c *gin.Context) {
|
||||
inboxIDStr := c.Param("inbox_id")
|
||||
inboxID, err := strconv.ParseUint(inboxIDStr, 10, 32)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Twilio webhook: invalid inbox_id %s", inboxIDStr)
|
||||
phoneNumber := c.Param("phone_number")
|
||||
if phoneNumber == "" {
|
||||
applogger.L().Warn("Twilio webhook: missing phone_number in path")
|
||||
c.Data(http.StatusOK, "application/xml", []byte("<Response></Response>"))
|
||||
return
|
||||
}
|
||||
|
||||
// Lookup inbox from database
|
||||
inbox, err := h.lookupInbox(uint(inboxID))
|
||||
inbox, err := h.lookupInboxByPhoneNumber(phoneNumber)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Twilio webhook: inbox lookup failed for id %d: %v", inboxID, err)
|
||||
applogger.L().Warnf("Twilio webhook: inbox lookup failed for phone_number %s: %v", phoneNumber, err)
|
||||
c.Data(http.StatusOK, "application/xml", []byte("<Response></Response>"))
|
||||
return
|
||||
}
|
||||
@@ -60,18 +61,17 @@ func (h *TwilioWebhookHandler) HandleTwilioInboundSMS(c *gin.Context) {
|
||||
|
||||
// HandleTwilioDeliveryStatus processes a Twilio delivery status callback.
|
||||
func (h *TwilioWebhookHandler) HandleTwilioDeliveryStatus(c *gin.Context) {
|
||||
inboxIDStr := c.Param("inbox_id")
|
||||
inboxID, err := strconv.ParseUint(inboxIDStr, 10, 32)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Twilio status webhook: invalid inbox_id %s", inboxIDStr)
|
||||
phoneNumber := c.Param("phone_number")
|
||||
if phoneNumber == "" {
|
||||
applogger.L().Warn("Twilio status webhook: missing phone_number in path")
|
||||
c.Status(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
// Lookup inbox from database
|
||||
inbox, err := h.lookupInbox(uint(inboxID))
|
||||
inbox, err := h.lookupInboxByPhoneNumber(phoneNumber)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Twilio status webhook: inbox lookup failed for id %d: %v", inboxID, err)
|
||||
applogger.L().Warnf("Twilio status webhook: inbox lookup failed for phone_number %s: %v", phoneNumber, err)
|
||||
c.Status(http.StatusOK)
|
||||
return
|
||||
}
|
||||
@@ -87,4 +87,23 @@ func (h *TwilioWebhookHandler) lookupInbox(inboxID uint) (*model.Inbox, error) {
|
||||
return nil, err
|
||||
}
|
||||
return &inbox, nil
|
||||
}
|
||||
}
|
||||
|
||||
// lookupInboxByPhoneNumber fetches an Inbox through the Twilio SMS channel record.
|
||||
// Chatwoot exposes /webhooks/sms/:phone_number and routes by the phone number.
|
||||
func (h *TwilioWebhookHandler) lookupInboxByPhoneNumber(phoneNumber string) (*model.Inbox, error) {
|
||||
if h.db == nil {
|
||||
return nil, fmt.Errorf("twilio webhook database is not configured")
|
||||
}
|
||||
|
||||
var channel channelmodel.ChannelTwilioSMS
|
||||
if err := h.db.Where("phone_number = ?", phoneNumber).First(&channel).Error; err != nil {
|
||||
return nil, fmt.Errorf("twilio sms channel not found for phone_number=%s: %w", phoneNumber, err)
|
||||
}
|
||||
|
||||
var inbox model.Inbox
|
||||
if err := h.db.Where("id = ? AND channel_type IN ?", channel.InboxID, []string{"twilio_sms", "sms"}).First(&inbox).Error; err != nil {
|
||||
return nil, fmt.Errorf("twilio inbox not found for channel inbox_id=%d: %w", channel.InboxID, err)
|
||||
}
|
||||
return &inbox, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
channelmodel "github.com/gochat/gochat/internal/model/channel"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newWebhookLookupTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
|
||||
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
&model.Inbox{},
|
||||
&channelmodel.ChannelTelegram{},
|
||||
&channelmodel.ChannelLINE{},
|
||||
&channelmodel.ChannelTwilioSMS{},
|
||||
&channelmodel.ChannelTikTok{},
|
||||
); err != nil {
|
||||
t.Fatalf("migrate webhook lookup models: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func seedWebhookInbox(t *testing.T, db *gorm.DB, channelType string) model.Inbox {
|
||||
t.Helper()
|
||||
|
||||
inbox := model.Inbox{
|
||||
AccountID: 1,
|
||||
Name: channelType + " inbox",
|
||||
ChannelType: channelType,
|
||||
ChannelID: 1,
|
||||
Enabled: true,
|
||||
}
|
||||
if err := db.Create(&inbox).Error; err != nil {
|
||||
t.Fatalf("create inbox: %v", err)
|
||||
}
|
||||
return inbox
|
||||
}
|
||||
|
||||
func TestTelegramWebhookLookupInboxByBotToken(t *testing.T) {
|
||||
db := newWebhookLookupTestDB(t)
|
||||
inbox := seedWebhookInbox(t, db, "telegram")
|
||||
channel := channelmodel.ChannelTelegram{
|
||||
AccountID: 1,
|
||||
InboxID: inbox.ID,
|
||||
BotToken: "123:secret-token",
|
||||
BotName: "support_bot",
|
||||
}
|
||||
if err := db.Create(&channel).Error; err != nil {
|
||||
t.Fatalf("create telegram channel: %v", err)
|
||||
}
|
||||
|
||||
h := NewTelegramWebhookHandler(nil, nil, db)
|
||||
found, err := h.lookupInbox("123:secret-token")
|
||||
if err != nil {
|
||||
t.Fatalf("lookup inbox: %v", err)
|
||||
}
|
||||
if found.ID != inbox.ID || found.ChannelType != "telegram" {
|
||||
t.Fatalf("unexpected inbox: id=%d type=%s", found.ID, found.ChannelType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLineWebhookLookupInboxByLineChannelID(t *testing.T) {
|
||||
db := newWebhookLookupTestDB(t)
|
||||
inbox := seedWebhookInbox(t, db, "line")
|
||||
channel := channelmodel.ChannelLINE{
|
||||
AccountID: 1,
|
||||
InboxID: inbox.ID,
|
||||
ChannelID: "line-channel-1",
|
||||
Name: "LINE OA",
|
||||
}
|
||||
if err := db.Create(&channel).Error; err != nil {
|
||||
t.Fatalf("create line channel: %v", err)
|
||||
}
|
||||
|
||||
h := NewLineWebhookHandler(nil, nil, nil, db)
|
||||
found, err := h.lookupInboxByLineChannelID("line-channel-1")
|
||||
if err != nil {
|
||||
t.Fatalf("lookup inbox: %v", err)
|
||||
}
|
||||
if found.ID != inbox.ID || found.ChannelType != "line" {
|
||||
t.Fatalf("unexpected inbox: id=%d type=%s", found.ID, found.ChannelType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTwilioWebhookLookupInboxByPhoneNumber(t *testing.T) {
|
||||
db := newWebhookLookupTestDB(t)
|
||||
inbox := seedWebhookInbox(t, db, "twilio_sms")
|
||||
channel := channelmodel.ChannelTwilioSMS{
|
||||
AccountID: 1,
|
||||
InboxID: inbox.ID,
|
||||
AccountSID: "AC123",
|
||||
PhoneNumber: "+15551234567",
|
||||
MessagingServiceSID: "MG123",
|
||||
}
|
||||
if err := db.Create(&channel).Error; err != nil {
|
||||
t.Fatalf("create twilio channel: %v", err)
|
||||
}
|
||||
|
||||
h := NewTwilioWebhookHandler(nil, db)
|
||||
found, err := h.lookupInboxByPhoneNumber("+15551234567")
|
||||
if err != nil {
|
||||
t.Fatalf("lookup inbox: %v", err)
|
||||
}
|
||||
if found.ID != inbox.ID || found.ChannelType != "twilio_sms" {
|
||||
t.Fatalf("unexpected inbox: id=%d type=%s", found.ID, found.ChannelType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTikTokWebhookLookupInboxByBusinessIDAndPayloadExtractor(t *testing.T) {
|
||||
db := newWebhookLookupTestDB(t)
|
||||
inbox := seedWebhookInbox(t, db, "tiktok")
|
||||
channel := channelmodel.ChannelTikTok{
|
||||
AccountID: 1,
|
||||
InboxID: inbox.ID,
|
||||
TikTokBusinessID: "biz-123",
|
||||
WebhookVerifyToken: "verify-token",
|
||||
}
|
||||
if err := db.Create(&channel).Error; err != nil {
|
||||
t.Fatalf("create tiktok channel: %v", err)
|
||||
}
|
||||
|
||||
h := NewTikTokWebhookHandler(nil, nil, db)
|
||||
found, err := h.lookupInboxByBusinessID("biz-123")
|
||||
if err != nil {
|
||||
t.Fatalf("lookup inbox: %v", err)
|
||||
}
|
||||
if found.ID != inbox.ID || found.ChannelType != "tiktok" {
|
||||
t.Fatalf("unexpected inbox: id=%d type=%s", found.ID, found.ChannelType)
|
||||
}
|
||||
|
||||
if got := extractTikTokBusinessID([]byte(`{"data":{"business_id":"biz-123"}}`)); got != "biz-123" {
|
||||
t.Fatalf("unexpected extracted business id: %s", got)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,11 @@ import (
|
||||
// Reference: P2E §4 — webhook authentication per channel type
|
||||
func WebhookAuth(registry *auth.WebhookTokenRegistry) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if registry == nil {
|
||||
response.AbortWithStatusError(c, http.StatusUnauthorized, response.ErrUnauthorized, "Webhook registry not configured")
|
||||
return
|
||||
}
|
||||
|
||||
channelType := c.Param("channel_type")
|
||||
identifier := c.Param("identifier")
|
||||
|
||||
@@ -23,4 +28,4 @@ func WebhookAuth(registry *auth.WebhookTokenRegistry) gin.HandlerFunc {
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,12 +31,12 @@ type ChannelTikTok struct {
|
||||
InboxID uint `gorm:"index" json:"inbox_id,omitempty"`
|
||||
|
||||
// TikTok Business account ID (obtained after OAuth authorization)
|
||||
TikTokBusinessID string `gorm:"type:varchar(255);not null" json:"tiktok_business_id"`
|
||||
TikTokBusinessID string `gorm:"column:tiktok_business_id;type:varchar(255);not null" json:"tiktok_business_id"`
|
||||
|
||||
// OAuth2 tokens (obtained via BuildAuthURL → ExchangeToken flow)
|
||||
AccessToken string `gorm:"type:varchar(512)" json:"access_token,omitempty"`
|
||||
RefreshToken string `gorm:"type:varchar(512)" json:"refresh_token,omitempty"`
|
||||
TokenExpiresAt time.Time `gorm:"" json:"token_expires_at,omitempty"`
|
||||
AccessToken string `gorm:"type:varchar(512)" json:"access_token,omitempty"`
|
||||
RefreshToken string `gorm:"type:varchar(512)" json:"refresh_token,omitempty"`
|
||||
TokenExpiresAt time.Time `gorm:"" json:"token_expires_at,omitempty"`
|
||||
|
||||
// Webhook verification token (set during channel creation for webhook setup)
|
||||
WebhookVerifyToken string `gorm:"type:varchar(255)" json:"webhook_verify_token,omitempty"`
|
||||
@@ -63,4 +63,4 @@ func (c ChannelTikTok) GetChannelBase() ChannelBase {
|
||||
func (c ChannelTikTok) GetChannelType() string { return "tiktok" }
|
||||
|
||||
// TableName returns the GORM table name for ChannelTikTok.
|
||||
func (ChannelTikTok) TableName() string { return "channel_tiktoks" }
|
||||
func (ChannelTikTok) TableName() string { return "channel_tiktoks" }
|
||||
|
||||
+114
-33
@@ -281,10 +281,10 @@ func RegisterRoutes(
|
||||
apiV2.Use(middleware.AuthMiddleware(jwtCfg))
|
||||
registerV2Routes(apiV2, handlers)
|
||||
|
||||
// Webhook callback routes — channel-specific auth
|
||||
// Reference: Chatwoot webhook routes for FB/WhatsApp/Telegram
|
||||
// Webhook callback routes.
|
||||
// Reference: Chatwoot routes provider-specific public webhook paths and lets
|
||||
// each provider handler verify its own token/signature contract.
|
||||
webhookGroup := engine.Group("/webhooks")
|
||||
webhookGroup.Use(middleware.WebhookAuth(webhookRegistry))
|
||||
|
||||
// Facebook/Instagram webhook — Meta Business Suite combined endpoint
|
||||
// GET: webhook verification (hub.mode=subscribe, hub.verify_token, hub.challenge)
|
||||
@@ -298,59 +298,140 @@ func RegisterRoutes(
|
||||
|
||||
// Telegram webhook — bot token in URL path for routing
|
||||
// Reference: Chatwoot routes at /webhooks/telegram/:bot_token
|
||||
if handlers.TelegramWebhook != nil {
|
||||
tgGroup := webhookGroup.Group("/telegram")
|
||||
tgGroup.POST("/:bot_token", handlers.TelegramWebhook.HandleTelegramWebhook)
|
||||
}
|
||||
tgGroup := webhookGroup.Group("/telegram")
|
||||
tgGroup.POST("/:bot_token", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TelegramWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TelegramWebhook.HandleTelegramWebhook(c)
|
||||
})
|
||||
|
||||
// WhatsApp webhook — Cloud API webhook verification + incoming events
|
||||
// GET: webhook verification (hub.mode=subscribe, hub.verify_token, hub.challenge)
|
||||
// POST: incoming message/event processing (X-Hub-Signature-256 validated)
|
||||
// Reference: Chatwoot routes at /webhooks/whatsapp/:phone_number
|
||||
// Reference: WhatsApp Cloud API https://developers.facebook.com/docs/whatsapp/cloud-api/get-started#verify-webhook
|
||||
if handlers.WhatsAppWebhook != nil {
|
||||
waGroup := webhookGroup.Group("/whatsapp")
|
||||
waGroup.GET("/:phone_number_id", handlers.WhatsAppWebhook.HandleWhatsAppVerification)
|
||||
waGroup.POST("/:phone_number_id", handlers.WhatsAppWebhook.HandleWhatsAppWebhook)
|
||||
}
|
||||
waGroup := webhookGroup.Group("/whatsapp")
|
||||
waGroup.GET("/:phone_number", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.WhatsAppWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.WhatsAppWebhook.HandleWhatsAppVerification(c)
|
||||
})
|
||||
waGroup.POST("/:phone_number", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.WhatsAppWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.WhatsAppWebhook.HandleWhatsAppWebhook(c)
|
||||
})
|
||||
|
||||
// TikTok webhook — Business API event notifications
|
||||
// GET: webhook URL verification request
|
||||
// POST: incoming message/event processing (X-TikTok-Signature validated)
|
||||
// Reference: TikTok Business API https://business-api.tiktok.com/portal/docs?id=1739584855420928
|
||||
if handlers.TikTokWebhook != nil {
|
||||
ttGroup := webhookGroup.Group("/tiktok")
|
||||
ttGroup.GET("/:business_id", handlers.TikTokWebhook.HandleTikTokVerification)
|
||||
ttGroup.POST("/:business_id", handlers.TikTokWebhook.HandleTikTokWebhook)
|
||||
}
|
||||
ttGroup := webhookGroup.Group("/tiktok")
|
||||
ttGroup.POST("", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TikTokWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TikTokWebhook.HandleTikTokWebhook(c)
|
||||
})
|
||||
ttGroup.GET("/:business_id", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TikTokWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TikTokWebhook.HandleTikTokVerification(c)
|
||||
})
|
||||
ttGroup.POST("/:business_id", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TikTokWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TikTokWebhook.HandleTikTokWebhook(c)
|
||||
})
|
||||
|
||||
// LINE webhook — Messaging API event notifications
|
||||
// POST: incoming message/event processing (X-Line-Signature HMAC-SHA256 validated)
|
||||
// Reference: LINE Messaging API https://developers.line.biz/en/docs/messaging-api/receiving-messages/
|
||||
if handlers.LineWebhook != nil {
|
||||
lineGroup := webhookGroup.Group("/line")
|
||||
lineGroup.POST("/:channel_id", handlers.LineWebhook.HandleLineWebhook)
|
||||
}
|
||||
lineGroup := webhookGroup.Group("/line")
|
||||
lineGroup.POST("/:line_channel_id", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.LineWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.LineWebhook.HandleLineWebhook(c)
|
||||
})
|
||||
|
||||
// Twilio SMS webhook — inbound SMS/MMS + delivery status callbacks
|
||||
// POST /sms/:phone_number: inbound SMS/MMS messages (form-encoded body, TwiML response)
|
||||
// POST /status/:phone_number: delivery status callbacks (delivered/undelivered/failed)
|
||||
// Reference: Twilio SMS API https://www.twilio.com/docs/sms/api/message-resource
|
||||
if handlers.TwilioWebhook != nil {
|
||||
twilioGroup := webhookGroup.Group("/twilio")
|
||||
twilioGroup.POST("/sms/:phone_number", handlers.TwilioWebhook.HandleTwilioInboundSMS)
|
||||
twilioGroup.POST("/status/:phone_number", handlers.TwilioWebhook.HandleTwilioDeliveryStatus)
|
||||
}
|
||||
webhookGroup.POST("/sms/:phone_number", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TwilioWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TwilioWebhook.HandleTwilioInboundSMS(c)
|
||||
})
|
||||
twilioGroup := webhookGroup.Group("/twilio")
|
||||
twilioGroup.POST("/sms/:phone_number", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TwilioWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TwilioWebhook.HandleTwilioInboundSMS(c)
|
||||
})
|
||||
twilioGroup.POST("/status/:phone_number", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TwilioWebhook == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TwilioWebhook.HandleTwilioDeliveryStatus(c)
|
||||
})
|
||||
|
||||
// Twitter webhook — Account Activity API CRC validation + event processing
|
||||
// GET: CRC challenge response (crc_token query param)
|
||||
// POST: incoming DM/event processing
|
||||
// Reference: Twitter API v2 Account Activity API https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/account-activity-api
|
||||
if handlers.TwitterChannel != nil {
|
||||
twWebhookGroup := webhookGroup.Group("/twitter")
|
||||
twWebhookGroup.GET("/webhook", handlers.TwitterChannel.WebhookCRC)
|
||||
twWebhookGroup.POST("/webhook", handlers.TwitterChannel.WebhookEvent)
|
||||
}
|
||||
twWebhookGroup := webhookGroup.Group("/twitter")
|
||||
twWebhookGroup.GET("", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TwitterChannel == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TwitterChannel.WebhookCRC(c)
|
||||
})
|
||||
twWebhookGroup.POST("", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TwitterChannel == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TwitterChannel.WebhookEvent(c)
|
||||
})
|
||||
// Legacy GoChat aliases kept for already configured Twitter webhooks.
|
||||
twWebhookGroup.GET("/webhook", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TwitterChannel == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TwitterChannel.WebhookCRC(c)
|
||||
})
|
||||
twWebhookGroup.POST("/webhook", func(c *gin.Context) {
|
||||
if handlers == nil || handlers.TwitterChannel == nil {
|
||||
chatwootParityStub(c)
|
||||
return
|
||||
}
|
||||
handlers.TwitterChannel.WebhookEvent(c)
|
||||
})
|
||||
|
||||
webhookGroup.GET("/instagram", chatwootParityStub)
|
||||
webhookGroup.POST("/instagram", chatwootParityStub)
|
||||
webhookGroup.POST("/shopify", chatwootParityStub)
|
||||
|
||||
// Microsoft webhook — Graph API subscription validation + notifications
|
||||
// POST: validation request (returns validationToken) + change notifications
|
||||
@@ -371,8 +452,8 @@ func RegisterRoutes(
|
||||
emailWebhookGroup.GET("/:inbox_id/verification", handlers.EmailWebhook.HandleEmailVerification)
|
||||
}
|
||||
|
||||
// Generic webhook fallback for other channels (WebWidget, etc.)
|
||||
webhookGroup.Any("/:channel_type/:identifier", webhookStub)
|
||||
// Generic webhook success fallback was removed for P6.7: provider paths above
|
||||
// should either process/verify the callback or return explicit not-implemented.
|
||||
|
||||
// WebSocket endpoints (ref: Chatwoot ActionCable mount at /cable)
|
||||
// P9: real-time communication — WebSocket upgrade with JWT/pubsub_token auth
|
||||
|
||||
@@ -38,6 +38,15 @@ func TestRegisterRoutesBootsWithChatwootParityConflictGroups(t *testing.T) {
|
||||
"PUT /public/api/v1/inboxes/:inbox_id/contacts/:contact_id/conversations/:conversation_id/messages/:message_id",
|
||||
"GET /api/v2/accounts/:account_id/reports/summary",
|
||||
"GET /api/v2/accounts/:account_id/live_reports/grouped_conversation_metrics",
|
||||
"GET /webhooks/twitter",
|
||||
"POST /webhooks/twitter",
|
||||
"POST /webhooks/telegram/:bot_token",
|
||||
"POST /webhooks/line/:line_channel_id",
|
||||
"POST /webhooks/sms/:phone_number",
|
||||
"GET /webhooks/whatsapp/:phone_number",
|
||||
"POST /webhooks/whatsapp/:phone_number",
|
||||
"POST /webhooks/tiktok",
|
||||
"POST /webhooks/shopify",
|
||||
}
|
||||
|
||||
for _, key := range expected {
|
||||
|
||||
Reference in New Issue
Block a user