一物一码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

284 lines
8.4 KiB

  1. package hdl
  2. import (
  3. "applet/app/db"
  4. "applet/app/db/model"
  5. "applet/app/enum"
  6. "applet/app/md"
  7. "applet/app/utils"
  8. "encoding/json"
  9. "encoding/xml"
  10. "errors"
  11. "fmt"
  12. "log"
  13. "time"
  14. "github.com/gin-gonic/gin"
  15. )
  16. const Token = "temptoken"
  17. // WXCheckSignature 微信接入校验
  18. func WXCheckSignature(c *gin.Context) {
  19. signature := c.Query("signature")
  20. timestamp := c.Query("timestamp")
  21. nonce := c.Query("nonce")
  22. echostr := c.Query("echostr")
  23. ok := utils.CheckSignature(signature, timestamp, nonce, Token)
  24. utils.FilePutContents("WXCheckSignature", utils.SerializeStr(map[string]interface{}{
  25. "signature": signature,
  26. "timestamp": timestamp,
  27. "nonce": nonce,
  28. "echostr": echostr,
  29. "ok": ok,
  30. }))
  31. if !ok {
  32. log.Println("[微信接入] - 微信公众号接入校验失败!")
  33. return
  34. }
  35. log.Println("[微信接入] - 微信公众号接入校验成功!")
  36. _, _ = c.Writer.WriteString(echostr)
  37. }
  38. // WXMsg 微信消息结构体
  39. type WXMsg struct {
  40. ToUserName string
  41. FromUserName string
  42. CreateTime int64
  43. MsgType string
  44. Content string
  45. MsgId int64
  46. Event string //事件类型,subscribe
  47. EventKey string //事件KEY值,qrscene_为前缀,后面为二维码的参数值
  48. Ticket string //二维码的ticket,可用来换取二维码图片
  49. }
  50. // WXTextMsg 微信文本消息结构体
  51. type WXTextMsg struct {
  52. ToUserName string
  53. FromUserName string
  54. CreateTime int64
  55. MsgType string
  56. Content string
  57. MsgId int64
  58. }
  59. // WXEventForSubscribeMsg 扫描带参数二维码事件消息结构体(用户未关注时,进行关注后的事件推送)
  60. type WXEventForSubscribeMsg struct {
  61. ToUserName string //开发者微信号
  62. FromUserName string //发送方帐号(一个OpenID)
  63. CreateTime int64 //消息创建时间 (整型)
  64. MsgType string //消息类型,event
  65. Event string //事件类型,subscribe
  66. EventKey string //事件KEY值,qrscene_为前缀,后面为二维码的参数值
  67. Ticket string //二维码的ticket,可用来换取二维码图片
  68. }
  69. // WXEventForScanMsg 扫描带参数二维码事件消息结构体(用户已关注时的事件推送)
  70. type WXEventForScanMsg struct {
  71. ToUserName string //开发者微信号
  72. FromUserName string //发送方帐号(一个OpenID)
  73. CreateTime int64 //消息创建时间 (整型)
  74. MsgType string //消息类型,event
  75. Event string //事件类型,subscribe
  76. EventKey string //事件KEY值,是一个32位无符号整数,即创建二维码时的二维码scene_id
  77. Ticket string //二维码的ticket,可用来换取二维码图片
  78. }
  79. // WXMsgReceive 微信消息接收
  80. func WXMsgReceive(c *gin.Context) {
  81. log.Printf("[消息接收] - 收到新消息")
  82. var msg WXMsg
  83. err := c.ShouldBindXML(&msg)
  84. if err != nil {
  85. log.Printf("[消息接收] - XML数据包解析失败: %v\n", err)
  86. return
  87. }
  88. utils.FilePutContents("WXMsgReceive", utils.SerializeStr(msg))
  89. log.Printf("[消息接收] - 收到消息, 消息类型为: %s", msg.MsgType)
  90. //if msg.MsgType == "event" {
  91. // //事件类型消息
  92. // eventMsg := msg
  93. // log.Printf("[事件类型]-收到消息, 事件类型为: %s, 事件KEY值为: %s\n, 二维码的ticket值为: %s\n", eventMsg.Event, eventMsg.EventKey, eventMsg.Ticket)
  94. // if eventMsg.Event == "subscribe" {
  95. // //用户未关注时,进行关注后的事件推送
  96. // err := DealCallBack(eventMsg.FromUserName, eventMsg.EventKey)
  97. // if err != nil {
  98. // WXMsgReply(c, eventMsg.ToUserName, eventMsg.FromUserName, err.Error())
  99. // }
  100. // }
  101. // if eventMsg.Event == "SCAN" {
  102. // //用户已关注时的事件推送
  103. // err := DealCallBack(eventMsg.FromUserName, eventMsg.EventKey)
  104. // if err != nil {
  105. // WXMsgReply(c, eventMsg.ToUserName, eventMsg.FromUserName, err.Error())
  106. // }
  107. // }
  108. // if eventMsg.Event == "CLICK" { //公众号点击
  109. // if strings.Contains(strings.ToLower(eventMsg.EventKey), "official_account_custom_reply") {
  110. // id := strings.ReplaceAll(strings.ToLower(eventMsg.EventKey), "official_account_custom_reply_", "")
  111. // var mod model.SysModule
  112. // db.Db.Where("mod_id=?", id).Get(&mod)
  113. // fmt.Println(mod)
  114. // if mod.Data == "" {
  115. // fmt.Println(333)
  116. //
  117. // return
  118. // }
  119. // var data []md.ReplyContent
  120. // json.Unmarshal([]byte(mod.Data), &data)
  121. // for _, v := range data {
  122. // if v.MsgType == "text" {
  123. // fmt.Println(1111)
  124. //
  125. // svc.WXMsgTextReply(c, msg.ToUserName, msg.FromUserName, v.Text.Content)
  126. // }
  127. // if v.MsgType == "image" {
  128. // fmt.Println(22222)
  129. // svc.WXMsgImageReply(c, msg.ToUserName, msg.FromUserName, v.Image.MediaId)
  130. // }
  131. // }
  132. // }
  133. // }
  134. //}
  135. if msg.MsgType == "text" {
  136. //文本类型消息
  137. textMsg := msg
  138. log.Printf("[文本消息]-收到消息, 消息内容为: %s", textMsg.Content)
  139. WXMsgReply(c, textMsg.ToUserName, textMsg.FromUserName, textMsg.Content)
  140. }
  141. }
  142. // WXRepTextMsg 微信回复文本消息结构体
  143. type WXRepTextMsg struct {
  144. ToUserName string
  145. FromUserName string
  146. CreateTime int64
  147. MsgType string
  148. Content string
  149. // 若不标记XMLName, 则解析后的xml名为该结构体的名称
  150. XMLName xml.Name `xml:"xml"`
  151. }
  152. // WXMsgReply 微信消息回复
  153. func WXMsgReply(c *gin.Context, fromUser, toUser, content string) {
  154. repTextMsg := WXRepTextMsg{
  155. ToUserName: toUser,
  156. FromUserName: fromUser,
  157. CreateTime: time.Now().Unix(),
  158. MsgType: "text",
  159. Content: fmt.Sprintf("[消息回复] - %s \n %s", time.Now().Format("2006-01-02 15:04:05"), content),
  160. }
  161. msg, err := xml.Marshal(&repTextMsg)
  162. if err != nil {
  163. log.Printf("[消息回复] - 将对象进行XML编码出错: %v\n", err)
  164. return
  165. }
  166. _, _ = c.Writer.Write(msg)
  167. }
  168. func DealCallBack(openId, ticket string) error {
  169. //1、查找对应的二维码记录
  170. qrcodeDb := db.QrcodeDb{}
  171. qrcodeDb.Set()
  172. qrcode, err := qrcodeDb.GetQrcodeByIndex(ticket)
  173. if err != nil {
  174. return err
  175. }
  176. if qrcode == nil {
  177. return errors.New("未查询到对应二维码记录")
  178. }
  179. //2、查找当前二维码是否可用
  180. qrcodeWithBatchRecordsDb := db.QrcodeWithBatchRecordsDb{}
  181. qrcodeWithBatchRecordsDb.Set()
  182. qrcodeWithBatchRecord, err := qrcodeWithBatchRecordsDb.GetQrcodeWithBatchRecordsByQrcodeId(qrcode.Id)
  183. if err != nil {
  184. return err
  185. }
  186. if qrcodeWithBatchRecord == nil {
  187. return errors.New("当前二维码不可使用!")
  188. }
  189. //3、查找当前用户是否使用过当前二维码
  190. userUseQrcodeRecordsDb := db.UserUseQrcodeRecordsDb{}
  191. userUseQrcodeRecordsDb.Set()
  192. userUseQrcodeRecords, err := userUseQrcodeRecordsDb.GetUserUseQrcodeRecordsByOpenId(openId)
  193. if err != nil {
  194. return err
  195. }
  196. if userUseQrcodeRecords != nil {
  197. return errors.New("请勿重复使用二维码!")
  198. }
  199. //4、发送微信红包
  200. post, err := utils.CurlPost("http://pay.izhyin.com/wx/redPackage/index", utils.SerializeStr(map[string]string{
  201. "openid": openId,
  202. "amount": utils.Float64ToStr(utils.StrToFloat64(qrcodeWithBatchRecord.Amount) * 100),
  203. }), nil)
  204. if err != nil {
  205. return err
  206. }
  207. utils.FilePutContents("send_redPackage", utils.SerializeStr(map[string]interface{}{
  208. "args": map[string]string{
  209. "openid": openId,
  210. "amount": utils.Float64ToStr(utils.StrToFloat64(qrcodeWithBatchRecord.Amount) * 100),
  211. },
  212. "resp": string(post),
  213. }))
  214. var result struct {
  215. Code int `json:"code"`
  216. Msg string `json:"msg"`
  217. Data interface{} `json:"data"`
  218. }
  219. err = json.Unmarshal(post, &result)
  220. if err != nil {
  221. return err
  222. }
  223. var data md.SendRedPackageResp
  224. err = json.Unmarshal(utils.Serialize(result.Data), &data)
  225. if err != nil {
  226. return err
  227. }
  228. utils.FilePutContents("send_redPackage", utils.SerializeStr(map[string]interface{}{
  229. "data": data,
  230. }))
  231. if data.ReturnCode != "SUCCESS" || data.ResultCode != "SUCCESS" {
  232. return errors.New(data.ReturnMsg)
  233. }
  234. //5、将当前二维码状态修改为“可用”
  235. qrcode.State = enum.QrcodeSateAllowUse
  236. _, err = qrcodeDb.BatchUpdateQrcode(qrcode, "state")
  237. if err != nil {
  238. return err
  239. }
  240. //6、将当前二维码记录修改为“已使用”
  241. qrcodeWithBatchRecord.State = enum.QrcodeWithBatchRecordsStateForAlready
  242. _, err = qrcodeWithBatchRecordsDb.UpdateQrcodeWithBatchRecord(qrcodeWithBatchRecord)
  243. if err != nil {
  244. return err
  245. }
  246. //7、新增用户使用记录
  247. _, err = userUseQrcodeRecordsDb.InsertUserUseQrcodeRecords(&model.UserUseQrcodeRecords{
  248. UserWxOpenId: openId,
  249. RecordsId: qrcodeWithBatchRecord.Id,
  250. State: 1,
  251. CreateAt: time.Now().Format("2006-01-02 15:04:05"),
  252. UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
  253. })
  254. if err != nil {
  255. return err
  256. }
  257. return nil
  258. }