token.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package wechat
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "hongze/hongze_api/services/alarm_msg"
  7. "hongze/hongze_api/utils"
  8. "io/ioutil"
  9. "net/http"
  10. "strings"
  11. )
  12. type WxTokenResp struct {
  13. Ret int
  14. Msg string
  15. ErrMsg string
  16. ErrCode string
  17. Data WxTokenData
  18. Success bool `description:"true 执行成功,false 执行失败"`
  19. IsSendEmail bool `json:"-"`
  20. }
  21. type WxTokenReq struct {
  22. WxAppId string `description:"公众号appId"`
  23. WxAppSecret string `description:"公众号appSecret"`
  24. }
  25. type WxTokenData struct {
  26. AccessToken string `description:"微信token"`
  27. }
  28. // GetAccessToken 获取微信token
  29. func GetAccessToken(tokenReq WxTokenReq) (accessToken string, err error, errMsg string) {
  30. if utils.EtaPubUrl == `` {
  31. // 找不到推送服务
  32. return
  33. }
  34. url := fmt.Sprintf("%s%s", utils.EtaPubUrl, "v1/wechat/access_token")
  35. defer func() {
  36. if err != nil {
  37. go alarm_msg.SendAlarmMsg(errMsg, 1)
  38. }
  39. }()
  40. postData, err := json.Marshal(tokenReq)
  41. if err != nil {
  42. errMsg = "SendTemplateMsg json.Marshal Err:" + err.Error()
  43. return
  44. }
  45. body := ioutil.NopCloser(strings.NewReader(string(postData)))
  46. client := &http.Client{}
  47. req, err := http.NewRequest("POST", url, body)
  48. if err != nil {
  49. errMsg = "SendTemplateMsg http.NewRequest Err:" + err.Error()
  50. return
  51. }
  52. contentType := "application/json;charset=utf-8"
  53. req.Header.Set("Content-Type", contentType)
  54. req.Header.Set("Authorization", utils.EtaPubAuthorization)
  55. resp, err := client.Do(req)
  56. if err != nil {
  57. errMsg = "http client.Do Err:" + err.Error()
  58. return
  59. }
  60. defer resp.Body.Close()
  61. b, err := ioutil.ReadAll(resp.Body)
  62. if err != nil {
  63. errMsg = "ioutil.ReadAll Err:" + err.Error()
  64. return
  65. }
  66. result := new(WxTokenResp)
  67. err = json.Unmarshal(b, &result)
  68. if err != nil {
  69. errMsg = "json.Unmarshal Err:" + err.Error()
  70. return
  71. }
  72. if result.Ret != 200 {
  73. err = errors.New(string(b))
  74. errMsg = "请求失败:" + err.Error()
  75. return
  76. }
  77. accessToken = result.Data.AccessToken
  78. if accessToken == "" {
  79. err = errors.New("请求accessToken失败")
  80. errMsg = "请求accessToken失败"
  81. return
  82. }
  83. return
  84. }