wechat.go 2.2 KB

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