wechat.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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/services/wechat"
  9. "hongze/hongze_api/utils"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. type WechatController struct {
  15. BaseAuthController
  16. }
  17. type WechatCommonController struct {
  18. BaseCommonController
  19. }
  20. // @Title 微信登录接口
  21. // @Description 微信登录接口
  22. // @Param Code query string true "微信唯一编码code"
  23. // @Success 200 {object} models.WxLoginResp
  24. // @router /login [get]
  25. func (this *WechatCommonController) WechatLogin() {
  26. br := new(models.BaseResponse).Init()
  27. defer func() {
  28. this.Data["json"] = br
  29. this.ServeJSON()
  30. }()
  31. resp := new(models.WxLoginResp)
  32. code := this.GetString("Code")
  33. fmt.Println("code:", code)
  34. utils.FileLog.Info("WechatLogin code:%s", code)
  35. wxCodeInfo, err := models.GetWxUserCode(code)
  36. if err == nil && wxCodeInfo != nil && wxCodeInfo.Id > 0 {
  37. utils.FileLog.Info("WechatLogin code exist:%s", code)
  38. resp.UserId = wxCodeInfo.UserId
  39. resp.Code = 0
  40. resp.FirstLogin = wxCodeInfo.FirstLogin
  41. resp.Authorization = wxCodeInfo.Authorization
  42. resp.UserPermission = wxCodeInfo.UserPermission
  43. br.Ret = 200
  44. br.Success = true
  45. br.Msg = "登录成功"
  46. br.Data = resp
  47. return
  48. }
  49. item, err := services.WxGetUserOpenIdByCode(code)
  50. if err != nil {
  51. br.Msg = "获取用户信息失败"
  52. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  53. return
  54. }
  55. if item.Errcode != 0 {
  56. br.Msg = "获取用户信息失败"
  57. br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
  58. return
  59. }
  60. openId := item.Openid
  61. if openId == "" {
  62. br.Msg = "获取用户信息失败"
  63. br.ErrMsg = "获取openid失败,openid:" + item.Openid
  64. return
  65. }
  66. accessToken, err, errMsg := services.GetDefaultWxAccessToken()
  67. if err != nil {
  68. br.Msg = "获取用户信息失败"
  69. br.ErrMsg = errMsg
  70. return
  71. }
  72. //获取用户信息
  73. wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
  74. if err != nil {
  75. br.Msg = "获取用户信息失败"
  76. br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
  77. return
  78. }
  79. if wxUserInfo.Errcode != 0 {
  80. userInfoJson, _ := json.Marshal(wxUserInfo)
  81. br.Msg = "登录失败"
  82. br.ErrMsg = "获取用户信息失败,err:" + string(userInfoJson)
  83. return
  84. }
  85. token, userId, firstLogin, permission, err := services.WxLogin(utils.WxPlatform, code, item, wxUserInfo)
  86. if err != nil {
  87. br.Msg = "微信登录失败"
  88. br.ErrMsg = "微信登录失败,err:" + err.Error()
  89. return
  90. }
  91. resp.UserId = userId
  92. resp.Code = 0
  93. resp.FirstLogin = firstLogin
  94. resp.Authorization = token
  95. resp.UserPermission = permission
  96. br.Ret = 200
  97. br.Success = true
  98. br.Msg = "登录成功"
  99. br.Data = resp
  100. //登录日志
  101. {
  102. returnResult, err := json.Marshal(br)
  103. if err != nil {
  104. utils.FileLog.Info(this.Ctx.Input.URI() + " Err:%s" + err.Error())
  105. }
  106. utils.FileLog.Info(this.Ctx.Input.URI()+" code: %s , return data: %s", code, string(returnResult))
  107. }
  108. }
  109. //作废于2021-03-29 10:14:54
  110. //func (this *WechatCommonController) WechatLoginV1() {
  111. // br := new(models.BaseResponse).Init()
  112. // defer func() {
  113. // this.Data["json"] = br
  114. // this.ServeJSON()
  115. // }()
  116. // resp := new(models.WxLoginResp)
  117. //
  118. // code := this.GetString("Code")
  119. // fmt.Println("code:", code)
  120. // utils.FileLog.Info("WechatLogin code:%s", code)
  121. // wxCodeInfo, err := models.GetWxUserCode(code)
  122. // if err == nil && wxCodeInfo != nil && wxCodeInfo.Id > 0 {
  123. // utils.FileLog.Info("WechatLogin code exist:%s", code)
  124. // resp.UserId = wxCodeInfo.UserId
  125. // resp.Code = 0
  126. // resp.FirstLogin = wxCodeInfo.FirstLogin
  127. // resp.Authorization = wxCodeInfo.Authorization
  128. // resp.UserPermission = wxCodeInfo.UserPermission
  129. // br.Ret = 200
  130. // br.Success = true
  131. // br.Msg = "登录成功"
  132. // br.Data = resp
  133. // return
  134. // }
  135. //
  136. // item, err := services.WxGetUserOpenIdByCode(code)
  137. // if err != nil {
  138. // br.Msg = "获取用户信息失败"
  139. // br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  140. // return
  141. // }
  142. // if item.Errcode != 0 {
  143. // br.Msg = "获取用户信息失败"
  144. // br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
  145. // return
  146. // }
  147. // openId := item.Openid
  148. // accessToken, err := services.WxGetAccessToken()
  149. // if err != nil {
  150. // br.Msg = "获取用户信息失败"
  151. // br.ErrMsg = "获取access_token失败,err:" + err.Error()
  152. // return
  153. // }
  154. // //获取用户信息
  155. // wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
  156. // if err != nil {
  157. // br.Msg = "获取用户信息失败"
  158. // br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
  159. // return
  160. // }
  161. // if wxUserInfo.Errcode != 0 {
  162. // userInfoJson, _ := json.Marshal(wxUserInfo)
  163. // br.Msg = "登录失败"
  164. // br.ErrMsg = "获取用户信息失败,err:" + string(userInfoJson)
  165. // return
  166. // }
  167. //
  168. // unionid := item.Unionid
  169. // if unionid == "" {
  170. // unionid = wxUserInfo.Unionid
  171. // }
  172. // firstLogin := 1
  173. // userId := 0
  174. // utils.FileLog.Info("openId:%s", openId)
  175. // utils.FileLog.Info("unionid:%s", unionid)
  176. // //获取成功
  177. // if openId != "" {
  178. // wxUser, err := models.GetWxUserItemByOpenId(openId)
  179. // if err != nil && err.Error() != utils.ErrNoRow() {
  180. // br.Msg = "获取用户信息失败"
  181. // br.ErrMsg = "根据openid获取用户信息失败,Eerr:" + err.Error()
  182. // return
  183. // }
  184. // if wxUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
  185. // user := new(models.WxUser)
  186. // user.OpenId = openId
  187. // user.CompanyId = 1
  188. // user.CreatedTime = time.Now()
  189. // user.UnionId = unionid
  190. // user.Unionid = unionid
  191. // user.NickName = wxUserInfo.Nickname
  192. // user.Sex = wxUserInfo.Sex
  193. // user.City = wxUserInfo.City
  194. // user.Province = wxUserInfo.Province
  195. // user.Country = wxUserInfo.Country
  196. // user.Headimgurl = wxUserInfo.Headimgurl
  197. // user.FirstLogin = 1
  198. // user.Enabled = 1
  199. // user.RegisterPlatform = 1
  200. // user.RegisterTime = time.Now()
  201. // _, err = models.AddWxUser(user)
  202. // wxUser, err = models.GetWxUserItemByOpenId(openId)
  203. // if err != nil {
  204. // br.Msg = "获取用户信息失败"
  205. // br.ErrMsg = "unionid登录,获取微信用户信息失败,Err:" + err.Error()
  206. // return
  207. // }
  208. // userId = wxUser.UserId
  209. // } else {
  210. // firstLogin = wxUser.FirstLogin
  211. // userId = wxUser.UserId
  212. // }
  213. // } else {
  214. // br.Msg = "获取用户信息失败"
  215. // br.ErrMsg = "获取openid失败,openid:" + item.Openid
  216. // return
  217. // }
  218. // permission, err := services.CheckUserPermission(userId)
  219. // if err != nil {
  220. // utils.FileLog.Info("userId:%s,err:%s", strconv.Itoa(userId), err)
  221. // }
  222. // //if err != nil {
  223. // // br.Msg = "登录失败"
  224. // // br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
  225. // // return
  226. // //}
  227. // var token string
  228. // tokenItem, err := models.GetTokenByUid(userId)
  229. // if err != nil && err.Error() != utils.ErrNoRow() {
  230. // br.Msg = "登录失败"
  231. // br.ErrMsg = "登录失败,获取token失败:" + err.Error()
  232. // return
  233. // }
  234. //
  235. // if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
  236. // timeUnix := time.Now().Unix()
  237. // timeUnixStr := strconv.FormatInt(timeUnix, 10)
  238. // token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
  239. // //新增session
  240. // {
  241. // session := new(models.Session)
  242. // session.OpenId = openId
  243. // session.UserId = userId
  244. // session.CreatedTime = time.Now()
  245. // session.LastUpdatedTime = time.Now()
  246. // session.ExpireTime = time.Now().AddDate(0, 3, 0)
  247. // session.AccessToken = token
  248. // err = models.AddSession(session)
  249. // if err != nil {
  250. // br.Msg = "登录失败"
  251. // br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
  252. // return
  253. // }
  254. // }
  255. // } else {
  256. // token = tokenItem.AccessToken
  257. // }
  258. //
  259. // if wxUserInfo != nil {
  260. // go models.ModifyWxUserInfo(wxUserInfo.Nickname, wxUserInfo.Headimgurl, wxUserInfo.City, wxUserInfo.Province, wxUserInfo.Country, wxUserInfo.Sex, userId)
  261. // }
  262. // //firstLogin==1,强制绑定手机号或者邮箱
  263. // {
  264. // newItem, _ := models.GetWxUserItemByUserId(userId)
  265. // if newItem.Mobile == "" && newItem.Email == "" {
  266. // firstLogin = 1
  267. // }
  268. // }
  269. // //新增登录日志
  270. // {
  271. // loginLog := new(models.WxUserLog)
  272. // loginLog.UserId = userId
  273. // loginLog.OpenId = openId
  274. // loginLog.UnionId = unionid
  275. // loginLog.CreateTime = time.Now()
  276. // loginLog.Handle = "wechat_login"
  277. // loginLog.Remark = token
  278. // go models.AddWxUserLog(loginLog)
  279. // }
  280. //
  281. // {
  282. // codeLog := new(models.WxUserCode)
  283. // codeLog.WxCode = code
  284. // codeLog.UserId = userId
  285. // codeLog.Code = 0
  286. // codeLog.FirstLogin = firstLogin
  287. // codeLog.Authorization = token
  288. // codeLog.UserPermission = permission
  289. // codeLog.CreateTime=time.Now()
  290. // models.AddWxUserCode(codeLog)
  291. // }
  292. //
  293. // resp.UserId = userId
  294. // resp.Code = 0
  295. // resp.FirstLogin = firstLogin
  296. // resp.Authorization = token
  297. // resp.UserPermission = permission
  298. // br.Ret = 200
  299. // br.Success = true
  300. // br.Msg = "登录成功"
  301. // br.Data = resp
  302. // //登录日志
  303. // {
  304. // returnResult, err := json.Marshal(br)
  305. // if err != nil {
  306. // utils.FileLog.Info(this.Ctx.Input.URI() + " Err:%s" + err.Error())
  307. // }
  308. // utils.FileLog.Info(this.Ctx.Input.URI()+" code: %s , return data: %s", code, string(returnResult))
  309. // }
  310. //}
  311. // @Title 微信获取签名接口
  312. // @Description 微信获取签名接口
  313. // @Param Url query string true "url地址"
  314. // @Success 200 {object} models.WechatSign
  315. // @router /getWxSign [get]
  316. func (this *WechatController) GetWxSign() {
  317. br := new(models.BaseResponse).Init()
  318. defer func() {
  319. this.Data["json"] = br
  320. this.ServeJSON()
  321. }()
  322. // 微信配置信息
  323. conf, e := models.GetBusinessConf()
  324. if e != nil {
  325. br.Msg = "获取失败"
  326. br.ErrMsg = "获取配置失败, Err: " + e.Error()
  327. return
  328. }
  329. appId := ""
  330. appSecret := ""
  331. if v, ok := conf[models.BusinessConfWxAppId]; ok {
  332. appId = v
  333. }
  334. if v, ok := conf[models.BusinessConfWxAppSecret]; ok {
  335. appSecret = v
  336. }
  337. if appId == "" || appSecret == "" {
  338. br.Msg = "微信公众号信息未配置"
  339. return
  340. }
  341. getUrl := this.GetString("Url")
  342. fmt.Println("getUrl:", getUrl)
  343. tReq := wechat.WxTokenReq{
  344. WxAppId: appId,
  345. WxAppSecret: appSecret,
  346. }
  347. accessToken, err, errMsg := wechat.GetAccessToken(tReq)
  348. if err != nil {
  349. br.Msg = "获取微信配置失败"
  350. br.ErrMsg = "获取access_token失败,err:" + errMsg
  351. return
  352. }
  353. errCode, ticket, err := services.GetWxTicket(accessToken)
  354. if err != nil {
  355. if errCode == 40001 {
  356. accessToken, err, errMsg = wechat.GetAccessToken(tReq)
  357. if err != nil {
  358. br.Msg = "获取微信配置失败"
  359. br.ErrMsg = "获取access_token失败,err:" + errMsg
  360. return
  361. }
  362. errCode, ticket, err = services.GetWxTicket(accessToken)
  363. if err != nil {
  364. br.Msg = "获取Ticket失败,请联系客服"
  365. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  366. return
  367. }
  368. }
  369. br.Msg = "获取Ticket失败,请联系客服"
  370. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  371. return
  372. }
  373. if ticket == "" {
  374. br.Msg = "获取Ticket失败,请联系客服"
  375. br.ErrMsg = "ticket为空" + ticket
  376. return
  377. }
  378. nonceStr := utils.GetRandStringNoSpecialChar(16)
  379. signature, nonceString, timestamp := services.GetWxSignature(ticket, getUrl, nonceStr)
  380. resp := new(models.WechatSign)
  381. resp.AppId = appId
  382. resp.NonceStr = nonceString
  383. resp.Timestamp = timestamp
  384. resp.Url = getUrl
  385. resp.Signature = signature
  386. br.Ret = 200
  387. br.Success = true
  388. br.Msg = "获取签名成功"
  389. br.Data = resp
  390. }
  391. // @Title 微信获取签名接口
  392. // @Description 微信获取签名接口
  393. // @Param Url query string true "url地址"
  394. // @Success 200 {object} models.WechatSign
  395. // @router /notify [get,post]
  396. func (this *WechatCommonController) Notify() {
  397. echostr := this.GetString("echostr")
  398. method := this.Ctx.Input.Method()
  399. if method == "POST" {
  400. body := this.Ctx.Input.RequestBody
  401. utils.FileLog.Info("wechat notify:" + string(body))
  402. item := new(Notify)
  403. err := xml.Unmarshal(body, &item)
  404. if err != nil {
  405. utils.FileLog.Info("xml.Unmarshal:" + err.Error())
  406. }
  407. //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 "
  408. contactMsg := "您好,消息已经收到,后台在看到私信后将及时回复您。\r\n也可以在公众号菜单栏【关于我们】界面联系弘则小助手。"
  409. var openId, returnResult string
  410. if item.MsgType != "" {
  411. openId = item.FromUserName
  412. }
  413. tmpXmlTpl := `<xml>
  414. <ToUserName><![CDATA[%s]]></ToUserName>
  415. <FromUserName><![CDATA[%s]]></FromUserName>
  416. <CreateTime>%s</CreateTime>
  417. <MsgType><![CDATA[text]]></MsgType>
  418. <Content><![CDATA[%s]]></Content>
  419. </xml>`
  420. xmlTpl := `<xml>
  421. <ToUserName><![CDATA[%s]]></ToUserName>
  422. <FromUserName><![CDATA[%s]]></FromUserName>
  423. <CreateTime>%s</CreateTime>
  424. <MsgType><![CDATA[text]]></MsgType>
  425. <Content><![CDATA[%s]]></Content>
  426. </xml>`
  427. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  428. xmlTpl = fmt.Sprintf(xmlTpl, openId, utils.WxId, createTime, contactMsg)
  429. if item.MsgType == "event" {
  430. switch item.Event {
  431. case "subscribe":
  432. fmt.Println("关注")
  433. go subscribe(openId)
  434. textMsg := "感谢您关注弘则研究。\r\n作为中国资本市场的独立研究机构,今年是我们运用投研经验,服务全球投资者的第10年。\r\n眼下波动加剧、信息噪音激增,但弘则与你同行,我们希望运用自己在数据洪流与预期纠偏中反复训练而来的系统性智慧,让研究价值不止于验证过往,更能指引未来。\r\n\n市场合作、业务咨询,请在公众号菜单栏【关于我们】界面联系弘则小助手。"
  435. returnResult = fmt.Sprintf(tmpXmlTpl, openId, utils.WxId, createTime, textMsg)
  436. break
  437. case "unsubscribe":
  438. fmt.Println("取消关注")
  439. go models.UserSubscribe(0, openId)
  440. break
  441. case "CLICK":
  442. switch item.EventKey {
  443. case `contact`:
  444. imgXmlTpl := `<xml>
  445. <ToUserName><![CDATA[%s]]></ToUserName>
  446. <FromUserName><![CDATA[%s]]></FromUserName>
  447. <CreateTime>%s</CreateTime>
  448. <MsgType><![CDATA[image]]></MsgType>
  449. <Image>
  450. <MediaId><![CDATA[%s]]></MediaId>
  451. </Image>
  452. </xml>`
  453. etaHelperImg := `9BdElil_491Cghjq24Sk_UFmBN4UUcZVLLGzCIcIOQpnH2j5gI88UxIRm_WdTzNy`
  454. returnResult = fmt.Sprintf(imgXmlTpl, openId, utils.WxId, createTime, etaHelperImg)
  455. case `more_eta`:
  456. moreEtaMsg := "ETA智能投研平台,是弘则基于10年业内领先研究智慧训练开发的新一代投研引擎,将顶尖投研方法论深度融入平台体系,让用户在使用中自然提升专业分析能力,赋能全品类、跨场景的开创性研究。\r\n平台集成全端数据采集、多维指标图表、0代码量化分析、AI价格预测与大模型知识库,灵活输出报告及PPT,沉淀智力资产。\r\n通过ETA,可快速构建企业投研能力壁垒,以高效汇聚市场共识为起点,前瞻性洞察市场变化,构建投研一体的决策闭环。\r\n查看文章了解详情:https://mp.weixin.qq.com/s/UVYXGb_h9CzC3X-cp6T8OQ"
  457. returnResult = fmt.Sprintf(tmpXmlTpl, openId, utils.WxId, createTime, moreEtaMsg)
  458. default:
  459. returnResult = xmlTpl
  460. }
  461. break
  462. default:
  463. utils.FileLog.Info("wechat notify event:" + item.Event)
  464. returnResult = xmlTpl
  465. }
  466. this.Ctx.WriteString(returnResult)
  467. } else if item.MsgType == "text" {
  468. textXmlTpl := `<xml>
  469. <ToUserName><![CDATA[%s]]></ToUserName>
  470. <FromUserName><![CDATA[%s]]></FromUserName>
  471. <CreateTime>%s</CreateTime>
  472. <MsgType><![CDATA[text]]></MsgType>
  473. <Content><![CDATA[%s]]></Content>
  474. </xml>`
  475. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  476. classifyArr := utils.ClassifyArr
  477. var flag bool
  478. for _, v := range classifyArr {
  479. if strings.Contains(v, item.Content) || strings.Contains(item.Content, v) {
  480. flag = true
  481. }
  482. }
  483. if flag {
  484. contactMsg = `请点击研究报告-FICC研报,查看报告`
  485. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  486. this.Ctx.WriteString(textXmlTpl)
  487. return
  488. }
  489. reportNameArr := utils.ReportNameArr
  490. for _, v := range reportNameArr {
  491. if strings.Contains(v, item.Content) || strings.Contains(item.Content, v) {
  492. flag = true
  493. }
  494. }
  495. if flag {
  496. contactMsg = `请点击研究报告-FICC研报-研报(左上),查看报告`
  497. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  498. this.Ctx.WriteString(textXmlTpl)
  499. return
  500. }
  501. if strings.Contains("解绑", item.Content) || strings.Contains(item.Content, "解绑") ||
  502. strings.Contains("手机号", item.Content) || strings.Contains(item.Content, "手机号") {
  503. flag = true
  504. }
  505. if flag {
  506. contactMsg = `请通过电话联系我们或者联系销售人员处理`
  507. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  508. this.Ctx.WriteString(textXmlTpl)
  509. return
  510. }
  511. returnResult = xmlTpl
  512. this.Ctx.WriteString(returnResult)
  513. } else {
  514. returnResult = xmlTpl
  515. }
  516. this.Ctx.WriteString(returnResult)
  517. } else {
  518. this.Ctx.WriteString(echostr)
  519. }
  520. }
  521. type Notify struct {
  522. ToUserName string `xml:"ToUserName"`
  523. FromUserName string `xml:"FromUserName"`
  524. CreateTime int `xml:"CreateTime"`
  525. MsgType string `xml:"MsgType"`
  526. Event string `xml:"Event"`
  527. EventKey string `xml:"EventKey"`
  528. Content string `xml:"Content"`
  529. }
  530. // subscribe 关注后的处理逻辑
  531. func subscribe(openId string) {
  532. accessToken, err, _ := services.GetDefaultWxAccessToken()
  533. if err != nil {
  534. fmt.Println("获取access_token失败,err:" + err.Error())
  535. return
  536. }
  537. userRecord, err := models.GetUserRecordByOpenId(openId)
  538. if err != nil && err.Error() != utils.ErrNoRow() {
  539. fmt.Println("通过openid获取user_record记录失败,err:" + err.Error())
  540. return
  541. }
  542. err = nil
  543. // openId已存在
  544. if userRecord != nil {
  545. if userRecord.UserId > 0 { //已经绑定了的话,那么就去修改用户状态
  546. models.UserSubscribe(1, openId)
  547. } else {
  548. // 没有绑定的话,那么校验下unionid,然后再去修改
  549. unionId := userRecord.UnionId
  550. if unionId == `` {
  551. wxUserItem, err := services.WxGetUserInfo(openId, accessToken)
  552. if err != nil {
  553. fmt.Println("获取用户信息失败,err:" + err.Error())
  554. return
  555. }
  556. if wxUserItem.Unionid != `` {
  557. unionId = wxUserItem.Unionid
  558. }
  559. }
  560. updateCol := make([]string, 0)
  561. userRecord.Subscribe = 1
  562. userRecord.SubscribeTime = time.Now()
  563. updateCol = append(updateCol, "Subscribe")
  564. if unionId != `` {
  565. userRecord.UnionId = unionId
  566. // 通过unionid获取已绑定用户的user_record信息
  567. bindUserRecord, _ := models.GetBindUserRecordByUnionId(unionId)
  568. if bindUserRecord != nil {
  569. userRecord.UserId = bindUserRecord.UserId
  570. userRecord.RealName = bindUserRecord.RealName
  571. userRecord.BindAccount = bindUserRecord.BindAccount
  572. userRecord.Sex = bindUserRecord.Sex
  573. updateCol = append(updateCol, "UserId", "RealName", "BindAccount")
  574. }
  575. }
  576. err = userRecord.Update(updateCol)
  577. if err != nil {
  578. fmt.Println("关注后,通过openid更新user_record异常,ERR:", err)
  579. }
  580. }
  581. return
  582. }
  583. // 没有记录,那么需要获取下unionid
  584. wxUserItem, err := services.WxGetUserInfo(openId, accessToken)
  585. if err != nil {
  586. fmt.Println("获取用户信息失败,err:" + err.Error())
  587. return
  588. }
  589. newUserRecord := &models.UserRecord{
  590. UserRecordId: 0,
  591. OpenId: openId,
  592. UnionId: wxUserItem.Unionid,
  593. Subscribe: 1,
  594. SubscribeTime: time.Now(),
  595. NickName: wxUserItem.Nickname,
  596. Sex: wxUserItem.Sex,
  597. Province: wxUserItem.Province,
  598. City: wxUserItem.City,
  599. Country: wxUserItem.Country,
  600. Headimgurl: wxUserItem.Headimgurl,
  601. CreateTime: time.Now(),
  602. CreatePlatform: 1,
  603. SessionKey: "",
  604. }
  605. if wxUserItem.Unionid != `` {
  606. // 通过unionid获取已绑定用户的user_record信息
  607. bindUserRecord, _ := models.GetBindUserRecordByUnionId(wxUserItem.Unionid)
  608. if bindUserRecord != nil {
  609. newUserRecord.UserId = bindUserRecord.UserId
  610. newUserRecord.RealName = bindUserRecord.RealName
  611. newUserRecord.BindAccount = bindUserRecord.BindAccount
  612. newUserRecord.Sex = bindUserRecord.Sex
  613. newUserRecord.Province = bindUserRecord.Province
  614. newUserRecord.City = bindUserRecord.City
  615. newUserRecord.Country = bindUserRecord.Country
  616. newUserRecord.Headimgurl = bindUserRecord.Headimgurl
  617. }
  618. }
  619. _, err = models.AddUserRecord(newUserRecord)
  620. if err != nil {
  621. fmt.Println("关注后,添加user_record信息失败,err:" + err.Error())
  622. return
  623. }
  624. }
  625. // @Title 微信获取签名接口-无token校验
  626. // @Description 微信获取签名接口
  627. // @Param Url query string true "url地址"
  628. // @Success 200 {object} models.WechatSign
  629. // @router /open/getWxSign [get]
  630. func (this *WechatCommonController) GetWxSign() {
  631. br := new(models.BaseResponse).Init()
  632. defer func() {
  633. this.Data["json"] = br
  634. this.ServeJSON()
  635. }()
  636. // 微信配置信息
  637. conf, e := models.GetBusinessConf()
  638. if e != nil {
  639. br.Msg = "获取失败"
  640. br.ErrMsg = "获取配置信息失败, Err: " + e.Error()
  641. return
  642. }
  643. appId := ""
  644. appSecret := ""
  645. if v, ok := conf[models.BusinessConfWxAppId]; ok {
  646. appId = v
  647. }
  648. if v, ok := conf[models.BusinessConfWxAppSecret]; ok {
  649. appSecret = v
  650. }
  651. if appId == "" || appSecret == "" {
  652. br.Msg = "微信公众号信息未配置"
  653. return
  654. }
  655. getUrl := this.GetString("Url")
  656. fmt.Println("getUrl:", getUrl)
  657. tReq := wechat.WxTokenReq{
  658. WxAppId: appId,
  659. WxAppSecret: appSecret,
  660. }
  661. accessToken, err, errMsg := wechat.GetAccessToken(tReq)
  662. if err != nil {
  663. br.Msg = "获取微信配置失败"
  664. br.ErrMsg = "获取access_token失败,err:" + errMsg
  665. return
  666. }
  667. errCode, ticket, err := services.GetWxTicket(accessToken)
  668. if err != nil {
  669. if errCode == 40001 {
  670. accessToken, err, errMsg = wechat.GetAccessToken(tReq)
  671. if err != nil {
  672. br.Msg = "获取微信配置失败"
  673. br.ErrMsg = "获取access_token失败,err:" + errMsg
  674. return
  675. }
  676. errCode, ticket, err = services.GetWxTicket(accessToken)
  677. if err != nil {
  678. br.Msg = "获取Ticket失败,请联系客服"
  679. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  680. return
  681. }
  682. }
  683. br.Msg = "获取Ticket失败,请联系客服"
  684. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  685. return
  686. }
  687. if ticket == "" {
  688. br.Msg = "获取Ticket失败,请联系客服"
  689. br.ErrMsg = "ticket为空" + ticket
  690. return
  691. }
  692. nonceStr := utils.GetRandStringNoSpecialChar(16)
  693. signature, nonceString, timestamp := services.GetWxSignature(ticket, getUrl, nonceStr)
  694. resp := new(models.WechatSign)
  695. resp.AppId = appId
  696. resp.NonceStr = nonceString
  697. resp.Timestamp = timestamp
  698. resp.Url = getUrl
  699. resp.Signature = signature
  700. br.Ret = 200
  701. br.Success = true
  702. br.Msg = "获取签名成功"
  703. br.Data = resp
  704. }