wx_public.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. package v1
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/aes"
  6. "crypto/cipher"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "encoding/base64"
  10. "encoding/binary"
  11. "encoding/hex"
  12. "encoding/xml"
  13. "errors"
  14. "fmt"
  15. "github.com/gin-gonic/gin"
  16. "io"
  17. "log"
  18. "property-callback-gateway/parser"
  19. "property-callback-gateway/pb"
  20. "property-callback-gateway/pb/v1"
  21. "sort"
  22. "strings"
  23. "time"
  24. )
  25. // CheckSignature 微信公众号签名检查
  26. func CheckSignature(signature, timestamp, nonce, token string) bool {
  27. arr := []string{timestamp, nonce, token}
  28. // 字典序排序
  29. sort.Strings(arr)
  30. n := len(timestamp) + len(nonce) + len(token)
  31. var b strings.Builder
  32. b.Grow(n)
  33. for i := 0; i < len(arr); i++ {
  34. b.WriteString(arr[i])
  35. }
  36. return Sha1(b.String()) == signature
  37. }
  38. // 进行Sha1编码
  39. func Sha1(str string) string {
  40. h := sha1.New()
  41. h.Write([]byte(str))
  42. return hex.EncodeToString(h.Sum(nil))
  43. }
  44. //
  45. // @Summary 微信公众号接入回调
  46. // @Description 微信公众号接入回调
  47. // @Tags callback
  48. // @Accept json
  49. // @Produce json
  50. // @Router /api/v1/wx/public [get]
  51. func (c *Controller) WxPublicIn(ctx *gin.Context) {
  52. signature := ctx.Query("signature")
  53. timestamp := ctx.Query("timestamp")
  54. nonce := ctx.Query("nonce")
  55. echostr := ctx.Query("echostr")
  56. fmt.Printf("%v,%v,%v,%v\n", signature, timestamp, nonce, echostr)
  57. token := parser.Conf.ThirdParty.Wx.PublicToken
  58. ok := CheckSignature(signature, timestamp, nonce, token)
  59. if !ok {
  60. log.Println("[微信接入] - 微信公众号接入校验失败!")
  61. return
  62. }
  63. log.Println("[微信接入] - 微信公众号接入校验成功!")
  64. _, _ = ctx.Writer.WriteString(echostr)
  65. }
  66. // WXTextMsg 微信文本消息结构体
  67. type WXTextMsg struct {
  68. ToUserName string
  69. FromUserName string
  70. CreateTime int64
  71. MsgType string
  72. Content string
  73. Event string
  74. MsgId int64
  75. Encrypt string
  76. }
  77. type TextRequestBody struct {
  78. XMLName xml.Name `xml:"xml"`
  79. ToUserName string
  80. FromUserName string
  81. CreateTime time.Duration
  82. MsgType string
  83. Content string
  84. MsgId int
  85. Event string
  86. }
  87. // WXRepTextMsg 微信回复文本消息结构体
  88. type WXRepTextMsg struct {
  89. ToUserName string
  90. FromUserName string
  91. CreateTime int64
  92. MsgType string
  93. Content string
  94. // 若不标记XMLName, 则解析后的xml名为该结构体的名称
  95. XMLName xml.Name `xml:"xml"`
  96. }
  97. func handlePublicOpenId(openId string) {
  98. if openId == "" {
  99. return
  100. }
  101. mreq := v1.UserWxPublicAddRequest{OpenId: openId}
  102. pb.Household.UserWxPublicAdd(context.Background(), &mreq)
  103. }
  104. type EncryptRequestBody struct {
  105. XMLName xml.Name `xml:"xml"`
  106. ToUserName string
  107. Encrypt string
  108. }
  109. func makeMsgSignature(token string, timestamp, nonce, msg_encrypt string) string {
  110. sl := []string{token, timestamp, nonce, msg_encrypt}
  111. sort.Strings(sl)
  112. s := sha1.New()
  113. io.WriteString(s, strings.Join(sl, ""))
  114. return fmt.Sprintf("%x", s.Sum(nil))
  115. }
  116. func validateMsg(timestamp, nonce, msgEncrypt, msgSignatureIn string) bool {
  117. msgSignatureGen := makeMsgSignature(parser.Conf.ThirdParty.Wx.PublicToken, timestamp, nonce, msgEncrypt)
  118. if msgSignatureGen != msgSignatureIn {
  119. return false
  120. }
  121. return true
  122. }
  123. var encodingAESKey = "9ppghgxzoJJEokyofNlM5P9yhJMBH43CQqNjX8O4txx"
  124. func encodingAESKey2AESKey(encodingKey string) []byte {
  125. data, _ := base64.StdEncoding.DecodeString(encodingKey + "=")
  126. return data
  127. }
  128. func aesDecrypt(cipherData []byte, aesKey []byte) ([]byte, error) {
  129. k := len(aesKey) //PKCS#7
  130. if len(cipherData)%k != 0 {
  131. return nil, errors.New("crypto/cipher: ciphertext size is not multiple of aes key length")
  132. }
  133. block, err := aes.NewCipher(aesKey)
  134. if err != nil {
  135. return nil, err
  136. }
  137. iv := make([]byte, aes.BlockSize)
  138. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  139. return nil, err
  140. }
  141. blockMode := cipher.NewCBCDecrypter(block, iv)
  142. plainData := make([]byte, len(cipherData))
  143. blockMode.CryptBlocks(plainData, cipherData)
  144. return plainData, nil
  145. }
  146. func parseEncryptTextRequestBody(plainText []byte) (*TextRequestBody, error) {
  147. fmt.Println(string(plainText))
  148. // Read length
  149. buf := bytes.NewBuffer(plainText[16:20])
  150. var length int32
  151. binary.Read(buf, binary.BigEndian, &length)
  152. fmt.Println(string(plainText[20 : 20+length]))
  153. // appID validation
  154. appIDstart := 20 + length
  155. id := plainText[appIDstart : int(appIDstart)+len(parser.Conf.ThirdParty.Wx.PublicAppId)]
  156. if string(id) != parser.Conf.ThirdParty.Wx.PublicAppId {
  157. log.Println("Wechat Service: appid is invalid!")
  158. return nil, errors.New("Appid is invalid")
  159. }
  160. log.Println("Wechat Service: appid validation is ok!")
  161. // xml Decoding
  162. textRequestBody := &TextRequestBody{}
  163. fmt.Printf("request decrypt:%s\n", plainText[20:20+length])
  164. xml.Unmarshal(plainText[20:20+length], textRequestBody)
  165. return textRequestBody, nil
  166. }
  167. //
  168. // @Summary 微信公众号接收事件通知
  169. // @Description 微信公众号接收事件通知
  170. // @Tags callback
  171. // @Accept json
  172. // @Produce json
  173. // @Router /api/v1/wx/public [post]
  174. func (c *Controller) WxPublicCallback(ctx *gin.Context) {
  175. timestamp := ctx.Query("timestamp")
  176. nonce := ctx.Query("nonce")
  177. var textMsg WXTextMsg
  178. err := ctx.ShouldBindXML(&textMsg)
  179. if err != nil {
  180. log.Printf("[消息接收] - XML数据包解析失败: %v\n", err)
  181. return
  182. }
  183. bytes, _ := xml.Marshal(textMsg)
  184. fmt.Printf("text:%s,%v\n", bytes, textMsg.FromUserName)
  185. if textMsg.Encrypt != "" {
  186. cipherData, err := base64.StdEncoding.DecodeString(textMsg.Encrypt)
  187. if err != nil {
  188. log.Println("Wechat Service: Decode base64 error:", err)
  189. return
  190. }
  191. aesKey := encodingAESKey2AESKey(encodingAESKey)
  192. // AES Decrypt
  193. plainData, err := aesDecrypt(cipherData, aesKey)
  194. if err != nil {
  195. fmt.Println(err)
  196. return
  197. }
  198. //Xml decoding
  199. textRequestBody, err := parseEncryptTextRequestBody(plainData)
  200. if err != nil {
  201. fmt.Println(err)
  202. return
  203. }
  204. if textRequestBody.Event == "subscribe" {
  205. openId := textRequestBody.FromUserName
  206. handlePublicOpenId(openId)
  207. }
  208. WXEncryptMsgReply(textRequestBody.ToUserName,
  209. textRequestBody.FromUserName,
  210. //fmt.Sprintf("[消息回复] - %s", time.Now().Format("2006-01-02 15:04:05")),
  211. `<a data-miniprogram-appid="`+parser.Conf.ThirdParty.Wx.AppletAppId+`" data-miniprogram-path="`+parser.Conf.ThirdParty.Wx.AppletPagepath+`">点击进入小程序</a>`,
  212. nonce,
  213. timestamp, aesKey, ctx)
  214. return
  215. }
  216. if textMsg.Event == "subscribe" {
  217. openId := textMsg.FromUserName
  218. handlePublicOpenId(openId)
  219. }
  220. //log.Printf("[消息接收] - 收到消息, 消息类型为: %s, 消息内容为: %s\n", textMsg.MsgType, textMsg.Content)
  221. WXMsgReply(ctx, textMsg.ToUserName, textMsg.FromUserName)
  222. }
  223. // WXMsgReply 微信消息回复
  224. func WXMsgReply(c *gin.Context, fromUser, toUser string) {
  225. repTextMsg := WXRepTextMsg{
  226. ToUserName: toUser,
  227. FromUserName: fromUser,
  228. CreateTime: time.Now().Unix(),
  229. MsgType: "text",
  230. Content: `<a data-miniprogram-appid="` + parser.Conf.ThirdParty.Wx.AppletAppId + `" data-miniprogram-path="` + parser.Conf.ThirdParty.Wx.AppletPagepath + `">点击进入小程序</a>`,
  231. }
  232. msg, _ := xml.Marshal(&repTextMsg)
  233. c.Writer.Write(msg)
  234. }
  235. type EncryptResponseBody struct {
  236. XMLName xml.Name `xml:"xml"`
  237. Encrypt CDATAText
  238. MsgSignature CDATAText
  239. TimeStamp string
  240. Nonce CDATAText
  241. }
  242. type TextResponseBody struct {
  243. XMLName xml.Name `xml:"xml"`
  244. ToUserName CDATAText
  245. FromUserName CDATAText
  246. CreateTime string
  247. MsgType CDATAText
  248. Content CDATAText
  249. }
  250. type CDATAText struct {
  251. Text string `xml:",innerxml"`
  252. }
  253. func PadLength(slice_length, blocksize int) (padlen int) {
  254. padlen = blocksize - slice_length%blocksize
  255. if padlen == 0 {
  256. padlen = blocksize
  257. }
  258. return padlen
  259. }
  260. func PKCS7Pad(message []byte, blocksize int) (padded []byte, err error) {
  261. // block size must be bigger or equal 2
  262. if blocksize < 1<<1 {
  263. return nil, errors.New("block size is too small (minimum is 2 bytes)")
  264. }
  265. // block size up to 255 requires 1 byte padding
  266. if blocksize < 1<<8 {
  267. // calculate padding length
  268. padlen := PadLength(len(message), blocksize)
  269. // define PKCS7 padding block
  270. padding := bytes.Repeat([]byte{byte(padlen)}, padlen)
  271. // apply padding
  272. padded = append(message, padding...)
  273. return padded, nil
  274. }
  275. // block size bigger or equal 256 is not currently supported
  276. return nil, errors.New("unsupported block size")
  277. }
  278. func WXEncryptMsgReply(fromUserName, toUserName, content, nonce, timestamp string, aesKey []byte, c *gin.Context) {
  279. encryptBody := &EncryptResponseBody{}
  280. encryptXmlData, _ := makeEncryptXmlData(fromUserName, toUserName, timestamp, content, aesKey)
  281. encryptBody.Encrypt = value2CDATA(encryptXmlData)
  282. encryptBody.MsgSignature = value2CDATA(makeMsgSignature(parser.Conf.ThirdParty.Wx.PublicToken, timestamp, nonce, encryptXmlData))
  283. encryptBody.TimeStamp = timestamp
  284. encryptBody.Nonce = value2CDATA(nonce)
  285. msg, _ := xml.MarshalIndent(encryptBody, " ", " ")
  286. c.Writer.Write(msg)
  287. }
  288. func value2CDATA(v string) CDATAText {
  289. //return CDATAText{[]byte("<![CDATA[" + v + "]]>")}
  290. return CDATAText{"<![CDATA[" + v + "]]>"}
  291. }
  292. func makeEncryptXmlData(fromUserName, toUserName, timestamp, content string, aesKey []byte) (string, error) {
  293. // Encrypt part3: Xml Encoding
  294. textResponseBody := &TextResponseBody{}
  295. textResponseBody.FromUserName = value2CDATA(fromUserName)
  296. textResponseBody.ToUserName = value2CDATA(toUserName)
  297. textResponseBody.MsgType = value2CDATA("text")
  298. textResponseBody.Content = value2CDATA(content)
  299. textResponseBody.CreateTime = timestamp
  300. body, err := xml.MarshalIndent(textResponseBody, " ", " ")
  301. if err != nil {
  302. return "", errors.New("xml marshal error")
  303. }
  304. // Encrypt part2: Length bytes
  305. buf := new(bytes.Buffer)
  306. err = binary.Write(buf, binary.BigEndian, int32(len(body)))
  307. if err != nil {
  308. fmt.Println("Binary write err:", err)
  309. }
  310. bodyLength := buf.Bytes()
  311. // Encrypt part1: Random bytes
  312. randomBytes := []byte("abcdefghijklmnop")
  313. // Encrypt Part, with part4 - appID
  314. plainData := bytes.Join([][]byte{randomBytes, bodyLength, body, []byte(parser.Conf.ThirdParty.Wx.PublicAppId)}, nil)
  315. cipherData, err := aesEncrypt(plainData, aesKey)
  316. if err != nil {
  317. return "", errors.New("aesEncrypt error")
  318. }
  319. return base64.StdEncoding.EncodeToString(cipherData), nil
  320. }
  321. func aesEncrypt(plainData []byte, aesKey []byte) ([]byte, error) {
  322. k := len(aesKey)
  323. var err error
  324. if len(plainData)%k != 0 {
  325. plainData, err = PKCS7Pad(plainData, k)
  326. if err != nil {
  327. return nil, err
  328. }
  329. }
  330. block, err := aes.NewCipher(aesKey)
  331. if err != nil {
  332. return nil, err
  333. }
  334. iv := make([]byte, aes.BlockSize)
  335. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  336. return nil, err
  337. }
  338. cipherData := make([]byte, len(plainData))
  339. blockMode := cipher.NewCBCEncrypter(block, iv)
  340. blockMode.CryptBlocks(cipherData, plainData)
  341. return cipherData, nil
  342. }