-
Notifications
You must be signed in to change notification settings - Fork 9
/
token.go
93 lines (78 loc) · 2.5 KB
/
token.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package wxspider
import (
"errors"
"github.com/imroc/req"
)
const BAIDU_AUTH_URL = "https://openapi.baidu.com/oauth/2.0/token"
//Authorizer 用于设置access_token
//可以通过RESTFul api的方式从百度方获取
//有效期为一个月,可以存至数据库中然后从数据库中获取
type Authorizer interface {
Authorize(*Client) error
}
type Client struct {
ClientID string
ClientSecret string
AccessToken string
Authorizer Authorizer
}
type AuthResponse struct {
AccessToken string `json:"access_token"` //要获取的Access Token
ExpireIn string `json:"expire_in"` //Access Token的有效期(秒为单位,一般为1个月);
RefreshToken string `json:"refresh_token"` //以下参数忽略,暂时不用
Scope string `json:"scope"`
SessionKey string `json:"session_key"`
SessionSecret string `json:"session_secret"`
ERROR string `json:"error"` //错误码;关于错误码的详细信息请参考鉴权认证错误码(http://ai.baidu.com/docs#/Auth/top)
ErrorDescription string `json:"error_description"` //错误描述信息,帮助理解和解决发生的错误。
}
type DefaultAuthorizer struct{}
func (da DefaultAuthorizer) Authorize(client *Client) error {
resp, err := req.Post(BAIDU_AUTH_URL, req.Param{
"grant_type": "client_credentials",
"client_id": client.ClientID,
"client_secret": client.ClientSecret,
})
if err != nil {
return err
}
authresponse := new(AuthResponse)
if err := resp.ToJSON(authresponse); err != nil {
return err
}
if authresponse.ERROR != "" || authresponse.AccessToken == "" {
return errors.New("授权失败:" + authresponse.ErrorDescription)
}
client.AccessToken = authresponse.AccessToken
return nil
}
func (client *Client) Auth() error {
if client.AccessToken != "" {
// return nil
}
if err := client.Authorizer.Authorize(client); err != nil {
return err
}
return nil
}
func (client *Client) SetAuther(auth Authorizer) {
client.Authorizer = auth
}
func NewClient(ApiKey, secretKey string) *Client {
return &Client{
ClientID: ApiKey,
ClientSecret: secretKey,
Authorizer: DefaultAuthorizer{},
}
}
var accessToken = ``
//GetToken 获取baidu api token 临时用
func GetToken() string {
if accessToken == `` {
cf := GetConf()
c := NewClient(cf.BaiDuAiConf.APIKey, cf.BaiDuAiConf.SecretKey)
c.Auth()
accessToken = c.AccessToken
}
return accessToken
}