feat(webhook): implement instagram and shopify ingress
This commit is contained in:
@@ -28,23 +28,25 @@ import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
fbchannel "github.com/gochat/gochat/internal/channel/facebook"
|
||||
"github.com/gochat/gochat/internal/channel"
|
||||
fbchannel "github.com/gochat/gochat/internal/channel/facebook"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
channelmodel "github.com/gochat/gochat/internal/model/channel"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// FacebookWebhookHandler processes Facebook/Instagram webhook requests via Gin.
|
||||
type FacebookWebhookHandler struct {
|
||||
fbProvider *fbchannel.FacebookProvider
|
||||
igProvider *fbchannel.InstagramProvider
|
||||
fbProvider *fbchannel.FacebookProvider
|
||||
igProvider *fbchannel.InstagramProvider
|
||||
webhookParser *fbchannel.WebhookParser
|
||||
db *gorm.DB
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewFacebookWebhookHandler creates a Facebook/Instagram webhook handler for Gin integration.
|
||||
@@ -70,25 +72,20 @@ func NewFacebookWebhookHandler(
|
||||
// Facebook sends a GET request with hub.mode=subscribe when verifying a new webhook subscription.
|
||||
// The server must respond with the hub.challenge value if hub.verify_token matches.
|
||||
func (h *FacebookWebhookHandler) HandleFacebookVerification(c *gin.Context) {
|
||||
inboxIDStr := c.Param("inbox_id")
|
||||
inboxID, err := strconv.ParseUint(inboxIDStr, 10, 32)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Facebook webhook verification: invalid inbox_id %s", inboxIDStr)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid inbox_id"})
|
||||
return
|
||||
}
|
||||
pageID := c.Param("page_id")
|
||||
inboxID, _ := parseOptionalUintParam(c.Param("inbox_id"))
|
||||
|
||||
// Extract verification parameters
|
||||
queryParams := map[string]string{
|
||||
"hub.mode": c.Query("hub.mode"),
|
||||
"hub.verify_token": c.Query("hub.verify_token"),
|
||||
"hub.challenge": c.Query("hub.challenge"),
|
||||
"hub.mode": c.Query("hub.mode"),
|
||||
"hub.verify_token": c.Query("hub.verify_token"),
|
||||
"hub.challenge": c.Query("hub.challenge"),
|
||||
}
|
||||
|
||||
// Look up the inbox to find the verify token stored in ChannelConfig
|
||||
inbox, err := h.lookupInbox(uint(inboxID))
|
||||
inbox, err := h.lookupFacebookInbox(pageID, inboxID)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Facebook webhook verification: inbox lookup failed for id %d: %v", inboxID, err)
|
||||
applogger.L().Warnf("Facebook webhook verification: inbox lookup failed for page_id=%s inbox_id=%d: %v", pageID, inboxID, err)
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "inbox not found"})
|
||||
return
|
||||
}
|
||||
@@ -96,7 +93,7 @@ func (h *FacebookWebhookHandler) HandleFacebookVerification(c *gin.Context) {
|
||||
// Resolve the verify token from channel config
|
||||
verifyToken := h.resolveVerifyToken(inbox)
|
||||
if verifyToken == "" {
|
||||
applogger.L().Warnf("Facebook webhook verification: no verify_token for inbox %d", inboxID)
|
||||
applogger.L().Warnf("Facebook webhook verification: no verify_token for inbox %d", inbox.ID)
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "verify token not configured"})
|
||||
return
|
||||
}
|
||||
@@ -104,12 +101,12 @@ func (h *FacebookWebhookHandler) HandleFacebookVerification(c *gin.Context) {
|
||||
// Delegate to the channel-level verification logic
|
||||
challenge, ok := fbchannel.VerifyWebhookChallenge(queryParams, verifyToken)
|
||||
if !ok {
|
||||
applogger.L().Warnf("Facebook webhook verification: token mismatch for inbox %d", inboxID)
|
||||
applogger.L().Warnf("Facebook webhook verification: token mismatch for inbox %d", inbox.ID)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "verification failed"})
|
||||
return
|
||||
}
|
||||
|
||||
applogger.L().Infof("Facebook webhook verified for inbox %d", inboxID)
|
||||
applogger.L().Infof("Facebook webhook verified for inbox %d", inbox.ID)
|
||||
|
||||
// Facebook expects the challenge value as the plain response body
|
||||
c.String(http.StatusOK, challenge)
|
||||
@@ -131,18 +128,13 @@ func (h *FacebookWebhookHandler) HandleFacebookVerification(c *gin.Context) {
|
||||
// 4. Delegate to appropriate provider's ProcessIncoming method
|
||||
// 5. Return 200 OK immediately (Facebook retries on non-200)
|
||||
func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
inboxIDStr := c.Param("inbox_id")
|
||||
inboxID, err := strconv.ParseUint(inboxIDStr, 10, 32)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Facebook webhook: invalid inbox_id %s", inboxIDStr)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
pageID := c.Param("page_id")
|
||||
inboxID, _ := parseOptionalUintParam(c.Param("inbox_id"))
|
||||
|
||||
// Read request body
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Facebook webhook: failed to read body for inbox %d: %v", inboxID, err)
|
||||
applogger.L().Errorf("Facebook webhook: failed to read body for page_id=%s inbox_id=%d: %v", pageID, inboxID, err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
@@ -150,9 +142,9 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
|
||||
// Validate webhook signature (X-Hub-Signature-256)
|
||||
signatureHeader := c.GetHeader("X-Hub-Signature-256")
|
||||
inbox, err := h.lookupInbox(uint(inboxID))
|
||||
inbox, err := h.lookupFacebookInbox(pageID, inboxID)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Facebook webhook: inbox lookup failed for id %d: %v", inboxID, err)
|
||||
applogger.L().Warnf("Facebook webhook: inbox lookup failed for page_id=%s inbox_id=%d: %v", pageID, inboxID, err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
@@ -161,7 +153,7 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
appSecret := h.resolveAppSecret(inbox)
|
||||
if appSecret != "" && signatureHeader != "" {
|
||||
if !fbchannel.ValidateWebhookSignature(appSecret, signatureHeader, body) {
|
||||
applogger.L().Warnf("Facebook webhook: signature validation failed for inbox %d", inboxID)
|
||||
applogger.L().Warnf("Facebook webhook: signature validation failed for inbox %d", inbox.ID)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "invalid signature"})
|
||||
return
|
||||
}
|
||||
@@ -171,12 +163,12 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
// object="page" → Facebook Messenger, object="instagram" → Instagram DMs
|
||||
parsedEvents, err := h.webhookParser.ParseWebhookPayload(body)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Facebook webhook: failed to parse payload for inbox %d: %v", inboxID, err)
|
||||
applogger.L().Errorf("Facebook webhook: failed to parse payload for inbox %d: %v", inbox.ID, err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
|
||||
applogger.L().Infof("Facebook webhook: received %d events for inbox %d", len(parsedEvents), inboxID)
|
||||
applogger.L().Infof("Facebook webhook: received %d events for inbox %d", len(parsedEvents), inbox.ID)
|
||||
|
||||
// Process each parsed event
|
||||
for _, event := range parsedEvents {
|
||||
@@ -188,7 +180,7 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
}
|
||||
applogger.L().Debug("Facebook webhook: skipping echo message",
|
||||
"mid", mid,
|
||||
"inbox_id", inboxID,
|
||||
"inbox_id", inbox.ID,
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -197,7 +189,7 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
if fbchannel.IsDeliveryOrReadReceipt(event) {
|
||||
applogger.L().Debug("Facebook webhook: skipping delivery/read receipt",
|
||||
"event_type", event.EventType,
|
||||
"inbox_id", inboxID,
|
||||
"inbox_id", inbox.ID,
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -206,7 +198,7 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
if fbchannel.IsThreadControlEvent(event) {
|
||||
applogger.L().Debug("Facebook webhook: skipping thread control event",
|
||||
"event_type", event.EventType,
|
||||
"inbox_id", inboxID,
|
||||
"inbox_id", inbox.ID,
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -217,7 +209,7 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
if fbchannel.IsIGCommentEvent(event) {
|
||||
applogger.L().Info("Facebook webhook: processing Instagram comment event",
|
||||
"event_type", event.EventType,
|
||||
"inbox_id", inboxID,
|
||||
"inbox_id", inbox.ID,
|
||||
)
|
||||
|
||||
commentMsg, err := h.igProvider.ProcessCommentIncoming(c.Request.Context(), inbox, event.Comment, event.EventType)
|
||||
@@ -237,7 +229,7 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
if !fbchannel.ShouldCreateMessage(event) {
|
||||
applogger.L().Debug("Facebook webhook: skipping non-message event",
|
||||
"event_type", event.EventType,
|
||||
"inbox_id", inboxID,
|
||||
"inbox_id", inbox.ID,
|
||||
)
|
||||
continue
|
||||
}
|
||||
@@ -260,7 +252,7 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
continue
|
||||
}
|
||||
default:
|
||||
applogger.L().Warnf("Facebook webhook: unknown object type %s for inbox %d", event.Object, inboxID)
|
||||
applogger.L().Warnf("Facebook webhook: unknown object type %s for inbox %d", event.Object, inbox.ID)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -276,6 +268,63 @@ func (h *FacebookWebhookHandler) HandleFacebookWebhook(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
// HandleInstagramVerification handles the Chatwoot-compatible no-param Instagram webhook verification route.
|
||||
func (h *FacebookWebhookHandler) HandleInstagramVerification(c *gin.Context) {
|
||||
token := c.Query("hub.verify_token")
|
||||
challenge := c.Query("hub.challenge")
|
||||
if h.validInstagramVerifyToken(token) {
|
||||
applogger.L().Info("Instagram webhook verified")
|
||||
c.String(http.StatusOK, challenge)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Error; wrong verify token"})
|
||||
}
|
||||
|
||||
// HandleInstagramWebhook processes the Chatwoot-compatible no-param Instagram event route.
|
||||
func (h *FacebookWebhookHandler) HandleInstagramWebhook(c *gin.Context) {
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Instagram webhook: failed to read body: %v", err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
defer c.Request.Body.Close()
|
||||
|
||||
parsedEvents, err := h.webhookParser.ParseWebhookPayload(body)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Instagram webhook: failed to parse payload: %v", err)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ignored"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(parsedEvents) == 0 {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
return
|
||||
}
|
||||
if parsedEvents[0].Object != "instagram" {
|
||||
applogger.L().Warnf("Message is not received from the instagram webhook event: %s", parsedEvents[0].Object)
|
||||
c.Status(http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.verifyInstagramSignature(c, body, parsedEvents); err != nil {
|
||||
applogger.L().Warnf("Instagram webhook: signature verification failed: %v", err)
|
||||
c.Status(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
for _, event := range parsedEvents {
|
||||
inbox, err := h.lookupInstagramInboxForEvent(event)
|
||||
if err != nil {
|
||||
applogger.L().Warnf("Instagram webhook: inbox lookup failed for page_id=%s sender=%s recipient=%s: %v", event.PageID, event.SenderID, event.RecipientID, err)
|
||||
continue
|
||||
}
|
||||
h.processInstagramEvent(c, inbox, event)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
}
|
||||
|
||||
// ===========================
|
||||
// Helper methods
|
||||
// ===========================
|
||||
@@ -289,6 +338,124 @@ func (h *FacebookWebhookHandler) lookupInbox(inboxID uint) (*model.Inbox, error)
|
||||
return &inbox, nil
|
||||
}
|
||||
|
||||
func (h *FacebookWebhookHandler) lookupFacebookInbox(pageID string, inboxID uint) (*model.Inbox, error) {
|
||||
if inboxID != 0 {
|
||||
return h.lookupInbox(inboxID)
|
||||
}
|
||||
return h.lookupInboxByFacebookPageID(pageID)
|
||||
}
|
||||
|
||||
func (h *FacebookWebhookHandler) lookupInboxByFacebookPageID(pageID string) (*model.Inbox, error) {
|
||||
var fb channelmodel.ChannelFacebook
|
||||
if err := h.db.Where("page_id = ?", pageID).First(&fb).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h.lookupInbox(fb.InboxID)
|
||||
}
|
||||
|
||||
func (h *FacebookWebhookHandler) lookupInstagramInboxForEvent(event *fbchannel.ParsedWebhookEvent) (*model.Inbox, error) {
|
||||
instagramID := event.RecipientID
|
||||
if fbchannel.IsEchoMessage(event) && event.SenderID != "" {
|
||||
instagramID = event.SenderID
|
||||
}
|
||||
if instagramID == "" {
|
||||
instagramID = event.PageID
|
||||
}
|
||||
|
||||
var ig channelmodel.ChannelInstagram
|
||||
if err := h.db.Where("instagram_account_id = ? OR instagram_business_account_id = ?", instagramID, instagramID).First(&ig).Error; err == nil {
|
||||
return h.lookupInbox(ig.InboxID)
|
||||
}
|
||||
|
||||
var fb channelmodel.ChannelFacebook
|
||||
if err := h.db.Where("instagram_business_account_id = ?", instagramID).First(&fb).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return h.lookupInbox(fb.InboxID)
|
||||
}
|
||||
|
||||
func (h *FacebookWebhookHandler) validInstagramVerifyToken(token string) bool {
|
||||
if token == "" {
|
||||
return false
|
||||
}
|
||||
return token == os.Getenv("IG_VERIFY_TOKEN") || token == os.Getenv("INSTAGRAM_VERIFY_TOKEN")
|
||||
}
|
||||
|
||||
func (h *FacebookWebhookHandler) verifyInstagramSignature(c *gin.Context, body []byte, events []*fbchannel.ParsedWebhookEvent) error {
|
||||
signatureHeader := c.GetHeader("X-Hub-Signature-256")
|
||||
if signatureHeader == "" {
|
||||
return strconv.ErrSyntax
|
||||
}
|
||||
|
||||
for _, secret := range h.instagramAppSecrets(events) {
|
||||
if fbchannel.ValidateWebhookSignature(secret, signatureHeader, body) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return strconv.ErrSyntax
|
||||
}
|
||||
|
||||
func (h *FacebookWebhookHandler) instagramAppSecrets(events []*fbchannel.ParsedWebhookEvent) []string {
|
||||
seen := map[string]bool{}
|
||||
secrets := make([]string, 0, 4)
|
||||
add := func(secret string) {
|
||||
if secret != "" && !seen[secret] {
|
||||
seen[secret] = true
|
||||
secrets = append(secrets, secret)
|
||||
}
|
||||
}
|
||||
|
||||
add(os.Getenv("INSTAGRAM_APP_SECRET"))
|
||||
add(os.Getenv("FB_APP_SECRET"))
|
||||
for _, event := range events {
|
||||
if inbox, err := h.lookupInstagramInboxForEvent(event); err == nil {
|
||||
add(h.resolveAppSecret(inbox))
|
||||
}
|
||||
}
|
||||
return secrets
|
||||
}
|
||||
|
||||
func (h *FacebookWebhookHandler) processInstagramEvent(c *gin.Context, inbox *model.Inbox, event *fbchannel.ParsedWebhookEvent) {
|
||||
if fbchannel.IsEchoMessage(event) || fbchannel.IsDeliveryOrReadReceipt(event) || fbchannel.IsThreadControlEvent(event) {
|
||||
return
|
||||
}
|
||||
|
||||
if fbchannel.IsIGCommentEvent(event) {
|
||||
if h.igProvider == nil {
|
||||
applogger.L().Warn("Instagram webhook: comment event ignored because Instagram provider is not configured")
|
||||
return
|
||||
}
|
||||
commentMsg, err := h.igProvider.ProcessCommentIncoming(c.Request.Context(), inbox, event.Comment, event.EventType)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Instagram webhook: comment processing failed: %v", err)
|
||||
}
|
||||
if commentMsg != nil {
|
||||
applogger.L().Infof("Instagram webhook: comment processed (inbox_id=%d, source_id=%s, type=%s)", commentMsg.InboxID, commentMsg.SourceID, event.EventType)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !fbchannel.ShouldCreateMessage(event) {
|
||||
return
|
||||
}
|
||||
incomingMsg, err := fbchannel.ExtractIncomingMessageFromEvent(event, inbox, channel.ChannelInstagram)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Instagram webhook: extract message failed: %v", err)
|
||||
return
|
||||
}
|
||||
if incomingMsg != nil {
|
||||
applogger.L().Infof("Instagram webhook: message extracted (inbox_id=%d, source_id=%s, type=%s)", incomingMsg.InboxID, incomingMsg.SourceID, event.EventType)
|
||||
}
|
||||
}
|
||||
|
||||
func parseOptionalUintParam(value string) (uint, error) {
|
||||
if value == "" {
|
||||
return 0, nil
|
||||
}
|
||||
parsed, err := strconv.ParseUint(value, 10, 32)
|
||||
return uint(parsed), err
|
||||
}
|
||||
|
||||
// resolveVerifyToken extracts the webhook verify token from the inbox ChannelConfig JSON.
|
||||
func (h *FacebookWebhookHandler) resolveVerifyToken(inbox *model.Inbox) string {
|
||||
config := h.parseChannelConfig(inbox)
|
||||
@@ -318,4 +485,4 @@ func (h *FacebookWebhookHandler) parseChannelConfig(inbox *model.Inbox) map[stri
|
||||
return map[string]interface{}{}
|
||||
}
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user