Browse Source

将新公众号的access_token保存到redis中

xiexiaoyuan 2 years ago
parent
commit
4162ed412a

+ 2 - 2
controllers/wechat.go

@@ -38,7 +38,7 @@ func (c *WeChatCommon) WeChatLogin() {
 	if openId == "" {
 		c.FailWithMessage("获取用户信息失败", "获取openid失败,openid:"+item.Openid)
 	}
-	accessToken, err := services.WxGetAccessToken(utils.WxAppId, utils.WxAppSecret)
+	accessToken, err := services.WxGetAccessToken()
 	if err != nil {
 		c.FailWithMessage("获取用户信息失败", "获取access_token失败,err:"+err.Error())
 	}
@@ -310,7 +310,7 @@ func (c *WeChatCommon) AdminWeChatLogin() {
 		c.FailWithMessage("获取用户信息失败", "获取openid失败,openid:"+item.Openid)
 		return
 	}
-	accessToken, err := services.WxGetAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
+	accessToken, err := services.WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
 	if err != nil {
 		c.FailWithMessage("获取用户信息失败", "获取access_token失败,err:"+err.Error())
 	}

+ 15 - 0
models/tables/admin/admin.go

@@ -169,4 +169,19 @@ func UpdateAdminOpenIdUnionId(adminId int, openId, unionId string) (err error)
 			  last_updated_time = NOW(),open_id=?,union_id=? WHERE admin_id = ? `
 	_, err = o.Raw(sql, openId, unionId, adminId).Exec()
 	return
+}
+
+type OpenIdList struct {
+	OpenId string
+	AdminId int
+}
+//GetOpenIdListByMobile 根据手机号获取用户的openid列表
+func GetOpenIdListByMobile(mobile, openIdStr string) (items []*OpenIdList, err error) {
+	sql := `SELECT admin_id, open_id FROM admin 
+          WHERE open_id != "" and mobile=? `
+	if openIdStr != "" {
+		sql += ` AND open_id in (` + openIdStr + `) `
+	}
+	_, err = orm.NewOrm().Raw(sql, mobile).QueryRows(&items)
+	return
 }

+ 5 - 6
models/tables/wx_token/wx_token.go

@@ -6,26 +6,25 @@ type WxToken struct {
 	AccessToken string
 	ExpiresIn   int64
 	Id          int `orm:"column(id);pk"`
-	WxAppId     string
 }
 
-func GetWxToken(wxAppId string) (item *WxToken, err error) {
+func GetWxToken() (item *WxToken, err error) {
 	sql := `SELECT *  FROM wx_token `
 	o := orm.NewOrm()
 	err = o.Raw(sql).QueryRow(&item)
 	return
 }
 
-func AddWxToken(token string, expiresIn int64, wxAppId string) (err error) {
+func AddWxToken(token string, expiresIn int64) (err error) {
 	sql := `INSERT INTO wx_token(access_token, expires_in)VALUES(?,?) `
 	o := orm.NewOrm()
 	_, err = o.Raw(sql, token, expiresIn).Exec()
 	return
 }
 
-func UpdateWxToken(token string, expiresIn int64, id int) (err error) {
-	sql := `UPDATE wx_token SET access_token=?, expires_in=? WHERE id=? `
+func UpdateWxToken(token string, expiresIn int64) (err error) {
+	sql := `UPDATE wx_token SET access_token=?, expires_in=?`
 	o := orm.NewOrm()
-	_, err = o.Raw(sql, token, expiresIn, id).Exec()
+	_, err = o.Raw(sql, token, expiresIn).Exec()
 	return
 }

+ 62 - 7
services/wechat.go

@@ -79,15 +79,15 @@ func WxGetToken(wxAppId, wxAppSecret string) (item *WxToken, err error) {
 	return
 }
 
-func WxGetAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error) {
-	wxToken, err := wx_token.GetWxToken(wxAppId)
+func WxGetAccessToken() (accessToken string, err error) {
+	wxToken, err := wx_token.GetWxToken()
 	fmt.Println(err, wxToken)
 	if err != nil && err.Error() != utils.ErrNoRow() {
 		return
 	}
 	//wx_token 不存在
 	if wxToken == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
-		token, err := WxGetToken(wxAppId, wxAppSecret)
+		token, err := WxGetToken(utils.WxAppId, utils.WxAppSecret)
 		if err != nil {
 			return accessToken, err
 		}
@@ -96,7 +96,7 @@ func WxGetAccessToken(wxAppId, wxAppSecret string) (accessToken string, err erro
 			return "", err
 		}
 		expiresIn := time.Now().Add(110 * time.Minute).Unix()
-		err = wx_token.AddWxToken(token.AccessToken, expiresIn, wxAppId)
+		err = wx_token.AddWxToken(token.AccessToken, expiresIn)
 		if err != nil {
 			err = errors.New("新增wx_token失败" + err.Error())
 			return accessToken, err
@@ -104,7 +104,7 @@ func WxGetAccessToken(wxAppId, wxAppSecret string) (accessToken string, err erro
 		accessToken = token.AccessToken
 	} else {
 		if wxToken.ExpiresIn <= time.Now().Unix() {
-			token, err := WxGetToken(wxAppId, wxAppSecret)
+			token, err := WxGetToken(utils.WxAppId, utils.WxAppSecret)
 			if err != nil {
 				return accessToken, err
 			}
@@ -113,7 +113,7 @@ func WxGetAccessToken(wxAppId, wxAppSecret string) (accessToken string, err erro
 				return "", err
 			}
 			expiresIn := time.Now().Add(110 * time.Minute).Unix()
-			err = wx_token.UpdateWxToken(token.AccessToken, expiresIn, wxToken.Id)
+			err = wx_token.UpdateWxToken(token.AccessToken, expiresIn)
 			if err != nil {
 				err = errors.New("修改wx_token失败" + err.Error())
 				return accessToken, err
@@ -126,6 +126,33 @@ func WxGetAccessToken(wxAppId, wxAppSecret string) (accessToken string, err erro
 	return
 }
 
+// WxGetRedisAccessToken 从redis中获取token
+func WxGetRedisAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error) {
+	//从redis中获取token校验验证码
+	accessToken, err = utils.Rc.RedisString(utils.HZ_ADMIN_WX_ACCESS_TOEKN+wxAppId)
+	if err != nil {
+		return
+	}
+	//wx_token 不存在
+	if accessToken == "" {
+		token, tErr := WxGetToken(wxAppId, wxAppSecret)
+		if tErr != nil {
+			return "", tErr
+		}
+		if token.Errmsg != "" {
+			err = errors.New("获取access_token 失败 errcode:" + token.Errmsg + " ;errmsg:" + token.Errmsg)
+			return "", err
+		}
+		err = utils.Rc.Put(utils.HZ_ADMIN_WX_ACCESS_TOEKN+wxAppId, token.AccessToken, 110 * time.Minute)
+		if err != nil {
+			err = errors.New("保存access_token失败 " + err.Error())
+			return accessToken, err
+		}
+		accessToken = token.AccessToken
+	}
+	return
+}
+
 type WxUserInfo struct {
 	Openid         string `json:"openid"`
 	Nickname       string `json:"nickname"`
@@ -211,7 +238,7 @@ type WxUsers struct {
 }
 
 func WxUsersGet() (openIdStr string) {
-	accessToken, err := WxGetAccessToken(utils.WxAppId, utils.WxAppSecret)
+	accessToken, err := WxGetAccessToken()
 	if err != nil {
 		utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
 		return
@@ -237,3 +264,31 @@ func WxUsersGet() (openIdStr string) {
 	openIdStr = "'" + openIdStr + "'"
 	return
 }
+
+func WxAdminOpenIdGet() (openIdStr string) {
+	accessToken, err := WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
+	if err != nil {
+		utils.FileLog.Info("GetWxAccessToken Err:%s", err.Error())
+		return
+	}
+	url := "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken
+	result, err := http.Get(url)
+	if err != nil {
+		utils.FileLog.Info("GetUser Err:", err.Error())
+		return
+	}
+	item := new(WxUsers)
+	err = json.Unmarshal(result, &item)
+	if err != nil {
+		fmt.Println("Unmarshal Err:", err.Error())
+		return
+	}
+	if item.Errcode != 0 {
+		utils.FileLog.Info("微信接口返回异常 Err:", item.Errmsg)
+		return
+	}
+	err = errors.New(item.Errmsg)
+	openIdStr = strings.Join(item.Data.Openid, "','")
+	openIdStr = "'" + openIdStr + "'"
+	return
+}

+ 48 - 17
services/wechat_send_msg.go

@@ -4,6 +4,7 @@ import (
 	"bytes"
 	"encoding/json"
 	"fmt"
+	"hongze/hongze_mobile_admin/models/tables/admin"
 	"hongze/hongze_mobile_admin/models/tables/user_template_record"
 	"hongze/hongze_mobile_admin/models/tables/wx_user"
 	"hongze/hongze_mobile_admin/services/alarm_msg"
@@ -101,7 +102,7 @@ func SendCompanyApplyWxTemplateMsg(mobile, redirectUrl, wxAppPath string, wxMsgM
 	}()
 	utils.FileLog.Info("%s", "services SendMsg")
 
-	accessToken, err := WxGetAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
+	accessToken, err := WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
 	if err != nil {
 		msg = "GetWxAccessToken Err:" + err.Error()
 		return
@@ -113,12 +114,18 @@ func SendCompanyApplyWxTemplateMsg(mobile, redirectUrl, wxAppPath string, wxMsgM
 	utils.FileLog.Info("mobile:%s", mobile)
 
 	//获取openid列表
-	openIdStr := WxUsersGet()
-	openIdList, err := wx_user.GetOpenIdListByMobile(mobile, openIdStr)
+	openIdStr := WxAdminOpenIdGet()
+	adminOpenIdList, err := admin.GetOpenIdListByMobile(mobile, openIdStr)
 	if err != nil {
 		msg = "get openIdList err:" + err.Error()
 		return
 	}
+	openIdList := make([]*wx_user.OpenIdList, 0)
+	for _, v := range adminOpenIdList {
+		tmp := new(wx_user.OpenIdList)
+		tmp.OpenId = v.OpenId
+		openIdList = append(openIdList, tmp)
+	}
 	utils.FileLog.Info("openIdListCount:%s", len(openIdList))
 	//fmt.Println("openIdListCount:", len(openIdList))
 	if len(openIdList) > 0 && utils.TemplateIdByCompanyApply != "" {
@@ -182,7 +189,7 @@ func SendWxMsgWithRoadshowDetailResult(first, keyword1, keyword2, remark, mobile
 	}()
 	utils.FileLog.Info("%s", "services SendMsg")
 
-	accessToken, err := WxGetAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
+	accessToken, err := WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
 	if err != nil {
 		msg = "GetWxAccessToken Err:" + err.Error()
 		return
@@ -194,12 +201,18 @@ func SendWxMsgWithRoadshowDetailResult(first, keyword1, keyword2, remark, mobile
 	utils.FileLog.Info("mobile:%s", mobile)
 
 	//获取openid列表
-	openIdStr := WxUsersGet()
-	openIdList, err := wx_user.GetOpenIdListByMobile(mobile, openIdStr)
+	openIdStr := WxAdminOpenIdGet()
+	adminOpenIdList, err := admin.GetOpenIdListByMobile(mobile, openIdStr)
 	if err != nil {
 		msg = "get openIdList err:" + err.Error()
 		return
 	}
+	openIdList := make([]*wx_user.OpenIdList, 0)
+	for _, v := range adminOpenIdList {
+		tmp := new(wx_user.OpenIdList)
+		tmp.OpenId = v.OpenId
+		openIdList = append(openIdList, tmp)
+	}
 	utils.FileLog.Info("openIdListCount:%s", len(openIdList))
 	//fmt.Println("openIdListCount:", len(openIdList))
 	if len(openIdList) > 0 && utils.TemplateIdByCompanyApply != "" {
@@ -244,7 +257,7 @@ func SendWxMsgWithRoadshowPending(first, keyword1, keyword2, keyword3, keyword4,
 	}()
 	utils.FileLog.Info("%s", "services SendMsg")
 
-	accessToken, err := WxGetAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
+	accessToken, err := WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
 	if err != nil {
 		msg = "GetWxAccessToken Err:" + err.Error()
 		return
@@ -255,12 +268,18 @@ func SendWxMsgWithRoadshowPending(first, keyword1, keyword2, keyword3, keyword4,
 	}
 
 	//获取openid列表
-	openIdStr := WxUsersGet()
-	openIdList, err := wx_user.GetOpenIdListByMobile(mobile, openIdStr)
+	openIdStr := WxAdminOpenIdGet()
+	adminOpenIdList, err := admin.GetOpenIdListByMobile(mobile, openIdStr)
 	if err != nil {
 		msg = "get openIdList err:" + err.Error()
 		return
 	}
+	openIdList := make([]*wx_user.OpenIdList, 0)
+	for _, v := range adminOpenIdList {
+		tmp := new(wx_user.OpenIdList)
+		tmp.OpenId = v.OpenId
+		openIdList = append(openIdList, tmp)
+	}
 	utils.FileLog.Info("openIdListCount:%s", len(openIdList))
 	//fmt.Println("openIdListCount:", len(openIdList))
 	if len(openIdList) > 0 && utils.TemplateIdByCompanyApply != "" {
@@ -305,7 +324,7 @@ func SendWxMsgWithRoadshowDeleteNotice(first, keyword1, keyword2, remark, wxAppP
 	}()
 	utils.FileLog.Info("%s", "services SendMsg")
 
-	accessToken, err := WxGetAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
+	accessToken, err := WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
 	if err != nil {
 		msg = "GetWxAccessToken Err:" + err.Error()
 		return
@@ -316,12 +335,18 @@ func SendWxMsgWithRoadshowDeleteNotice(first, keyword1, keyword2, remark, wxAppP
 	}
 
 	//获取openid列表
-	openIdStr := WxUsersGet()
-	openIdList, err := wx_user.GetOpenIdListByMobile(mobile, openIdStr)
+	openIdStr := WxAdminOpenIdGet()
+	adminOpenIdList, err := admin.GetOpenIdListByMobile(mobile, openIdStr)
 	if err != nil {
 		msg = "get openIdList err:" + err.Error()
 		return
 	}
+	openIdList := make([]*wx_user.OpenIdList, 0)
+	for _, v := range adminOpenIdList {
+		tmp := new(wx_user.OpenIdList)
+		tmp.OpenId = v.OpenId
+		openIdList = append(openIdList, tmp)
+	}
 	utils.FileLog.Info("openIdListCount:%s", len(openIdList))
 	//fmt.Println("openIdListCount:", len(openIdList))
 	if len(openIdList) > 0 && utils.TemplateIdByCompanyApply != "" {
@@ -360,7 +385,7 @@ func SendSealFinishedWxTemplateMsg(mobile string, companyName string, sealId int
 		}
 	}()
 	utils.FileLog.Info("%s", "services SendMsg")
-	accessToken, err := WxGetAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
+	accessToken, err := WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
 	if err != nil {
 		msg = "GetWxAccessToken Err:" + err.Error()
 		return
@@ -370,12 +395,18 @@ func SendSealFinishedWxTemplateMsg(mobile string, companyName string, sealId int
 		return
 	}
 	utils.FileLog.Info("mobile:%s", mobile)
-	openIdStr := WxUsersGet()
-	openIdList, err := wx_user.GetOpenIdListByMobile(mobile, openIdStr)
+	openIdStr := WxAdminOpenIdGet()
+	adminOpenIdList, err := admin.GetOpenIdListByMobile(mobile, openIdStr)
 	if err != nil {
 		msg = "get openIdList err:" + err.Error()
 		return
 	}
+	openIdList := make([]*wx_user.OpenIdList, 0)
+	for _, v := range adminOpenIdList {
+		tmp := new(wx_user.OpenIdList)
+		tmp.OpenId = v.OpenId
+		openIdList = append(openIdList, tmp)
+	}
 	utils.FileLog.Info("openIdListCount:%s", len(openIdList))
 
 	if len(openIdList) > 0 && utils.WxMsgTemplateIdWithSealApplyFinished != "" {
@@ -418,8 +449,8 @@ func SendYbQuestionDistributeWxMsg(questionId, userId int, openid, questionTitle
 			go alarm_msg.SendAlarmMsg(alarmMsg, 3)
 		}
 	}()
-
-	accessToken, err := WxGetAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
+	// todo 修改openID
+	accessToken, err := WxGetRedisAccessToken(utils.AdminWxAppId, utils.AdminWxAppSecret)
 	if err != nil {
 		errMsg = "GetWxAccessToken Err:" + err.Error()
 		return

+ 1 - 0
utils/constants.go

@@ -113,6 +113,7 @@ const (
 	CACHE_KEY_ADMIN_ID = "calendar:admin:id:list"  //系统用户列表缓存key
 	HZ_MOBILE_ADMIN_WXLOGIN_TOKEN = "hz_mobile_admin:wxLogin:admin_token:"
 	HZ_MOBILE_ADMIN_WXLOGIN_MOBILE_CODE = "hz_mobile_admin:wxLogin:mobile_code:"
+	HZ_ADMIN_WX_ACCESS_TOEKN = "hz_admin:wx:access_token:"
 )
 
 // 微信用户user_record注册平台