Files
utils/tencentx/wechatx/notify.go
T
2023-09-17 18:05:01 +08:00

88 lines
1.9 KiB
Go

package wechatx
import (
"encoding/xml"
"errors"
"fmt"
"code.yun.ink/open/utils/convx"
"code.yun.ink/open/utils/encryptx/sha1x"
"code.yun.ink/open/utils/tencentx/wechatx/cryptx"
"github.com/gin-gonic/gin"
)
// 解密微信消息
func (w *wechat) DecryptMsg(ctx *gin.Context) (*WechatMessage, error) {
by, err := ctx.GetRawData()
if err != nil {
return nil, err
}
msg_sign := ctx.Query("msg_signature")
timestamp := ctx.Query("timestamp")
nonce := ctx.Query("nonce")
t, _ := convx.ToInt64(timestamp)
ct, err := cryptx.NewWXBizMsgCrypt(w.token, w.encodingAesKey, w.appid)
if err != nil {
return nil, err
}
code, resp := ct.DecryptMsg(string(by), msg_sign, t, nonce)
if code != 0 {
return nil, errors.New("解析失败")
}
fmt.Println(resp)
wm := &WechatMessage{}
err = xml.Unmarshal([]byte(resp), &wm)
if err != nil {
return nil, err
}
return wm, nil
}
// 加密微信消息
func (w *wechat) EncryptMsg(msg *WechatMessage) (string, error) {
ct, err := cryptx.NewWXBizMsgCrypt(w.token, w.encodingAesKey, w.appid)
if err != nil {
return "", err
}
// if msg.MsgId == "" {
// msg.MsgId = uuid.NewV4().String()
// }
// if msg.CreateTime == 0 {
// msg.CreateTime = time.Now().Unix()
// }
xmlBy, err := xml.Marshal(msg)
code, enMsg := ct.EncryptMsg(string(xmlBy), msg.MsgId, msg.CreateTime)
if code != cryptx.WXBizMsgCrypt_OK {
return "", errors.New(fmt.Sprintf("%d", code))
}
return enMsg, nil
}
// 回调验证
func (w *wechat) Verify(ctx *gin.Context) {
timestamp := ctx.Query("timestamp")
nonce := ctx.Query("nonce")
signature := ctx.Query("signature")
echostr := ctx.Query("echostr")
verifyStr := fmt.Sprintf("%+v%+v%+v", nonce, timestamp, w.token)
sha1Str := sha1x.Sha1(verifyStr)
if sha1Str == signature {
fmt.Fprint(ctx.Writer, echostr)
// ctx.String(200, echostr)
} else {
fmt.Fprint(ctx.Writer, "false")
// ctx.String(200, "false")
}
}