This commit is contained in:
laodaming
2023-11-07 10:16:20 +08:00
parent be7823cfba
commit 975469e190
4 changed files with 45 additions and 58 deletions

View File

@@ -2,14 +2,12 @@ package logic
import (
"encoding/json"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"io"
"net/http"
"context"
"fusenapi/server/feishu-sync/internal/svc"
"fusenapi/server/feishu-sync/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
@@ -27,10 +25,14 @@ func NewWebhookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WebhookLo
}
}
// 处理进入前逻辑w,r
// func (l *WebhookLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }
// webhook消息事件基础信息
type WebhookMsg struct {
Type string `json:"type"`
Challenge string `json:"challenge"`
Header map[string]interface{} `json:"header"`
Event map[string]interface{} `json:"event"`
}
// webhook消息事件header(body参数)基础信息
type BaseWebhookMsgHeaderType struct {
EventId string `json:"event_id"` //事件id(可作为消息唯一性确认)
EventType string `json:"event_type"` //事件类型
@@ -40,16 +42,39 @@ type BaseWebhookMsgHeaderType struct {
TenantKey string `json:"tenant_key"` //租户key
}
func (l *WebhookLogic) Webhook(req *types.WebhookReq, userinfo *auth.UserInfo) (resp *basic.Response) {
logx.Info("收到事件:", req)
var msgHeader BaseWebhookMsgHeaderType
if req.Event["header"] == nil {
logx.Error("invalid request")
return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "invalid request")
func (l *WebhookLogic) Webhook(w http.ResponseWriter, r *http.Request) {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
logx.Error("读取请求body失败", err)
return
}
if err := json.Unmarshal([]byte(req.Event["header"].(string)), &msgHeader); err != nil {
logx.Error(err)
return resp.SetStatusAddMessage(basic.CodeJsonErr, "failed to parse params")
defer r.Body.Close()
//如果只是验证http连接的消息
var webhookMsg WebhookMsg
if err = json.Unmarshal(bodyBytes, &webhookMsg); err != nil {
logx.Error("反序列化请求body失败", err)
return
}
logx.Info("收到消息:", webhookMsg)
//验证连接(直接返回)
if webhookMsg.Type == "url_verification" {
challengeRsp := map[string]string{
"challenge": webhookMsg.Challenge,
}
b, _ := json.Marshal(challengeRsp)
w.Write(b)
return
}
headerByte, err := json.Marshal(webhookMsg.Header)
if err != nil {
logx.Error("序列化请求体header失败:", err)
return
}
var msgHeader BaseWebhookMsgHeaderType
if err = json.Unmarshal(headerByte, &msgHeader); err != nil {
logx.Error("反序列化请求体中的header失败", err)
return
}
switch msgHeader.EventType {
case "contact.custom_attr_event.updated_v3": //成员字段管理属性变更事件
@@ -67,7 +92,7 @@ func (l *WebhookLogic) Webhook(req *types.WebhookReq, userinfo *auth.UserInfo) (
case "contact.user.updated_v3": //员工信息变化
}
return resp.SetStatus(basic.CodeOK)
return
}
// 处理逻辑后 w,r 如:重定向, resp 必须重新处理