From 6b4231238feb19782a8c1409d20612a6289ea585 Mon Sep 17 00:00:00 2001 From: birjemin Date: Sun, 27 Dec 2020 15:48:09 +0800 Subject: [PATCH] add --- README.md | 117 +++++++++++++++++++++++++++++++++++++------------ default.go | 1 + qq.go | 38 ++++++++-------- utils/http.go | 8 ++++ wechat.go | 2 +- wechat_test.go | 4 +- weibo.go | 5 ++- weibo_test.go | 4 +- 8 files changed, 124 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index 3f06439..f714fb3 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,108 @@ -## wxgameod-微信小游戏开放数据后台接口 +## go-socialite -[![Build Status](https://travis-ci.com/Birjemin/wxgameod.svg?branch=master)](https://travis-ci.com/Birjemin/wxgameod) -[![Go Report Card](https://goreportcard.com/badge/github.com/birjemin/wxgameod)](https://goreportcard.com/report/github.com/birjemin/wxgameod) -[![codecov](https://codecov.io/gh/Birjemin/wxgameod/branch/master/graph/badge.svg)](https://codecov.io/gh/Birjemin/wxgameod) +oauth2授权登录(QQ、Wchat、Weibo) +[![Build Status](https://travis-ci.com/Birjemin/go-socialite.svg?branch=master)](https://travis-ci.com/Birjemin/go-socialite) +[![Go Report Card](https://goreportcard.com/badge/github.com/birjemin/go-socialite)](https://goreportcard.com/report/github.com/birjemin/go-socialite) +[![codecov](https://codecov.io/gh/Birjemin/go-socialite/branch/master/graph/badge.svg)](https://codecov.io/gh/Birjemin/go-socialite) -[开发者中心](https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/data/storage.removeUserStorage.html) ### 引入方式 ``` -go get github.com/birjemin/wxgameod +go get github.com/birjemin/go-socialite ``` -### 接口列表 +### 使用方式 -- [removeUserStorage](https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/data/storage.removeUserStorage.html) ✅ -- [setUserInteractiveData](https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/data/storage.setUserInteractiveData.html) ✅ -- [setUserStorage](https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/data/storage.setUserStorage.html) ✅ +- 初始化 -### 使用方式 +```golang +var ( + httpClient = &utils.HTTPClient{ + Client: &http.Client{ + Timeout: 5 * time.Second, + }, + } + + defaultObj = &socialite.Default{} + + qqObj = &socialite.Qq{ + AppID: "", + AppSecret: "x", + RedirectURL: "https://domain/qq/callback", + HTTPRequest: httpClient, + } + + wxObj = &socialite.Wechat{ + AppID: "", + AppSecret: "", + RedirectURL: "https://domain/qq/callback", + HTTPRequest: httpClient, + } + + wbObj = &socialite.Weibo{ + ClientID: "", + ClientSecret: "", + RedirectURL: "http://domain.com/wb/callback", + HTTPRequest: httpClient, + } +) + +func dispatch(platform string) socialite.ISocialite { + var obj socialite.ISocialite + + switch platform { + case "qq": + obj = qqObj + case "wx": + obj = wxObj + case "wb": + obj = wbObj + default: + obj = defaultObj + } + + return obj +} +obj := dispatch("wx") +// obj := dispatch("wb") +// obj := dispatch("qq") + +``` -- 示例 +- 获取授权地址(登录完成之后会带上`CODE`跳转到回调地址中) +```golang +log.Print("authorize_url: ", obj.GetAuthorizeURL()) +``` +- 获取授权AccessToken() ```golang -httpClient := &utils.HTTPClient{ - Client: &http.Client{ - Timeout: 5 * time.Second, - }, +// 上一步得到的CODE +resp, err := obj.Token("CODE") +// 断言 +ret, ok := resp.(*socialite.WxRespToken) +if ok { + log.Printf("ret: %#v", ret) } -var m = SetUserStorage{ - AccessToken: "ACCESS_TOKEN", - SessionKey: "SESSION_KEY", - OpenID: "OPEN_ID", - KvList: "{\"kv_list\":[{\"key\":\"1\",\"value\":\"0\"}]}", - HTTPRequest: httpClient, +``` + +- 获取用户的OPEN_ID(QQ接口专有,wechat、weibo在上一步中已经返回用户标识) +```golang +resp, err := obj.GetMe("ACCESS_TOKEN") +// 断言 +ret, ok := resp.(*socialite.QqRespMe) +if ok { + log.Printf("ret: %#v", ret) } +``` -if ret, err := m.doSetUserStorage(ts.URL); err != nil { - t.Error(err) -} else { - if ret.ErrCode != 0 { - t.Error(errors.New("msg: " + ret.ErrMsg)) - } +- 获取用户信息 +```golang +resp, err := obj.GetUserInfo("ACCESS_TOKEN", "OPEN_ID") +// 断言 +ret, ok := resp.(*socialite.WxUserInfo) +if ok { + log.Printf("ret: %#v", ret) } ``` diff --git a/default.go b/default.go index 1a88374..127afc6 100644 --- a/default.go +++ b/default.go @@ -32,6 +32,7 @@ type RespToken struct { OpenID string `json:"openid"` } +// Default struct type Default struct{} // GetAuthorizeURL get authorize url diff --git a/qq.go b/qq.go index 0a223d4..7c7d207 100644 --- a/qq.go +++ b/qq.go @@ -24,7 +24,7 @@ const ( qqUserInfoURL = "https://graph.qq.com/user/get_user_info" ) -// Qq +// Qq struct // @doc: https://wiki.open.qq.com/wiki/website/%E4%BD%BF%E7%94%A8Authorization_Code%E8%8E%B7%E5%8F%96Access_Token type Qq struct { AppID string @@ -188,23 +188,22 @@ func (q *Qq) getRespToken(b []byte) (*QqRespToken, error) { } return ret, errors.New("get token error") - } else { + } - pattern, err := regexp.Compile(`access_token=(\S*)&expires_in=(\S*)&refresh_token=(\S*)`) - if err != nil { - return ret, err - } - temp := pattern.FindSubmatch(b) + pattern, err := regexp.Compile(`access_token=(\S*)&expires_in=(\S*)&refresh_token=(\S*)`) + if err != nil { + return ret, err + } + temp := pattern.FindSubmatch(b) - if len(temp) != 4 { - return ret, errors.New("length of result is invalid") - } - ret.AccessToken = string(temp[1]) - expired, _ := strconv.ParseInt(string(temp[2]), 10, 64) - ret.ExpiresIn = int(expired) - ret.RefreshToken = string(temp[3]) - return ret, nil + if len(temp) != 4 { + return ret, errors.New("length of result is invalid") } + ret.AccessToken = string(temp[1]) + expired, _ := strconv.ParseInt(string(temp[2]), 10, 64) + ret.ExpiresIn = int(expired) + ret.RefreshToken = string(temp[3]) + return ret, nil } // GetMe get me @@ -254,13 +253,12 @@ func (q *Qq) getRespMe(b []byte) (*QqRespMe, error) { } return ret, errors.New("get token error") - } else { + } - if err := jsoniter.Unmarshal(pattern.Find(b), &ret); err != nil { - return ret, err - } - return ret, nil + if err := jsoniter.Unmarshal(pattern.Find(b), &ret); err != nil { + return ret, err } + return ret, nil } // GetUserInfo get user info diff --git a/utils/http.go b/utils/http.go index 49b07e5..4576d93 100644 --- a/utils/http.go +++ b/utils/http.go @@ -57,6 +57,14 @@ func (c *HTTPClient) GetResponseJSON(response interface{}) error { return errors.New("http request response body is empty") } + + // b ,err := ioutil.ReadAll(c.Response.Body) + // if err != nil { + // log.Println("body11: ", err.Error()) + // } + // log.Println("body22: ", string(b)) + + var json = jsoniter.ConfigCompatibleWithStandardLibrary defer c.Response.Body.Close() return json.NewDecoder(c.Response.Body).Decode(response) diff --git a/wechat.go b/wechat.go index 7044a0e..31350ae 100644 --- a/wechat.go +++ b/wechat.go @@ -20,7 +20,7 @@ const ( wxUserInfoURL = "https://api.weixin.qq.com/sns/userinfo" ) -// Wechat +// Wechat struct // @doc: https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html type Wechat struct { AppID string diff --git a/wechat_test.go b/wechat_test.go index 821bd79..37444f3 100644 --- a/wechat_test.go +++ b/wechat_test.go @@ -10,7 +10,7 @@ import ( ) var ( - wxHttpClient = &utils.HTTPClient{ + wxHTTPClient = &utils.HTTPClient{ Client: &http.Client{ Timeout: 5 * time.Second, }, @@ -20,7 +20,7 @@ var ( AppID: "APPID", AppSecret: "SECRET", RedirectURL: "REDIRECT_URI", - HTTPRequest: wxHttpClient, + HTTPRequest: wxHTTPClient, } ) diff --git a/weibo.go b/weibo.go index f017391..f236935 100644 --- a/weibo.go +++ b/weibo.go @@ -17,6 +17,7 @@ const ( wbUserInfoURL = "https://api.weibo.com/2/users/show.json" ) +// Weibo struct type Weibo struct { ClientID string ClientSecret string @@ -29,7 +30,7 @@ type wbRespErrorToken struct { ErrorCode int `json:"error_code"` Error string `json:"error"` Request string `json:"request"` - ErrorUri string `json:"error_uri"` + ErrorURI string `json:"error_uri"` } // WbRespToken response of me @@ -42,7 +43,7 @@ type WbRespToken struct { IsRealName string `json:"isRealName"` } -// WbUserInfoWbUserInfo user info +// WbUserInfo user info type WbUserInfo struct { wbRespErrorToken ID int `json:"id"` diff --git a/weibo_test.go b/weibo_test.go index 0aab3e0..948aa07 100644 --- a/weibo_test.go +++ b/weibo_test.go @@ -10,7 +10,7 @@ import ( ) var ( - wbHttpClient = &utils.HTTPClient{ + wbHTTPClient = &utils.HTTPClient{ Client: &http.Client{ Timeout: 5 * time.Second, }, @@ -20,7 +20,7 @@ var ( ClientID: "CLIENT_ID", ClientSecret: "CLIENT_SECRET", RedirectURL: "REDIRECT_URI", - HTTPRequest: wbHttpClient, + HTTPRequest: wbHTTPClient, } )