chore: import clean Agent Desk snapshot (3/7)

This commit is contained in:
2026-10-16 11:58:36 +00:00
parent 89c5231c4c
commit fe4a99cf4b
127 changed files with 29641 additions and 0 deletions

140
internal/zalo/client.go Normal file
View File

@@ -0,0 +1,140 @@
package zalo
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const defaultBaseURL = "https://openapi.zalo.me"
type Client struct {
accessToken string
baseURL string
httpClient *http.Client
}
func NewClient(accessToken string) *Client {
return &Client{
accessToken: strings.TrimSpace(accessToken),
baseURL: defaultBaseURL,
httpClient: &http.Client{Timeout: 15 * time.Second},
}
}
func (c *Client) SetBaseURL(u string) {
if strings.TrimSpace(u) != "" {
c.baseURL = strings.TrimRight(strings.TrimSpace(u), "/")
}
}
func (c *Client) SendCSMessage(ctx context.Context, userID string, text string) (*APIResponse, error) {
if strings.TrimSpace(userID) == "" {
return nil, fmt.Errorf("zalo user_id is required")
}
if strings.TrimSpace(text) == "" {
return nil, fmt.Errorf("zalo message text is required")
}
reqPayload := SendMessageRequest{
Recipient: UserRef{ID: strings.TrimSpace(userID)},
Message: SendContent{Text: text},
}
var resp APIResponse
if err := c.doPost(ctx, "/v3.0/oa/message/cs", reqPayload, &resp); err != nil {
return nil, err
}
if resp.Error != 0 {
return nil, fmt.Errorf("zalo send message failed (%d): %s", resp.Error, resp.Message)
}
return &resp, nil
}
func (c *Client) GetUserProfile(ctx context.Context, userID string) (*UserProfile, error) {
if strings.TrimSpace(userID) == "" {
return nil, fmt.Errorf("zalo user_id is required")
}
params := url.Values{}
params.Set("data", fmt.Sprintf(`{"user_id":"%s"}`, strings.TrimSpace(userID)))
var resp UserProfileResponse
if err := c.doGet(ctx, "/v3.0/oa/user/detail?"+params.Encode(), &resp); err != nil {
return nil, err
}
if resp.Error != 0 {
return nil, fmt.Errorf("zalo get user profile failed (%d): %s", resp.Error, resp.Message)
}
return &resp.Data, nil
}
func (c *Client) doPost(ctx context.Context, path string, payload any, result any) error {
if c.accessToken == "" {
return fmt.Errorf("zalo access_token is required")
}
endpoint := fmt.Sprintf("%s%s", c.baseURL, path)
bodyBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal zalo request failed: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(bodyBytes))
if err != nil {
return fmt.Errorf("create zalo request failed: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("access_token", c.accessToken)
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("zalo http request failed: %w", err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("read zalo response failed: %w", err)
}
if err := json.Unmarshal(body, result); err != nil {
return fmt.Errorf("unmarshal zalo response failed: %w (body: %s)", err, string(body))
}
return nil
}
func (c *Client) doGet(ctx context.Context, path string, result any) error {
if c.accessToken == "" {
return fmt.Errorf("zalo access_token is required")
}
endpoint := fmt.Sprintf("%s%s", c.baseURL, path)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return fmt.Errorf("create zalo request failed: %w", err)
}
req.Header.Set("access_token", c.accessToken)
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("zalo http request failed: %w", err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("read zalo response failed: %w", err)
}
if err := json.Unmarshal(body, result); err != nil {
return fmt.Errorf("unmarshal zalo response failed: %w (body: %s)", err, string(body))
}
return nil
}

View File

@@ -0,0 +1,81 @@
package zalo
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestZaloClient_SendCSMessage(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v3.0/oa/message/cs" {
http.NotFound(w, r)
return
}
if r.Header.Get("access_token") != "test_access_token_123" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
var req SendMessageRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Recipient.ID != "zalo_user_001" || req.Message.Text != "Xin chào từ Crove Desk!" {
http.Error(w, "invalid payload", http.StatusBadRequest)
return
}
_ = json.NewEncoder(w).Encode(APIResponse{
Error: 0,
Message: "Success",
Data: map[string]any{
"message_id": "zalo_msg_1001",
},
})
}))
defer ts.Close()
client := NewClient("test_access_token_123")
client.SetBaseURL(ts.URL)
resp, err := client.SendCSMessage(context.Background(), "zalo_user_001", "Xin chào từ Crove Desk!")
if err != nil {
t.Fatalf("SendCSMessage failed: %v", err)
}
if resp.Error != 0 {
t.Fatalf("unexpected resp: %+v", resp)
}
}
func TestZaloClient_GetUserProfile(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v3.0/oa/user/detail" {
http.NotFound(w, r)
return
}
_ = json.NewEncoder(w).Encode(UserProfileResponse{
Error: 0,
Message: "Success",
Data: UserProfile{
UserID: "zalo_user_001",
DisplayName: "Nguyen Van B",
UserGender: "1",
Avatar: "https://avatar.zalo.me/1.jpg",
},
})
}))
defer ts.Close()
client := NewClient("test_access_token_123")
client.SetBaseURL(ts.URL)
profile, err := client.GetUserProfile(context.Background(), "zalo_user_001")
if err != nil {
t.Fatalf("GetUserProfile failed: %v", err)
}
if profile.DisplayName != "Nguyen Van B" || profile.UserID != "zalo_user_001" {
t.Fatalf("unexpected profile: %+v", profile)
}
}

59
internal/zalo/types.go Normal file
View File

@@ -0,0 +1,59 @@
package zalo
// WebhookEvent represents an incoming webhook event from Zalo Official Account.
type WebhookEvent struct {
EventName string `json:"event_name"`
AppID string `json:"app_id"`
Sender UserRef `json:"sender"`
Recipient UserRef `json:"recipient"`
Message *EventMessage `json:"message,omitempty"`
Info map[string]any `json:"info,omitempty"`
Timestamp string `json:"timestamp"`
}
type UserRef struct {
ID string `json:"id"`
}
type EventMessage struct {
MsgID string `json:"msg_id"`
Text string `json:"text,omitempty"`
Attachments []EventAttachment `json:"attachments,omitempty"`
}
type EventAttachment struct {
Type string `json:"type"`
Payload any `json:"payload"`
}
// SendMessageRequest represents payload for Zalo OA Customer Support message API (/v3.0/oa/message/cs).
type SendMessageRequest struct {
Recipient UserRef `json:"recipient"`
Message SendContent `json:"message"`
}
type SendContent struct {
Text string `json:"text"`
}
// APIResponse represents standard Zalo OpenAPI response.
type APIResponse struct {
Error int `json:"error"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
// UserProfileResponse represents Zalo OA get profile API response.
type UserProfileResponse struct {
Error int `json:"error"`
Message string `json:"message"`
Data UserProfile `json:"data"`
}
type UserProfile struct {
UserID string `json:"user_id"`
DisplayName string `json:"display_name"`
UserGender string `json:"user_gender"`
Avatar string `json:"avatar"`
IsSensitive bool `json:"is_sensitive"`
}