token.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package wechat
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta_gn/eta_report/models"
  6. "eta_gn/eta_report/services/alarm_msg"
  7. "eta_gn/eta_report/utils"
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "strings"
  12. "time"
  13. )
  14. type WxTokenResp struct {
  15. Ret int
  16. Msg string
  17. ErrMsg string
  18. ErrCode string
  19. Data WxTokenData
  20. Success bool `description:"true 执行成功,false 执行失败"`
  21. IsSendEmail bool `json:"-"`
  22. }
  23. type WxTokenReq struct {
  24. WxAppId string `description:"公众号appId"`
  25. WxAppSecret string `description:"公众号appSecret"`
  26. }
  27. type WxTokenData struct {
  28. AccessToken string `description:"微信token"`
  29. }
  30. // GetAccessToken 获取微信token
  31. func GetAccessToken(tokenReq WxTokenReq) (accessToken string, err error, errMsg string) {
  32. if utils.EtaPubUrl == `` {
  33. // 找不到推送服务
  34. return
  35. }
  36. url := fmt.Sprintf("%s%s", utils.EtaPubUrl, "v1/wechat/access_token")
  37. defer func() {
  38. if err != nil {
  39. go alarm_msg.SendAlarmMsg(errMsg, 1)
  40. }
  41. }()
  42. postData, err := json.Marshal(tokenReq)
  43. if err != nil {
  44. errMsg = "SendTemplateMsg json.Marshal Err:" + err.Error()
  45. return
  46. }
  47. body := ioutil.NopCloser(strings.NewReader(string(postData)))
  48. client := &http.Client{}
  49. req, err := http.NewRequest("POST", url, body)
  50. if err != nil {
  51. errMsg = "SendTemplateMsg http.NewRequest Err:" + err.Error()
  52. return
  53. }
  54. contentType := "application/json;charset=utf-8"
  55. req.Header.Set("Content-Type", contentType)
  56. req.Header.Set("Authorization", utils.EtaPubAuthorization)
  57. resp, err := client.Do(req)
  58. if err != nil {
  59. errMsg = "http client.Do Err:" + err.Error()
  60. return
  61. }
  62. defer resp.Body.Close()
  63. b, err := ioutil.ReadAll(resp.Body)
  64. if err != nil {
  65. errMsg = "ioutil.ReadAll Err:" + err.Error()
  66. return
  67. }
  68. result := new(WxTokenResp)
  69. err = json.Unmarshal(b, &result)
  70. if err != nil {
  71. errMsg = "json.Unmarshal Err:" + err.Error()
  72. return
  73. }
  74. if result.Ret != 200 {
  75. err = errors.New(string(b))
  76. errMsg = "请求失败:" + err.Error()
  77. return
  78. }
  79. accessToken = result.Data.AccessToken
  80. if accessToken == "" {
  81. err = errors.New("请求accessToken失败")
  82. errMsg = "请求accessToken失败"
  83. return
  84. }
  85. return
  86. }
  87. // GetWxAccessToken 获取微信token
  88. func GetWxAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error, errMsg string) {
  89. accessToken, err, errMsg = getWxAccessToken(wxAppId, wxAppSecret)
  90. if err != nil {
  91. utils.FileLog.Info(fmt.Sprintf("获取Token失败,err:%s,errMsg:%s", err.Error(), errMsg))
  92. return
  93. }
  94. return
  95. }
  96. // getWxAccessToken 获取微信token
  97. func getWxAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error, errMsg string) {
  98. redisKey := getRedisKeyByAppid(wxAppId)
  99. if redisKey == `` {
  100. errMsg = "未配置缓存key"
  101. err = errors.New(errMsg)
  102. return
  103. }
  104. accessToken, err = utils.Rc.RedisString(redisKey)
  105. //fmt.Println(err)
  106. //fmt.Println(accessToken)
  107. //if err != nil {
  108. // errMsg = "GetWxAccessToken Err:" + err.Error()
  109. // utils.FileLog.Info("获取Token失败,msg:" + errMsg)
  110. // return
  111. //}
  112. //取到数据后就直接返回了,没有后续了
  113. if accessToken != "" {
  114. return
  115. }
  116. //缓存中没有取到数据,那么需要去强制刷新新的accessToken
  117. return refreshWxAccessToken(wxAppId, wxAppSecret)
  118. }
  119. // refreshWxAccessToken 强制刷新微信token
  120. func refreshWxAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error, errMsg string) {
  121. fmt.Println("强制刷新" + wxAppId + "微信token")
  122. defer func() {
  123. if errMsg != `` {
  124. utils.FileLog.Info(fmt.Sprintf("强制刷新%s微信token异常:%s", wxAppId, errMsg))
  125. }
  126. }()
  127. if wxAppId == "" || wxAppSecret == "" {
  128. errMsg = fmt.Sprintf("必要信息为空, wxAppId: %s, wxAppSecret: %s", wxAppId, wxAppSecret)
  129. err = errors.New(errMsg)
  130. return
  131. }
  132. redisKey := getRedisKeyByAppid(wxAppId)
  133. if redisKey == `` {
  134. errMsg = "未配置缓存key"
  135. err = errors.New(errMsg)
  136. return
  137. }
  138. //调用微信官方接口获取新的accessToken
  139. wxAccessToken, tmpErr := models.GetWxToken(wxAppId, wxAppSecret)
  140. if tmpErr != nil {
  141. err = tmpErr
  142. errMsg = "通过微信接口获取accessToken失败 Err:" + err.Error()
  143. return
  144. }
  145. //如果没有token数据
  146. if wxAccessToken.AccessToken == "" {
  147. errMsg = "微信返回的accessToken异常: Err:" + wxAccessToken.Errmsg
  148. err = errors.New(errMsg)
  149. return
  150. }
  151. accessToken = wxAccessToken.AccessToken
  152. ////如果是弘则研究的appid,那么需要更新mysql的accessToken
  153. //if wxAppId == utils.WxAppId {
  154. // expiresIn := time.Now().Add(time.Duration(wxAccessToken.ExpiresIn) * time.Second).Unix()
  155. // err = models.ModifyAccessToken(wxAccessToken.AccessToken, expiresIn)
  156. // if err != nil {
  157. // errMsg = "更新mysql中的accessToken失败 Err:" + err.Error()
  158. // return
  159. // }
  160. //}
  161. //更新redis的accessToken(过期时间提前十分钟)
  162. redisTimeExpire := time.Duration(wxAccessToken.ExpiresIn-600) * time.Second
  163. err = utils.Rc.Put(redisKey, accessToken, redisTimeExpire)
  164. if err != nil {
  165. errMsg = "更新redis中的accessToken失败 Err:" + err.Error()
  166. return
  167. }
  168. return
  169. }
  170. // 根据微信appid获取对应的缓存key
  171. func getRedisKeyByAppid(wxAppId string) (redisKey string) {
  172. redisKey = utils.ETA_WX_ACCESS_TOEKN + wxAppId
  173. //switch wxAppId {
  174. //case utils.WxAppId:
  175. // redisKey = utils.CACHE_WX_ACCESS_TOKEN_HZ
  176. //case utils.AdminWxAppId:
  177. // redisKey = utils.HZ_ADMIN_WX_ACCESS_TOEKN + wxAppId
  178. //default:
  179. // redisKey = utils.HZ_ADMIN_WX_ACCESS_TOEKN + wxAppId
  180. //}
  181. return redisKey
  182. }