Kaynağa Gözat

微信相关接口,对象

huangrf 6 yıl önce
ebeveyn
işleme
2b89e39ae3
3 değiştirilmiş dosya ile 176 ekleme ve 9 silme
  1. 43 9
      third/wx/global.go
  2. 85 0
      third/wx/token.go
  3. 48 0
      third/wx/wx.go

+ 43 - 9
third/wx/global.go

@@ -7,23 +7,44 @@ import (
 	"time"
 
 	"github.com/silenceper/wechat"
+	"github.com/silenceper/wechat/oauth"
 	"github.com/silenceper/wechat/cache"
 )
 
 var wc *wechat.Wechat
+var wxoauth *oauth.Oauth
+
+var wxConfig struct {
+	WxPayCallback  string // 完整微信支付回调url,
+	AppId          string // 公众号appid
+	AppSecret      string // 公众号appsecret
+	Token          string // 设置token
+	EncodingAseKey string // ase key
+	PayMchId       string // 商户号id
+	PayKey         string // 商户支付设置的key
+	RedirectUrl    string // 微信Oauth完整跳转uri
+	Scope          string // 微信Oauth的scope
+	ResponseType   string // 微信oauth的response type
+	State          string // 微信oauth的state
+}
 
 func init() {
 	c := &LocalCache{}
-	wxpayCallback := config.AppConfig.GetKey("wxpay_callback") // 完整微信回调url,
-	appId := config.AppConfig.GetKey("app_id")					// 公众号appid
-	appSecret := config.AppConfig.GetKey("app_secret")			// 公众号app secret
-	token := config.AppConfig.GetKey("token")
-	encodingAseKey := config.AppConfig.GetKey("encoding_aes_key")
-	payMchId := config.AppConfig.GetKey("mch_id")				// 商户号id
-	payKey := config.AppConfig.GetKey("pay_key")				// 商户支付设置的key
-
-	config := &wechat.Config{appId, appSecret, token, encodingAseKey, payMchId, wxpayCallback, payKey, c}
+	wxConfig.WxPayCallback = config.AppConfig.GetKey("wxpay_callback") // 完整微信回调url,
+	wxConfig.AppId = config.AppConfig.GetKey("appid")					// 公众号appid
+	wxConfig.AppSecret = config.AppConfig.GetKey("appsecret")			// 公众号appsecret
+	wxConfig.Token = config.AppConfig.GetKey("token")
+	wxConfig.EncodingAseKey = config.AppConfig.GetKey("encoding_aes_key")
+	wxConfig.PayMchId = config.AppConfig.GetKey("mch_id")				// 商户号id
+	wxConfig.PayKey = config.AppConfig.GetKey("pay_key")				// 商户支付设置的key
+	wxConfig.RedirectUrl = config.AppConfig.GetKey("redirect_url")
+	wxConfig.Scope = config.AppConfig.GetKey("scope")
+	wxConfig.ResponseType = config.AppConfig.GetKey("response_type")
+	wxConfig.State = config.AppConfig.GetKey("state")
+
+	config := &wechat.Config{wxConfig.AppId, wxConfig.AppSecret, wxConfig.Token, wxConfig.EncodingAseKey, wxConfig.PayMchId, wxConfig.WxPayCallback, wxConfig.PayKey, c}
 	wc = wechat.NewWechat(config)
+	wxoauth = wc.GetOauth()
 }
 
 /*********************local cache*************************/
@@ -89,3 +110,16 @@ type PayParams struct{
 	PaySign   string `json:"paySign"`
 	OutTradeNo   string `json:"outTradeNo"`
 }
+
+// 微信oauth跳转信息,
+type WxOAuthConfig struct {
+	AuthUrl          string `json:"auth_url"`
+	AppId            string `json:"app_id"`
+	// 给微信跳转的url
+	RedirectUrl      string `json:"redirect_url"`
+	ResponseType     string `json:"response_type"`
+	Scope            string `json:"scope"`
+	State            string `json:"state"`
+	// 完整的微信Oauth的url
+	OAuthRedirectUrl string `json:"oauth_redirect_url"`
+}

+ 85 - 0
third/wx/token.go

