Explorar o código

修改发送给管理员的模版消息

xiexiaoyuan %!s(int64=2) %!d(string=hai) anos
pai
achega
bbd996b8f4

+ 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
@@ -147,7 +147,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
 }

+ 22 - 49
services/wechat/template_msg.go

@@ -118,7 +118,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,
@@ -129,14 +129,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
@@ -164,7 +165,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 {
@@ -232,7 +233,7 @@ func SendQuestionReplyWxMsg(questionId, userId int, questionTitle string) (err e
 	if wxAppPath != "" {
 		sendMap["miniprogram"] = map[string]interface{}{"appid": WxYbAppId, "pagepath": wxAppPath}
 	}
-	err = SendMultiTemplateMsg(sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION)
+	err = SendMultiTemplateMsg(WxAppId, WxAppSecret, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION)
 	return
 }
 
@@ -285,13 +286,13 @@ func SendVoiceBroadcastWxMsg(broadcastId int, sectionName, broadcastName string)
 	if wxAppPath != "" {
 		sendMap["miniprogram"] = map[string]interface{}{"appid": WxYbAppId, "pagepath": wxAppPath}
 	}
-	err = SendMultiTemplateMsgNoReturn(sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_VOICE_BROADCAST)
+	err = SendMultiTemplateMsgNoReturn(WxAppId, WxAppSecret, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_VOICE_BROADCAST)
 	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
@@ -319,7 +320,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 {
@@ -330,8 +331,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
@@ -341,25 +342,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{})
@@ -375,7 +362,7 @@ func SendQuestionToAdmin(questionId, userId int, questionTitle string) (err erro
 	sendData["keyword2"] = map[string]interface{}{"value": keyword2, "color": "#173177"}
 	sendData["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
 
-	sendMap["template_id"] = TemplateIdWithCommunityQuestion
+	sendMap["template_id"] = TemplateIdWithCommunityQuestionNotifyAdmin
 	sendMap["data"] = sendData
 
 	wxAppPath := fmt.Sprintf("/pages-question/detail/index?type=question&id=%d", questionId)
@@ -386,13 +373,13 @@ func SendQuestionToAdmin(questionId, userId int, questionTitle string) (err erro
 	if wxAppPath != "" {
 		sendMap["miniprogram"] = map[string]interface{}{"appid": WxMobileCrmAppId, "pagepath": wxAppPath}
 	}
-	err = SendMultiTemplateMsg(sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION)
+	err = SendMultiTemplateMsg(AdminWxAppId, AdminWxAppSecret, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION)
 	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
@@ -402,25 +389,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{})
@@ -436,7 +409,7 @@ func SendQuestionCommentToAdmin(commentId, userId int, commentContent string) (e
 	sendData["keyword2"] = map[string]interface{}{"value": keyword2, "color": "#173177"}
 	sendData["remark"] = map[string]interface{}{"value": remark, "color": "#173177"}
 
-	sendMap["template_id"] = TemplateIdWithCommunityQuestion
+	sendMap["template_id"] = TemplateIdWithCommunityQuestionNotifyAdmin
 	sendMap["data"] = sendData
 
 	wxAppPath := fmt.Sprintf("/pages-question/detail/index?type=comment&id=%d", commentId)
@@ -447,6 +420,6 @@ func SendQuestionCommentToAdmin(commentId, userId int, commentContent string) (e
 	if wxAppPath != "" {
 		sendMap["miniprogram"] = map[string]interface{}{"appid": WxMobileCrmAppId, "pagepath": wxAppPath}
 	}
-	err = SendMultiTemplateMsg(sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION)
+	err = SendMultiTemplateMsg(AdminWxAppId, AdminWxAppSecret, sendMap, openIdList, wxAppPath, utils.TEMPLATE_MSG_YB_COMMUNITY_QUESTION)
 	return
 }

+ 49 - 10
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,12 +46,17 @@ 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"
 
@@ -54,57 +66,63 @@ func init() {
 		WxId = "gh_b67e0049fb8c"
 
 		TemplateIdWithCommunityQuestion = "dYg6iHooRq74PyCXmw_Ns7qdJZmbtLoKS2p2FKeaXl0"
+		TemplateIdWithCommunityQuestionNotifyAdmin = "rciDm9ThigRBGi1SZ4TFd74XA4aoAxSz_ugdv_tZ450"
 		PcWxAppId = "wx4da95782cfc8c5eb"
 		PcWxAppSecret = "8f82ebf2ba3aa06ce44541726385df64"
 
 	}
 }
 
-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
@@ -118,7 +136,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"
@@ -157,3 +194,5 @@ func PcWxGetUserInfo(openId, accessToken string) (item *pc.WxUserInfo, err error
 	err = json.Unmarshal(result, &item)
 	return
 }
+
+

+ 1 - 0
utils/constants.go

@@ -124,6 +124,7 @@ const ALIYUN_YBIMG_HOST = "https://hzstatic.hzinsights.com/static/yb_wx/"
 const HZ_DEFAULT_AVATAR = "https://hzstatic.hzinsights.com/static/yb_wx/hz_default_avatar.png"
 
 const HZPHONE = "057187186319" //弘则电话
+const HZ_ADMIN_WX_ACCESS_TOEKN = "hz_admin:wx:access_token:"
 
 //模板消息推送类型
 const (