wechat.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "eta/eta_mini_api/models"
  6. "eta/eta_mini_api/models/request"
  7. "eta/eta_mini_api/models/response"
  8. "eta/eta_mini_api/services/wechat"
  9. "eta/eta_mini_api/services/wx_app"
  10. "eta/eta_mini_api/utils"
  11. "fmt"
  12. "strconv"
  13. "time"
  14. )
  15. type WechatController struct {
  16. BaseCommonController
  17. }
  18. // @Title 微信获取签名接口
  19. // @Description 微信获取签名接口
  20. // @Param Url query string true "url地址"
  21. // @Success 200 {object} models.WechatSign
  22. // @router /notify [get,post]
  23. func (this *WechatController) Notify() {
  24. echostr := this.GetString("echostr")
  25. method := this.Ctx.Input.Method()
  26. type Notify struct {
  27. ToUserName string `xml:"ToUserName"`
  28. FromUserName string `xml:"FromUserName"`
  29. CreateTime int `xml:"CreateTime"`
  30. MsgType string `xml:"MsgType"`
  31. Event string `xml:"Event"`
  32. EventKey string `xml:"EventKey"`
  33. Content string `xml:"Content"`
  34. }
  35. if method == "POST" {
  36. body := this.Ctx.Input.RequestBody
  37. utils.FileLog.Info("wechat notify:" + string(body))
  38. item := new(Notify)
  39. err := xml.Unmarshal(body, &item)
  40. if err != nil {
  41. utils.FileLog.Info("xml.Unmarshal:" + err.Error())
  42. }
  43. contactMsg := "感谢关注东吴期货研究所\r\n公司地址:上海市黄浦区西藏南路1208号东吴证券大厦19楼\r\n\r\n业务合作:\r\n电话:021-6312 3065\r\n邮箱:lvan@dwqh88.com\r\n邮编:200001"
  44. var openId, returnResult string
  45. if item.MsgType != "" {
  46. openId = item.FromUserName
  47. }
  48. xmlTpl := `<xml>
  49. <ToUserName><![CDATA[%s]]></ToUserName>
  50. <FromUserName><![CDATA[%s]]></FromUserName>
  51. <CreateTime>%s</CreateTime>
  52. <MsgType><![CDATA[text]]></MsgType>
  53. <Content><![CDATA[%s]]></Content>
  54. </xml>`
  55. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  56. xmlTpl = fmt.Sprintf(xmlTpl, openId, utils.DW_WX_Id, createTime, contactMsg)
  57. if item.MsgType == "event" {
  58. switch item.Event {
  59. case "subscribe":
  60. fmt.Println("关注")
  61. go subscribe(openId)
  62. case "unsubscribe":
  63. fmt.Println("取消关注")
  64. go models.UserSubscribe(0, openId)
  65. case "CLICK":
  66. returnResult = xmlTpl
  67. default:
  68. utils.FileLog.Info("wechat notify event:" + item.Event)
  69. }
  70. this.Ctx.WriteString(xmlTpl)
  71. } else {
  72. returnResult = xmlTpl
  73. }
  74. this.Ctx.WriteString(returnResult)
  75. } else {
  76. this.Ctx.WriteString(echostr)
  77. }
  78. }
  79. // subscribe 关注后的处理逻辑
  80. func subscribe(openId string) {
  81. userRecord, err := models.GetUserRecordByOpenId(openId)
  82. if err != nil && err.Error() != utils.ErrNoRow() {
  83. fmt.Println("通过openid获取user_record记录失败,err:" + err.Error())
  84. return
  85. }
  86. err = nil
  87. // openId已存在
  88. if userRecord != nil {
  89. if userRecord.UserId > 0 { //已经绑定了的话,那么就去修改用户状态
  90. models.UserSubscribe(1, openId)
  91. } else {
  92. // 没有绑定的话,那么校验下unionid,然后再去修改
  93. unionId := userRecord.UnionId
  94. if unionId == `` {
  95. wxUserItem, err := wechat.GetUserInfo(openId)
  96. if err != nil {
  97. fmt.Println("获取用户信息失败,err:" + err.Error())
  98. return
  99. }
  100. if wxUserItem.UnionID != `` {
  101. unionId = wxUserItem.UnionID
  102. }
  103. }
  104. updateCol := make([]string, 0)
  105. userRecord.Subscribe = 1
  106. userRecord.SubscribeTime = time.Now()
  107. updateCol = append(updateCol, "Subscribe")
  108. if unionId != `` {
  109. userRecord.UnionId = unionId
  110. // 通过unionid获取已绑定用户的user_record信息
  111. bindUserRecord, _ := models.GetBindUserRecordByUnionId(unionId)
  112. if bindUserRecord != nil {
  113. userRecord.UserId = bindUserRecord.UserId
  114. userRecord.RealName = bindUserRecord.RealName
  115. userRecord.Sex = bindUserRecord.Sex
  116. updateCol = append(updateCol, "UserId", "RealName")
  117. }
  118. }
  119. err = userRecord.Update(updateCol)
  120. if err != nil {
  121. fmt.Println("关注后,通过openid更新user_record异常,ERR:", err)
  122. }
  123. }
  124. return
  125. }
  126. // 没有记录,那么需要获取下unionid
  127. wxUserItem, err := wechat.GetUserInfo(openId)
  128. if err != nil {
  129. fmt.Println("获取用户信息失败,err:" + err.Error())
  130. return
  131. }
  132. newUserRecord := &models.UserRecord{
  133. UserRecordId: 0,
  134. OpenId: openId,
  135. UnionId: wxUserItem.UnionID,
  136. Subscribe: 1,
  137. SubscribeTime: time.Now(),
  138. NickName: wxUserItem.Nickname,
  139. Sex: int(wxUserItem.Sex),
  140. Province: wxUserItem.Province,
  141. City: wxUserItem.City,
  142. Country: wxUserItem.Country,
  143. Headimgurl: wxUserItem.Headimgurl,
  144. CreateTime: time.Now(),
  145. }
  146. if wxUserItem.UnionID != `` {
  147. // 通过unionid获取已绑定用户的user_record信息
  148. bindUserRecord, _ := models.GetBindUserRecordByUnionId(wxUserItem.UnionID)
  149. if bindUserRecord != nil {
  150. newUserRecord.UserId = bindUserRecord.UserId
  151. newUserRecord.RealName = bindUserRecord.RealName
  152. newUserRecord.Sex = bindUserRecord.Sex
  153. newUserRecord.Province = bindUserRecord.Province
  154. newUserRecord.City = bindUserRecord.City
  155. newUserRecord.Country = bindUserRecord.Country
  156. newUserRecord.Headimgurl = bindUserRecord.Headimgurl
  157. }
  158. }
  159. err = newUserRecord.Insert()
  160. if err != nil {
  161. fmt.Println("关注后,添加user_record信息失败,err:" + err.Error())
  162. return
  163. }
  164. }
  165. // @Title 微信登录
  166. // @Description 微信登录
  167. // @Param request body models.LoginReq true "type json string"
  168. // @Success 200 {object} models.LoginResp
  169. // @router /login [post]
  170. func (this *WechatController) Login() {
  171. br := new(models.BaseResponse).Init()
  172. defer func() {
  173. if err := recover(); err != nil {
  174. fmt.Println(err)
  175. }
  176. this.Data["json"] = br
  177. this.ServeJSON()
  178. }()
  179. var req request.WeChatLoginReq
  180. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  181. if err != nil {
  182. br.Msg = "参数解析失败"
  183. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  184. return
  185. }
  186. if req.Code == "" {
  187. br.Msg = "授权码不存在"
  188. return
  189. }
  190. userInfo, err := wx_app.GetSession(req.Code)
  191. if err != nil {
  192. br.Msg = "登录失败,请重新尝试"
  193. br.ErrMsg = "用户信息获取失败,系统错误,Err:" + err.Error()
  194. return
  195. }
  196. user, err := models.GetUserByOpenId(userInfo.OpenID)
  197. if err != nil {
  198. if err.Error() == utils.ErrNoRow() && user == nil {
  199. tmpUser := &models.User{
  200. OpenId: userInfo.OpenID,
  201. UnionId: userInfo.UnionID,
  202. }
  203. tmpUserId, er := tmpUser.Insert()
  204. if er != nil {
  205. br.Msg = "登录失败"
  206. br.ErrMsg = "登录失败,新增用户信息失败:" + er.Error()
  207. return
  208. }
  209. user = tmpUser
  210. user.UserId = int(tmpUserId)
  211. } else {
  212. br.Msg = "获取用户信息失败"
  213. br.ErrMsg = "获取用户信息失败,系统错误,Err:" + err.Error()
  214. return
  215. }
  216. }
  217. var token string
  218. if user.AccessToken == "" {
  219. timeUnix := time.Now().Unix()
  220. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  221. token = utils.MD5(strconv.Itoa(user.UserId)) + utils.MD5(timeUnixStr)
  222. user.AccessToken = token
  223. _, err = user.Update([]string{"access_token"})
  224. if err != nil {
  225. br.Msg = "微信登录失败"
  226. br.ErrMsg = "微信登录失败,更新用户信息失败:" + err.Error()
  227. return
  228. }
  229. }
  230. token = user.AccessToken
  231. resp := new(response.WeChatLoginResp)
  232. resp.Authorization = token
  233. br.Data = resp
  234. br.Msg = "登录成功"
  235. br.Success = true
  236. br.Ret = 200
  237. }