wechat.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/medivhzhan/weapp/v2"
  6. "hongze/hongze_cygx/models"
  7. "hongze/hongze_cygx/services"
  8. "hongze/hongze_cygx/utils"
  9. "strconv"
  10. "time"
  11. )
  12. type WechatController struct {
  13. BaseAuthController
  14. }
  15. type WechatCommonController struct {
  16. BaseCommonController
  17. }
  18. // @Title 微信登录接口
  19. // @Description 微信登录接口
  20. // @Param Code query string true "微信唯一编码code"
  21. // @Success 200 {object} models.WxLoginResp
  22. // @router /login [get]
  23. func (this *WechatCommonController) WechatLogin() {
  24. br := new(models.BaseResponse).Init()
  25. defer func() {
  26. this.Data["json"] = br
  27. this.ServeJSON()
  28. }()
  29. code := this.GetString("Code")
  30. if code == "" {
  31. br.Msg = "参数错误"
  32. br.ErrMsg = "Code 为空"
  33. return
  34. }
  35. wxInfo, err := weapp.Login(utils.WxAppId, utils.WxAppSecret, code)
  36. if err != nil {
  37. br.Msg = "获取用户信息失败"
  38. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  39. return
  40. }
  41. if err = wxInfo.GetResponseError(); err != nil {
  42. br.Msg = "获取用户信息失败"
  43. br.ErrMsg = "获取用户信息失败,code:" + strconv.Itoa(wxInfo.ErrCode) + ",msg:" + wxInfo.ErrMSG
  44. return
  45. }
  46. wxUserInfo := new(services.WxUserInfo)
  47. wxUserInfo.Unionid = wxInfo.UnionID
  48. wxUserInfo.Openid = wxInfo.OpenID
  49. wxUserInfo.Errcode = wxInfo.ErrCode
  50. wxUserInfo.Errmsg = wxInfo.ErrMSG
  51. wxUserInfo.SessionKey = wxInfo.SessionKey
  52. token, userId, firstLogin, _, err := services.WxLogin(code, wxInfo.OpenID, wxInfo.UnionID, wxUserInfo)
  53. if err != nil && err.Error() != utils.ErrNoRow() {
  54. br.Msg = "微信登录失败"
  55. br.ErrMsg = "微信登录失败,err:" + err.Error()
  56. return
  57. }
  58. if token == "" {
  59. br.Msg = "微信登录失败"
  60. br.ErrMsg = "token:" + token + "" + code + " " + wxInfo.OpenID + " " + wxInfo.UnionID
  61. return
  62. }
  63. //新增登录日志
  64. {
  65. loginLog := new(models.WxUserLog)
  66. loginLog.UserId = userId
  67. loginLog.OpenId = wxInfo.OpenID
  68. loginLog.UnionId = wxInfo.UnionID
  69. loginLog.CreateTime = time.Now()
  70. loginLog.Handle = "wechat_login_cygx"
  71. loginLog.Remark = token
  72. go models.AddWxUserLog(loginLog)
  73. }
  74. {
  75. codeLog := new(models.WxUserCode)
  76. codeLog.WxCode = code
  77. codeLog.UserId = userId
  78. codeLog.Code = 0
  79. codeLog.FirstLogin = firstLogin
  80. codeLog.Authorization = token
  81. codeLog.UserPermission = 1
  82. codeLog.CreateTime = time.Now()
  83. models.AddWxUserCode(codeLog)
  84. }
  85. resp := new(models.WxLoginResp)
  86. resp.UserId = userId
  87. resp.FirstLogin = firstLogin
  88. resp.Authorization = token
  89. br.Ret = 200
  90. br.Success = true
  91. br.Msg = "登录成功"
  92. br.Data = resp
  93. }
  94. // @Title 小程序获取用户信息
  95. // @Description 小程序获取用户信息接口(需要登录)
  96. // @Param request body models.WxGetUserInfoReq true "type json string"
  97. // @Success 200 {object} models.WxGetUserInfoResp
  98. // @router /getUserInfo [post]
  99. func (this *WechatController) GetUserInfo() {
  100. br := new(models.BaseResponse).Init()
  101. defer func() {
  102. this.Data["json"] = br
  103. this.ServeJSON()
  104. }()
  105. var req models.WxGetUserInfoReq
  106. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  107. if err != nil {
  108. br.Msg = "参数解析异常!"
  109. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  110. return
  111. }
  112. if req.RawData == "" || req.EncryptedData == "" || req.Signature == "" || req.Iv == "" {
  113. br.Msg = "参数错误"
  114. return
  115. }
  116. user := this.User
  117. if user == nil {
  118. br.Msg = "请登陆"
  119. br.Ret = 408
  120. return
  121. }
  122. userId := user.UserId
  123. sessionKey := user.SessionKey
  124. fmt.Println("sessionKey:", sessionKey)
  125. fmt.Println(sessionKey, req.RawData, req.EncryptedData, req.Signature, req.Iv)
  126. userInfo, err := weapp.DecryptUserInfo(sessionKey, req.RawData, req.EncryptedData, req.Signature, req.Iv)
  127. fmt.Println("weapp.DecryptUserInfo ", err)
  128. if err != nil {
  129. br.Msg = "解析用户信息失败"
  130. br.ErrMsg = "解析用户信息失败,DecryptUserInfo Err:" + err.Error()
  131. return
  132. }
  133. //修改用户微信信息
  134. err = models.ModifyUserRecordByDetail(userInfo.OpenID, userInfo.UnionID, userInfo.Nickname, userInfo.Avatar, userInfo.City, userInfo.Province, userInfo.Country, userInfo.Gender, userId)
  135. if err != nil {
  136. br.Msg = "授权失败"
  137. br.ErrMsg = "授权失败,修改用户信息失败:" + err.Error()
  138. return
  139. }
  140. var token string
  141. tokenItem, err := models.GetTokenByOpenId(userInfo.OpenID)
  142. if err != nil && err.Error() != utils.ErrNoRow() {
  143. br.Msg = "授权失败"
  144. br.ErrMsg = "授权失败,获取token失败:" + err.Error()
  145. return
  146. }
  147. if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
  148. timeUnix := time.Now().Unix()
  149. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  150. token = utils.MD5(userInfo.OpenID) + utils.MD5(timeUnixStr)
  151. //新增session
  152. {
  153. session := new(models.CygxSession)
  154. session.OpenId = userInfo.OpenID
  155. session.UnionId = userInfo.UnionID
  156. session.UserId = userId
  157. session.CreatedTime = time.Now()
  158. session.LastUpdatedTime = time.Now()
  159. session.ExpireTime = time.Now().AddDate(0, 3, 0)
  160. session.AccessToken = token
  161. err = models.AddSession(session)
  162. if err != nil {
  163. br.Msg = "授权失败"
  164. br.ErrMsg = "授权失败,新增用户session信息失败:" + err.Error()
  165. return
  166. }
  167. }
  168. } else {
  169. token = tokenItem.AccessToken
  170. }
  171. resp := new(models.WxGetUserInfoResp)
  172. resp.Authorization = token
  173. br.Msg = "获取成功!"
  174. br.Ret = 200
  175. br.Success = true
  176. }
  177. // @Title 小程序获取用户绑定手机号
  178. // @Description 小程序获取用户绑定手机号接口(需要登录)
  179. // @Param request body models.WxGetPhoneNumberReq true "type json string"
  180. // @Success 200 {object} models.WxGetPhoneNumberResp
  181. // @router /getPhoneNumber [post]
  182. func (this *WechatController) GetPhoneNumber() {
  183. br := new(models.BaseResponse).Init()
  184. defer func() {
  185. this.Data["json"] = br
  186. this.ServeJSON()
  187. }()
  188. var req models.WxGetPhoneNumberReq
  189. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  190. if err != nil {
  191. br.Msg = "参数解析异常!"
  192. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  193. return
  194. }
  195. if req.EncryptedData == "" || req.Iv == "" {
  196. br.Msg = "参数错误"
  197. return
  198. }
  199. user := this.User
  200. if user == nil {
  201. br.Msg = "请登陆"
  202. br.Ret = 408
  203. return
  204. }
  205. sessionKey := user.SessionKey
  206. wxMobile, err := weapp.DecryptMobile(sessionKey, req.EncryptedData, req.Iv)
  207. if err != nil {
  208. br.Msg = "解析用户手机号信息失败"
  209. br.ErrMsg = "解析用户手机号信息失败,Err:" + err.Error()
  210. return
  211. }
  212. err = models.ModifyUsersMobile(user.UserId, wxMobile.PurePhoneNumber)
  213. if err != nil {
  214. br.Msg = "获取失败"
  215. br.ErrMsg = "获取失败,Err:" + err.Error()
  216. return
  217. }
  218. resp := new(models.WxGetPhoneNumberResp)
  219. resp.PhoneNumber = wxMobile.PhoneNumber
  220. resp.PurePhoneNumber = wxMobile.PurePhoneNumber
  221. resp.CountryCode = wxMobile.CountryCode
  222. br.Msg = "获取成功!"
  223. br.Ret = 200
  224. br.Success = true
  225. br.Data = resp
  226. }
  227. // @Title 获取短信验证码
  228. // @Description 获取短信验证码接口
  229. // @Param Mobile query string true "手机号码"
  230. // @Param AreaNum query string true "地区编码"
  231. // @Success Ret=200 获取成功
  232. // @router /getSmsCode [get]
  233. func (this *WechatController) GetSmsCode() {
  234. br := new(models.BaseResponse).Init()
  235. defer func() {
  236. this.Data["json"] = br
  237. this.ServeJSON()
  238. }()
  239. mobile := this.GetString("Mobile")
  240. if mobile == "" {
  241. br.Msg = "请输入手机号"
  242. return
  243. }
  244. areaNum := this.GetString("AreaNum")
  245. msgCode := utils.GetRandDigit(4)
  246. var result bool
  247. if areaNum == "86" || areaNum == "" || areaNum == "0" {
  248. result = services.SendSmsCode(mobile, msgCode)
  249. } else {
  250. result = services.SendSmsCodeGj(mobile, msgCode, areaNum)
  251. }
  252. //发送成功
  253. if result {
  254. item := new(models.MsgCode)
  255. item.OpenId = ""
  256. item.Code = msgCode
  257. item.Mobile = mobile
  258. item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
  259. item.Enabled = 1
  260. item.CreatedTime = time.Now()
  261. err := models.AddMsgCode(item)
  262. if err != nil {
  263. br.Msg = "发送失败"
  264. br.ErrMsg = "发送失败,Err:" + err.Error()
  265. return
  266. }
  267. br.Msg = "发送成功"
  268. } else {
  269. br.Msg = "发送失败"
  270. }
  271. br.Ret = 200
  272. br.Success = true
  273. }
  274. // @Title 获取邮件验证码
  275. // @Description 获取邮件验证码接口
  276. // @Param Email query string true "邮箱"
  277. // @Success Ret=200 获取成功
  278. // @router /getEmailCode [get]
  279. func (this *WechatController) GetEmailCode() {
  280. br := new(models.BaseResponse).Init()
  281. defer func() {
  282. this.Data["json"] = br
  283. this.ServeJSON()
  284. }()
  285. email := this.GetString("Email")
  286. if email == "" {
  287. br.Msg = "请输入邮箱地址"
  288. return
  289. }
  290. if !utils.ValidateEmailFormatat(email) {
  291. br.Msg = "邮箱格式错误,请重新输入"
  292. return
  293. }
  294. msgCode := utils.GetRandDigit(4)
  295. content := "尊敬的用户:</br>您好,感谢您使用弘则研究,您正在进行邮箱验证,本次请求的验证码为:" + msgCode + "(为了保障您账号的安全性,请在15分钟内完成验证。)</br>弘则研究团队 </br>2019年05月11日"
  296. title := "弘则研究登陆验证"
  297. //发送邮件
  298. result, err := utils.SendEmailByHz(title, content, email)
  299. if err != nil {
  300. br.Msg = "发送失败"
  301. br.ErrMsg = "发送失败,Err:" + err.Error()
  302. return
  303. }
  304. if result {
  305. item := new(models.MsgCode)
  306. item.OpenId = ""
  307. item.Code = msgCode
  308. item.Mobile = email
  309. item.ExpiredIn = time.Now().Add(15 * time.Minute).Unix()
  310. item.Enabled = 1
  311. item.CreatedTime = time.Now()
  312. err := models.AddMsgCode(item)
  313. if err != nil {
  314. br.Msg = "发送失败"
  315. br.ErrMsg = "发送失败,Err:" + err.Error()
  316. return
  317. }
  318. br.Msg = "发送成功"
  319. } else {
  320. br.Msg = "发送失败"
  321. }
  322. br.Ret = 200
  323. br.Success = true
  324. }
  325. // @Title 更新微信token
  326. // @Description 更新微信token
  327. // @Success Ret=200 更新成功
  328. // @router /updateWxAccesstoken [get]
  329. func (this *WechatController) UpdateWxAccesstoken() {
  330. br := new(models.BaseResponse).Init()
  331. defer func() {
  332. this.Data["json"] = br
  333. this.ServeJSON()
  334. }()
  335. accessToken, err := models.GetWxAccessToken()
  336. if err != nil {
  337. utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
  338. return
  339. }
  340. br.Data = accessToken
  341. br.Ret = 200
  342. br.Success = true
  343. }
  344. // @Title 微信登录小助手接口
  345. // @Description 微信登录小助手接口
  346. // @Param Code query string true "微信唯一编码code"
  347. // @Success 200 {object} models.WxLoginResp
  348. // @router /loginByxzs [get]
  349. func (this *WechatCommonController) WechatLoginByxzs() {
  350. br := new(models.BaseResponse).Init()
  351. defer func() {
  352. this.Data["json"] = br
  353. this.ServeJSON()
  354. }()
  355. code := this.GetString("Code")
  356. if code == "" {
  357. br.Msg = "参数错误"
  358. br.ErrMsg = "Code 为空"
  359. return
  360. }
  361. item, err := services.WxGetUserOpenIdByCodeXzs(code)
  362. if err != nil {
  363. br.Msg = "获取用户信息失败"
  364. br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
  365. return
  366. }
  367. if item.Errcode != 0 {
  368. br.Msg = "获取用户信息失败"
  369. br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
  370. return
  371. }
  372. openId := item.Openid
  373. if openId == "" {
  374. br.Msg = "获取用户信息失败"
  375. br.ErrMsg = "获取openid失败,openid:" + item.Openid
  376. return
  377. }
  378. unionId := item.Unionid
  379. if unionId == "" {
  380. br.Msg = "获取用户信息失败"
  381. br.ErrMsg = "获取unionid失败,unionid:" + item.Openid
  382. return
  383. }
  384. total, err := models.GetCygxUserRecordCount(openId)
  385. if err != nil {
  386. br.Msg = "获取用户信息失败"
  387. br.ErrMsg = "查询数量失败,Err:" + err.Error()
  388. return
  389. }
  390. if total == 0 {
  391. items := new(models.CygxUserRecord)
  392. items.OpenId = openId
  393. items.UnionId = unionId
  394. items.CreateTime = time.Now()
  395. _, err = models.AddCygxUserRecord(items)
  396. if err != nil {
  397. br.Msg = "获取用户信息失败"
  398. br.ErrMsg = "添加openid失败,Err:" + err.Error()
  399. return
  400. }
  401. }
  402. br.Ret = 200
  403. br.Success = true
  404. br.Msg = "获取成功"
  405. br.Data = item
  406. }