webpage.go 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 webpage
  13. // 代公众号发起网页授权
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "net/url"
  18. "strings"
  19. "gitee.com/yansen_zh/wxcomponent/config"
  20. wxerr "gitee.com/yansen_zh/wxcomponent/errors"
  21. "gitee.com/yansen_zh/wxcomponent/utils/request"
  22. )
  23. // GetOAuthCodeLink 代公众号发起网页授权, 构造授权链接
  24. // redirectURI 必须是未经编码的原始网址字符串
  25. func GetOAuthCodeLink(appID, redirectURI, state string, scopes ...string) string {
  26. params := url.Values{}
  27. params.Set("appid", appID)
  28. params.Set("redirect_uri", redirectURI)
  29. params.Set("response_type", "code")
  30. params.Set("scope", strings.Join(scopes, ","))
  31. params.Set("state", state)
  32. params.Set("component_appid", config.GetAppID())
  33. return "https://open.weixin.qq.com/connect/oauth2/authorize?" + params.Encode()
  34. }
  35. // MpOAuthAccessTokenResult 网页授权, 通过 code 换取 access_token 返回值
  36. type MpOAuthAccessTokenResult struct {
  37. wxerr.Error
  38. // AccessToken 接口调用凭证
  39. AccessToken string `json:"access_token"`
  40. // ExpiresIn access_token 接口调用凭证超时时间,单位(秒)
  41. ExpiresIn int `json:"expires_in"`
  42. // RefreshToken 用户刷新 access_token
  43. RefreshToken string `json:"refresh_token"`
  44. // Openid 授权用户唯一标识
  45. OpenID string `json:"openid"`
  46. // Scope 用户授权的作用域,使用逗号(,)分隔
  47. Scope string `json:"scope"`
  48. }
  49. const apiOAuthAccessToken = "https://api.weixin.qq.com/sns/oauth2/component/access_token"
  50. // GetOAuthAccessToken 网页授权, 通过 code 换取 access_token
  51. func GetOAuthAccessToken(appID, code string) (*MpOAuthAccessTokenResult, error) {
  52. if appID == "" || code == "" {
  53. return nil, errors.New("获取网页授权Token appID 或者 code 不能为空")
  54. }
  55. param := url.Values{}
  56. param.Set("appid", appID)
  57. param.Set("code", code)
  58. param.Set("grant_type", "authorization_code")
  59. param.Set("component_appid", config.GetAppID())
  60. param.Set("component_access_token", config.GetAccessToken())
  61. resp, e2 := request.GetJSON(apiOAuthAccessToken, &param)
  62. if e2 != nil {
  63. return nil, e2
  64. }
  65. result := MpOAuthAccessTokenResult{}
  66. if err := json.Unmarshal(resp, &result); err != nil {
  67. return nil, err
  68. }
  69. return &result, nil
  70. }