component_token.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. wxerr "gitee.com/yansen_zh/wxcomponent/errors"
  17. "gitee.com/yansen_zh/wxcomponent/utils/request"
  18. )
  19. // ComponentTokenParam 获取令牌参数
  20. type ComponentTokenParam struct {
  21. ComponentAppId string `json:"component_appid"`
  22. ComponentAppSecret string `json:"component_appsecret"`
  23. ComponentVerifyTicket string `json:"component_verify_ticket"`
  24. }
  25. // ComponentTokenResult 获取令牌结果
  26. type ComponentTokenResult struct {
  27. wxerr.Error
  28. ComponentAccessToken string `json:"component_access_token"`
  29. ExpiresIn int `json:"expires_in"`
  30. }
  31. const (
  32. apiComponentToken = "https://apies.weixin.qq.com/cgi-bin/component/api_component_token"
  33. )
  34. // ComponentVerifyTicket 获取令牌
  35. func ComponentToken(data ComponentTokenParam) (*ComponentTokenResult, error) {
  36. if data.ComponentAppId == "" {
  37. return nil, errors.New("获取令牌 第三方平台的 appid 不能为空")
  38. }
  39. if data.ComponentAppSecret == "" {
  40. return nil, errors.New("获取令牌 第三方平台的 appsecret 不能为空")
  41. }
  42. if data.ComponentVerifyTicket == "" {
  43. return nil, errors.New("获取令牌 推送 ticket 不能为空")
  44. }
  45. resp, e2 := request.PostJSON(apiComponentToken, nil, data)
  46. if e2 != nil {
  47. return nil, e2
  48. }
  49. result := ComponentTokenResult{}
  50. if err := json.Unmarshal(resp, &result); err != nil {
  51. return nil, err
  52. }
  53. return &result, nil
  54. }