access.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package huawei
  2. // http://developer.huawei.com/consumer/cn/service/hms/catalog/huaweipush.html?page=hmssdk_huaweipush_api_reference_s1
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "time"
  9. )
  10. const (
  11. _accessTokenURL = "https://login.vmall.com/oauth2/token"
  12. _grantType = "client_credentials"
  13. _respCodeSuccess = 0
  14. )
  15. // Access huawei access token.
  16. type Access struct {
  17. AppID string
  18. Token string
  19. Expire int64
  20. }
  21. type accessResponse struct {
  22. Token string `json:"access_token"`
  23. Expire int64 `json:"expires_in"` // Access Token的有效期,以秒为单位
  24. Scope string `json:"scope"` // Access Token的访问范围,即用户实际授予的权限列表
  25. Code int `json:"error"`
  26. Desc string `json:"error_description"`
  27. }
  28. // NewAccess get token.
  29. func NewAccess(clientID, clientSecret string) (a *Access, err error) {
  30. params := url.Values{}
  31. params.Add("grant_type", _grantType)
  32. params.Add("client_id", clientID)
  33. params.Add("client_secret", clientSecret)
  34. res, err := http.PostForm(_accessTokenURL, params)
  35. if err != nil {
  36. return
  37. }
  38. defer res.Body.Close()
  39. dc := json.NewDecoder(res.Body)
  40. resp := new(accessResponse)
  41. if err = dc.Decode(resp); err != nil {
  42. return
  43. }
  44. if resp.Code == _respCodeSuccess {
  45. a = &Access{
  46. AppID: clientID,
  47. Token: resp.Token,
  48. Expire: time.Now().Unix() + resp.Expire,
  49. }
  50. return
  51. }
  52. err = fmt.Errorf("new access error, code(%d) description(%s)", resp.Code, resp.Desc)
  53. return
  54. }
  55. // IsExpired judge that whether privilige expired.
  56. func (a *Access) IsExpired() bool {
  57. return a.Expire <= time.Now().Add(8*time.Hour).Unix() // 提前8小时过期,for renew auth
  58. }