pre_auth_code.go 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // PreAuthCodeParam 获取预授权码参数
  21. type PreAuthCodeParam struct {
  22. ComponentAppId string `json:"component_appid"`
  23. }
  24. // PreAuthCodeResult 获取预授权码结果
  25. type PreAuthCodeResult struct {
  26. wxerr.Error
  27. PreAuthCode string `json:"pre_auth_code"`
  28. ExpiresIn int `json:"expires_in"`
  29. }
  30. const (
  31. apiCreatePreauthcode = "https://apies.weixin.qq.com/cgi-bin/component/api_create_preauthcode"
  32. )
  33. // CreatePreAuthCode 获取预授权码
  34. func CreatePreAuthCode(componentAccessToken string, data PreAuthCodeParam) (*PreAuthCodeResult, 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. queryParam := url.Values{}
  42. queryParam.Set("component_access_token", componentAccessToken)
  43. resp, e2 := request.PostJSON(apiCreatePreauthcode, &queryParam, data)
  44. if e2 != nil {
  45. return nil, e2
  46. }
  47. result := PreAuthCodeResult{}
  48. if err := json.Unmarshal(resp, &result); err != nil {
  49. return nil, err
  50. }
  51. return &result, nil
  52. }