wechat.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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. var openId, returnResult string
  409. if item.MsgType != "" {
  410. openId = item.FromUserName
  411. }
  412. xmlTpl := `<xml>
  413. <ToUserName><![CDATA[%s]]></ToUserName>
  414. <FromUserName><![CDATA[%s]]></FromUserName>
  415. <CreateTime>%s</CreateTime>
  416. <MsgType><![CDATA[text]]></MsgType>
  417. <Content><![CDATA[%s]]></Content>
  418. </xml>`
  419. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  420. xmlTpl = fmt.Sprintf(xmlTpl, openId, utils.WxId, createTime, contactMsg)
  421. if item.MsgType == "event" {
  422. switch item.Event {
  423. case "subscribe":
  424. fmt.Println("关注")
  425. go subscribe(openId)
  426. break
  427. case "unsubscribe":
  428. fmt.Println("取消关注")
  429. go models.UserSubscribe(0, openId)
  430. break
  431. case "CLICK":
  432. returnResult = xmlTpl
  433. break
  434. default:
  435. utils.FileLog.Info("wechat notify event:" + item.Event)
  436. }
  437. this.Ctx.WriteString(xmlTpl)
  438. } else if item.MsgType == "text" {
  439. textXmlTpl := `<xml>
  440. <ToUserName><![CDATA[%s]]></ToUserName>
  441. <FromUserName><![CDATA[%s]]></FromUserName>
  442. <CreateTime>%s</CreateTime>
  443. <MsgType><![CDATA[text]]></MsgType>
  444. <Content><![CDATA[%s]]></Content>
  445. </xml>`
  446. createTime := strconv.FormatInt(time.Now().Unix(), 10)
  447. classifyArr := utils.ClassifyArr
  448. var flag bool
  449. for _, v := range classifyArr {
  450. if strings.Contains(v, item.Content) || strings.Contains(item.Content, v) {
  451. flag = true
  452. }
  453. }
  454. if flag {
  455. contactMsg = `请点击研究报告-FICC研报,查看报告`
  456. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  457. this.Ctx.WriteString(textXmlTpl)
  458. return
  459. }
  460. reportNameArr := utils.ReportNameArr
  461. for _, v := range reportNameArr {
  462. if strings.Contains(v, item.Content) || strings.Contains(item.Content, v) {
  463. flag = true
  464. }
  465. }
  466. if flag {
  467. contactMsg = `请点击研究报告-FICC研报-研报(左上),查看报告`
  468. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  469. this.Ctx.WriteString(textXmlTpl)
  470. return
  471. }
  472. if strings.Contains("解绑", item.Content) || strings.Contains(item.Content, "解绑") ||
  473. strings.Contains("手机号", item.Content) || strings.Contains(item.Content, "手机号") {
  474. flag = true
  475. }
  476. if flag {
  477. contactMsg = `请通过电话联系我们或者联系销售人员处理`
  478. textXmlTpl = fmt.Sprintf(textXmlTpl, item.FromUserName, utils.WxId, createTime, contactMsg)
  479. this.Ctx.WriteString(textXmlTpl)
  480. return
  481. }
  482. returnResult = xmlTpl
  483. this.Ctx.WriteString(returnResult)
  484. } else {
  485. returnResult = xmlTpl
  486. }
  487. this.Ctx.WriteString(returnResult)
  488. } else {
  489. this.Ctx.WriteString(echostr)
  490. }
  491. }
  492. type Notify struct {
  493. ToUserName string `xml:"ToUserName"`
  494. FromUserName string `xml:"FromUserName"`
  495. CreateTime int `xml:"CreateTime"`
  496. MsgType string `xml:"MsgType"`
  497. Event string `xml:"Event"`
  498. EventKey string `xml:"EventKey"`
  499. Content string `xml:"Content"`
  500. }
  501. // subscribe 关注后的处理逻辑
  502. func subscribe(openId string) {
  503. accessToken, err, _ := services.GetDefaultWxAccessToken()
  504. if err != nil {
  505. fmt.Println("获取access_token失败,err:" + err.Error())
  506. return
  507. }
  508. userRecord, err := models.GetUserRecordByOpenId(openId)
  509. if err != nil && err.Error() != utils.ErrNoRow() {
  510. fmt.Println("通过openid获取user_record记录失败,err:" + err.Error())
  511. return
  512. }
  513. err = nil
  514. // openId已存在
  515. if userRecord != nil {
  516. if userRecord.UserId > 0 { //已经绑定了的话,那么就去修改用户状态
  517. models.UserSubscribe(1, openId)
  518. } else {
  519. // 没有绑定的话,那么校验下unionid,然后再去修改
  520. unionId := userRecord.UnionId
  521. if unionId == `` {
  522. wxUserItem, err := services.WxGetUserInfo(openId, accessToken)
  523. if err != nil {
  524. fmt.Println("获取用户信息失败,err:" + err.Error())
  525. return
  526. }
  527. if wxUserItem.Unionid != `` {
  528. unionId = wxUserItem.Unionid
  529. }
  530. }
  531. updateCol := make([]string, 0)
  532. userRecord.Subscribe = 1
  533. userRecord.SubscribeTime = time.Now()
  534. updateCol = append(updateCol, "Subscribe")
  535. if unionId != `` {
  536. userRecord.UnionId = unionId
  537. // 通过unionid获取已绑定用户的user_record信息
  538. bindUserRecord, _ := models.GetBindUserRecordByUnionId(unionId)
  539. if bindUserRecord != nil {
  540. userRecord.UserId = bindUserRecord.UserId
  541. userRecord.RealName = bindUserRecord.RealName
  542. userRecord.BindAccount = bindUserRecord.BindAccount
  543. userRecord.Sex = bindUserRecord.Sex
  544. updateCol = append(updateCol, "UserId", "RealName", "BindAccount")
  545. }
  546. }
  547. err = userRecord.Update(updateCol)
  548. if err != nil {
  549. fmt.Println("关注后,通过openid更新user_record异常,ERR:", err)
  550. }
  551. }
  552. return
  553. }
  554. // 没有记录,那么需要获取下unionid
  555. wxUserItem, err := services.WxGetUserInfo(openId, accessToken)
  556. if err != nil {
  557. fmt.Println("获取用户信息失败,err:" + err.Error())
  558. return
  559. }
  560. newUserRecord := &models.UserRecord{
  561. UserRecordId: 0,
  562. OpenId: openId,
  563. UnionId: wxUserItem.Unionid,
  564. Subscribe: 1,
  565. SubscribeTime: time.Now(),
  566. NickName: wxUserItem.Nickname,
  567. Sex: wxUserItem.Sex,
  568. Province: wxUserItem.Province,
  569. City: wxUserItem.City,
  570. Country: wxUserItem.Country,
  571. Headimgurl: wxUserItem.Headimgurl,
  572. CreateTime: time.Now(),
  573. CreatePlatform: 1,
  574. SessionKey: "",
  575. }
  576. if wxUserItem.Unionid != `` {
  577. // 通过unionid获取已绑定用户的user_record信息
  578. bindUserRecord, _ := models.GetBindUserRecordByUnionId(wxUserItem.Unionid)
  579. if bindUserRecord != nil {
  580. newUserRecord.UserId = bindUserRecord.UserId
  581. newUserRecord.RealName = bindUserRecord.RealName
  582. newUserRecord.BindAccount = bindUserRecord.BindAccount
  583. newUserRecord.Sex = bindUserRecord.Sex
  584. newUserRecord.Province = bindUserRecord.Province
  585. newUserRecord.City = bindUserRecord.City
  586. newUserRecord.Country = bindUserRecord.Country
  587. newUserRecord.Headimgurl = bindUserRecord.Headimgurl
  588. }
  589. }
  590. _, err = models.AddUserRecord(newUserRecord)
  591. if err != nil {
  592. fmt.Println("关注后,添加user_record信息失败,err:" + err.Error())
  593. return
  594. }
  595. }
  596. // @Title 微信获取签名接口-无token校验
  597. // @Description 微信获取签名接口
  598. // @Param Url query string true "url地址"
  599. // @Success 200 {object} models.WechatSign
  600. // @router /open/getWxSign [get]
  601. func (this *WechatCommonController) GetWxSign() {
  602. br := new(models.BaseResponse).Init()
  603. defer func() {
  604. this.Data["json"] = br
  605. this.ServeJSON()
  606. }()
  607. // 微信配置信息
  608. conf, e := models.GetBusinessConf()
  609. if e != nil {
  610. br.Msg = "获取失败"
  611. br.ErrMsg = "获取配置信息失败, Err: " + e.Error()
  612. return
  613. }
  614. appId := ""
  615. appSecret := ""
  616. if v, ok := conf[models.BusinessConfWxAppId]; ok {
  617. appId = v
  618. }
  619. if v, ok := conf[models.BusinessConfWxAppSecret]; ok {
  620. appSecret = v
  621. }
  622. if appId == "" || appSecret == "" {
  623. br.Msg = "微信公众号信息未配置"
  624. return
  625. }
  626. getUrl := this.GetString("Url")
  627. fmt.Println("getUrl:", getUrl)
  628. tReq := wechat.WxTokenReq{
  629. WxAppId: appId,
  630. WxAppSecret: appSecret,
  631. }
  632. accessToken, err, errMsg := wechat.GetAccessToken(tReq)
  633. if err != nil {
  634. br.Msg = "获取微信配置失败"
  635. br.ErrMsg = "获取access_token失败,err:" + errMsg
  636. return
  637. }
  638. errCode, ticket, err := services.GetWxTicket(accessToken)
  639. if err != nil {
  640. if errCode == 40001 {
  641. accessToken, err, errMsg = wechat.GetAccessToken(tReq)
  642. if err != nil {
  643. br.Msg = "获取微信配置失败"
  644. br.ErrMsg = "获取access_token失败,err:" + errMsg
  645. return
  646. }
  647. errCode, ticket, err = services.GetWxTicket(accessToken)
  648. if err != nil {
  649. br.Msg = "获取Ticket失败,请联系客服"
  650. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  651. return
  652. }
  653. }
  654. br.Msg = "获取Ticket失败,请联系客服"
  655. br.ErrMsg = "获取Ticket失败,Err" + err.Error()
  656. return
  657. }
  658. if ticket == "" {
  659. br.Msg = "获取Ticket失败,请联系客服"
  660. br.ErrMsg = "ticket为空" + ticket
  661. return
  662. }
  663. nonceStr := utils.GetRandStringNoSpecialChar(16)
  664. signature, nonceString, timestamp := services.GetWxSignature(ticket, getUrl, nonceStr)
  665. resp := new(models.WechatSign)
  666. resp.AppId = appId
  667. resp.NonceStr = nonceString
  668. resp.Timestamp = timestamp
  669. resp.Url = getUrl
  670. resp.Signature = signature
  671. br.Ret = 200
  672. br.Success = true
  673. br.Msg = "获取签名成功"
  674. br.Data = resp
  675. }