accessToken.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. // Package context 开放平台相关context
  2. package context
  3. import (
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "net/url"
  8. "time"
  9. "github.com/silenceper/wechat/v2/cache"
  10. "github.com/silenceper/wechat/v2/util"
  11. )
  12. const (
  13. componentAccessTokenURL = "https://api.weixin.qq.com/cgi-bin/component/api_component_token"
  14. getPreCodeURL = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=%s"
  15. queryAuthURL = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=%s"
  16. refreshTokenURL = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=%s"
  17. getComponentInfoURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=%s"
  18. 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"
  19. 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"
  20. // TODO 获取授权方选项信息
  21. // getComponentConfigURL = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token=%s"
  22. // TODO 获取已授权的账号信息
  23. // getuthorizerListURL = "POST https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token=%s"
  24. )
  25. // ComponentAccessToken 第三方平台
  26. type ComponentAccessToken struct {
  27. util.CommonError
  28. AccessToken string `json:"component_access_token"`
  29. ExpiresIn int64 `json:"expires_in"`
  30. }
  31. // GetComponentAccessTokenContext 获取 ComponentAccessToken
  32. func (ctx *Context) GetComponentAccessTokenContext(stdCtx context.Context) (string, error) {
  33. accessTokenCacheKey := fmt.Sprintf("component_access_token_%s", ctx.AppID)
  34. val := cache.GetContext(stdCtx, ctx.Cache, accessTokenCacheKey)
  35. if val == nil {
  36. return "", fmt.Errorf("cann't get component access token")
  37. }
  38. return val.(string), nil
  39. }
  40. // GetComponentAccessToken 获取 ComponentAccessToken
  41. func (ctx *Context) GetComponentAccessToken() (string, error) {
  42. return ctx.GetComponentAccessTokenContext(context.Background())
  43. }
  44. // SetComponentAccessTokenContext 通过component_verify_ticket 获取 ComponentAccessToken
  45. func (ctx *Context) SetComponentAccessTokenContext(stdCtx context.Context, verifyTicket string) (*ComponentAccessToken, error) {
  46. body := map[string]string{
  47. "component_appid": ctx.AppID,
  48. "component_appsecret": ctx.AppSecret,
  49. "component_verify_ticket": verifyTicket,
  50. }
  51. respBody, err := util.PostJSONContext(stdCtx, componentAccessTokenURL, body)
  52. if err != nil {
  53. return nil, err
  54. }
  55. at := &ComponentAccessToken{}
  56. if err := json.Unmarshal(respBody, at); err != nil {
  57. return nil, err
  58. }
  59. if at.ErrCode != 0 {
  60. return nil, fmt.Errorf("SetComponentAccessToken Error , errcode=%d , errmsg=%s", at.ErrCode, at.ErrMsg)
  61. }
  62. accessTokenCacheKey := fmt.Sprintf("component_access_token_%s", ctx.AppID)
  63. expires := at.ExpiresIn - 1500
  64. if err := cache.SetContext(stdCtx, ctx.Cache, accessTokenCacheKey, at.AccessToken, time.Duration(expires)*time.Second); err != nil {
  65. return nil, nil
  66. }
  67. return at, nil
  68. }
  69. // SetComponentAccessToken 通过component_verify_ticket 获取 ComponentAccessToken
  70. func (ctx *Context) SetComponentAccessToken(stdCtx context.Context, verifyTicket string) (*ComponentAccessToken, error) {
  71. return ctx.SetComponentAccessTokenContext(stdCtx, verifyTicket)
  72. }
  73. // GetPreCodeContext 获取预授权码
  74. func (ctx *Context) GetPreCodeContext(stdCtx context.Context) (string, error) {
  75. cat, err := ctx.GetComponentAccessTokenContext(stdCtx)
  76. if err != nil {
  77. return "", err
  78. }
  79. req := map[string]string{
  80. "component_appid": ctx.AppID,
  81. }
  82. uri := fmt.Sprintf(getPreCodeURL, cat)
  83. body, err := util.PostJSONContext(stdCtx, uri, req)
  84. if err != nil {
  85. return "", err
  86. }
  87. var ret struct {
  88. PreCode string `json:"pre_auth_code"`
  89. }
  90. if err := json.Unmarshal(body, &ret); err != nil {
  91. return "", err
  92. }
  93. return ret.PreCode, nil
  94. }
  95. // GetPreCode 获取预授权码
  96. func (ctx *Context) GetPreCode() (string, error) {
  97. return ctx.GetPreCodeContext(context.Background())
  98. }
  99. // GetComponentLoginPageContext 获取第三方公众号授权链接(扫码授权)
  100. func (ctx *Context) GetComponentLoginPageContext(stdCtx context.Context, redirectURI string, authType int, bizAppID string) (string, error) {
  101. code, err := ctx.GetPreCodeContext(stdCtx)
  102. if err != nil {
  103. return "", err
  104. }
  105. return fmt.Sprintf(componentLoginURL, ctx.AppID, code, url.QueryEscape(redirectURI), authType, bizAppID), nil
  106. }
  107. // GetComponentLoginPage 获取第三方公众号授权链接(扫码授权)
  108. func (ctx *Context) GetComponentLoginPage(redirectURI string, authType int, bizAppID string) (string, error) {
  109. return ctx.GetComponentLoginPageContext(context.Background(), redirectURI, authType, bizAppID)
  110. }
  111. // GetBindComponentURLContext 获取第三方公众号授权链接(链接跳转,适用移动端)
  112. func (ctx *Context) GetBindComponentURLContext(stdCtx context.Context, redirectURI string, authType int, bizAppID string) (string, error) {
  113. code, err := ctx.GetPreCodeContext(stdCtx)
  114. if err != nil {
  115. return "", err
  116. }
  117. return fmt.Sprintf(bindComponentURL, authType, ctx.AppID, code, url.QueryEscape(redirectURI), bizAppID), nil
  118. }
  119. // GetBindComponentURL 获取第三方公众号授权链接(链接跳转,适用移动端)
  120. func (ctx *Context) GetBindComponentURL(redirectURI string, authType int, bizAppID string) (string, error) {
  121. return ctx.GetBindComponentURLContext(context.Background(), redirectURI, authType, bizAppID)
  122. }
  123. // ID 微信返回接口中各种类型字段
  124. type ID struct {
  125. ID int `json:"id"`
  126. }
  127. // AuthBaseInfo 授权的基本信息
  128. type AuthBaseInfo struct {
  129. AuthrAccessToken
  130. FuncInfo []AuthFuncInfo `json:"func_info"`
  131. }
  132. // AuthFuncInfo 授权的接口内容
  133. type AuthFuncInfo struct {
  134. FuncscopeCategory ID `json:"funcscope_category"`
  135. }
  136. // AuthrAccessToken 授权方AccessToken
  137. type AuthrAccessToken struct {
  138. Appid string `json:"authorizer_appid"`
  139. AccessToken string `json:"authorizer_access_token"`
  140. ExpiresIn int64 `json:"expires_in"`
  141. RefreshToken string `json:"authorizer_refresh_token"`
  142. }
  143. // QueryAuthCodeContext 使用授权码换取公众号或小程序的接口调用凭据和授权信息
  144. func (ctx *Context) QueryAuthCodeContext(stdCtx context.Context, authCode string) (*AuthBaseInfo, error) {
  145. cat, err := ctx.GetComponentAccessTokenContext(stdCtx)
  146. if err != nil {
  147. return nil, err
  148. }
  149. req := map[string]string{
  150. "component_appid": ctx.AppID,
  151. "authorization_code": authCode,
  152. }
  153. uri := fmt.Sprintf(queryAuthURL, cat)
  154. body, err := util.PostJSONContext(stdCtx, uri, req)
  155. if err != nil {
  156. return nil, err
  157. }
  158. var ret struct {
  159. util.CommonError
  160. Info *AuthBaseInfo `json:"authorization_info"`
  161. }
  162. if err := json.Unmarshal(body, &ret); err != nil {
  163. return nil, err
  164. }
  165. if ret.ErrCode != 0 {
  166. err = fmt.Errorf("QueryAuthCode error : errcode=%v , errmsg=%v", ret.ErrCode, ret.ErrMsg)
  167. return nil, err
  168. }
  169. return ret.Info, nil
  170. }
  171. // QueryAuthCode 使用授权码换取公众号或小程序的接口调用凭据和授权信息
  172. func (ctx *Context) QueryAuthCode(authCode string) (*AuthBaseInfo, error) {
  173. return ctx.QueryAuthCodeContext(context.Background(), authCode)
  174. }
  175. // RefreshAuthrTokenContext 获取(刷新)授权公众号或小程序的接口调用凭据(令牌)
  176. func (ctx *Context) RefreshAuthrTokenContext(stdCtx context.Context, appid, refreshToken string) (*AuthrAccessToken, error) {
  177. cat, err := ctx.GetComponentAccessTokenContext(stdCtx)
  178. if err != nil {
  179. return nil, err
  180. }
  181. req := map[string]string{
  182. "component_appid": ctx.AppID,
  183. "authorizer_appid": appid,
  184. "authorizer_refresh_token": refreshToken,
  185. }
  186. uri := fmt.Sprintf(refreshTokenURL, cat)
  187. body, err := util.PostJSONContext(stdCtx, uri, req)
  188. if err != nil {
  189. return nil, err
  190. }
  191. ret := &AuthrAccessToken{}
  192. if err := json.Unmarshal(body, ret); err != nil {
  193. return nil, err
  194. }
  195. authrTokenKey := "authorizer_access_token_" + appid
  196. if err := cache.SetContext(stdCtx, ctx.Cache, authrTokenKey, ret.AccessToken, time.Second*time.Duration(ret.ExpiresIn-30)); err != nil {
  197. return nil, err
  198. }
  199. return ret, nil
  200. }
  201. // RefreshAuthrToken 获取(刷新)授权公众号或小程序的接口调用凭据(令牌)
  202. func (ctx *Context) RefreshAuthrToken(appid, refreshToken string) (*AuthrAccessToken, error) {
  203. return ctx.RefreshAuthrTokenContext(context.Background(), appid, refreshToken)
  204. }
  205. // GetAuthrAccessTokenContext 获取授权方AccessToken
  206. func (ctx *Context) GetAuthrAccessTokenContext(stdCtx context.Context, appid string) (string, error) {
  207. authrTokenKey := "authorizer_access_token_" + appid
  208. val := cache.GetContext(stdCtx, ctx.Cache, authrTokenKey)
  209. if val == nil {
  210. return "", fmt.Errorf("cannot get authorizer %s access token", appid)
  211. }
  212. return val.(string), nil
  213. }
  214. // GetAuthrAccessToken 获取授权方AccessToken
  215. func (ctx *Context) GetAuthrAccessToken(appid string) (string, error) {
  216. return ctx.GetAuthrAccessTokenContext(context.Background(), appid)
  217. }
  218. // AuthorizerInfo 授权方详细信息
  219. type AuthorizerInfo struct {
  220. NickName string `json:"nick_name"`
  221. HeadImg string `json:"head_img"`
  222. ServiceTypeInfo ID `json:"service_type_info"`
  223. VerifyTypeInfo ID `json:"verify_type_info"`
  224. UserName string `json:"user_name"`
  225. PrincipalName string `json:"principal_name"`
  226. BusinessInfo struct {
  227. OpenStore string `json:"open_store"`
  228. OpenScan string `json:"open_scan"`
  229. OpenPay string `json:"open_pay"`
  230. OpenCard string `json:"open_card"`
  231. OpenShake string `json:"open_shake"`
  232. }
  233. Alias string `json:"alias"`
  234. QrcodeURL string `json:"qrcode_url"`
  235. MiniProgramInfo *MiniProgramInfo `json:"MiniProgramInfo"`
  236. RegisterType int `json:"register_type"`
  237. AccountStatus int `json:"account_status"`
  238. BasicConfig *AuthorizerBasicConfig `json:"basic_config"`
  239. }
  240. // AuthorizerBasicConfig 授权账号的基础配置结构体
  241. type AuthorizerBasicConfig struct {
  242. IsPhoneConfigured bool `json:"isPhoneConfigured"`
  243. IsEmailConfigured bool `json:"isEmailConfigured"`
  244. }
  245. // MiniProgramInfo 授权账号小程序配置 授权账号为小程序时存在
  246. type MiniProgramInfo struct {
  247. Network struct {
  248. RequestDomain []string `json:"RequestDomain"`
  249. WsRequestDomain []string `json:"WsRequestDomain"`
  250. UploadDomain []string `json:"UploadDomain"`
  251. DownloadDomain []string `json:"DownloadDomain"`
  252. BizDomain []string `json:"BizDomain"`
  253. UDPDomain []string `json:"UDPDomain"`
  254. } `json:"network"`
  255. Categories []CategoriesInfo `json:"categories"`
  256. }
  257. // CategoriesInfo 授权账号小程序配置的类目信息
  258. type CategoriesInfo struct {
  259. First string `wx:"first"`
  260. Second string `wx:"second"`
  261. }
  262. // GetAuthrInfoContext 获取授权方的帐号基本信息
  263. func (ctx *Context) GetAuthrInfoContext(stdCtx context.Context, appid string) (*AuthorizerInfo, *AuthBaseInfo, error) {
  264. cat, err := ctx.GetComponentAccessTokenContext(stdCtx)
  265. if err != nil {
  266. return nil, nil, err
  267. }
  268. req := map[string]string{
  269. "component_appid": ctx.AppID,
  270. "authorizer_appid": appid,
  271. }
  272. uri := fmt.Sprintf(getComponentInfoURL, cat)
  273. body, err := util.PostJSONContext(stdCtx, uri, req)
  274. if err != nil {
  275. return nil, nil, err
  276. }
  277. var ret struct {
  278. AuthorizerInfo *AuthorizerInfo `json:"authorizer_info"`
  279. AuthorizationInfo *AuthBaseInfo `json:"authorization_info"`
  280. }
  281. if err := json.Unmarshal(body, &ret); err != nil {
  282. return nil, nil, err
  283. }
  284. return ret.AuthorizerInfo, ret.AuthorizationInfo, nil
  285. }
  286. // GetAuthrInfo 获取授权方的帐号基本信息
  287. func (ctx *Context) GetAuthrInfo(appid string) (*AuthorizerInfo, *AuthBaseInfo, error) {
  288. return ctx.GetAuthrInfoContext(context.Background(), appid)
  289. }