package wechat import ( "encoding/json" "errors" "fmt" "hongze/hongze_api/services/alarm_msg" "hongze/hongze_api/utils" "io/ioutil" "net/http" "strings" ) type WxTokenResp struct { Ret int Msg string ErrMsg string ErrCode string Data WxTokenData Success bool `description:"true 执行成功,false 执行失败"` IsSendEmail bool `json:"-"` } type WxTokenReq struct { WxAppId string `description:"公众号appId"` WxAppSecret string `description:"公众号appSecret"` } type WxTokenData struct { AccessToken string `description:"微信token"` } // GetAccessToken 获取微信token func GetAccessToken(tokenReq WxTokenReq) (accessToken string, err error, errMsg string) { if utils.EtaPubUrl == `` { // 找不到推送服务 return } url := fmt.Sprintf("%s%s", utils.EtaPubUrl, "v1/wechat/access_token") defer func() { if err != nil { go alarm_msg.SendAlarmMsg(errMsg, 1) } }() postData, err := json.Marshal(tokenReq) if err != nil { errMsg = "SendTemplateMsg json.Marshal Err:" + err.Error() return } body := ioutil.NopCloser(strings.NewReader(string(postData))) client := &http.Client{} req, err := http.NewRequest("POST", url, body) if err != nil { errMsg = "SendTemplateMsg http.NewRequest Err:" + err.Error() return } contentType := "application/json;charset=utf-8" req.Header.Set("Content-Type", contentType) req.Header.Set("Authorization", utils.EtaPubAuthorization) resp, err := client.Do(req) if err != nil { errMsg = "http client.Do Err:" + err.Error() return } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { errMsg = "ioutil.ReadAll Err:" + err.Error() return } result := new(WxTokenResp) err = json.Unmarshal(b, &result) if err != nil { errMsg = "json.Unmarshal Err:" + err.Error() return } if result.Ret != 200 { err = errors.New(string(b)) errMsg = "请求失败:" + err.Error() return } accessToken = result.Data.AccessToken if accessToken == "" { err = errors.New("请求accessToken失败") errMsg = "请求accessToken失败" return } return }