-
Notifications
You must be signed in to change notification settings - Fork 0
/
request_oauth.go
75 lines (65 loc) · 2.13 KB
/
request_oauth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package ernieapi
import (
"context"
"fmt"
"net/http"
"net/url"
)
const DefaultGrantType = "client_credentials"
type OAuthTokenRequest struct {
GrantType string `json:"grant_type"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
type OAuthTokenResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
AccessToken string `json:"data"`
}
type BCEOAuthTokenResponse struct {
ExpiresIn int `json:"expires_in"`
AccessToken string `json:"access_token"`
}
func CreateOAuthToken(ctx context.Context, request *OAuthTokenRequest) (response *OAuthTokenResponse, err error) {
client := NewClientWithConfig(DefaultConfig(""))
urlSuffix := "/oauth/token"
if request.GrantType == "" {
request.GrantType = DefaultGrantType
}
QueryParams := url.Values{}
QueryParams.Add("grant_type", request.GrantType)
QueryParams.Add("client_id", request.ClientID)
QueryParams.Add("client_secret", request.ClientSecret)
requestUrl := client.config.BaseURL + urlSuffix + "?" + QueryParams.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, requestUrl, nil)
if err != nil {
return
}
errResponse := &ResponseError{}
err = client.sendRequest(req, &response, errResponse)
return
}
func CreateBCEOAuthToken(ctx context.Context, request *OAuthTokenRequest) (response *BCEOAuthTokenResponse, err error) {
client := NewClientWithConfig(DefaultBCEConfig(""))
urlSuffix := "/oauth/2.0/token"
if request.GrantType == "" {
request.GrantType = DefaultGrantType
}
QueryParams := url.Values{}
QueryParams.Add("grant_type", request.GrantType)
QueryParams.Add("client_id", request.ClientID)
QueryParams.Add("client_secret", request.ClientSecret)
requestUrl := client.config.BaseURL + urlSuffix + "?" + QueryParams.Encode()
fmt.Println(requestUrl)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, requestUrl, nil)
if err != nil {
return
}
type BCEResponseError struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
errResponse := &BCEResponseError{}
err = client.sendRequest(req, &response, errResponse)
return
}