pre_auth_code.go 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package authorization
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/url"
  6. wxerr "gitee.com/yansen_zh/wxcomponent/errors"
  7. "gitee.com/yansen_zh/wxcomponent/utils/request"
  8. )
  9. // PreAuthCodeParam 获取预授权码参数
  10. type PreAuthCodeParam struct {
  11. ComponentAppId string `json:"component_appid"`
  12. }
  13. // PreAuthCodeResult 获取预授权码结果
  14. type PreAuthCodeResult struct {
  15. wxerr.Error
  16. PreAuthCode string `json:"pre_auth_code"`
  17. ExpiresIn float64 `json:"expires_in"`
  18. }
  19. const (
  20. apiCreatePreauthcode = "https://apies.weixin.qq.com/cgi-bin/component/api_create_preauthcode"
  21. )
  22. // CreatePreAuthCode 获取预授权码
  23. func CreatePreAuthCode(componentAccessToken string, data PreAuthCodeParam) (*PreAuthCodeResult, error) {
  24. if componentAccessToken == "" {
  25. return nil, errors.New("获取预授权码 第三方平台的 component_access_token 不能为空")
  26. }
  27. if data.ComponentAppId == "" {
  28. return nil, errors.New("获取预授权码 第三方平台的 appid 不能为空")
  29. }
  30. queryParam := url.Values{}
  31. queryParam.Set("component_access_token", componentAccessToken)
  32. apiUrl, _ := request.ParseURL(apiCreatePreauthcode, &queryParam)
  33. resp, e2 := request.PostJSON(apiUrl.String(), data)
  34. if e2 != nil {
  35. return nil, e2
  36. }
  37. result := PreAuthCodeResult{}
  38. if err := json.Unmarshal(resp, &result); err != nil {
  39. return nil, err
  40. }
  41. if result.Code != 0 {
  42. return &result, result.Error
  43. }
  44. return &result, nil
  45. }