bind_component.go 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // AuthLinkParam 构建授权链接入参
  20. type AuthLinkParam struct {
  21. ComponentAppId string
  22. PreAuthCode string
  23. // RedirectUri 不需要转码
  24. RedirectUri string
  25. AuthType int
  26. BizAppId string
  27. }
  28. const (
  29. componentloginpage = "https://mp.weixin.qq.com/cgi-bin/componentloginpage"
  30. bindcomponent = "https://mp.weixin.qq.com/safe/bindcomponent"
  31. )
  32. // GetPCAuthLink 构建PC端授权链接
  33. func GetPCAuthLink(preAuthCode, redirectURI, bizAppID string, authType int) (string, error) {
  34. return GetAuthLink("PC", preAuthCode, redirectURI, bizAppID, authType)
  35. }
  36. // GetH5AuthLink 构建H5端授权链接
  37. func GetH5AuthLink(preAuthCode, redirectURI, bizAppID string, authType int) (string, error) {
  38. return GetAuthLink("H5", preAuthCode, redirectURI, bizAppID, authType)
  39. }
  40. // GetAuthLink 构建授权链接
  41. // redirectURI 回调地址必须是未经过处理的原始URL字符串
  42. func GetAuthLink(client, preAuthCode, redirectURI, bizAppID string, authType int) (string, error) {
  43. isH5 := client == "H5"
  44. if preAuthCode == "" {
  45. return "", errors.New("构建授权链接 预授权码 不能为空")
  46. }
  47. if redirectURI == "" {
  48. return "", errors.New("构建授权链接 回调 URI 不能为空")
  49. }
  50. if authType < 1 || authType > 3 {
  51. authType = 3
  52. }
  53. queryParams := url.Values{}
  54. if isH5 {
  55. queryParams.Set("action", "bindcomponent")
  56. queryParams.Set("no_scan", "1")
  57. }
  58. queryParams.Set("component_appid", config.GetAppID())
  59. queryParams.Set("pre_auth_code", preAuthCode)
  60. queryParams.Set("redirect_uri", redirectURI)
  61. // auth_type、biz_appid 两个字段互斥
  62. if bizAppID != "" {
  63. queryParams.Set("biz_appid", bizAppID)
  64. } else {
  65. queryParams.Set("auth_type", strconv.Itoa(authType))
  66. }
  67. link := componentloginpage
  68. if isH5 {
  69. link = bindcomponent
  70. }
  71. link += "?" + queryParams.Encode()
  72. if isH5 {
  73. link += "#wechat_redirect"
  74. }
  75. return link, nil
  76. }