ExchangeCodeForToken fetches an access token for the given application using the provided code.
(httpClient *http.Client, baseDomain, clientID, clientSecret, code, cbURL string)
| 19 | |
| 20 | // ExchangeCodeForToken fetches an access token for the given application using the provided code. |
| 21 | func ExchangeCodeForToken(httpClient *http.Client, baseDomain, clientID, clientSecret, code, cbURL string) (*TokenResponse, error) { |
| 22 | data := url.Values{ |
| 23 | "grant_type": {"authorization_code"}, |
| 24 | "client_id": {clientID}, |
| 25 | "client_secret": {clientSecret}, |
| 26 | "code": {code}, |
| 27 | "redirect_uri": {cbURL}, |
| 28 | } |
| 29 | |
| 30 | u := url.URL{Scheme: "https", Host: baseDomain, Path: "/oauth/token"} |
| 31 | r, err := httpClient.PostForm(u.String(), data) |
| 32 | if err != nil { |
| 33 | return nil, fmt.Errorf("unable to exchange code for token: %w", err) |
| 34 | } |
| 35 | defer func() { |
| 36 | _ = r.Body.Close() |
| 37 | }() |
| 38 | |
| 39 | if r.StatusCode != http.StatusOK { |
| 40 | return nil, fmt.Errorf("unable to exchange code for token: %s", r.Status) |
| 41 | } |
| 42 | |
| 43 | var res *TokenResponse |
| 44 | err = json.NewDecoder(r.Body).Decode(&res) |
| 45 | if err != nil { |
| 46 | return nil, fmt.Errorf("cannot decode response: %w", err) |
| 47 | } |
| 48 | |
| 49 | return res, nil |
| 50 | } |