|
| 1 | +// Copyright 2026 The OpenAgent Authors. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package chat |
| 16 | + |
| 17 | +import ( |
| 18 | + "encoding/json" |
| 19 | + "fmt" |
| 20 | + "net/http" |
| 21 | + "strings" |
| 22 | +) |
| 23 | + |
| 24 | +const whatsAppApiBaseUrl = "https://graph.facebook.com/v19.0" |
| 25 | + |
| 26 | +type WhatsAppChatProvider struct { |
| 27 | + accessToken string |
| 28 | + phoneNumberId string |
| 29 | + verifyToken string |
| 30 | + httpClient *http.Client |
| 31 | +} |
| 32 | + |
| 33 | +type whatsAppWebhookPayload struct { |
| 34 | + Object string `json:"object"` |
| 35 | + Entry []whatsAppEntry `json:"entry"` |
| 36 | +} |
| 37 | + |
| 38 | +type whatsAppEntry struct { |
| 39 | + Id string `json:"id"` |
| 40 | + Changes []whatsAppChange `json:"changes"` |
| 41 | +} |
| 42 | + |
| 43 | +type whatsAppChange struct { |
| 44 | + Value whatsAppValue `json:"value"` |
| 45 | + Field string `json:"field"` |
| 46 | +} |
| 47 | + |
| 48 | +type whatsAppValue struct { |
| 49 | + MessagingProduct string `json:"messaging_product"` |
| 50 | + Metadata whatsAppMetadata `json:"metadata"` |
| 51 | + Contacts []whatsAppContact `json:"contacts"` |
| 52 | + Messages []whatsAppMessage `json:"messages"` |
| 53 | +} |
| 54 | + |
| 55 | +type whatsAppMetadata struct { |
| 56 | + DisplayPhoneNumber string `json:"display_phone_number"` |
| 57 | + PhoneNumberId string `json:"phone_number_id"` |
| 58 | +} |
| 59 | + |
| 60 | +type whatsAppContact struct { |
| 61 | + Profile whatsAppProfile `json:"profile"` |
| 62 | + WaId string `json:"wa_id"` |
| 63 | +} |
| 64 | + |
| 65 | +type whatsAppProfile struct { |
| 66 | + Name string `json:"name"` |
| 67 | +} |
| 68 | + |
| 69 | +type whatsAppMessage struct { |
| 70 | + From string `json:"from"` |
| 71 | + Id string `json:"id"` |
| 72 | + Timestamp string `json:"timestamp"` |
| 73 | + Type string `json:"type"` |
| 74 | + Text *whatsAppText `json:"text,omitempty"` |
| 75 | +} |
| 76 | + |
| 77 | +type whatsAppText struct { |
| 78 | + Body string `json:"body"` |
| 79 | +} |
| 80 | + |
| 81 | +type whatsAppSendPayload struct { |
| 82 | + MessagingProduct string `json:"messaging_product"` |
| 83 | + To string `json:"to"` |
| 84 | + Type string `json:"type"` |
| 85 | + Text whatsAppTextPayload `json:"text"` |
| 86 | +} |
| 87 | + |
| 88 | +type whatsAppTextPayload struct { |
| 89 | + Body string `json:"body"` |
| 90 | +} |
| 91 | + |
| 92 | +func NewWhatsAppChatProvider(accessToken string, phoneNumberId string, verifyToken string, httpClient *http.Client) (*WhatsAppChatProvider, error) { |
| 93 | + return &WhatsAppChatProvider{ |
| 94 | + accessToken: accessToken, |
| 95 | + phoneNumberId: strings.TrimSpace(phoneNumberId), |
| 96 | + verifyToken: verifyToken, |
| 97 | + httpClient: httpClient, |
| 98 | + }, nil |
| 99 | +} |
| 100 | + |
| 101 | +func (p *WhatsAppChatProvider) authorizationHeaders() map[string]string { |
| 102 | + return map[string]string{ |
| 103 | + "Authorization": fmt.Sprintf("Bearer %s", p.accessToken), |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +func (p *WhatsAppChatProvider) SendMessage(chatId string, text string) error { |
| 108 | + payload := whatsAppSendPayload{ |
| 109 | + MessagingProduct: "whatsapp", |
| 110 | + To: chatId, |
| 111 | + Type: "text", |
| 112 | + Text: whatsAppTextPayload{Body: text}, |
| 113 | + } |
| 114 | + _, err := doJSONRequest( |
| 115 | + p.httpClient, |
| 116 | + "WhatsApp", |
| 117 | + http.MethodPost, |
| 118 | + fmt.Sprintf("%s/%s/messages", whatsAppApiBaseUrl, p.phoneNumberId), |
| 119 | + p.authorizationHeaders(), |
| 120 | + payload, |
| 121 | + http.StatusOK, |
| 122 | + http.StatusCreated, |
| 123 | + ) |
| 124 | + return err |
| 125 | +} |
| 126 | + |
| 127 | +func (p *WhatsAppChatProvider) ParseWebhookRequest(body []byte) (*IncomingMessage, error) { |
| 128 | + var payload whatsAppWebhookPayload |
| 129 | + if err := json.Unmarshal(body, &payload); err != nil { |
| 130 | + return nil, err |
| 131 | + } |
| 132 | + |
| 133 | + for _, entry := range payload.Entry { |
| 134 | + for _, change := range entry.Changes { |
| 135 | + if change.Field != "messages" { |
| 136 | + continue |
| 137 | + } |
| 138 | + contacts := change.Value.Contacts |
| 139 | + for i, message := range change.Value.Messages { |
| 140 | + if message.Type != "text" || message.Text == nil || message.Text.Body == "" { |
| 141 | + continue |
| 142 | + } |
| 143 | + |
| 144 | + userId := message.From |
| 145 | + username := message.From |
| 146 | + if i < len(contacts) { |
| 147 | + username = contacts[i].Profile.Name |
| 148 | + } |
| 149 | + |
| 150 | + return &IncomingMessage{ |
| 151 | + ChatId: message.From, |
| 152 | + UserId: userId, |
| 153 | + Text: message.Text.Body, |
| 154 | + Username: username, |
| 155 | + }, nil |
| 156 | + } |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + return nil, nil |
| 161 | +} |
| 162 | + |
| 163 | +// VerifyWebhook handles the Meta webhook verification challenge (GET request). |
| 164 | +// The verify token is the pipe name, which must match what is configured in |
| 165 | +// the Meta Developer Console as the webhook verify token. |
| 166 | +func (p *WhatsAppChatProvider) VerifyWebhook(params map[string]string) (*WebhookResponse, error) { |
| 167 | + mode := params["hub.mode"] |
| 168 | + verifyToken := params["hub.verify_token"] |
| 169 | + challenge := params["hub.challenge"] |
| 170 | + |
| 171 | + if mode != "subscribe" || verifyToken != p.verifyToken { |
| 172 | + return &WebhookResponse{StatusCode: http.StatusForbidden}, nil |
| 173 | + } |
| 174 | + |
| 175 | + return &WebhookResponse{ |
| 176 | + StatusCode: http.StatusOK, |
| 177 | + ContentType: "text/plain", |
| 178 | + Body: []byte(challenge), |
| 179 | + }, nil |
| 180 | +} |
| 181 | + |
| 182 | +// SetWebhook returns nil because WhatsApp webhooks are configured manually in |
| 183 | +// the Meta Developer Console. The caller displays the webhook URL to the user. |
| 184 | +func (p *WhatsAppChatProvider) SetWebhook(webhookUrl string) error { |
| 185 | + return nil |
| 186 | +} |
0 commit comments