wechat.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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/alarm_msg"
  9. "eta/eta_mini_api/services/wechat"
  10. "eta/eta_mini_api/services/wx_app"
  11. "eta/eta_mini_api/utils"
  12. "fmt"
  13. "strconv"
  14. "time"
  15. )
  16. type WechatController struct {
  17. BaseCommonController
  18. }
  19. // @Title 微信获取签名接口
  20. // @Description 微信获取签名接口
  21. // @Param Url query string true "url地址"
  22. // @Success 200 {object} models.WechatSign
  23. // @router /notify [get,post]
  24. func (this *WechatController) Notify() {
  25. echostr := this.GetString("echostr")
  26. method := this.Ctx.Input.Method()
  27. type Notify struct {
  28. ToUserName string `xml:"ToUserName"`
  29. FromUserName string `xml:"FromUserName"`
  30. CreateTime int `xml:"CreateTime"`
  31. MsgType string `xml:"MsgType"`
  32. Event string `xml:"Event"`
  33. EventKey string `xml:"EventKey"`
  34. Content string `xml:"Content"`
  35. }
  36. if method == "POST" {
  37. body := this.Ctx.Input.RequestBody
  38. utils.FileLog.Info("wechat notify:" + string(body))
  39. item := new(Notify)
  40. err := xml.Unmarshal(body, &item)
  41. if err != nil {
  42. utils.FileLog.Info("xml.Unmarshal:" + err.Error())
  43. }
  44. contactMsg := "感谢关注东吴期货研究所\r\n公司地址:上海市黄浦区西藏南路1208号东吴证券大厦19楼\r\n\r\n业务合作:\r\n电话:021-6312 3065\r\n邮箱:lvan@dwqh88.com\r\n邮编:200001"
  45. var openId, returnResult string
  46. if item.MsgType != "" {
  47. openId = item.FromUserName
  48. }
  49. xmlTpl := `<xml>
  50. <ToUserName><![CDATA[%s]]></ToUserName>
  51. <FromUserName><![CDATA[%s]]></FromUserName>
  52. <CreateTime>%s</CreateTime>
  53. <MsgType><![CDATA[text]]></MsgType>
  54. <Content><![CDATA[%s]]></Content>
  55. </xml>`
  56. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  57. xmlTpl = fmt.Sprintf(xmlTpl, openId, utils.DW_WX_Id, createTime, contactMsg)
  58. if item.MsgType == "event" {
  59. switch item.Event {
  60. case "subscribe":
  61. fmt.Println("关注")
  62. go subscribe(openId)
  63. case "unsubscribe":
  64. fmt.Println("取消关注")
  65. go models.UserSubscribe(0, openId)
  66. case "CLICK":
  67. returnResult = xmlTpl
  68. default:
  69. utils.FileLog.Info("wechat notify event:" + item.Event)
  70. }
  71. this.Ctx.WriteString(xmlTpl)
  72. } else {
  73. returnResult = xmlTpl
  74. }
  75. this.Ctx.WriteString(returnResult)
  76. } else {
  77. this.Ctx.WriteString(echostr)
  78. }
  79. }
  80. // subscribe 关注后的处理逻辑
  81. func subscribe(openId string) {
  82. userRecord, err := models.GetUserRecordByOpenId(openId)
  83. if err != nil && err.Error() != utils.ErrNoRow() {
  84. fmt.Println("通过openid获取user_record记录失败,err:" + err.Error())
  85. return
  86. }
  87. err = nil
  88. // openId已存在
  89. if userRecord != nil {
  90. if userRecord.UserId > 0 { //已经绑定了的话,那么就去修改用户状态
  91. models.UserSubscribe(1, openId)
  92. } else {
  93. // 没有绑定的话,那么校验下unionid,然后再去修改
  94. unionId := userRecord.UnionId
  95. if unionId == `` {
  96. wxUserItem, err := wechat.GetUserInfo(openId)
  97. if err != nil {
  98. fmt.Println("获取用户信息失败,err:" + err.Error())
  99. return
  100. }
  101. if wxUserItem.UnionID != `` {
  102. unionId = wxUserItem.UnionID
  103. }
  104. }
  105. updateCol := make([]string, 0)
  106. userRecord.Subscribe = 1
  107. userRecord.SubscribeTime = time.Now()
  108. updateCol = append(updateCol, "Subscribe")
  109. if unionId != `` {
  110. userRecord.UnionId = unionId
  111. // 通过unionid获取已绑定用户的user_record信息
  112. bindUserRecord, _ := models.GetBindUserRecordByUnionId(unionId)
  113. if bindUserRecord != nil {
  114. userRecord.UserId = bindUserRecord.UserId
  115. userRecord.RealName = bindUserRecord.RealName
  116. userRecord.Sex = bindUserRecord.Sex
  117. updateCol = append(updateCol, "UserId", "RealName")
  118. }
  119. }
  120. err = userRecord.Update(updateCol)
  121. if err != nil {
  122. fmt.Println("关注后,通过openid更新user_record异常,ERR:", err)
  123. }
  124. }
  125. return
  126. }
  127. // 没有记录,那么需要获取下unionid
  128. wxUserItem, err := wechat.GetUserInfo(openId)
  129. if err != nil {
  130. fmt.Println("获取用户信息失败,err:" + err.Error())
  131. return
  132. }
  133. newUserRecord := &models.UserRecord{
  134. UserRecordId: 0,
  135. OpenId: openId,
  136. UnionId: wxUserItem.UnionID,
  137. Subscribe: 1,
  138. SubscribeTime: time.Now(),
  139. NickName: wxUserItem.Nickname,
  140. Sex: int(wxUserItem.Sex),
  141. Province: wxUserItem.Province,
  142. City: wxUserItem.City,
  143. Country: wxUserItem.Country,
  144. Headimgurl: wxUserItem.Headimgurl,
  145. CreateTime: time.Now(),
  146. }
  147. if wxUserItem.UnionID != `` {
  148. // 通过unionid获取已绑定用户的user_record信息
  149. bindUserRecord, _ := models.GetBindUserRecordByUnionId(wxUserItem.UnionID)
  150. if bindUserRecord != nil {
  151. newUserRecord.UserId = bindUserRecord.UserId
  152. newUserRecord.RealName = bindUserRecord.RealName
  153. newUserRecord.Sex = bindUserRecord.Sex
  154. newUserRecord.Province = bindUserRecord.Province
  155. newUserRecord.City = bindUserRecord.City
  156. newUserRecord.Country = bindUserRecord.Country
  157. newUserRecord.Headimgurl = bindUserRecord.Headimgurl
  158. }
  159. }
  160. insertId, err := newUserRecord.Insert()
  161. newUserRecord.UserRecordId = int(insertId)
  162. if err != nil {
  163. fmt.Println("关注后,添加user_record信息失败,err:" + err.Error())
  164. return
  165. }
  166. }
  167. // @Title 微信登录
  168. // @Description 微信登录
  169. // @Param request body models.LoginReq true "type json string"
  170. // @Success 200 {object} models.LoginResp
  171. // @router /login [post]
  172. func (this *WechatController) Login() {
  173. br := new(models.BaseResponse).Init()
  174. defer func() {
  175. if err := recover(); err != nil {
  176. fmt.Println(err)
  177. }
  178. this.Data["json"] = br
  179. this.ServeJSON()
  180. }()
  181. var req request.WeChatLoginReq
  182. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  183. if err != nil {
  184. br.Msg = "参数解析失败"
  185. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  186. return
  187. }
  188. if req.Code == "" {
  189. br.Msg = "授权码不存在"
  190. return
  191. }
  192. userInfo, err := wx_app.GetSession(req.Code)
  193. if err != nil {
  194. br.Msg = "登录失败,请重新尝试"
  195. br.ErrMsg = "用户信息获取失败,系统错误,Err:" + err.Error()
  196. return
  197. }
  198. session, err := models.GetWxSessionByOpenId(userInfo.OpenID)
  199. if err != nil && err.Error() != utils.ErrNoRow() {
  200. br.Msg = "登录失败,请重新尝试"
  201. br.ErrMsg = "用户信息获取失败,系统错误,Err:" + err.Error()
  202. return
  203. }
  204. if session == nil {
  205. session = &models.WxSession{
  206. OpenId: userInfo.OpenID,
  207. UnionId: userInfo.UnionID,
  208. CreateTime: time.Now(),
  209. }
  210. insertId, er := session.Insert()
  211. session.WxSessionId = int(insertId)
  212. if er != nil {
  213. br.Msg = "用户登录失败"
  214. br.ErrMsg = "用户登录获取失败,系统错误,Err:" + er.Error()
  215. return
  216. }
  217. }
  218. var token string
  219. timeUnix := time.Now().Unix()
  220. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  221. token = utils.MD5(session.OpenId) + utils.MD5(timeUnixStr)
  222. session.AccessToken = token
  223. session.LastUpdateTime = time.Now()
  224. err = session.Update([]string{"access_token", "last_update_time"})
  225. if err != nil {
  226. br.Msg = "微信登录失败"
  227. br.ErrMsg = "微信登录失败,更新用户信息失败:" + err.Error()
  228. return
  229. }
  230. token = session.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. }
  238. // @Title 公众号绑定
  239. // @Description 公众号绑定
  240. // @Param request body request.WeChatLoginReq true "type json string"
  241. // @Success 200 {object} models.LoginResp
  242. // @router /subscribe [post]
  243. func (this *WechatController) Subscribe() {
  244. br := new(models.BaseResponse).Init()
  245. defer func() {
  246. if err := recover(); err != nil {
  247. fmt.Println(err)
  248. }
  249. this.Data["json"] = br
  250. this.ServeJSON()
  251. }()
  252. var req request.WeChatLoginReq
  253. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  254. if err != nil {
  255. br.Msg = "参数解析失败"
  256. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  257. return
  258. }
  259. if req.Code == "" {
  260. br.Msg = "授权码不存在"
  261. return
  262. }
  263. info, err := wechat.GetWxUserInfo(req.Code)
  264. if err != nil {
  265. br.Msg = "获取失败"
  266. br.ErrMsg = "获取失败,Err:" + err.Error()
  267. return
  268. }
  269. bodyInfo, _ := json.Marshal(info)
  270. alarm_msg.SendAlarmMsg(string(bodyInfo), 1)
  271. if info.ErrCode != 0 {
  272. br.Msg = "获取失败"
  273. br.ErrMsg = "获取失败,Err:" + info.ErrMsg
  274. return
  275. }
  276. u := &models.UserRecord{
  277. OpenId: info.OpenId,
  278. UnionId: info.UnionId,
  279. }
  280. _, err = u.Insert()
  281. if err != nil {
  282. br.Msg = "新增失败"
  283. br.ErrMsg = "新增失败,Err:" + err.Error()
  284. return
  285. }
  286. if u.UnionId == "" {
  287. wxInfo, er := wechat.GetUserInfo(u.OpenId)
  288. if er != nil {
  289. br.Msg = "获取失败"
  290. br.ErrMsg = "获取失败,Err:" + er.Error()
  291. return
  292. }
  293. wxBody, _ := json.Marshal(wxInfo)
  294. alarm_msg.SendAlarmMsg(string(wxBody), 1)
  295. u.UnionId = wxInfo.UnionID
  296. er = u.Update([]string{"union_id"})
  297. if er != nil {
  298. br.Msg = "获取失败"
  299. br.ErrMsg = "获取失败,Err:" + er.Error()
  300. return
  301. }
  302. }
  303. user, err := models.GetUserByUnionId(u.UnionId)
  304. if err != nil && err.Error() != utils.ErrNoRow() {
  305. br.Msg = "获取用户信息失败"
  306. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  307. return
  308. }
  309. if user != nil {
  310. user.IsSubscribed = true
  311. err := user.Update([]string{"is_subscribed"})
  312. if err != nil {
  313. br.Msg = "更新用户信息失败"
  314. br.ErrMsg = "更新用户信息失败,Err:" + err.Error()
  315. return
  316. }
  317. }
  318. br.Msg = "获取成功"
  319. br.Success = true
  320. br.Ret = 200
  321. }