authorizer_token.go 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * Copyright (c) 2022 Yansen Zhang
  3. * wxcomponent is licensed under Mulan PSL v2.
  4. * You can use this software according to the terms and conditions of the Mulan PSL v2.
  5. * You may obtain a copy of Mulan PSL v2 at:
  6. * http://license.coscl.org.cn/MulanPSL2
  7. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
  8. * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
  9. * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  10. * See the Mulan PSL v2 for more details.
  11. **/
  12. package authorization
  13. import (
  14. "encoding/json"
  15. "errors"
  16. "net/url"
  17. wxerr "gitee.com/yansen_zh/wxcomponent/errors"
  18. "gitee.com/yansen_zh/wxcomponent/utils/request"
  19. )
  20. // AuthorizerTokenParam 获取/刷新接口调用令牌参数
  21. type AuthorizerTokenParam struct {
  22. ComponentAppId string `json:"component_appid"`
  23. AuthorizerAppId string `json:"authorizer_appid"`
  24. AuthorizerRefreshToken string `json:"authorizer_refresh_token"`
  25. }
  26. // AuthorizerTokenResult 获取/刷新接口调用令牌结果
  27. type AuthorizerTokenResult struct {
  28. wxerr.Error
  29. AuthorizerAccessToken string `json:"authorizer_access_token"`
  30. ExpiresIn int `json:"expires_in"`
  31. AuthorizerRefreshToken string `json:"authorizer_refresh_token"`
  32. }
  33. const (
  34. apiAuthorizerToken = "https://apies.weixin.qq.com/cgi-bin/component/api_authorizer_token"
  35. )
  36. // AuthorizerToken 获取/刷新接口调用令牌
  37. func AuthorizerToken(componentAccessToken string, data AuthorizerTokenParam) (*AuthorizerTokenResult, error) {
  38. if componentAccessToken == "" {
  39. return nil, errors.New("获取/刷新接口调用令牌 第三方平台的 component_access_token 不能为空")
  40. }
  41. if data.ComponentAppId == "" {
  42. return nil, errors.New("获取/刷新接口调用令牌 第三方平台的 appid 不能为空")
  43. }
  44. if data.AuthorizerAppId == "" {
  45. return nil, errors.New("获取/刷新接口调用令牌 授权方 appid 不能为空")
  46. }
  47. if data.AuthorizerRefreshToken == "" {
  48. return nil, errors.New("获取/刷新接口调用令牌 刷新令牌 不能为空")
  49. }
  50. queryParam := url.Values{}
  51. queryParam.Set("component_access_token", componentAccessToken)
  52. apiUrl, _ := request.ParseURL(apiAuthorizerToken, &queryParam)
  53. resp, e2 := request.PostJSON(apiUrl.String(), data)
  54. if e2 != nil {
  55. return nil, e2
  56. }
  57. result := AuthorizerTokenResult{}
  58. if err := json.Unmarshal(resp, &result); err != nil {
  59. return nil, err
  60. }
  61. if result.Code != 0 {
  62. return &result, result.Error
  63. }
  64. return &result, nil
  65. }