欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java通过微信公众号分角色推送消息提醒

程序员文章站 2022-04-05 16:09:59
...

一、业务需求:   

数据录入并提交审核后需要通过微信公众号给经理发送审核提醒,若经理审核通过需要给发送者提供反馈(发消息提醒)还需给财务部发送审核通过提醒;若审核不通过只需给发送者推送审核不通过及不通过原因提醒。

二、分析:一个审核流程需要写三个发送提醒方法

  1. 录入者提交审核后向经理发送提醒;

  2. 经理审核通过:

    1. 给录入者发送反馈信息

    2. 给财务部发送通过信息

  3. 经理审核不通过,给录入者发送反馈信息

三、开发:使用fastWeixin缩短开发时间

    1.准备发送消息工具类WechatNoticeUtil

package com.app.common.wechat;

import com.github.sd4324530.fastweixin.api.TemplateMsgAPI;
import com.github.sd4324530.fastweixin.api.config.ApiConfig;
import com.github.sd4324530.fastweixin.api.entity.TemplateMsg;
import com.github.sd4324530.fastweixin.api.entity.TemplateParam;
import com.github.sd4324530.fastweixin.api.response.SendTemplateResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author annong
 * 微信消息提醒功能
 */
public class WechatNoticeUtil {

    private static Logger logger = LoggerFactory.getLogger(WechatNoticeUtil.class);

    public static String sendMessage(String newtemplateMsg,String userOpenId,String url, Map<String,TemplateParam> data){

        String sendMessage="";

        TemplateMsg templateMsg = new TemplateMsg();
        templateMsg.setTemplateId(newtemplateMsg);
        templateMsg.setTouser(userOpenId);
        templateMsg.setUrl(url);
        templateMsg.setData(data);

        try {
            ApiConfig apiConfig = new ApiConfig(WeChatConfig.appid, WeChatConfig.appSecret);
            TemplateMsgAPI templateMsgAPI = new TemplateMsgAPI(apiConfig);
            SendTemplateResponse response = templateMsgAPI.send(templateMsg);
            String messageId = response.getMsgid();
            sendMessage=response.getErrmsg();

            logger.debug("messageId = {}",messageId);

        }catch (Exception e){
            logger.error("微信消息发送失败:"+e.getMessage());
        }

        return sendMessage;
    }


}

    2.编写保存消息的实体类MessageInfo.java 

package com.app.common.model;

import org.hibernate.envers.Audited;

import javax.persistence.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author annong
 * 消息提醒内容,pc端首页展示条数
 * 手机端消息查看消息详情
 */
@Entity
@Table(name = "message_info")
@Audited
public class MessageInfo {
    @Id
    @GeneratedValue
    /**
     * 流水号
     */
    private Integer id;

    /**
     * 发送者id
     */
    private Integer sendUserId;

    /**
     * 接收者id
     */
    private Integer receiveUserId;

    /**
     * 消息名称
     */
    private String title;

    /**
     * 消息类型
     */
    private String messageType;

    /**
     * 内容
     */
    @Column(length = 3000)
    private String content;

    /**
     * 发送时间
     */
    @Temporal(TemporalType.DATE)
    private Date sendTime;

    /**
     * 阅读状态   1未读  2已读
     */
    private Integer flag;

    /**
     * 微信推送返回的消息
     */
    private String sendMessaage;

    public String getSendMessaage() {
        return sendMessaage;
    }

