Browse Source

update wechat mini

ls 6 months ago
parent
commit
533206b765
2 changed files with 43 additions and 4 deletions
  1. 36 4
      wechat/mini.go
  2. 7 0
      wechat/structure.go

+ 36 - 4
wechat/mini.go

@@ -1,16 +1,22 @@
 package wechat
 
 import (
+	"encoding/json"
 	"net/url"
 	"time"
 
 	"git.chuangxin1.com/cx/myth"
+	"git.chuangxin1.com/cx/myth/cache"
 )
 
 func keyMini(appid string) string {
 	return "wechat:mini:client:" + appid
 }
 
+func keyMiniToken(appid string) string {
+	return "wechat:mini:client:token:" + appid
+}
+
 // NewMiniClient new mini client
 func NewMiniClient(appID, appSecret string) *MiniClient {
 	key := keyMini(appID)
@@ -23,7 +29,7 @@ func NewMiniClient(appID, appSecret string) *MiniClient {
 }
 
 // GetMiniOpenID get openid by code
-func (mc *MiniClient) GetMiniOpenID(frm FormCode) (openid string, err error) {
+func (mc *MiniClient) GetMiniOpenID(frm FormCode) (s MiniSession, err error) {
 	uri := BaseURL + "/sns/jscode2session?"
 
 	args := url.Values{}
@@ -35,13 +41,35 @@ func (mc *MiniClient) GetMiniOpenID(frm FormCode) (openid string, err error) {
 	uri += args.Encode()
 	var jq *myth.JSONQuery
 	if jq, err = getJSON(uri); err == nil {
-		openid, err = jq.String(`openid`)
+		s.OpenID, err = jq.String(`openid`)
+		s.SessionKey, _ = jq.String(`session_key`)
+		s.UnionID, _ = jq.String(`unionid`)
 	}
 	return
 }
 
 // getToken get token
 func (mc *MiniClient) getToken() (token string, err error) {
+	/*
+		now := time.Now().Unix()
+		if mc.LastTokenTime > 0 {
+			if now-mc.LastTokenTime < TokenExpires {
+				token = mc.AccessToken
+				return
+			}
+		}
+		// */
+	key := keyMiniToken(mc.AppID)
+	var ct ClientToken
+	s := ``
+	s, err = cache.Get(key)
+	if err != nil {
+		return
+	}
+	err = json.Unmarshal([]byte(s), &ct)
+	if err != nil {
+		return
+	}
 	now := time.Now().Unix()
 	if mc.LastTokenTime > 0 {
 		if now-mc.LastTokenTime < TokenExpires {
@@ -49,6 +77,7 @@ func (mc *MiniClient) getToken() (token string, err error) {
 			return
 		}
 	}
+
 	uri := BaseURL + "/cgi-bin/token?"
 
 	args := url.Values{}
@@ -62,8 +91,11 @@ func (mc *MiniClient) getToken() (token string, err error) {
 		mc.LastTokenTime = now
 		mc.AccessToken, err = jq.String(`access_token`)
 		token = mc.AccessToken
-		key := keyMini(mc.AppID)
-		memcache.Store(key, mc)
+		k := keyMini(mc.AppID)
+		memcache.Store(k, mc)
+		ct := ClientToken{AppID: mc.AppID, AccessToken: mc.AccessToken, LastTokenTime: now}
+		bs, _ := json.Marshal(ct)
+		cache.Set(key, string(bs), 0)
 	}
 	return
 }

+ 7 - 0
wechat/structure.go

@@ -44,6 +44,13 @@ type ResponseMsg struct {
 	ErrMsg  string `json:"errmsg"`
 }
 
+// MiniSession mini session
+type MiniSession struct {
+	OpenID     string `json:"openid"`
+	SessionKey string `json:"session_key"`
+	UnionID    string `json:"unionid"`
+}
+
 // FormSignature signature
 type FormSignature struct {
 	TimeStamp string `form:"timestamp" json:"timestamp"`