| 70 | } |
| 71 | |
| 72 | func getToken(ctx context.Context, c *http.Client, corpID, secret string) (*tokenValue, error) { |
| 73 | url, err := url.Parse("https://qyapi.weixin.qq.com/cgi-bin/gettoken") |
| 74 | if err != nil { |
| 75 | return nil, errors.Wrapf(err, "failed to parse url") |
| 76 | } |
| 77 | q := url.Query() |
| 78 | q.Set("corpid", corpID) |
| 79 | q.Set("corpsecret", secret) |
| 80 | url.RawQuery = q.Encode() |
| 81 | |
| 82 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url.String(), nil) |
| 83 | if err != nil { |
| 84 | return nil, errors.Wrapf(err, "construct GET %s", url) |
| 85 | } |
| 86 | resp, err := c.Do(req) |
| 87 | if err != nil { |
| 88 | return nil, errors.Wrapf(err, "GET %s", url) |
| 89 | } |
| 90 | defer resp.Body.Close() |
| 91 | |
| 92 | if resp.StatusCode != http.StatusOK { |
| 93 | return nil, errors.Errorf("received non-200 HTTP status code %d", resp.StatusCode) |
| 94 | } |
| 95 | |
| 96 | b, err := io.ReadAll(resp.Body) |
| 97 | if err != nil { |
| 98 | return nil, errors.Wrapf(err, "read body of POST %s", url) |
| 99 | } |
| 100 | |
| 101 | var payload accessTokenResponse |
| 102 | if err := json.Unmarshal(b, &payload); err != nil { |
| 103 | return nil, errors.Wrapf(err, "failed to unmarshal") |
| 104 | } |
| 105 | if payload.ErrCode != 0 { |
| 106 | return nil, errors.Errorf("response errcode %d, errmsg %s", payload.ErrCode, payload.ErrMsg) |
| 107 | } |
| 108 | |
| 109 | return &tokenValue{ |
| 110 | token: payload.AccessToken, |
| 111 | expireAt: time.Now().Add(time.Second * time.Duration(payload.Expire)), |
| 112 | }, nil |
| 113 | } |
| 114 | |
| 115 | func (p *provider) refreshToken(ctx context.Context) error { |
| 116 | token, err := getTokenCached(ctx, p.c, p.corpID, p.secret) |