    public void setSendMessaage(String sendMessaage) {
        this.sendMessaage = sendMessaage;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getSendUserId() {
        return sendUserId;
    }

    public void setSendUserId(Integer sendUserId) {
        this.sendUserId = sendUserId;
    }

    public Integer getReceiveUserId() {
        return receiveUserId;
    }

    public void setReceiveUserId(Integer receiveUserId) {
        this.receiveUserId = receiveUserId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getSendTime() {
        return sendTime;
    }

    public void setSendTime(Date sendTime) {
        this.sendTime = sendTime;
    }

    public Integer getFlag() {
        return flag;
    }

    public void setFlag(Integer flag) {
        this.flag = flag;
    }

    @Transient
    public String getFlagText(){
        if (this.flag != null && flag == 2) {
            return "已读";
        }else {
            return "未读";
        }
    }
}

    3.编写消息推送服务层公共方法 MessageInfoService.java

package com.app.common.service;

import com.app.building.model.Contract;
import com.app.common.model.MessageInfo;
import com.app.common.model.Role;
import com.app.common.model.UserInfo;
import com.app.common.model.UserInfoRole;
import com.app.common.wechat.WechatNoticeUtil;
import com.github.sd4324530.fastweixin.api.entity.TemplateParam;
import com.sqds.hibernate.HibernateDao;
import com.sqds.page.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息推送内容
 * @author  annong
 */
@Service
public class MessageInfoService extends HibernateDao<MessageInfo> {
    @Value("#{configProperties['weChat.send.code']}")
    private boolean sendCode;
    @Autowired private UserService userService;
    @Autowired private RoleService roleService;
    @Autowired private UserInfoRoleService userInfoRoleService;

    /**
     * 根据接收者userid查询未读消息
     * @param receiveUserId
     * @return
     */
    public List<MessageInfo> messageInfoList(Integer receiveUserId){
        String hql = " from MessageInfo m where m.receiveUserId = ? and flag = 1 ";
        return list(hql,receiveUserId);
    }

    /**
     * pc端查看消息列表
     * @param pageInfo
     * @return
     */
    public PageInfo<MessageInfo> msgPageInfo(PageInfo<MessageInfo> pageInfo,Integer receiveUserId){
        String hql = "from MessageInfo m where m.receiveUserId = ? order by flag ,sendTime desc,id";
        pageInfo = list(pageInfo, hql,receiveUserId);
        return pageInfo;
    }

    /**
     * 根据id查询推送消息内容
     * @param msgId
     * @return
     */
    public MessageInfo getMessageInfo(Integer msgId){
        String hql = " from MessageInfo m where m.id = ? ";
        return findUnique(hql,msgId);
    }

    /**
     * 调整合同 发送提醒
     * roleName接收人员角色名,user发送者,msgType 消息类型,title消息标题,content消息内容 自行拼接
     */
    public void saveContractPush(UserInfo user,String anotherName,String msgType,String title,String content){
        //推送消息开关
        if (sendCode){
            Role role = roleService.getByAnotherName(anotherName);
            List<UserInfoRole> userInfoRoleList = userInfoRoleService.listByRoleId(role.getId());
            MessageInfo msg = new MessageInfo();
            String url = "";
            //保存发送者id
            msg.setSendUserId(user.getUserId());
            //初始化阅读状态
            msg.setFlag(1);
            //消息发送时间
            msg.setSendTime(new Date());
            //消息类型
            msg.setMessageType(msgType);
            //标题
            msg.setTitle(title);
            //消息内容
            msg.setContent(content);

            //需要先保存一下,保存后获取id
            this.save(msg);
            //微信提醒中点击查看详情页面,pc端写好即可
            url = "/manage/message/weChatView?uuid=" + msg.getId();

            //需要接收的人员,只推送给有效用户
            for (UserInfoRole userInfoRole : userInfoRoleList){
                UserInfo userInfo = userService.get(userInfoRole.getUserId());
                //判断是否有效用户
                if (userInfo.getValid() == 1){
                    //保存接收者id
                    msg.setReceiveUserId(userInfo.getUserId());
                    sendTaskRemind(userInfo,url,msg);
                }
            }
        }
    }

    public void sendTaskRemind(UserInfo user,String mobileUrl,MessageInfo msg){
        Map<String, TemplateParam> data = new HashMap<String, TemplateParam>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        data.put("first", new TemplateParam(msg.getTitle()));
        data.put("keyword1", new TemplateParam(sdf.format(new Date())));
        data.put("keyword2", new TemplateParam(msg.getContent()));
        data.put("remark", new TemplateParam("请登录电脑端楼宇系统进行处理!"));
        //公众号中  “今日工作提醒” 模板(可自定义)
        String nameplateMsg = "O0H_4eZTeEBWuRFXRyIGkvmrRnyGb5LIsz66Pd7DZdc";
        //本地推送测试网址(测试电脑ip):http://10.0.0.162:8080
        String sendMessage = WechatNoticeUtil.sendMessage(nameplateMsg, user.getWeChatToken(), "http://10.0.0.194:8080" + mobileUrl, data);
        //正式网址:http://**.**.com
//        String sendMessage = WechatNoticeUtil.sendMessage(nameplateMsg, user.getWeChatToken(), "http://**.**.com" + mobileUrl, data);
        //保存发送内容
        msg.setSendMessaage(sendMessage);
        this.save(msg);
    }
}

    4.只需在需要发消息提醒处调用以下方法并传递相关参数即可完成。

messageInfoService.saveContractPush(userInfo, roleName, msgType, title, content);

例如:

//微信提醒内容
                    String title = "【"+contract.getBuilding().getBuildingName() + "】有合同提交了审核申请";
                    String roleName = "招商部录入人员";
                    String msgType = "合同录入待审核";
                    String content = contract.getBuilding().getBuildingName() + contract.getHouseNum() + "房间" +
                            "的合同录入完成,请审核!";

                    messageInfoService.saveContractPush(user, roleName, msgType, title, content);

微信公众号效果图:

java通过微信公众号分角色推送消息提醒


测试中使用的是模板库中的模板,与该业务契合度不是很高,故自定义模板已提交给微信开发者平台,读者也可自主申请模板。