wechat.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "encoding/xml"
  5. "fmt"
  6. "hongze/hongze_api/models"
  7. "hongze/hongze_api/services"
  8. "hongze/hongze_api/utils"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. type WechatController struct {
  14. BaseAuthController
  15. }
  16. type WechatCommonController struct {
  17. BaseCommonController
  18. }
  19. // @Title 微信登录接口
  20. // @Description 微信登录接口
  21. // @Param Code query string true "微信唯一编码code"
  22. // @Success 200 {object} models.WxLoginResp
  23. // @router /login [get]
  24. func (this *WechatCommonController) WechatLogin() {
  25. br := new(models.BaseResponse).Init()
  26. defer func() {
  27. this.Data["json"] = br
  28. this.ServeJSON()
  29. }()
  30. resp := new(models.WxLoginResp)
  31. code := this.GetString("Code")
  32. fmt.Println("code:", code)
  33. utils.FileLog.Info("WechatLogin code:%s", code)
  34. wxCodeInfo, err := models.GetWxUserCode(code)
  35. if err == nil && wxCodeInfo != nil && wxCodeInfo.Id > 0 {
  36. utils.FileLog.Info("WechatLogin code exist:%s", code)
  37. resp.UserId = wxCodeInfo.UserId
  38. resp.Code = 0
  39. resp.FirstLogin = wxCodeInfo.FirstLogin
  40. resp.Authorization = wxCodeInfo.Authorization
  41. resp.UserPermission = wxCodeInfo.UserPermission
  42. br.Ret = 200
  43. br.Success = true
  44. br.Msg = "登录成功"
  45. br.Data = resp
  46. return
  47. }
  48. item, err := services.WxGetUserOpenIdByCode(code)
  49. if err != nil {
  50. br.Msg = "获取用户信息失败"
  51. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  52. return
  53. }
  54. if item.Errcode != 0 {
  55. br.Msg = "获取用户信息失败"
  56. br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
  57. return
  58. }
  59. openId := item.Openid
  60. if openId == "" {
  61. br.Msg = "获取用户信息失败"
  62. br.ErrMsg = "获取openid失败,openid:" + item.Openid
  63. return
  64. }
  65. accessToken, err := services.WxGetAccessToken()
  66. if err != nil {
  67. br.Msg = "获取用户信息失败"
  68. br.ErrMsg = "获取access_token失败,err:" + err.Error()
  69. return
  70. }
  71. //获取用户信息
  72. wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
  73. if err != nil {
  74. br.Msg = "获取用户信息失败"
  75. br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
  76. return
  77. }
  78. if wxUserInfo.Errcode != 0 {
  79. userInfoJson, _ := json.Marshal(wxUserInfo)
  80. br.Msg = "登录失败"
  81. br.ErrMsg = "获取用户信息失败,err:" + string(userInfoJson)
  82. return
  83. }
  84. token, userId, firstLogin, permission, err := services.WxLogin(utils.WxPlatform, code, item, wxUserInfo)
  85. if err != nil {
  86. br.Msg = "微信登录失败"
  87. br.ErrMsg = "微信登录失败,err:" + err.Error()
  88. return
  89. }
  90. resp.UserId = userId
  91. resp.Code = 0
  92. resp.FirstLogin = firstLogin
  93. resp.Authorization = token
  94. resp.UserPermission = permission
  95. br.Ret = 200
  96. br.Success = true
  97. br.Msg = "登录成功"
  98. br.Data = resp
  99. //登录日志
  100. {
  101. returnResult, err := json.Marshal(br)
  102. if err != nil {
  103. utils.FileLog.Info(this.Ctx.Input.URI() + " Err:%s" + err.Error())
  104. }
  105. utils.FileLog.Info(this.Ctx.Input.URI()+" code: %s , return data: %s", code, string(returnResult))
  106. }
  107. }
  108. //作废于2021-03-29 10:14:54
  109. //func (this *WechatCommonController) WechatLoginV1() {
  110. // br := new(models.BaseResponse).Init()
  111. // defer func() {
  112. // this.Data["json"] = br
  113. // this.ServeJSON()
  114. // }()
  115. // resp := new(models.WxLoginResp)
  116. //
  117. // code := this.GetString("Code")
  118. // fmt.Println("code:", code)
  119. // utils.FileLog.Info("WechatLogin code:%s", code)
  120. // wxCodeInfo, err := models.GetWxUserCode(code)
  121. // if err == nil && wxCodeInfo != nil && wxCodeInfo.Id > 0 {
  122. // utils.FileLog.Info("WechatLogin code exist:%s", code)
  123. // resp.UserId = wxCodeInfo.UserId
  124. // resp.Code = 0
  125. // resp.FirstLogin = wxCodeInfo.FirstLogin
  126. // resp.Authorization = wxCodeInfo.Authorization
  127. // resp.UserPermission = wxCodeInfo.UserPermission
  128. // br.Ret = 200
  129. // br.Success = true
  130. // br.Msg = "登录成功"
  131. // br.Data = resp
  132. // return
  133. // }
  134. //
  135. // item, err := services.WxGetUserOpenIdByCode(code)
  136. // if err != nil {
  137. // br.Msg = "获取用户信息失败"
  138. // br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  139. // return
  140. // }
  141. // if item.Errcode != 0 {
  142. // br.Msg = "获取用户信息失败"
  143. // br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
  144. // return
  145. // }
  146. // openId := item.Openid
  147. // accessToken, err := services.WxGetAccessToken()
  148. // if err != nil {
  149. // br.Msg = "获取用户信息失败"
  150. // br.ErrMsg = "获取access_token失败,err:" + err.Error()
  151. // return
  152. // }
  153. // //获取用户信息
  154. // wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
  155. // if err != nil {
  156. // br.Msg = "获取用户信息失败"
  157. // br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
  158. // return
  159. // }
  160. // if wxUserInfo.Errcode != 0 {
  161. // userInfoJson, _ := json.Marshal(wxUserInfo)
  162. // br.Msg = "登录失败"
  163. // br.ErrMsg = "获取用户信息失败,err:" + string(userInfoJson)
  164. // return
  165. // }
  166. //
  167. // unionid := item.Unionid
  168. // if unionid == "" {
  169. // unionid = wxUserInfo.Unionid
  170. // }
  171. // firstLogin := 1
  172. // userId := 0
  173. // utils.FileLog.Info("openId:%s", openId)
  174. // utils.FileLog.Info("unionid:%s", unionid)
  175. // //获取成功
  176. // if openId != "" {
  177. // wxUser, err := models.GetWxUserItemByOpenId(openId)
  178. // if err != nil && err.Error() != utils.ErrNoRow() {
  179. // br.Msg = "获取用户信息失败"
  180. // br.ErrMsg = "根据openid获取用户信息失败,Eerr:" + err.Error()
  181. // return
  182. // }
  183. // if wxUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
  184. // user := new(models.WxUser)
  185. // user.OpenId = openId
  186. // user.CompanyId = 1
  187. // user.CreatedTime = time.Now()
  188. // user.UnionId = unionid
  189. // user.Unionid = unionid
  190. // user.NickName = wxUserInfo.Nickname
  191. // user.Sex = wxUserInfo.Sex
  192. // user.City = wxUserInfo.City
  193. // user.Province = wxUserInfo.Province
  194. // user.Country = wxUserInfo.Country
  195. // user.Headimgurl = wxUserInfo.Headimgurl
  196. // user.FirstLogin = 1
  197. // user.Enabled = 1
  198. // user.RegisterPlatform = 1
  199. // user.RegisterTime = time.Now()
  200. // _, err = models.AddWxUser(user)
  201. // wxUser, err = models.GetWxUserItemByOpenId(openId)
  202. // if err != nil {
  203. // br.Msg = "获取用户信息失败"
  204. // br.ErrMsg = "unionid登录,获取微信用户信息失败,Err:" + err.Error()
  205. // return
  206. // }
  207. // userId = wxUser.UserId
  208. // } else {
  209. // firstLogin = wxUser.FirstLogin
  210. // userId = wxUser.UserId
  211. // }
  212. // } else {
  213. // br.Msg = "获取用户信息失败"
  214. // br.ErrMsg = "获取openid失败,openid:" + item.Openid
  215. // return
  216. // }
  217. // permission, err := services.CheckUserPermission(userId)
  218. // if err != nil {
  219. // utils.FileLog.Info("userId:%s,err:%s", strconv.Itoa(userId), err)
  220. // }
  221. // //if err != nil {
  222. // // br.Msg = "登录失败"
  223. // // br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
  224. // // return
  225. // //}
  226. // var token string
  227. // tokenItem, err := models.GetTokenByUid(userId)
  228. // if err != nil && err.Error() != utils.ErrNoRow() {
  229. // br.Msg = "登录失败"
  230. // br.ErrMsg = "登录失败,获取token失败:" + err.Error()
  231. // return
  232. // }
  233. //
  234. // if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
  235. // timeUnix := time.Now().Unix()
  236. // timeUnixStr := strconv.FormatInt(timeUnix, 10)
  237. // token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
  238. // //新增session
  239. // {
  240. // session := new(models.Session)
  241. // session.OpenId = openId
  242. // session.UserId = userId
  243. // session.CreatedTime = time.Now()
  244. // session.LastUpdatedTime = time.Now()
  245. // session.ExpireTime = time.Now().AddDate(0, 3, 0)
  246. // session.AccessToken = token
  247. // err = models.AddSession(session)
  248. // if err != nil {
  249. // br.Msg = "登录失败"
  250. // br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
  251. // return
  252. // }
  253. // }
  254. // } else {
  255. // token = tokenItem.AccessToken
  256. // }
  257. //
  258. // if wxUserInfo != nil {
  259. // go models.ModifyWxUserInfo(wxUserInfo.Nickname, wxUserInfo.Headimgurl, wxUserInfo.City, wxUserInfo.Province, wxUserInfo.Country, wxUserInfo.Sex, userId)
  260. // }
  261. // //firstLogin==1,强制绑定手机号或者邮箱
  262. // {
  263. // newItem, _ := models.GetWxUserItemByUserId(userId)
  264. // if newItem.Mobile == "" && newItem.Email == "" {
  265. // firstLogin = 1
  266. // }
  267. // }
  268. // //新增登录日志
  269. // {
  270. // loginLog := new(models.WxUserLog)
  271. // loginLog.UserId = userId
  272. // loginLog.OpenId = openId
  273. // loginLog.UnionId = unionid
  274. // loginLog.CreateTime = time.Now()
  275. // loginLog.Handle = "wechat_login"
  276. // loginLog.Remark = token
  277. // go models.AddWxUserLog(loginLog)
  278. // }
  279. //
  280. // {
  281. // codeLog := new(models.WxUserCode)
  282. // codeLog.WxCode = code
  283. // codeLog.UserId = userId
  284. // codeLog.Code = 0
  285. // codeLog.FirstLogin = firstLogin
  286. // codeLog.Authorization = token
  287. // codeLog.UserPermission = permission
  288. // codeLog.CreateTime=time.Now()
  289. // models.AddWxUserCode(codeLog)
  290. // }
  291. //
  292. // resp.UserId = userId
  293. // resp.Code = 0
  294. // resp.FirstLogin = firstLogin
  295. // resp.Authorization = token
  296. // resp.UserPermission = permission
  297. // br.Ret = 200
  298. // br.Success = true
  299. // br.Msg = "登录成功"
  300. // br.Data = resp
  301. // //登录日志
  302. // {
  303. // returnResult, err := json.Marshal(br)
  304. // if err != nil {
  305. // utils.FileLog.Info(this.Ctx.Input.URI() + " Err:%s" + err.Error())
  306. // }
  307. // utils.FileLog.Info(this.Ctx.Input.URI()+" code: %s , return data: %s", code, string(returnResult))
  308. // }
  309. //}
  310. // @Title 微信获取签名接口
  311. // @Description 微信获取签名接口
  312. // @Param Url query string true "url地址"
  313. // @Success 200 {object} models.WechatSign
  314. // @router /getWxSign [get]
  315. func (this *WechatController) GetWxSign() {
  316. br := new(models.BaseResponse).Init()
  317. defer func() {
  318. this.Data["json"] = br
  319. this.ServeJSON()
  320. }()
  321. getUrl := this.GetString("Url")
  322. fmt.Println("getUrl:", getUrl)
  323. accessToken, err := services.WxGetAccessToken()
  324. if err != nil {
  325. br.Msg = "获取用户信息失败"
  326. br.ErrMsg = "获取access_token失败,err:" + err.Error()
  327. return
  328. }
  329. ticket, err := services.GetWxTicket(accessToken)
  330. if err != nil {
  331. br.Msg = "获取Ticket失败,请联系客服"
  332. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  333. return
  334. }
  335. if ticket == "" {
  336. br.Msg = "获取Ticket失败,请联系客服"
  337. br.ErrMsg = "ticket为空" + ticket
  338. return
  339. }
  340. nonceStr := utils.GetRandStringNoSpecialChar(16)
  341. signature, nonceString, timestamp := services.GetWxSignature(ticket, getUrl, nonceStr)
  342. resp := new(models.WechatSign)
  343. resp.AppId = utils.WxAppId
  344. resp.NonceStr = nonceString
  345. resp.Timestamp = timestamp
  346. resp.Url = getUrl
  347. resp.Signature = signature
  348. br.Ret = 200
  349. br.Success = true
  350. br.Msg = "获取签名成功"
  351. br.Data = resp
  352. }
  353. // @Title 微信获取签名接口
  354. // @Description 微信获取签名接口
  355. // @Param Url query string true "url地址"
  356. // @Success 200 {object} models.WechatSign
  357. // @router /notify [get,post]
  358. func (this *WechatCommonController) Notify() {
  359. echostr := this.GetString("echostr")
  360. method := this.Ctx.Input.Method()
  361. if method == "POST" {
  362. body := this.Ctx.Input.RequestBody
  363. utils.FileLog.Info("wechat notify:" + string(body))
  364. item := new(Notify)
  365. err := xml.Unmarshal(body, &item)
  366. if err != nil {
  367. utils.FileLog.Info("xml.Unmarshal:" + err.Error())
  368. }
  369. contactMsg := "感谢关注弘则研究。\r\n公司地址:上海市世纪大道210号21世纪中心大厦12层1206室\r\n\r\n业务合作:\r\n电话:86-21-61645300\r\n邮箱:service@hzinsights.com\r\n邮编:200120\r\n\r\n海外业务:\r\n邮箱:yyu@hzinsights.com "
  370. var openId, returnResult string
  371. if item.MsgType != "" {
  372. openId = item.FromUserName
  373. }
  374. xmlTpl := `<xml>
  375. <ToUserName><![CDATA[%s]]></ToUserName>
  376. <FromUserName><![CDATA[%s]]></FromUserName>
  377. <CreateTime>%s</CreateTime>
  378. <MsgType><![CDATA[text]]></MsgType>
  379. <Content><![CDATA[%s]]></Content>
  380. </xml>`
  381. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  382. xmlTpl = fmt.Sprintf(xmlTpl, openId, utils.WxId, createTime, contactMsg)
  383. if item.MsgType == "event" {
  384. switch item.Event {
  385. case "subscribe":
  386. fmt.Println("关注")
  387. go models.UserSubscribe(1, openId)
  388. break
  389. case "unsubscribe":
  390. fmt.Println("取消关注")
  391. go models.UserSubscribe(0, openId)
  392. break
  393. case "CLICK":
  394. returnResult = xmlTpl
  395. break
  396. default:
  397. utils.FileLog.Info("wechat notify event:" + item.Event)
  398. }
  399. this.Ctx.WriteString(xmlTpl)
  400. } else if item.MsgType == "text" {
  401. textXmlTpl := `<xml>
  402. <ToUserName><![CDATA[%s]]></ToUserName>
  403. <FromUserName><![CDATA[%s]]></FromUserName>
  404. <CreateTime>%s</CreateTime>
  405. <MsgType><![CDATA[text]]></MsgType>
  406. <Content><![CDATA[%s]]></Content>
  407. </xml>`
  408. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  409. classifyArr := utils.ClassifyArr
  410. var flag bool
  411. for _, v := range classifyArr {
  412. if strings.Contains(v, item.Content) || strings.Contains(item.Content, v) {
  413. flag=true
  414. }
  415. }
  416. if flag {
  417. contactMsg=`请点击研究报告-FICC研报,查看报告`
  418. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  419. this.Ctx.WriteString(textXmlTpl)
  420. return
  421. }
  422. reportNameArr := utils.ReportNameArr
  423. for _, v := range reportNameArr {
  424. if strings.Contains(v, item.Content) || strings.Contains(item.Content, v) {
  425. flag=true
  426. }
  427. }
  428. if flag {
  429. contactMsg=`请点击研究报告-FICC研报-研报(左上),查看报告`
  430. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  431. this.Ctx.WriteString(textXmlTpl)
  432. return
  433. }
  434. if strings.Contains("解绑", item.Content) || strings.Contains(item.Content, "解绑") ||
  435. strings.Contains("手机号", item.Content) || strings.Contains(item.Content, "手机号") {
  436. flag=true
  437. }
  438. if flag {
  439. contactMsg=`请通过电话联系我们或者联系销售人员处理`
  440. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  441. this.Ctx.WriteString(textXmlTpl)
  442. return
  443. }
  444. returnResult = xmlTpl
  445. this.Ctx.WriteString(returnResult)
  446. } else {
  447. returnResult = xmlTpl
  448. }
  449. this.Ctx.WriteString(returnResult)
  450. } else {
  451. this.Ctx.WriteString(echostr)
  452. }
  453. }
  454. type Notify struct {
  455. ToUserName string `xml:"ToUserName"`
  456. FromUserName string `xml:"FromUserName"`
  457. CreateTime int `xml:"CreateTime"`
  458. MsgType string `xml:"MsgType"`
  459. Event string `xml:"Event"`
  460. EventKey string `xml:"EventKey"`
  461. Content string `xml:"Content"`
  462. }