@@ -0,0 +1,85 @@
+package wx
+
+import (
+	"github.com/silenceper/wechat/oauth"
+	"sync"
+	"time"
+)
+
+type tokenTiming struct {
+	Token *oauth.ResAccessToken
+	Timing time.Time
+}
+
+var tokenMap map[string]*tokenTiming
+var mutex sync.Mutex
+
+func init(){
+	tokenMap = make(map[string]*tokenTiming)
+	tokenCheckLoop()
+}
+
+func addToken(openId string, token *oauth.ResAccessToken) {
+	mutex.Lock()
+	defer mutex.Unlock()
+
+	if _, exists := tokenMap[openId]; !exists{
+		tokenMap[openId] = &tokenTiming{
+			Token: token,
+			Timing: time.Now(),
+		}
+	}
+}
+
+func getToken(openId string) *oauth.ResAccessToken{
+	mutex.Lock()
+	defer mutex.Unlock()
+
+	if t, exists := tokenMap[openId]; !exists{
+		return nil
+	}else{
+		return t.Token
+	}
+}
+
+func removeToken(openId string){
+	mutex.Lock()
+	defer mutex.Unlock()
+
+	if _, exists := tokenMap[openId]; exists{
+		delete(tokenMap, openId)
+	}
+}
+
+func tokenCheckLoop(){
+	go func(){
+		t:=time.NewTicker(10 * 60 * time.Second)
+		for {
+			select {
+			case <-t.C:
+				mutex.Lock()
+				ks := make([]string, 0)
+				for k, v := range tokenMap{
+					if time.Now().Sub(v.Timing) > 90 * time.Minute{
+						ks = append(ks, k)
+					}
+				}
+				for i := range ks{
+					//t, err := wxoauth.RefreshAccessToken(tokenMap[ks[i]].Token.RefreshToken)
+					//if err != nil{
+					//	delete(tokenMap, ks[i])
+					//	continue
+					//}else{
+					//	tokenMap[ks[i]] = t
+					//}
+					// 暂时删除不刷新
+					delete(tokenMap, ks[i])
+				}
+				mutex.Unlock()
+			}
+		}
+	}()
+}
+
+
+

+ 48 - 0
third/wx/wx.go

@@ -6,6 +6,7 @@ import (
 	"git.qianqiusoft.com/qianqiusoft/light-apiengine/models"
 	"git.qianqiusoft.com/qianqiusoft/light-apiengine/utils"
 	"errors"
+	"github.com/silenceper/wechat/oauth"
 	"github.com/silenceper/wechat/pay"
 	"github.com/silenceper/wechat/util"
 	"strconv"
@@ -105,3 +106,50 @@ func PayJSAPI(params *PayParams)(*JSAPIPayConfig, error){
 		return nil, err
 	}
 }
+
+// 获取微信OAuth认证参数
+func GetOAuthParams()(*WxOAuthConfig, error){
+	config := WxOAuthConfig{}
+
+	url, err := wxoauth.GetRedirectURL(wxConfig.RedirectUrl, wxConfig.Scope, wxConfig.State)
+	if err != nil{
+		return nil, err
+	}
+	config.OAuthRedirectUrl = url
+	config.AppId = wxConfig.AppId
+	config.State = wxConfig.State
+	config.Scope = wxConfig.Scope
+	config.ResponseType = wxConfig.ResponseType
+	config.AuthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize"
+	config.RedirectUrl = wxConfig.RedirectUrl
+
+	return &config, nil
+}
+
+// 获取token
+func GetOpenId(code string)(string, error){
+	resToken, err := wxoauth.GetUserAccessToken(code)
+	if err == nil{
+		addToken(resToken.OpenID, &resToken)
+	}
+	return resToken.OpenID, err
+}
+
+// 根据code获取用户信息(需scope为 snsapi_userinfo)
+func GetUserInfoByCode(code string)(*oauth.UserInfo, error){
+	openId, err := GetOpenId(code)
+	if err != nil{
+		return nil, err
+	}
+	return GetUserInfo(openId)
+}
+
+// 获取用户信息(需scope为 snsapi_userinfo)
+func GetUserInfo(openId string)(*oauth.UserInfo, error){
+	token := getToken(openId)
+	if token == nil{
+		return nil, errors.New("token of openid " + openId + "does not exist")
+	}
+	userInfo, err := wxoauth.GetUserInfo(token.AccessToken, openId)
+	return &userInfo, err
+}