accessToken.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Package context 开放平台相关context
  2. package context
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "net/url"
  7. "time"
  8. "github.com/silenceper/wechat/v2/util"
  9. )
  10. const (
  11. componentAccessTokenURL = "https://api.weixin.qq.com/cgi-bin/component/api_component_token"
  12. getPreCodeURL = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=%s"
  13. queryAuthURL = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=%s"
  14. refreshTokenURL = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=%s"
  15. getComponentInfoURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=%s"
  16. componentLoginURL = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s&auth_type=%d&biz_appid=%s"
  17. bindComponentURL = "https://mp.weixin.qq.com/safe/bindcomponent?action=bindcomponent&auth_type=%d&no_scan=1&component_appid=%s&pre_auth_code=%s&redirect_uri=%s&biz_appid=%s#wechat_redirect"
  18. // TODO 获取授权方选项信息
  19. // getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
  20. // TODO 获取已授权的账号信息
  21. // getuthorizerListURL = "POST https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token=%s"
  22. )
  23. // ComponentAccessToken 第三方平台
  24. type ComponentAccessToken struct {
  25. AccessToken string `json:"component_access_token"`
  26. ExpiresIn int64 `json:"expires_in"`
  27. }
  28. // GetComponentAccessToken 获取 ComponentAccessToken
  29. func (ctx *Context) GetComponentAccessToken() (string, error) {
  30. accessTokenCacheKey := fmt.Sprintf("component_access_token_%s", ctx.AppID)
  31. val := ctx.Cache.Get(accessTokenCacheKey)
  32. if val == nil {
  33. return "", fmt.Errorf("cann't get component access token")
  34. }
  35. return val.(string), nil
  36. }
  37. // SetComponentAccessToken 通过component_verify_ticket 获取 ComponentAccessToken
  38. func (ctx *Context) SetComponentAccessToken(verifyTicket string) (*ComponentAccessToken, error) {
  39. body := map[string]string{
  40. "component_appid": ctx.AppID,
  41. "component_appsecret": ctx.AppSecret,
  42. "component_verify_ticket": verifyTicket,
  43. }
  44. respBody, err := util.PostJSON(componentAccessTokenURL, body)
  45. if err != nil {
  46. return nil, err
  47. }
  48. at := &ComponentAccessToken{}
  49. if err := json.Unmarshal(respBody, at); err != nil {
  50. return nil, err
  51. }
  52. accessTokenCacheKey := fmt.Sprintf("component_access_token_%s", ctx.AppID)
  53. expires := at.ExpiresIn - 1500
  54. if err := ctx.Cache.Set(accessTokenCacheKey, at.AccessToken, time.Duration(expires)*time.Second); err != nil {
  55. return nil, nil
  56. }
  57. return at, nil
  58. }
  59. // GetPreCode 获取预授权码
  60. func (ctx *Context) GetPreCode() (string, error) {
  61. cat, err := ctx.GetComponentAccessToken()
  62. if err != nil {
  63. return "", err
  64. }
  65. req := map[string]string{
  66. "component_appid": ctx.AppID,
  67. }
  68. uri := fmt.Sprintf(getPreCodeURL, cat)
  69. body, err := util.PostJSON(uri, req)
  70. if err != nil {
  71. return "", err
  72. }
  73. var ret struct {
  74. PreCode string `json:"pre_auth_code"`
  75. }
  76. if err := json.Unmarshal(body, &ret); err != nil {
  77. return "", err
  78. }
  79. return ret.PreCode, nil
  80. }
  81. // GetComponentLoginPage 获取第三方公众号授权链接(扫码授权)
  82. func (ctx *Context) GetComponentLoginPage(redirectURI string, authType int, bizAppID string) (string, error) {
  83. code, err := ctx.GetPreCode()
  84. if err != nil {
  85. return "", err
  86. }
  87. return fmt.Sprintf(componentLoginURL, ctx.AppID, code, url.QueryEscape(redirectURI), authType, bizAppID), nil
  88. }
  89. // GetBindComponentURL 获取第三方公众号授权链接(链接跳转,适用移动端)
  90. func (ctx *Context) GetBindComponentURL(redirectURI string, authType int, bizAppID string) (string, error) {
  91. code, err := ctx.GetPreCode()
  92. if err != nil {
  93. return "", err
  94. }
  95. return fmt.Sprintf(bindComponentURL, authType, ctx.AppID, code, url.QueryEscape(redirectURI), bizAppID), nil
  96. }
  97. // ID 微信返回接口中各种类型字段
  98. type ID struct {
  99. ID int `json:"id"`
  100. }
  101. // AuthBaseInfo 授权的基本信息
  102. type AuthBaseInfo struct {
  103. AuthrAccessToken
  104. FuncInfo []AuthFuncInfo `json:"func_info"`
  105. }
  106. // AuthFuncInfo 授权的接口内容
  107. type AuthFuncInfo struct {
  108. FuncscopeCategory ID `json:"funcscope_category"`
  109. }
  110. // AuthrAccessToken 授权方AccessToken
  111. type AuthrAccessToken struct {
  112. Appid string `json:"authorizer_appid"`
  113. AccessToken string `json:"authorizer_access_token"`
  114. ExpiresIn int64 `json:"expires_in"`
  115. RefreshToken string `json:"authorizer_refresh_token"`
  116. }
  117. // QueryAuthCode 使用授权码换取公众号或小程序的接口调用凭据和授权信息
  118. func (ctx *Context) QueryAuthCode(authCode string) (*AuthBaseInfo, error) {
  119. cat, err := ctx.GetComponentAccessToken()
  120. if err != nil {
  121. return nil, err
  122. }
  123. req := map[string]string{
  124. "component_appid": ctx.AppID,
  125. "authorization_code": authCode,
  126. }
  127. uri := fmt.Sprintf(queryAuthURL, cat)
  128. body, err := util.PostJSON(uri, req)
  129. if err != nil {
  130. return nil, err
  131. }
  132. var ret struct {
  133. util.CommonError
  134. Info *AuthBaseInfo `json:"authorization_info"`
  135. }
  136. if err := json.Unmarshal(body, &ret); err != nil {
  137. return nil, err
  138. }
  139. if ret.ErrCode != 0 {
  140. err = fmt.Errorf("QueryAuthCode error : errcode=%v , errmsg=%v", ret.ErrCode, ret.ErrMsg)
  141. return nil, err
  142. }
  143. return ret.Info, nil
  144. }
  145. // RefreshAuthrToken 获取(刷新)授权公众号或小程序的接口调用凭据(令牌)
  146. func (ctx *Context) RefreshAuthrToken(appid, refreshToken string) (*AuthrAccessToken, error) {
  147. cat, err := ctx.GetComponentAccessToken()
  148. if err != nil {
  149. return nil, err
  150. }
  151. req := map[string]string{
  152. "component_appid": ctx.AppID,
  153. "authorizer_appid": appid,
  154. "authorizer_refresh_token": refreshToken,
  155. }
  156. uri := fmt.Sprintf(refreshTokenURL, cat)
  157. body, err := util.PostJSON(uri, req)
  158. if err != nil {
  159. return nil, err
  160. }
  161. ret := &AuthrAccessToken{}
  162. if err := json.Unmarshal(body, ret); err != nil {
  163. return nil, err
  164. }
  165. authrTokenKey := "authorizer_access_token_" + appid
  166. if err := ctx.Cache.Set(authrTokenKey, ret.AccessToken, time.Minute*80); err != nil {
  167. return nil, err
  168. }
  169. return ret, nil
  170. }
  171. // GetAuthrAccessToken 获取授权方AccessToken
  172. func (ctx *Context) GetAuthrAccessToken(appid string) (string, error) {
  173. authrTokenKey := "authorizer_access_token_" + appid
  174. val := ctx.Cache.Get(authrTokenKey)
  175. if val == nil {
  176. return "", fmt.Errorf("cannot get authorizer %s access token", appid)
  177. }
  178. return val.(string), nil
  179. }
  180. // AuthorizerInfo 授权方详细信息
  181. type AuthorizerInfo struct {
  182. NickName string `json:"nick_name"`
  183. HeadImg string `json:"head_img"`
  184. ServiceTypeInfo ID `json:"service_type_info"`
  185. VerifyTypeInfo ID `json:"verify_type_info"`
  186. UserName string `json:"user_name"`
  187. PrincipalName string `json:"principal_name"`
  188. BusinessInfo struct {
  189. OpenStore string `json:"open_store"`
  190. OpenScan string `json:"open_scan"`
  191. OpenPay string `json:"open_pay"`
  192. OpenCard string `json:"open_card"`
  193. OpenShake string `json:"open_shake"`
  194. }
  195. Alias string `json:"alias"`
  196. QrcodeURL string `json:"qrcode_url"`
  197. }
  198. // GetAuthrInfo 获取授权方的帐号基本信息
  199. func (ctx *Context) GetAuthrInfo(appid string) (*AuthorizerInfo, *AuthBaseInfo, error) {
  200. cat, err := ctx.GetComponentAccessToken()
  201. if err != nil {
  202. return nil, nil, err
  203. }
  204. req := map[string]string{
  205. "component_appid": ctx.AppID,
  206. "authorizer_appid": appid,
  207. }
  208. uri := fmt.Sprintf(getComponentInfoURL, cat)
  209. body, err := util.PostJSON(uri, req)
  210. if err != nil {
  211. return nil, nil, err
  212. }
  213. var ret struct {
  214. AuthorizerInfo *AuthorizerInfo `json:"authorizer_info"`
  215. AuthorizationInfo *AuthBaseInfo `json:"authorization_info"`
  216. }
  217. if err := json.Unmarshal(body, &ret); err != nil {
  218. return nil, nil, err
  219. }
  220. return ret.AuthorizerInfo, ret.AuthorizationInfo, nil
  221. }