12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // QueryAuthParam 获取授权信息参数
  21. type QueryAuthParam struct {
  22. ComponentAppId string `json:"component_appid"`
  23. AuthorizationCode string `json:"authorization_code"`
  24. }
  25. // QueryAuthResult 获取授权信息结果
  26. type QueryAuthResult struct {
  27. wxerr.Error
  28. AuthorizationInfo AuthorizationInfo `json:"authorization_info"`
  29. }
  30. const (
  31. apiQueryAuth = "https://apies.weixin.qq.com/cgi-bin/component/api_query_auth"
  32. )
  33. // QueryAuth 获取授权信息
  34. func QueryAuth(componentAccessToken string, data QueryAuthParam) (*QueryAuthResult, error) {
  35. if componentAccessToken == "" {
  36. return nil, errors.New("获取授权信息 第三方平台的 component_access_token 不能为空")
  37. }
  38. if data.ComponentAppId == "" {
  39. return nil, errors.New("获取授权信息 第三方平台的 appid 不能为空")
  40. }
  41. if data.AuthorizationCode == "" {
  42. return nil, errors.New("获取授权信息 授权码 不能为空")
  43. }
  44. queryParam := url.Values{}
  45. queryParam.Set("component_access_token", componentAccessToken)
  46. apiUrl, _ := request.ParseURL(apiQueryAuth, &queryParam)
  47. resp, e2 := request.PostJSON(apiUrl.String(), data)
  48. if e2 != nil {
  49. return nil, e2
  50. }
  51. result := QueryAuthResult{}
  52. if err := json.Unmarshal(resp, &result); err != nil {
  53. return nil, err
  54. }
  55. if result.Code != 0 {
  56. return &result, result.Error
  57. }
  58. return &result, nil
  59. }