wechat.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "hongze/hongze_mobile_admin/models/response/wechat"
  6. services "hongze/hongze_mobile_admin/service"
  7. "hongze/hongze_mobile_admin/utils"
  8. "strconv"
  9. "time"
  10. )
  11. type WeChatCommon struct {
  12. BaseNotAuth
  13. }
  14. // @Title 微信登录接口
  15. // @Description 微信登录接口
  16. // @Param Code query string true "微信唯一编码code"
  17. // @Success 200 {object} wechat.WxLoginResp
  18. // @router /login [get]
  19. func (this *WeChatCommon) WeChatLogin() {
  20. code := this.GetString("Code")
  21. fmt.Println("code:", code)
  22. utils.FileLog.Info("WechatLogin code:%s", code)
  23. item, err := services.WxGetUserOpenIdByCode(code)
  24. if err != nil {
  25. this.FailWithMessage(fmt.Sprintf("%v", err), fmt.Sprintf("%v", err))
  26. return
  27. }
  28. if item.Errcode != 0 {
  29. this.FailWithMessage("获取用户信息失败", "获取access_token 失败 errcode:"+strconv.Itoa(item.Errcode)+" ;errmsg:"+item.Errmsg)
  30. }
  31. openId := item.Openid
  32. if openId == "" {
  33. this.FailWithMessage("获取用户信息失败", "获取openid失败,openid:"+item.Openid)
  34. }
  35. accessToken, err := services.WxGetAccessToken()
  36. if err != nil {
  37. this.FailWithMessage("获取用户信息失败", "获取access_token失败,err:"+err.Error())
  38. }
  39. //获取用户信息
  40. wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
  41. if err != nil {
  42. this.FailWithMessage("获取用户信息失败", "获取微信用户信息失败,Err:"+err.Error())
  43. }
  44. if wxUserInfo.Errcode != 0 {
  45. userInfoJson, _ := json.Marshal(wxUserInfo)
  46. this.FailWithMessage("登录失败", "获取用户信息失败,err:"+string(userInfoJson))
  47. return
  48. }
  49. token, adminWx, err := services.WxLogin(utils.WxPlatform, item, wxUserInfo)
  50. if err != nil {
  51. this.FailWithMessage("微信登录失败", "微信登录失败,err:"+err.Error())
  52. return
  53. }
  54. resp := wechat.WxLoginResp{
  55. AdminId: adminWx.AdminId,
  56. Code: 0,
  57. Authorization: token,
  58. Headimgurl: adminWx.Headimgurl,
  59. RealName: adminWx.RealName,
  60. }
  61. //登录日志
  62. {
  63. returnResult, err := json.Marshal(resp)
  64. if err != nil {
  65. utils.FileLog.Info(this.Ctx.Input.URI() + " Err:%s" + err.Error())
  66. }
  67. utils.FileLog.Info(this.Ctx.Input.URI()+" code: %s , return data: %s", code, string(returnResult))
  68. }
  69. this.OkDetailed(resp, "登录成功")
  70. }
  71. // @Title test
  72. // @Description test
  73. // @Success 200 {string} string "{"code":0,"data":{"Id":9},"msg":"操作成功"}"
  74. // @Failure 403 body is empty
  75. // @router /test [get]
  76. func (this *BaseNotAuth) Test() {
  77. time.Sleep(time.Second * 5)
  78. this.OkWithData(1)
  79. }