bind_component.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package authorization
  2. import (
  3. "errors"
  4. "net/url"
  5. "strconv"
  6. "gitee.com/yansen_zh/wxcomponent/utils/request"
  7. )
  8. // BindComponentParam 构建授权链接入参
  9. type BindComponentParam struct {
  10. ComponentAppId string
  11. PreAuthCode string
  12. // RedirectUri 不需要转码
  13. RedirectUri string
  14. AuthType int
  15. BizAppId string
  16. }
  17. const (
  18. componentloginpage = "https://mp.weixin.qq.com/cgi-bin/componentloginpage"
  19. bindcomponent = "https://mp.weixin.qq.com/safe/bindcomponent"
  20. )
  21. // BindComponentByPC 构建PC端授权链接
  22. func BindComponentByPC(param BindComponentParam) (*url.URL, error) {
  23. return BindComponent("PC", param)
  24. }
  25. // BindComponentByH5 构建H5端授权链接
  26. func BindComponentByH5(param BindComponentParam) (*url.URL, error) {
  27. return BindComponent("H5", param)
  28. }
  29. // BindComponent 构建授权链接
  30. func BindComponent(client string, param BindComponentParam) (*url.URL, error) {
  31. isH5 := client == "H5"
  32. if param.ComponentAppId == "" {
  33. return nil, errors.New("构建授权链接 第三方平台的 appid 不能为空")
  34. }
  35. if param.PreAuthCode == "" {
  36. return nil, errors.New("构建授权链接 预授权码 不能为空")
  37. }
  38. if param.RedirectUri == "" {
  39. return nil, errors.New("构建授权链接 回调 URI 不能为空")
  40. }
  41. if param.AuthType < 1 || param.AuthType > 3 {
  42. param.AuthType = 3
  43. }
  44. queryParams := url.Values{}
  45. if isH5 {
  46. queryParams.Set("action", "bindcomponent")
  47. queryParams.Set("no_scan", "1")
  48. }
  49. queryParams.Set("component_appid", param.ComponentAppId)
  50. queryParams.Set("pre_auth_code", param.PreAuthCode)
  51. queryParams.Set("redirect_uri", param.RedirectUri)
  52. // auth_type、biz_appid 两个字段互斥
  53. if param.BizAppId != "" {
  54. queryParams.Set("biz_appid", param.BizAppId)
  55. } else {
  56. queryParams.Set("auth_type", strconv.Itoa(param.AuthType))
  57. }
  58. apiUrl := componentloginpage
  59. if isH5 {
  60. apiUrl = bindcomponent
  61. }
  62. u, err := request.ParseURL(apiUrl, &queryParams)
  63. if err != nil {
  64. return nil, err
  65. }
  66. if isH5 {
  67. u.Fragment = "wechat_redirect"
  68. }
  69. return u, nil
  70. }