wechat.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. WxId := "gh_5dc508325c6f" // 弘则投研公众号原始id
  58. xmlTpl = fmt.Sprintf(xmlTpl, openId, WxId, createTime, contactMsg)
  59. if item.MsgType == "event" {
  60. switch item.Event {
  61. case "subscribe":
  62. fmt.Println("关注")
  63. go subscribe(openId)
  64. case "unsubscribe":
  65. fmt.Println("取消关注")
  66. go unsubscribe(openId)
  67. case "CLICK":
  68. returnResult = xmlTpl
  69. default:
  70. utils.FileLog.Info("wechat notify event:" + item.Event)
  71. }
  72. this.Ctx.WriteString(xmlTpl)
  73. } else {
  74. returnResult = xmlTpl
  75. }
  76. this.Ctx.WriteString(returnResult)
  77. } else {
  78. this.Ctx.WriteString(echostr)
  79. }
  80. }
  81. // subscribe 关注后的处理逻辑
  82. func subscribe(openId string) {
  83. userRecord, err := models.GetUserRecordByOpenId(openId)
  84. if err != nil && err.Error() != utils.ErrNoRow() {
  85. fmt.Println("通过openid获取user_record记录失败,err:" + err.Error())
  86. return
  87. }
  88. err = nil
  89. // openId已存在
  90. if userRecord != nil {
  91. if userRecord.UserId > 0 && userRecord.UnionId != "" { //已经绑定了的话,那么就去修改用户状态
  92. models.UserSubscribe(1, openId)
  93. } else {
  94. // 没有绑定的话,那么校验下unionid,然后再去修改
  95. unionId := userRecord.UnionId
  96. if unionId == `` {
  97. wxUserItem, err := wechat.GetUserInfo(openId)
  98. if err != nil {
  99. fmt.Println("获取用户信息失败,err:" + err.Error())
  100. return
  101. }
  102. if wxUserItem.UnionID != `` {
  103. unionId = wxUserItem.UnionID
  104. }
  105. }
  106. userRecord.UnionId = unionId
  107. userRecord.Subscribe = 1
  108. userRecord.SubscribeTime = time.Now()
  109. err = userRecord.Update([]string{"union_id", "subscribe", "subscribe_time"})
  110. if err != nil {
  111. fmt.Println("关注后,通过openid更新user_record异常,err:", err)
  112. return
  113. }
  114. user, err := models.GetUserByUnionId(unionId)
  115. if err != nil {
  116. fmt.Println("关注后,通过unionid获取user记录失败,err:" + err.Error())
  117. return
  118. }
  119. if user != nil {
  120. user.IsSubscribed = true
  121. user.ModifyTime = time.Now()
  122. err = user.Update([]string{"modify_time", "is_subscribed"})
  123. if err != nil {
  124. fmt.Println("关注后,修改绑定用户状态异常,err:", err)
  125. return
  126. }
  127. }
  128. }
  129. return
  130. }
  131. // 没有记录,那么需要获取下unionid
  132. wxUserItem, err := wechat.GetUserInfo(openId)
  133. if err != nil {
  134. fmt.Println("获取用户信息失败,err:" + err.Error())
  135. return
  136. }
  137. newUserRecord := &models.UserRecord{
  138. OpenId: openId,
  139. UnionId: wxUserItem.UnionID,
  140. Subscribe: 1,
  141. SubscribeTime: time.Now(),
  142. NickName: wxUserItem.Nickname,
  143. Sex: int(wxUserItem.Sex),
  144. Province: wxUserItem.Province,
  145. City: wxUserItem.City,
  146. Country: wxUserItem.Country,
  147. Headimgurl: wxUserItem.Headimgurl,
  148. CreateTime: time.Now(),
  149. }
  150. insertId, err := newUserRecord.Insert()
  151. newUserRecord.UserRecordId = int(insertId)
  152. if err != nil {
  153. fmt.Println("关注后,添加user_record信息失败,err:" + err.Error())
  154. return
  155. }
  156. // 检测用户是否绑定小程序,如果绑定修改用户状态
  157. user, err := models.GetUserByUnionId(newUserRecord.UnionId)
  158. if err != nil {
  159. fmt.Println("修改绑定用户状态异常,ERR:", err)
  160. return
  161. }
  162. if user != nil {
  163. user.IsRegistered = true
  164. user.ModifyTime = time.Now()
  165. err = user.Update([]string{"is_registered", "modify_time"})
  166. if err != nil {
  167. fmt.Println("关注后,修改绑定用户状态异常,ERR:", err)
  168. return
  169. }
  170. }
  171. }
  172. // unsubscribe 取消关注后的处理逻辑
  173. func unsubscribe(openId string) {
  174. userRecord, err := models.GetUserRecordByOpenId(openId)
  175. if err != nil {
  176. return
  177. }
  178. userRecord.Subscribe = 0
  179. err = userRecord.Update([]string{"subscribe"})
  180. if err != nil {
  181. return
  182. }
  183. if userRecord.UnionId != "" {
  184. user, err := models.GetUserByUnionId(userRecord.UnionId)
  185. if err != nil {
  186. return
  187. }
  188. if user != nil {
  189. user.IsSubscribed = false
  190. user.ModifyTime = time.Now()
  191. err = user.Update([]string{"is_subscribed", "modify_time"})
  192. if err != nil {
  193. return
  194. }
  195. }
  196. }
  197. }
  198. // @Title 微信登录
  199. // @Description 微信登录
  200. // @Param request body models.LoginReq true "type json string"
  201. // @Success 200 {object} models.LoginResp
  202. // @router /login [post]
  203. func (this *WechatController) Login() {
  204. br := new(models.BaseResponse).Init()
  205. defer func() {
  206. if err := recover(); err != nil {
  207. fmt.Println(err)
  208. }
  209. this.Data["json"] = br
  210. this.ServeJSON()
  211. }()
  212. var req request.WeChatLoginReq
  213. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  214. if err != nil {
  215. br.Msg = "参数解析失败"
  216. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  217. return
  218. }
  219. if req.Code == "" {
  220. br.Msg = "授权码不存在"
  221. return
  222. }
  223. userInfo, err := wx_app.GetSession(req.Code)
  224. if err != nil {
  225. br.Msg = "登录失败,请重新尝试"
  226. br.ErrMsg = "用户信息获取失败,系统错误,Err:" + err.Error()
  227. return
  228. }
  229. session, err := models.GetWxSessionByOpenId(userInfo.OpenID)
  230. if err != nil && err.Error() != utils.ErrNoRow() {
  231. br.Msg = "登录失败,请重新尝试"
  232. br.ErrMsg = "用户信息获取失败,系统错误,Err:" + err.Error()
  233. return
  234. }
  235. if session == nil {
  236. session = &models.WxSession{
  237. OpenId: userInfo.OpenID,
  238. UnionId: userInfo.UnionID,
  239. CreateTime: time.Now(),
  240. }
  241. insertId, er := session.Insert()
  242. session.WxSessionId = int(insertId)
  243. if er != nil {
  244. br.Msg = "用户登录失败"
  245. br.ErrMsg = "用户登录获取失败,系统错误,Err:" + er.Error()
  246. return
  247. }
  248. }
  249. var token string
  250. timeUnix := time.Now().Unix()
  251. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  252. token = utils.MD5(session.OpenId) + utils.MD5(timeUnixStr)
  253. session.AccessToken = token
  254. session.LastUpdateTime = time.Now()
  255. err = session.Update([]string{"access_token", "last_update_time"})
  256. if err != nil {
  257. br.Msg = "微信登录失败"
  258. br.ErrMsg = "微信登录失败,更新用户信息失败:" + err.Error()
  259. return
  260. }
  261. token = session.AccessToken
  262. resp := new(response.WeChatLoginResp)
  263. resp.Authorization = token
  264. br.Data = resp
  265. br.Msg = "登录成功"
  266. br.Success = true
  267. br.Ret = 200
  268. }
  269. // @Title 公众号绑定
  270. // @Description 公众号绑定
  271. // @Param request body request.WeChatLoginReq true "type json string"
  272. // @Success 200 {object} models.LoginResp
  273. // @router /subscribe [post]
  274. func (this *WechatController) Subscribe() {
  275. br := new(models.BaseResponse).Init()
  276. defer func() {
  277. if err := recover(); err != nil {
  278. fmt.Println(err)
  279. }
  280. if br.Ret != 200 {
  281. b, _ := json.Marshal(br)
  282. alarm_msg.SendAlarmMsg(string(b), 1)
  283. }
  284. this.Data["json"] = br
  285. this.ServeJSON()
  286. }()
  287. var req request.WeChatLoginReq
  288. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  289. if err != nil {
  290. br.Msg = "参数解析失败"
  291. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  292. return
  293. }
  294. if req.Code == "" {
  295. br.Msg = "授权码不存在"
  296. return
  297. }
  298. info, err := wechat.GetWxUserInfo(req.Code)
  299. if err != nil {
  300. br.Msg = "获取失败"
  301. br.ErrMsg = "获取失败,Err:" + err.Error()
  302. return
  303. }
  304. if info.ErrCode != 0 {
  305. br.Msg = "获取失败"
  306. br.ErrMsg = "获取失败,Err:" + info.ErrMsg
  307. return
  308. }
  309. userRecord, err := models.GetUserRecordByOpenId(info.OpenId)
  310. if err != nil && err.Error() != utils.ErrNoRow() {
  311. br.Msg = "获取用户关注记录失败"
  312. br.ErrMsg = "获取用户关注记录失败,Err:" + err.Error()
  313. return
  314. }
  315. // 如果不存在就新增一条记录
  316. if userRecord == nil {
  317. userRecord := &models.UserRecord{
  318. OpenId: info.OpenId,
  319. }
  320. insertId, err := userRecord.Insert()
  321. if err != nil {
  322. br.Msg = "新增失败"
  323. br.ErrMsg = "新增失败,Err:" + err.Error()
  324. return
  325. }
  326. userRecord.UserRecordId = int(insertId)
  327. }
  328. if userRecord.UnionId == "" {
  329. wxInfo, er := wechat.GetUserInfo(userRecord.OpenId)
  330. if er != nil {
  331. br.Msg = "获取失败"
  332. br.ErrMsg = "获取失败,Err:" + er.Error()
  333. return
  334. }
  335. wxBody, _ := json.Marshal(wxInfo)
  336. alarm_msg.SendAlarmMsg(string(wxBody), 1)
  337. userRecord.UnionId = wxInfo.UnionID
  338. er = userRecord.Update([]string{"union_id"})
  339. if er != nil {
  340. br.Msg = "获取失败"
  341. br.ErrMsg = "获取失败,Err:" + er.Error()
  342. return
  343. }
  344. }
  345. user, err := models.GetUserByUnionId(userRecord.UnionId)
  346. if err != nil && err.Error() != utils.ErrNoRow() {
  347. br.Msg = "获取用户信息失败"
  348. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  349. return
  350. }
  351. if user != nil {
  352. user.IsSubscribed = true
  353. err := user.Update([]string{"is_subscribed"})
  354. if err != nil {
  355. br.Msg = "更新用户信息失败"
  356. br.ErrMsg = "更新用户信息失败,Err:" + err.Error()
  357. return
  358. }
  359. }
  360. br.Msg = "获取成功"
  361. br.Success = true
  362. br.Ret = 200
  363. }