bind_component.go 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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/utils/request"
  18. )
  19. // BindComponentParam 构建授权链接入参
  20. type BindComponentParam 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. // BindComponentByPC 构建PC端授权链接
  33. func BindComponentByPC(param BindComponentParam) (*url.URL, error) {
  34. return BindComponent("PC", param)
  35. }
  36. // BindComponentByH5 构建H5端授权链接
  37. func BindComponentByH5(param BindComponentParam) (*url.URL, error) {
  38. return BindComponent("H5", param)
  39. }
  40. // BindComponent 构建授权链接
  41. func BindComponent(client string, param BindComponentParam) (*url.URL, error) {
  42. isH5 := client == "H5"
  43. if param.ComponentAppId == "" {
  44. return nil, errors.New("构建授权链接 第三方平台的 appid 不能为空")
  45. }
  46. if param.PreAuthCode == "" {
  47. return nil, errors.New("构建授权链接 预授权码 不能为空")
  48. }
  49. if param.RedirectUri == "" {
  50. return nil, errors.New("构建授权链接 回调 URI 不能为空")
  51. }
  52. if param.AuthType < 1 || param.AuthType > 3 {
  53. param.AuthType = 3
  54. }
  55. queryParams := url.Values{}
  56. if isH5 {
  57. queryParams.Set("action", "bindcomponent")
  58. queryParams.Set("no_scan", "1")
  59. }
  60. queryParams.Set("component_appid", param.ComponentAppId)
  61. queryParams.Set("pre_auth_code", param.PreAuthCode)
  62. queryParams.Set("redirect_uri", param.RedirectUri)
  63. // auth_type、biz_appid 两个字段互斥
  64. if param.BizAppId != "" {
  65. queryParams.Set("biz_appid", param.BizAppId)
  66. } else {
  67. queryParams.Set("auth_type", strconv.Itoa(param.AuthType))
  68. }
  69. apiUrl := componentloginpage
  70. if isH5 {
  71. apiUrl = bindcomponent
  72. }
  73. u, err := request.ParseURL(apiUrl, &queryParams)
  74. if err != nil {
  75. return nil, err
  76. }
  77. if isH5 {
  78. u.Fragment = "wechat_redirect"
  79. }
  80. return u, nil
  81. }