Browse Source

Merge branch 'feature/migrate_wechat_msg' into debug

# Conflicts:
#	services/wechat/template_msg.go
#	services/wechat/wechat.go
xiexiaoyuan 2 years ago
parent
commit
4ba7c10e1c

+ 2 - 2
controller/wechat/wechat.go

@@ -19,7 +19,7 @@ func GetQrCode(c *gin.Context) {
 
 func GetUserInfo(c *gin.Context) {
 	openid := `oN0jD1S3P-FVosLhq-YiVOXldtRo`
-	userInfo, err := wechat.GetUserInfo(openid)
+	userInfo, err := wechat.GetUserInfo(openid, wechat.WxAppId, wechat.WxAppSecret)
 	if err != nil {
 		response.Fail("获取失败,Err:"+err.Error(), c)
 		return
@@ -161,7 +161,7 @@ func GetEncryptInfo(c *gin.Context) {
 // @router /getWxJsConf [get]
 func GetWxJsConf(c *gin.Context) {
 	getUrl := c.DefaultQuery("Url", "")
-	jsConf, err := wechat.GetJsConfig(getUrl)
+	jsConf, err := wechat.GetJsConfig(getUrl, wechat.WxAppId, wechat.WxAppSecret)
 	if err != nil {
 		response.Fail("获取失败,Err:"+err.Error(), c)
 		return

+ 1 - 5
logic/yb_community_question/yb_community_question_comment.go

@@ -434,12 +434,8 @@ func wxMessageToAdmin(adminInfo admin.Admin, communityQuestionComment *yb_commun
 	if global.CONFIG.Serve.RunMode == "debug" {
 		adminInfo.Mobile = `18221983795`
 	}
-	wxUser, err := wx_user.GetByMobile(adminInfo.Mobile)
-	if err != nil {
-		return
-	}
 
-	err = wechat.SendQuestionCommentToAdmin(int(communityQuestionComment.CommunityQuestionCommentID), int(wxUser.UserID), communityQuestionComment.Content)
+	err = wechat.SendQuestionCommentToAdmin(int(communityQuestionComment.CommunityQuestionCommentID), int(adminInfo.AdminID), adminInfo.OpenId, communityQuestionComment.Content)
 	return
 }
 

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

@@ -27,6 +27,7 @@ type Admin struct {
 	GroupName               string    `gorm:"column:group_name;type:varchar(100)" json:"groupName"`                  // 分组名称
 	Authority               int8      `gorm:"column:authority;type:tinyint(4);default:0" json:"authority"`           // 管理权限,0:无,1:部门负责人,2:小组负责人,3:超级管理员
 	Position                string    `gorm:"column:position;type:varchar(100)" json:"position"`                     // 职位
+	OpenId                  string    `gorm:"column:open_id;type:varchar(100)" json:"open_id"`                       // 弘则部门openid
 }
 
 // TableName get sql table name.获取数据库表名

+ 1 - 0
models/tables/user_template_record/entity.go

@@ -12,6 +12,7 @@ type UserTemplateRecord struct {
 	CreateTime string `gorm:"column:create_time;type:datetime" json:"createTime"`
 	SendStatus int    `gorm:"column:send_status;type:tinyint(4);default:1" json:"sendStatus"` // 1:发送成功,0:发送失败
 	SendType   int    `gorm:"column:send_type;type:tinyint(4);default:1" json:"sendType"`     // 1:报告,2:指标更新提醒,3:审批通知,4:销售领取客户通知,5:活动取消通知,6活动更改时间通知,7:关注的作者发布报告通知,8:发送日报(周报、双周报、月报)模板消息,9:活动预约/报名时间通知
+	WxAppId    string `gorm:"column:wx_app_id;type:varchar(50)" json:"wx_app_id"` // 公众号appid
 }
 
 // TableName get sql table name.获取数据库表名

+ 1 - 5
services/community/question.go

@@ -590,11 +590,7 @@ func wxMessageToAdmin(adminInfo admin.Admin, ybCommunityQuestion *yb_community_q
 	if global.CONFIG.Serve.RunMode == "debug" {
 		adminInfo.Mobile = `18221983795`
 	}
-	wxUser, err := wx_user.GetByMobile(adminInfo.Mobile)
-	if err != nil {
-		return
-	}
 
-	err = wechat.SendQuestionToAdmin(ybCommunityQuestion.CommunityQuestionID, int(wxUser.UserID), ybCommunityQuestion.QuestionContent)
+	err = wechat.SendQuestionToAdmin(ybCommunityQuestion.CommunityQuestionID, int(adminInfo.AdminID), adminInfo.OpenId, ybCommunityQuestion.QuestionContent)
 	return
 }

+ 23 - 53
services/wechat/template_msg.go

@@ -47,6 +47,7 @@ type OpenIdList struct {
 }
 
 type SendWxTemplate struct {
+	WxAppId        string   `description:"公众号appId"`
 	First          string   `description:"模板消息first字段"`
 	Keyword1       string   `description:"模板消息keyword1字段"`
 	Keyword2       string   `description:"模板消息keyword2字段"`
@@ -175,7 +176,7 @@ func (c *TemplateMsgSendClient) ClearQuota() (result *ClearQuotaResponse, err er
 }
 
 // AddUserTemplateRecord 新增模板消息推送记录
-func AddUserTemplateRecord(userId, sendStatus, sendType int, openid, resource, sendData, result string) (err error) {
+func AddUserTemplateRecord(wxAppId string, userId, sendStatus, sendType int, openid, resource, sendData, result string) (err error) {
 	item := &user_template_record.UserTemplateRecord{
 		UserID:     userId,
 		OpenID:     openid,
@@ -186,14 +187,15 @@ func AddUserTemplateRecord(userId, sendStatus, sendType int, openid, resource, s
 		CreateTime: time.Now().Format(utils.FormatDateTime),
 		SendStatus: sendStatus,
 		SendType:   sendType,
+		WxAppId:    wxAppId,
 	}
 	err = item.Create()
 	return
 }
 
 // SendMultiTemplateMsg 推送模板消息至多个用户
-func SendMultiTemplateMsg(sendMap map[string]interface{}, items []*OpenIdList, resource string, sendType int) (err error) {
-	ws := GetWxChat()
+func SendMultiTemplateMsg(wxAppId, wxAppSecret string, sendMap map[string]interface{}, items []*OpenIdList, resource string, sendType int) (err error) {
+	ws := GetWxChat(wxAppId, wxAppSecret)
 	accessToken, err := ws.GetAccessToken()
 	if err != nil {
 		return
@@ -221,7 +223,7 @@ func SendMultiTemplateMsg(sendMap map[string]interface{}, items []*OpenIdList, r
 					sendStatus = 0
 				}
 				resultJson, _ := json.Marshal(result)
-				_ = AddUserTemplateRecord(v.UserId, sendStatus, sendType, v.OpenId, resource, string(data), string(resultJson))
+				_ = AddUserTemplateRecord(wxAppId, v.UserId, sendStatus, sendType, v.OpenId, resource, string(data), string(resultJson))
 			}(item)
 		}
 		if e != nil {
@@ -297,6 +299,7 @@ func SendQuestionReplyWxMsg(questionId, userId int, questionTitle string) (err e
 	}
 
 	sendInfo := new(SendWxTemplate)
+	sendInfo.WxAppId = WxAppId
 	sendInfo.First = first
 	sendInfo.Keyword1 = keyword1
 	sendInfo.Keyword2 = keyword2
@@ -309,7 +312,6 @@ func SendQuestionReplyWxMsg(questionId, userId int, questionTitle string) (err e
 	sendInfo.OpenIdArr = openIdArr
 
 	err = SendTemplateMsg(sendInfo)
-
 	return
 }
 
@@ -368,8 +370,8 @@ func SendVoiceBroadcastWxMsg(broadcastId int, sectionName, broadcastName string)
 	for i, v := range openIdList {
 		openIdArr[i] = v.OpenId
 	}
-
 	sendInfo := new(SendWxTemplate)
+	sendInfo.WxAppId = WxAppId
 	sendInfo.First = first
 	sendInfo.Keyword1 = keyword1
 	sendInfo.Keyword2 = keyword2
@@ -382,13 +384,12 @@ func SendVoiceBroadcastWxMsg(broadcastId int, sectionName, broadcastName string)
 	sendInfo.OpenIdArr = openIdArr
 
 	err = SendTemplateMsg(sendInfo)
-
 	return
 }
 
 // SendMultiTemplateMsg 推送模板消息至多个用户中间出错不返回
-func SendMultiTemplateMsgNoReturn(sendMap map[string]interface{}, items []*OpenIdList, resource string, sendType int) (err error) {
-	ws := GetWxChat()
+func SendMultiTemplateMsgNoReturn(wxAppId, wxAppSecret string, sendMap map[string]interface{}, items []*OpenIdList, resource string, sendType int) (err error) {
+	ws := GetWxChat(wxAppId, wxAppSecret)
 	accessToken, err := ws.GetAccessToken()
 	if err != nil {
 		return
@@ -416,7 +417,7 @@ func SendMultiTemplateMsgNoReturn(sendMap map[string]interface{}, items []*OpenI
 					sendStatus = 0
 				}
 				resultJson, _ := json.Marshal(result)
-				_ = AddUserTemplateRecord(v.UserId, sendStatus, sendType, v.OpenId, resource, string(data), string(resultJson))
+				_ = AddUserTemplateRecord(wxAppId, v.UserId, sendStatus, sendType, v.OpenId, resource, string(data), string(resultJson))
 			}(item)
 		}
 		if e != nil {
@@ -427,8 +428,8 @@ func SendMultiTemplateMsgNoReturn(sendMap map[string]interface{}, items []*OpenI
 }
 
 // SendQuestionToAdmin 推送研报小程序模板消息-用户提问时,通知到管理员
-func SendQuestionToAdmin(questionId, userId int, questionTitle string) (err error) {
-	if userId == 0 {
+func SendQuestionToAdmin(questionId, adminId int, adminOpenId string, questionTitle string) (err error) {
+	if adminId == 0 || adminOpenId == "" {
 		return
 	}
 	var errMsg string
@@ -438,25 +439,11 @@ func SendQuestionToAdmin(questionId, userId int, questionTitle string) (err erro
 			go alarm_msg.SendAlarmMsg(alarmMsg, 3)
 		}
 	}()
-	// 校验用户是否取消关注公众号
-	userRecord, e := user_record.GetByUserId(userId, utils.USER_RECORD_PLATFORM_RDDP)
-	if e != nil {
-		// 用户无公众号信息
-		if e == utils.ErrNoRow {
-			return
-		}
-		err = errors.New("获取用户Record信息失败, Err:" + e.Error())
-		return
-	}
-	// 取消关注则不推送
-	if userRecord.Subscribe == 0 {
-		return
-	}
 
 	openIdList := make([]*OpenIdList, 0)
 	openIdList = append(openIdList, &OpenIdList{
-		OpenId: userRecord.OpenID,
-		UserId: userId,
+		OpenId: adminOpenId,
+		UserId: 0,
 	})
 
 	//sendMap := make(map[string]interface{})
@@ -471,7 +458,6 @@ func SendQuestionToAdmin(questionId, userId int, questionTitle string) (err erro
 	//sendData["keyword1"] = map[string]interface{}{"value": keyword1, "color": "#173177"}
 	//sendData["keyword2"] = map[string]interface{}{"value": keyword2, "color": "#173177"}
 	//sendData["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
-
 	//sendMap["template_id"] = TemplateIdWithCommunityQuestion
 	//sendMap["data"] = sendData
 
@@ -489,27 +475,26 @@ func SendQuestionToAdmin(questionId, userId int, questionTitle string) (err erro
 	for i, v := range openIdList {
 		openIdArr[i] = v.OpenId
 	}
-
 	sendInfo := new(SendWxTemplate)
+	sendInfo.WxAppId = AdminWxAppId
 	sendInfo.First = first
 	sendInfo.Keyword1 = keyword1
 	sendInfo.Keyword2 = keyword2
 	sendInfo.Remark = remark
 	sendInfo.RedirectUrl = wxAppPath
-	sendInfo.TemplateId = TemplateIdWithCommunityQuestion
+	sendInfo.TemplateId = TemplateIdWithCommunityQuestionNotifyAdmin
 	sendInfo.RedirectTarget = 2
 	sendInfo.Resource = wxAppPath
 	sendInfo.SendType = utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION
 	sendInfo.OpenIdArr = openIdArr
 
 	err = SendTemplateMsg(sendInfo)
-
 	return
 }
 
 // SendQuestionCommentToAdmin 推送研报小程序模板消息-用户评论问答时,通知到管理员
-func SendQuestionCommentToAdmin(commentId, userId int, commentContent string) (err error) {
-	if userId == 0 {
+func SendQuestionCommentToAdmin(commentId, adminId int, adminOpenId string,  commentContent string) (err error) {
+	if adminId == 0 || adminOpenId == "" {
 		return
 	}
 	var errMsg string
@@ -519,25 +504,11 @@ func SendQuestionCommentToAdmin(commentId, userId int, commentContent string) (e
 			go alarm_msg.SendAlarmMsg(alarmMsg, 3)
 		}
 	}()
-	// 校验用户是否取消关注公众号
-	userRecord, e := user_record.GetByUserId(userId, utils.USER_RECORD_PLATFORM_RDDP)
-	if e != nil {
-		// 用户无公众号信息
-		if e == utils.ErrNoRow {
-			return
-		}
-		err = errors.New("获取用户Record信息失败, Err:" + e.Error())
-		return
-	}
-	// 取消关注则不推送
-	if userRecord.Subscribe == 0 {
-		return
-	}
 
 	openIdList := make([]*OpenIdList, 0)
 	openIdList = append(openIdList, &OpenIdList{
-		OpenId: userRecord.OpenID,
-		UserId: userId,
+		OpenId: adminOpenId,
+		UserId: 0,
 	})
 
 	//sendMap := make(map[string]interface{})
@@ -552,7 +523,6 @@ func SendQuestionCommentToAdmin(commentId, userId int, commentContent string) (e
 	//sendData["keyword1"] = map[string]interface{}{"value": keyword1, "color": "#173177"}
 	//sendData["keyword2"] = map[string]interface{}{"value": keyword2, "color": "#173177"}
 	//sendData["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
-
 	//sendMap["template_id"] = TemplateIdWithCommunityQuestion
 	//sendMap["data"] = sendData
 
@@ -570,14 +540,14 @@ func SendQuestionCommentToAdmin(commentId, userId int, commentContent string) (e
 	for i, v := range openIdList {
 		openIdArr[i] = v.OpenId
 	}
-
 	sendInfo := new(SendWxTemplate)
+	sendInfo.WxAppId = AdminWxAppId
 	sendInfo.First = first
 	sendInfo.Keyword1 = keyword1
 	sendInfo.Keyword2 = keyword2
 	sendInfo.Remark = remark
 	sendInfo.RedirectUrl = wxAppPath
-	sendInfo.TemplateId = TemplateIdWithCommunityQuestion
+	sendInfo.TemplateId = TemplateIdWithCommunityQuestionNotifyAdmin
 	sendInfo.RedirectTarget = 2
 	sendInfo.Resource = wxAppPath
 	sendInfo.SendType = utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION

+ 51 - 12
services/wechat/wechat.go

@@ -1,6 +1,7 @@
 package wechat
 
 import (
+	"context"
 	"encoding/json"
 	"errors"
 	"fmt"
@@ -15,6 +16,7 @@ import (
 	"hongze/hongze_yb/global"
 	"hongze/hongze_yb/models/response/pc"
 	"hongze/hongze_yb/models/tables/wx_token"
+	"hongze/hongze_yb/utils"
 	"time"
 )
 
@@ -23,6 +25,7 @@ var (
 	WxAppId                         string
 	WxAppSecret                     string
 	TemplateIdWithCommunityQuestion string // 问答社区回复模板消息ID
+	TemplateIdWithCommunityQuestionNotifyAdmin string // 问答社区 有提问通知管理员
 	WxYbAppId                       string // 研报小程序AppID
 	PcWxAppId                       string //pc版AppId
 	PcWxAppSecret                   string //pc版AppSecret
@@ -30,6 +33,10 @@ var (
 	WxMobileCrmAppId     string //随手办公小程序appid
 	WxMobileCrmId        string //随手办公小程序id
 	WxAppMobileCrmSecret string //随手办公小程序秘钥
+
+	//内部员工公众号(弘则部门)
+	AdminWxAppId                    string
+	AdminWxAppSecret                string
 )
 
 func init() {
@@ -39,68 +46,79 @@ func init() {
 	WxMobileCrmId = `wx67b68e39913e511e`
 	WxAppMobileCrmSecret = `660b0375f701a19220bb8a662b41c77c`
 
+	//内部员工公众号(弘则部门)
+	AdminWxAppId = "wx1392111da5426e9e"
+	AdminWxAppSecret = "30eceb7cf29bf2f046031155ab55d7b4"
+
 	if global.CONFIG.Serve.RunMode == "debug" {
 		WxAppId = "wx9b5d7291e581233a"
 		WxAppSecret = "f4d52e34021eee262dce9682b31f8861"
 		WxId = "gh_5dc508325c6f"
+		TemplateIdWithCommunityQuestion = "CB7bOl7f3viMG4s1uhRo7WM0Jbx3WvodKuIZ8A_z8fM"
+		TemplateIdWithCommunityQuestionNotifyAdmin = "rciDm9ThigRBGi1SZ4TFd74XA4aoAxSz_ugdv_tZ450"
 		PcWxAppId = "wxcba9a7ec590ee2d5"
 		PcWxAppSecret = "aa58d257e2521d768cbf1bf89989769d"
-		TemplateIdWithCommunityQuestion = "CB7bOl7f3viMG4s1uhRo7WM0Jbx3WvodKuIZ8A_z8fM"
 	} else {
 		WxAppId = "wx4a844c734d8c8e56"
 		WxAppSecret = "26c586e7ccb3c575433f0f37797b3eeb"
 		WxId = "gh_b67e0049fb8c"
+		TemplateIdWithCommunityQuestion = "dYg6iHooRq74PyCXmw_Ns7qdJZmbtLoKS2p2FKeaXl0"
+		TemplateIdWithCommunityQuestionNotifyAdmin = "rciDm9ThigRBGi1SZ4TFd74XA4aoAxSz_ugdv_tZ450"
 		PcWxAppId = "wx4da95782cfc8c5eb"
 		PcWxAppSecret = "8f82ebf2ba3aa06ce44541726385df64"
-		TemplateIdWithCommunityQuestion = "dYg6iHooRq74PyCXmw_Ns7qdJZmbtLoKS2p2FKeaXl0"
 	}
 }
 
-func GetWxChat() (officialAccount *officialaccount.OfficialAccount) {
+func GetWxChat(wxAppId, wxAppSecret string) (officialAccount *officialaccount.OfficialAccount) {
 	wc := wechat.NewWechat()
 	memory := cache.NewMemory()
 	conf := &config.Config{
-		AppID:          WxAppId,
-		AppSecret:      WxAppSecret,
+		AppID:          wxAppId,
+		AppSecret:      wxAppSecret,
 		Token:          "",
 		EncodingAESKey: "",
 		Cache:          memory,
 	}
 	officialAccount = wc.GetOfficialAccount(conf)
-
-	wechatAccessToken := &WechatAccessToken{}
+	wechatAccessToken := &WechatAccessToken{WxAppId: wxAppId,WxAppSecret: wxAppSecret}
 	officialAccount.SetAccessTokenHandle(wechatAccessToken)
 	return
 }
 
 // GetUserInfo 获取微信用户详情
-func GetUserInfo(openid string) (userInfo *user.Info, err error) {
-	wechatClient := GetWxChat()
+func GetUserInfo(openid, wxAppId, wxAppSecret string) (userInfo *user.Info, err error) {
+	wechatClient := GetWxChat(wxAppId, wxAppSecret)
 	userClient := wechatClient.GetUser()
 	userInfo, err = userClient.GetUserInfo(openid)
 	return
 }
 
 // GetJsConfig 获取公众号jsConfig
-func GetJsConfig(signUrl string) (jsConf *js.Config, err error) {
-	wechatClient := GetWxChat()
+func GetJsConfig(signUrl, wxAppId, wxAppSecret string) (jsConf *js.Config, err error) {
+	wechatClient := GetWxChat(wxAppId, wxAppSecret)
 	j := wechatClient.GetJs()
 	jsConf, err = j.GetConfig(signUrl)
 	return
 }
 
 type WechatAccessToken struct {
+	WxAppId     string
+	WxAppSecret string
 }
 
+
 // GetAccessToken 获取accessToken
 func (wechat WechatAccessToken) GetAccessToken() (accessToken string, err error) {
+	if wechat.WxAppId != WxAppId {
+		return WxGetRedisAccessToken(wechat.WxAppId, wechat.WxAppSecret)
+	}
 	wxToken, err := wx_token.GetById()
 	if err != nil {
 		return
 	}
 	//如果300s就要过期了,那么就去刷新accessToken
 	if wxToken.ExpiresIn < time.Now().Unix()+300 {
-		tmpAccessToken, expires, tmpErr := getTokenFromServer(WxAppId, WxAppSecret)
+		tmpAccessToken, expires, tmpErr := getTokenFromServer(wechat.WxAppId, wechat.WxAppSecret)
 		if tmpErr != nil {
 			err = tmpErr
 			return
@@ -114,7 +132,26 @@ func (wechat WechatAccessToken) GetAccessToken() (accessToken string, err error)
 	accessToken = wxToken.AccessToken
 	return
 }
+// WxGetRedisAccessToken 从redis中获取token
+func WxGetRedisAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error) {
+	//从redis中获取token校验验证码
+	accessToken, err = global.Redis.Get(context.TODO(), utils.HZ_ADMIN_WX_ACCESS_TOEKN+wxAppId).Result()
+	if err != nil {
+		err = nil
+		token, expires, tErr := getTokenFromServer(wxAppId, wxAppSecret)
+		if tErr != nil {
+			err = tErr
+			return
+		}
 
+		//更新redis的accessToken(过期时间提前十分钟)
+		redisTimeExpire := time.Duration(expires - 600) * time.Second
+		global.Redis.SetEX(context.TODO(), utils.HZ_ADMIN_WX_ACCESS_TOEKN+wxAppId, token, redisTimeExpire)
+		accessToken = token
+		return
+	}
+	return
+}
 // getTokenFromServer 服务端获取accessToken
 func getTokenFromServer(appid, wxSecret string) (accessToken string, expires int64, err error) {
 	apiUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
@@ -153,3 +190,5 @@ func PcWxGetUserInfo(openId, accessToken string) (item *pc.WxUserInfo, err error
 	err = json.Unmarshal(result, &item)
 	return
 }
+
+

+ 1 - 0
utils/constants.go

@@ -129,6 +129,7 @@ const (
 )
 
 const HZPHONE = "057187186319" //弘则电话
+const HZ_ADMIN_WX_ACCESS_TOEKN = "hz_admin:wx:access_token:"
 
 //模板消息推送类型
 const (