Files
ai-agent/internal/controllers/third/wechat_controller.go
T

69 lines
1.6 KiB
Go
Raw Normal View History

2026-04-09 10:01:23 +08:00
package third
import (
"cs-agent/internal/pkg/httpx/params"
2026-04-09 10:01:23 +08:00
"cs-agent/internal/wxwork"
"io"
2026-04-09 10:01:23 +08:00
"net/http"
"github.com/gin-gonic/gin"
2026-04-09 10:01:23 +08:00
"github.com/silenceper/wechat/v2/work/kf"
)
type WechatController struct {
Ctx *gin.Context
2026-04-09 10:01:23 +08:00
}
// GetCallback GET请求用于校验回调是否配置正确
func (c *WechatController) GetCallback() {
cli, err := wxwork.GetWorkCli().GetKF()
if err != nil {
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
2026-04-09 10:01:23 +08:00
return
}
options := kf.SignatureOptions{}
if err := params.ReadForm(c.Ctx, &options); err != nil {
c.Ctx.AbortWithError(http.StatusUnauthorized, err)
2026-04-09 10:01:23 +08:00
return
}
// 调用VerifyURL方法校验当前请求,如果合法则把解密后的内容作为响应返回给微信服务器
echo, err := cli.VerifyURL(options)
if err == nil {
c.Ctx.String(http.StatusOK, echo)
2026-04-09 10:01:23 +08:00
} else {
c.Ctx.AbortWithError(http.StatusUnauthorized, err)
2026-04-09 10:01:23 +08:00
}
}
// PostCallback POST请求用于接收回调
func (c *WechatController) PostCallback() {
cli, err := wxwork.GetWorkCli().GetKF()
if err != nil {
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
2026-04-09 10:01:23 +08:00
return
}
var (
message kf.CallbackMessage
body []byte
)
// 读取原始消息内容
body, err = io.ReadAll(c.Ctx.Request.Body)
2026-04-09 10:01:23 +08:00
if err != nil {
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
2026-04-09 10:01:23 +08:00
return
}
// 解析原始数据
message, err = cli.GetCallbackMessage(body)
if err != nil {
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
2026-04-09 10:01:23 +08:00
return
}
if err := wxwork.ConsumeCallback(message); err != nil {
c.Ctx.AbortWithError(http.StatusInternalServerError, err)
2026-04-09 10:01:23 +08:00
return
}
c.Ctx.String(http.StatusOK, "ok")
2026-04-09 10:01:23 +08:00
}