wechat.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. xmlTpl = fmt.Sprintf(xmlTpl, 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[img]]></MsgType>
  449. <Content><![CDATA[%s]]></Content>
  450. </xml>`
  451. etaHelperImg := `9BdElil_491Cghjq24Sk_UFmBN4UUcZVLLGzCIcIOQpnH2j5gI88UxIRm_WdTzNy`
  452. xmlTpl = fmt.Sprintf(imgXmlTpl, openId, utils.WxId, createTime, etaHelperImg)
  453. case `more_eta`:
  454. moreEtaMsg := "ETA智能投研平台,是弘则基于10年业内领先研究智慧训练开发的新一代投研引擎,将顶尖投研方法论深度融入平台体系,让用户在使用中自然提升专业分析能力,赋能全品类、跨场景的开创性研究。\r\n平台集成全端数据采集、多维指标图表、0代码量化分析、AI价格预测与大模型知识库,灵活输出报告及PPT,沉淀智力资产。\r\n通过ETA,可快速构建企业投研能力壁垒,以高效汇聚市场共识为起点,前瞻性洞察市场变化,构建投研一体的决策闭环。\r\n查看文章了解详情:点击查看【https://mp.weixin.qq.com/s/UVYXGb_h9CzC3X-cp6T8OQ】"
  455. xmlTpl = fmt.Sprintf(tmpXmlTpl, openId, utils.WxId, createTime, moreEtaMsg)
  456. default:
  457. returnResult = xmlTpl
  458. }
  459. break
  460. default:
  461. utils.FileLog.Info("wechat notify event:" + item.Event)
  462. }
  463. this.Ctx.WriteString(xmlTpl)
  464. } else if item.MsgType == "text" {
  465. textXmlTpl := `<xml>
  466. <ToUserName><![CDATA[%s]]></ToUserName>
  467. <FromUserName><![CDATA[%s]]></FromUserName>
  468. <CreateTime>%s</CreateTime>
  469. <MsgType><![CDATA[text]]></MsgType>
  470. <Content><![CDATA[%s]]></Content>
  471. </xml>`
  472. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  473. classifyArr := utils.ClassifyArr
  474. var flag bool
  475. for _, v := range classifyArr {
  476. if strings.Contains(v, item.Content) || strings.Contains(item.Content, v) {
  477. flag = true
  478. }
  479. }
  480. if flag {
  481. contactMsg = `请点击研究报告-FICC研报,查看报告`
  482. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  483. this.Ctx.WriteString(textXmlTpl)
  484. return
  485. }
  486. reportNameArr := utils.ReportNameArr
  487. for _, v := range reportNameArr {
  488. if strings.Contains(v, item.Content) || strings.Contains(item.Content, v) {
  489. flag = true
  490. }
  491. }
  492. if flag {
  493. contactMsg = `请点击研究报告-FICC研报-研报(左上),查看报告`
  494. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  495. this.Ctx.WriteString(textXmlTpl)
  496. return
  497. }
  498. if strings.Contains("解绑", item.Content) || strings.Contains(item.Content, "解绑") ||
  499. strings.Contains("手机号", item.Content) || strings.Contains(item.Content, "手机号") {
  500. flag = true
  501. }
  502. if flag {
  503. contactMsg = `请通过电话联系我们或者联系销售人员处理`
  504. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  505. this.Ctx.WriteString(textXmlTpl)
  506. return
  507. }
  508. returnResult = xmlTpl
  509. this.Ctx.WriteString(returnResult)
  510. } else {
  511. returnResult = xmlTpl
  512. }
  513. this.Ctx.WriteString(returnResult)
  514. } else {
  515. this.Ctx.WriteString(echostr)
  516. }
  517. }
  518. type Notify struct {
  519. ToUserName string `xml:"ToUserName"`
  520. FromUserName string `xml:"FromUserName"`
  521. CreateTime int `xml:"CreateTime"`
  522. MsgType string `xml:"MsgType"`
  523. Event string `xml:"Event"`
  524. EventKey string `xml:"EventKey"`
  525. Content string `xml:"Content"`
  526. }
  527. // subscribe 关注后的处理逻辑
  528. func subscribe(openId string) {
  529. accessToken, err, _ := services.GetDefaultWxAccessToken()
  530. if err != nil {
  531. fmt.Println("获取access_token失败,err:" + err.Error())
  532. return
  533. }
  534. userRecord, err := models.GetUserRecordByOpenId(openId)
  535. if err != nil && err.Error() != utils.ErrNoRow() {
  536. fmt.Println("通过openid获取user_record记录失败,err:" + err.Error())
  537. return
  538. }
  539. err = nil
  540. // openId已存在
  541. if userRecord != nil {
  542. if userRecord.UserId > 0 { //已经绑定了的话,那么就去修改用户状态
  543. models.UserSubscribe(1, openId)
  544. } else {
  545. // 没有绑定的话,那么校验下unionid,然后再去修改
  546. unionId := userRecord.UnionId
  547. if unionId == `` {
  548. wxUserItem, err := services.WxGetUserInfo(openId, accessToken)
  549. if err != nil {
  550. fmt.Println("获取用户信息失败,err:" + err.Error())
  551. return
  552. }
  553. if wxUserItem.Unionid != `` {
  554. unionId = wxUserItem.Unionid
  555. }
  556. }
  557. updateCol := make([]string, 0)
  558. userRecord.Subscribe = 1
  559. userRecord.SubscribeTime = time.Now()
  560. updateCol = append(updateCol, "Subscribe")
  561. if unionId != `` {
  562. userRecord.UnionId = unionId
  563. // 通过unionid获取已绑定用户的user_record信息
  564. bindUserRecord, _ := models.GetBindUserRecordByUnionId(unionId)
  565. if bindUserRecord != nil {
  566. userRecord.UserId = bindUserRecord.UserId
  567. userRecord.RealName = bindUserRecord.RealName
  568. userRecord.BindAccount = bindUserRecord.BindAccount
  569. userRecord.Sex = bindUserRecord.Sex
  570. updateCol = append(updateCol, "UserId", "RealName", "BindAccount")
  571. }
  572. }
  573. err = userRecord.Update(updateCol)
  574. if err != nil {
  575. fmt.Println("关注后,通过openid更新user_record异常,ERR:", err)
  576. }
  577. }
  578. return
  579. }
  580. // 没有记录,那么需要获取下unionid
  581. wxUserItem, err := services.WxGetUserInfo(openId, accessToken)
  582. if err != nil {
  583. fmt.Println("获取用户信息失败,err:" + err.Error())
  584. return
  585. }
  586. newUserRecord := &models.UserRecord{
  587. UserRecordId: 0,
  588. OpenId: openId,
  589. UnionId: wxUserItem.Unionid,
  590. Subscribe: 1,
  591. SubscribeTime: time.Now(),
  592. NickName: wxUserItem.Nickname,
  593. Sex: wxUserItem.Sex,
  594. Province: wxUserItem.Province,
  595. City: wxUserItem.City,
  596. Country: wxUserItem.Country,
  597. Headimgurl: wxUserItem.Headimgurl,
  598. CreateTime: time.Now(),
  599. CreatePlatform: 1,
  600. SessionKey: "",
  601. }
  602. if wxUserItem.Unionid != `` {
  603. // 通过unionid获取已绑定用户的user_record信息
  604. bindUserRecord, _ := models.GetBindUserRecordByUnionId(wxUserItem.Unionid)
  605. if bindUserRecord != nil {
  606. newUserRecord.UserId = bindUserRecord.UserId
  607. newUserRecord.RealName = bindUserRecord.RealName
  608. newUserRecord.BindAccount = bindUserRecord.BindAccount
  609. newUserRecord.Sex = bindUserRecord.Sex
  610. newUserRecord.Province = bindUserRecord.Province
  611. newUserRecord.City = bindUserRecord.City
  612. newUserRecord.Country = bindUserRecord.Country
  613. newUserRecord.Headimgurl = bindUserRecord.Headimgurl
  614. }
  615. }
  616. _, err = models.AddUserRecord(newUserRecord)
  617. if err != nil {
  618. fmt.Println("关注后,添加user_record信息失败,err:" + err.Error())
  619. return
  620. }
  621. }
  622. // @Title 微信获取签名接口-无token校验
  623. // @Description 微信获取签名接口
  624. // @Param Url query string true "url地址"
  625. // @Success 200 {object} models.WechatSign
  626. // @router /open/getWxSign [get]
  627. func (this *WechatCommonController) GetWxSign() {
  628. br := new(models.BaseResponse).Init()
  629. defer func() {
  630. this.Data["json"] = br
  631. this.ServeJSON()
  632. }()
  633. // 微信配置信息
  634. conf, e := models.GetBusinessConf()
  635. if e != nil {
  636. br.Msg = "获取失败"
  637. br.ErrMsg = "获取配置信息失败, Err: " + e.Error()
  638. return
  639. }
  640. appId := ""
  641. appSecret := ""
  642. if v, ok := conf[models.BusinessConfWxAppId]; ok {
  643. appId = v
  644. }
  645. if v, ok := conf[models.BusinessConfWxAppSecret]; ok {
  646. appSecret = v
  647. }
  648. if appId == "" || appSecret == "" {
  649. br.Msg = "微信公众号信息未配置"
  650. return
  651. }
  652. getUrl := this.GetString("Url")
  653. fmt.Println("getUrl:", getUrl)
  654. tReq := wechat.WxTokenReq{
  655. WxAppId: appId,
  656. WxAppSecret: appSecret,
  657. }
  658. accessToken, err, errMsg := wechat.GetAccessToken(tReq)
  659. if err != nil {
  660. br.Msg = "获取微信配置失败"
  661. br.ErrMsg = "获取access_token失败,err:" + errMsg
  662. return
  663. }
  664. errCode, ticket, err := services.GetWxTicket(accessToken)
  665. if err != nil {
  666. if errCode == 40001 {
  667. accessToken, err, errMsg = wechat.GetAccessToken(tReq)
  668. if err != nil {
  669. br.Msg = "获取微信配置失败"
  670. br.ErrMsg = "获取access_token失败,err:" + errMsg
  671. return
  672. }
  673. errCode, ticket, err = services.GetWxTicket(accessToken)
  674. if err != nil {
  675. br.Msg = "获取Ticket失败,请联系客服"
  676. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  677. return
  678. }
  679. }
  680. br.Msg = "获取Ticket失败,请联系客服"
  681. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  682. return
  683. }
  684. if ticket == "" {
  685. br.Msg = "获取Ticket失败,请联系客服"
  686. br.ErrMsg = "ticket为空" + ticket
  687. return
  688. }
  689. nonceStr := utils.GetRandStringNoSpecialChar(16)
  690. signature, nonceString, timestamp := services.GetWxSignature(ticket, getUrl, nonceStr)
  691. resp := new(models.WechatSign)
  692. resp.AppId = appId
  693. resp.NonceStr = nonceString
  694. resp.Timestamp = timestamp
  695. resp.Url = getUrl
  696. resp.Signature = signature
  697. br.Ret = 200
  698. br.Success = true
  699. br.Msg = "获取签名成功"
  700. br.Data = resp
  701. }