浏览代码

fix:添加微信公众号订阅消息回调

Roc 7 月之前
父节点
当前提交
637dafcdfd

+ 6 - 6
controllers/user/user_controller.go

@@ -472,7 +472,7 @@ type BindGzhReq struct {
 // @Summary 微信公众号回调
 // @Description 微信公众号回调
 // @Success 200 {object} controllers.BaseResponse
-// @router /notify [get,post]
+// @router /wx/notify [get,post]
 func (u *UserController) Notify() {
 	echostr := u.GetString("echostr")
 	method := u.Ctx.Input.Method()
@@ -483,7 +483,7 @@ func (u *UserController) Notify() {
 		if err != nil {
 			logger.Info("xml.Unmarshal:" + err.Error())
 		}
-		contactMsg := ""
+		contactMsg := "你好,欢迎关注期海通行-投研点金!"
 
 		var openId, returnResult string
 		if item.MsgType != "" {
@@ -498,18 +498,18 @@ func (u *UserController) Notify() {
 		</xml>`
 		createTime := strconv.FormatInt(time.Now().Unix(), 10)
 		// WxId := "gh_5dc508325c6f" // 弘则投研公众号原始id
-		xmlTpl = fmt.Sprintf(xmlTpl, openId, "gh_b2f5b115ec8d", createTime, contactMsg)
+		xmlTpl = fmt.Sprintf(xmlTpl, openId, auth.HT_WX_ID, createTime, contactMsg)
 
 		if item.MsgType == "event" {
 			switch item.Event {
 			case "subscribe":
 				fmt.Println("关注")
-				//go subscribe(openId)
+				go auth.BindWxGzhByOpenId(openId)
 			case "unsubscribe":
 				fmt.Println("取消关注")
-				//go unsubscribe(openId)
+				go auth.BindWxGzhByOpenId(openId)
 			case "CLICK":
-				returnResult = xmlTpl
+				//returnResult = xmlTpl
 			default:
 				logger.Info("wechat notify event:" + item.Event)
 			}

+ 21 - 17
domian/user/user_serivce.go

@@ -8,12 +8,13 @@ import (
 )
 
 type UserDTO struct {
-	Id        int
-	Username  string
-	Mobile    string
-	OpenId    string
-	UnionId   string
-	GzhOpenId string
+	Id           int
+	Username     string
+	Mobile       string
+	OpenId       string
+	UnionId      string
+	FollowingGzh int
+	GzhOpenId    string
 }
 
 type FeedbackDTO struct {
@@ -24,10 +25,11 @@ type FeedbackDTO struct {
 
 func convertUserDTO(user userDao.TemplateUser) UserDTO {
 	return UserDTO{
-		Id:       user.Id,
-		Username: user.Username,
-		Mobile:   user.Mobile,
-		OpenId:   user.OpenId,
+		Id:           user.Id,
+		Username:     user.Username,
+		Mobile:       user.Mobile,
+		OpenId:       user.OpenId,
+		FollowingGzh: user.FollowingGzh,
 	}
 }
 func GetUserByMobile(mobile string) (UserDTO, error) {
@@ -82,11 +84,12 @@ func FeedBack(dto FeedbackDTO) (err error) {
 
 func convertToTemplateUser(dto *UserDTO) userDao.TemplateUser {
 	return userDao.TemplateUser{
-		Username:  dto.Username,
-		Mobile:    dto.Mobile,
-		OpenId:    dto.OpenId,
-		UnionId:   dto.UnionId,
-		GzhOpenId: dto.GzhOpenId,
+		Username:     dto.Username,
+		Mobile:       dto.Mobile,
+		OpenId:       dto.OpenId,
+		UnionId:      dto.UnionId,
+		GzhOpenId:    dto.GzhOpenId,
+		FollowingGzh: dto.FollowingGzh,
 	}
 }
 
@@ -96,6 +99,7 @@ func convertToUserDTO(templateUser userDao.TemplateUser, dto *UserDTO) {
 	dto.Mobile = templateUser.Mobile
 	dto.OpenId = templateUser.OpenId
 	dto.UnionId = templateUser.UnionId
+	dto.FollowingGzh = templateUser.FollowingGzh
 }
 
 func BindUserMobile(userId int, mobile string) (err error) {
@@ -145,8 +149,8 @@ func BindUserXcxOpenId(userId int, openId string) (err error) {
 }
 
 // 绑定公众号OpenId
-func BindUserGzhOpenId(userId int, openId string) (err error) {
-	err = userDao.BindGzhOpenId(userId, openId)
+func BindUserGzhOpenId(userId int, openId string, followingGzh int) (err error) {
+	err = userDao.BindGzhOpenId(userId, openId, followingGzh)
 	if err != nil {
 		if !errors.Is(err, gorm.ErrRecordNotFound) {
 			logger.Error("绑定公众号openId失败:%v", err)

+ 1 - 0
middleware/auth_middleware.go

@@ -40,6 +40,7 @@ func rd() *cache.RedisCache {
 var publicRoutes = []string{
 	"/auth/refreshToken",
 	"/user/bind_gzh",
+	"/user/wx/notify",
 }
 
 func AuthMiddleware() web.FilterFunc {

+ 3 - 2
models/user/template_user.go

@@ -19,6 +19,7 @@ type TemplateUser struct {
 	GzhOpenId    string    `gorm:"column:gzh_open_id;type:varchar(255);comment:gzh_open_id"`
 	UnionId      string    `gorm:"column:union_id;type:varchar(50);comment:union_id"`
 	ReadCount    int       `gorm:"column:read_count;type:int(11);comment:阅读次数"`
+	FollowingGzh int       `gorm:"column:following_gzh;type:int(1);comment:是否关注公众号"`
 	LastReadTime time.Time `gorm:"column:last_read_time;type:timestamps;comment:最后阅读时间"`
 	IsDeleted    int       `gorm:"column:is_deleted;type:int(11);comment:是否删除"`
 	CreatedTime  time.Time `gorm:"column:created_time;type:timestamps;comment:创建时间"`
@@ -65,8 +66,8 @@ func BindXcxOpenId(userId int, xcxOpenId string) (err error) {
 	return
 }
 
-func BindGzhOpenId(userId int, gzhOpenId string) (err error) {
-	err = models.Main().Table("template_users").Where("id = ?", userId).Updates(map[string]interface{}{"gzh_open_id": gzhOpenId, "updated_time": time.Now()}).Error
+func BindGzhOpenId(userId int, gzhOpenId string, followingGzh int) (err error) {
+	err = models.Main().Table("template_users").Where("id = ?", userId).Updates(map[string]interface{}{"gzh_open_id": gzhOpenId, "following_gzh": followingGzh, "updated_time": time.Now()}).Error
 	return
 }
 

+ 9 - 9
routers/commentsRouter.go

@@ -320,15 +320,6 @@ func init() {
             Filters: nil,
             Params: nil})
 
-    beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/user:UserController"] = append(beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/user:UserController"],
-        beego.ControllerComments{
-            Method: "Notify",
-            Router: `/notify`,
-            AllowHTTPMethods: []string{"get","post"},
-            MethodParams: param.Make(),
-            Filters: nil,
-            Params: nil})
-
     beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/user:UserController"] = append(beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/user:UserController"],
         beego.ControllerComments{
             Method: "Profile",
@@ -356,4 +347,13 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/user:UserController"] = append(beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/user:UserController"],
+        beego.ControllerComments{
+            Method: "Notify",
+            Router: `/wx/notify`,
+            AllowHTTPMethods: []string{"get","post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
 }

+ 18 - 2
service/auth/auth_service.go

@@ -312,8 +312,17 @@ func BindWxGzh(code string) (isBind bool, err error) {
 		return
 	}
 
-	openId := wxUser.OpenId
+	return BindWxGzhByOpenId(wxUser.OpenId)
+}
 
+// BindWxGzhByOpenId
+// @Description: 通过openid绑定微信公众号
+// @author: Roc
+// @datetime 2024-08-13 13:19:49
+// @param openId string
+// @return isBind bool
+// @return err error
+func BindWxGzhByOpenId(openId string) (isBind bool, err error) {
 	logger.Info("openId:" + openId)
 	wxUserDetail, err := GetWxUserDetail(openId)
 	if err != nil {
@@ -323,6 +332,7 @@ func BindWxGzh(code string) (isBind bool, err error) {
 	}
 
 	unionId := wxUserDetail.UnionID
+	followingGzh := int(wxUserDetail.Subscribe)
 
 	logger.Info("unionId:" + unionId)
 	var isAdd bool
@@ -341,6 +351,7 @@ func BindWxGzh(code string) (isBind bool, err error) {
 	if isAdd {
 		user.GzhOpenId = openId
 		user.UnionId = unionId
+		user.FollowingGzh = followingGzh
 		var isRegister bool
 
 		//判断unionid是否存在
@@ -364,13 +375,18 @@ func BindWxGzh(code string) (isBind bool, err error) {
 			}
 		} else { //修改微信小程序openid
 			logger.Info("wxUser.Id:%d", wxUser.Id)
-			err = userService.BindUserGzhOpenId(wxUser.Id, openId)
+			err = userService.BindUserGzhOpenId(wxUser.Id, openId, followingGzh)
 			if err != nil {
 				logger.Info("BindUserGzhOpenId,Err" + err.Error())
 			}
 		}
 	} else {
 		isBind = true
+		err = userService.BindUserGzhOpenId(user.Id, openId, followingGzh)
+		if err != nil {
+			logger.Info("BindUserGzhOpenId,Err" + err.Error())
+		}
 	}
+
 	return
 }

+ 1 - 0
service/auth/wechat.go

@@ -27,6 +27,7 @@ var (
 const (
 	HT_WX_APPID      = "wxf0dfb65c325fee66"
 	HT_WX_APP_SECRET = "4f2a6c4f9b0a9dee08d1b3b316f33228"
+	HT_WX_ID         = "gh_b2f5b115ec8d"
 )
 
 type WechatAccessToken struct {