wechat.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. insertId, err := newUserRecord.Insert()
  160. newUserRecord.UserRecordId = int(insertId)
  161. if err != nil {
  162. fmt.Println("关注后,添加user_record信息失败,err:" + err.Error())
  163. return
  164. }
  165. }
  166. // @Title 微信登录
  167. // @Description 微信登录
  168. // @Param request body models.LoginReq true "type json string"
  169. // @Success 200 {object} models.LoginResp
  170. // @router /login [post]
  171. func (this *WechatController) Login() {
  172. br := new(models.BaseResponse).Init()
  173. defer func() {
  174. if err := recover(); err != nil {
  175. fmt.Println(err)
  176. }
  177. this.Data["json"] = br
  178. this.ServeJSON()
  179. }()
  180. var req request.WeChatLoginReq
  181. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  182. if err != nil {
  183. br.Msg = "参数解析失败"
  184. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  185. return
  186. }
  187. if req.Code == "" {
  188. br.Msg = "授权码不存在"
  189. return
  190. }
  191. userInfo, err := wx_app.GetSession(req.Code)
  192. if err != nil {
  193. br.Msg = "登录失败,请重新尝试"
  194. br.ErrMsg = "用户信息获取失败,系统错误,Err:" + err.Error()
  195. return
  196. }
  197. session, err := models.GetWxSessionByOpenId(userInfo.OpenID)
  198. if err != nil && err.Error() != utils.ErrNoRow() {
  199. br.Msg = "登录失败,请重新尝试"
  200. br.ErrMsg = "用户信息获取失败,系统错误,Err:" + err.Error()
  201. return
  202. }
  203. if session == nil {
  204. session = &models.WxSession{
  205. OpenId: userInfo.OpenID,
  206. UnionId: userInfo.UnionID,
  207. CreateTime: time.Now(),
  208. }
  209. insertId, er := session.Insert()
  210. session.WxSessionId = int(insertId)
  211. if er != nil {
  212. br.Msg = "用户登录失败"
  213. br.ErrMsg = "用户登录获取失败,系统错误,Err:" + er.Error()
  214. return
  215. }
  216. }
  217. var token string
  218. timeUnix := time.Now().Unix()
  219. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  220. token = utils.MD5(session.OpenId) + utils.MD5(timeUnixStr)
  221. session.AccessToken = token
  222. session.LastUpdateTime = time.Now()
  223. err = session.Update([]string{"access_token", "last_update_time"})
  224. if err != nil {
  225. br.Msg = "微信登录失败"
  226. br.ErrMsg = "微信登录失败,更新用户信息失败:" + err.Error()
  227. return
  228. }
  229. token = session.AccessToken
  230. resp := new(response.WeChatLoginResp)
  231. resp.Authorization = token
  232. br.Data = resp
  233. br.Msg = "登录成功"
  234. br.Success = true
  235. br.Ret = 200
  236. }
  237. // @Title 公众号绑定
  238. // @Description 公众号绑定
  239. // @Param request body request.WeChatLoginReq true "type json string"
  240. // @Success 200 {object} models.LoginResp
  241. // @router /subscribe [post]
  242. func (this *WechatController) Subscribe() {
  243. br := new(models.BaseResponse).Init()
  244. defer func() {
  245. if err := recover(); err != nil {
  246. fmt.Println(err)
  247. }
  248. this.Data["json"] = br
  249. this.ServeJSON()
  250. }()
  251. var req request.WeChatLoginReq
  252. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  253. if err != nil {
  254. br.Msg = "参数解析失败"
  255. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  256. return
  257. }
  258. if req.Code == "" {
  259. br.Msg = "授权码不存在"
  260. return
  261. }
  262. info, err := wechat.GetWxUserInfo(req.Code)
  263. if err != nil {
  264. br.Msg = "获取失败"
  265. br.ErrMsg = "获取失败,Err:" + err.Error()
  266. return
  267. }
  268. if info.ErrCode != 0 {
  269. br.Msg = "获取失败"
  270. br.ErrMsg = "获取失败,Err:" + info.ErrMsg
  271. return
  272. }
  273. u := &models.UserRecord{
  274. OpenId: info.OpenId,
  275. UnionId: info.UnionId,
  276. }
  277. _, err = u.Insert()
  278. if err != nil {
  279. br.Msg = "新增失败"
  280. br.ErrMsg = "新增失败,Err:" + err.Error()
  281. return
  282. }
  283. if u.UnionId == "" {
  284. wxInfo, er := wechat.GetUserInfo(u.OpenId)
  285. if er != nil {
  286. br.Msg = "获取失败"
  287. br.ErrMsg = "获取失败,Err:" + er.Error()
  288. return
  289. }
  290. u.UnionId = wxInfo.UnionID
  291. er = u.Update([]string{"union_id"})
  292. if er != nil {
  293. br.Msg = "获取失败"
  294. br.ErrMsg = "获取失败,Err:" + er.Error()
  295. return
  296. }
  297. }
  298. user, err := models.GetUserByUnionId(u.UnionId)
  299. if err != nil && err.Error() != utils.ErrNoRow() {
  300. br.Msg = "获取用户信息失败"
  301. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  302. return
  303. }
  304. if user != nil {
  305. user.IsSubscribed = true
  306. err := user.Update([]string{"is_subscribed"})
  307. if err != nil {
  308. br.Msg = "更新用户信息失败"
  309. br.ErrMsg = "更新用户信息失败,Err:" + err.Error()
  310. return
  311. }
  312. }
  313. br.Msg = "获取成功"
  314. br.Success = true
  315. br.Ret = 200
  316. }