封装的方法类
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package wechatx
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"yunink/app/pkg/convx"
|
||||
encryptsha1 "yunink/app/pkg/encryptx/sha1x"
|
||||
"yunink/app/pkg/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 := encryptsha1.Sha1(verifyStr)
|
||||
if sha1Str == signature {
|
||||
fmt.Fprint(ctx.Writer, echostr)
|
||||
// ctx.String(200, echostr)
|
||||
} else {
|
||||
fmt.Fprint(ctx.Writer, "false")
|
||||
// ctx.String(200, "false")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user