bind_component.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. "errors"
  15. "net/url"
  16. "strconv"
  17. "gitee.com/yansen_zh/wxcomponent/config"
  18. )
  19. const (
  20. componentloginpage = "https://mp.weixin.qq.com/cgi-bin/componentloginpage"
  21. bindcomponent = "https://mp.weixin.qq.com/safe/bindcomponent"
  22. )
  23. // GetAuthLink 构建授权链接
  24. // redirectURI 回调地址必须是未经过处理的原始URL字符串
  25. func GetAuthLink(client, preAuthCode, redirectURI, bizAppID string, authType int) (string, error) {
  26. isH5 := client == "H5"
  27. if preAuthCode == "" {
  28. return "", errors.New("构建授权链接 预授权码 不能为空")
  29. }
  30. if redirectURI == "" {
  31. return "", errors.New("构建授权链接 回调 URI 不能为空")
  32. }
  33. if authType < 1 || authType > 3 {
  34. authType = 3
  35. }
  36. queryParams := url.Values{}
  37. if isH5 {
  38. queryParams.Set("action", "bindcomponent")
  39. queryParams.Set("no_scan", "1")
  40. }
  41. queryParams.Set("component_appid", config.GetAppID())
  42. queryParams.Set("pre_auth_code", preAuthCode)
  43. queryParams.Set("redirect_uri", redirectURI)
  44. // auth_type、biz_appid 两个字段互斥
  45. if bizAppID != "" {
  46. queryParams.Set("biz_appid", bizAppID)
  47. } else {
  48. queryParams.Set("auth_type", strconv.Itoa(authType))
  49. }
  50. link := componentloginpage
  51. if isH5 {
  52. link = bindcomponent
  53. }
  54. link += "?" + queryParams.Encode()
  55. if isH5 {
  56. link += "#wechat_redirect"
  57. }
  58. return link, nil
  59. }