java微信公众号消息管理开发(接受与发送聊天信息)

260 阅读5分钟

接受微信消息处理

@Controller
@RequestMapping("/wxIm")
public class WxIm {
 
 @Resource
 private IWxService wxService;
 @Resource
 private WXPublicUtils wxPublicUtils;
 
 @Resource
 private IChatGroupService chatgroupService;
 
 @Resource
 private MsgController msg;
 
 @Resource
 private IParamService paramService;
 
 @Resource
 private IUserService userservice;
 
 int sort = 0;
 String kf = "";
 
 @RequestMapping("/receiveWxMsg")
 @ResponseBody
 public void receiveWxMsg(HttpServletRequest request, HttpServletResponse response)
   throws IOException, WxErrorException {
         
  String token = "";
  Wx wx = wxService.selectById(1);
  if (wx.getExpires().getTime() < new Date().getTime()) {
   token = wxPublicUtils.getAccessToken();
   wx.setToken(token);
   wx.setExpires(new Date((new Date().getTime()) + 5400000));
   wxService.updateById(wx);
  } else {
   token = wx.getToken();
  }
 
  Message message = wxPublicUtils.receiveWxMsg(request, response, token);
  // 此处写逻辑,接受的各种数据消息
  HashMap<String, Object> map = new HashMap<>();
  map.put("openid", message.getFromUserName());
  List<ChatGroup> list = chatgroupService.selectByMap(map);
  String roomid = "";
  String nickname = "";
  String customerId = "";
  String openid =message.getFromUserName();
  String avatar="";
  
//   msgType 消息主题(MsgType:文本-text;图片-image;语音-voice;视频-video;)   
  try {
   Param param = paramService.selectById(1);
   if (list.size() == 0) {
    // 获取用户信息
    JSONObject json = wxPublicUtils.findUserInfo(token, message.getFromUserName());
    if(json.getString("errcode")!=null)
    {
     token = wxPublicUtils.getAccessToken();
     wx.setToken(token);
     wx.setExpires(new Date((new Date().getTime()) + 5400000));
     wxService.updateById(wx);
     json = wxPublicUtils.findUserInfo(token, message.getFromUserName());
    }
    System.out.println(json.toJSONString());
    
    customerId = "c" + System.currentTimeMillis();
    if(StringUtils.isBlank(openid))
    {
     return ;
    }
    msg.register(customerId, openid);
 
    // 创建房间,要根据配置,选择分配客服
    kf = kfgz(param.getCustomer());
    if (kf.equals("")) {
     wxPublicUtils.sendWxMsg(openid, "text", "客服在忙,请稍等", null);
     return;
    }
    roomid = msg.createChatRoom(customerId, "微信", kf);
    ChatGroup chat = new ChatGroup();
    if (!roomid.equals("")) {
     chat.setRoomid(roomid);
     ChatGroup chatGroup = chatgroupService.selectByRoomid(chat);
     // 修改用户基本信息
     chatGroup.setName(json.getString("nickname"));
     chatGroup.setGroupname(json.getString("nickname").replaceAll("[\ue000-\uefff]", ""));
     chatGroup.setOpenid(json.getString("openid"));
     chatGroup.setAddress(
       json.getString("province") + json.getString("city") + json.getString("country"));
     chatGroup.setAvatar(json.getString("headimgurl"));
     chatGroup.setCustomerId(customerId);
     chatgroupService.updateById(chatGroup);
     nickname = chatGroup.getGroupname();
    }
    // 接入回复
 
    if (param.getAccess().equals(2)) {
     wxPublicUtils.sendWxMsg(message.getFromUserName(), "text", param.getAccessContent(), null);
    }
   } else {
    roomid = list.get(0).getRoomid();
    if(list.get(0).getBlacklist().equals(1))
    {
       //拉黑的不做任何操作
     return;
    }
    if(list.get(0).getIsover().equals(2))
    {
     list.get(0).setIsover(1);//设置开始
     list.get(0).setCreateTime(DateUtil.getTime());
     chatgroupService.updateById(list.get(0));
    }
    User u = userservice.getByAccount(list.get(0).getFirstservice());
    if (!u.getStatus().equals(1))// 如果客服不在线就把客户安排给其他客服
    {
     kf = kfgz(param.getCustomer());// 重新分配客服
     if (kf.equals("")) {
      wxPublicUtils.sendWxMsg(openid, "text", "客服在忙,请稍等", null);
      return;
     }
     list.get(0).setFirstservice(kf);
     chatgroupService.updateById(list.get(0));// 重新分配客服
    } else {
     kf = list.get(0).getFirstservice();
    }
 
    openid = list.get(0).getOpenid();
    nickname = list.get(0).getName();
    customerId = list.get(0).getCustomerId();
    avatar=list.get(0).getAvatar();
   }
 
   if (message!=null) {
               String messageId=MD5Util.encrypt(System.currentTimeMillis() + UUID.randomUUID().toString());
    String content = "";
    MsgData data = new MsgData();
    
    MsgData dataSource = new MsgData();
    
    if (message.getMsgType().equals("text")) {
     data.setType("0");
     content = msg.msgData(message.getContent(), 0, customerId, roomid, "0", 0, nickname,avatar,messageId);
     dataSource=msg.msgData(message.getContent(), 0, customerId, roomid, "0", 0, nickname,avatar,messageId,0,0);
    }
    if (message.getMsgType().equals("image")) {
     data.setType("1");
     content = msg.msgData(message.getContent(), 1, customerId, roomid, "0", 0, nickname,avatar,messageId);
     dataSource=msg.msgData(message.getContent(), 1, customerId, roomid, "0", 0, nickname,avatar,messageId,0,0);
    }
    if (message.getMsgType().equals("voice")) {
     data.setType("2");
     content = msg.msgData(message.getContent(), 2, customerId, roomid, "0", 0, nickname,avatar,messageId);
     int d=(int) (Math.random()*10);
     dataSource=msg.msgData(message.getContent(), 2, customerId, roomid, "0", 0, nickname,avatar,messageId,0,d);
    }
    if (message.getMsgType().equals("video")) {
     data.setType("3");
     content = msg.msgData(message.getContent(), 3, customerId, roomid, "0", 0, nickname,avatar,messageId);
     dataSource=msg.msgData(message.getContent(), 3, customerId, roomid, "0", 0, nickname,avatar,messageId,0,0);
    }
    // 消息内容
    data.setMessageId(messageId);
    data.setContent(message.getContent());
    data.setUsername(customerId);
    data.setSessionId(roomid+"@");
    data.setInternal(0);// 外部消息
    data.setRole(0);// 0客户1客服2师傅
    data.setNickname(nickname);
    data.setAvatar(avatar);
    data.setSendTime((new Date().getTime())+"");
    // 发送消息
    msg.sendChatGroupMessage(roomid, customerId, content);
    // 发送给相关客服单聊消息通知app
//      msg.sendChatMessage(openid, kf, content);
    sendMessage(customerId, dataSource,roomid);
    // 保存聊天记录
    msg.saveRecordWx(data);
 
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 
 }
 
 public String sendwxMsg(String openid, String content, int type)  {
  String flag="0";
  try {
    if (type == 0) {
      wxPublicUtils.sendWxMsg(openid, "text", content, null);
    }
    if (type == 1) {
     File image = downUrlTxt(System.currentTimeMillis() + "", content, "");
  //     File image = new File(content);
     wxPublicUtils.sendWxMsg(openid, "image", null, image);
     image.delete();
    }
    if (type == 2) {
     File voice = downUrlTxt(System.currentTimeMillis() + "", content, "");
  //    File voice = new File(content);
     wxPublicUtils.sendWxMsg(openid, "voice", null, voice);
     voice.delete();
    }
    if (type == 3) {
     File video = downUrlTxt(System.currentTimeMillis() + "", content, "");
  //    File video = new File(content);
     wxPublicUtils.sendWxMsg(openid, "video", null, video);
     video.delete();
    }
    //商品消息
    if(type==4)
    {
     if(content!=null)
     {
      JSONObject o=JSONObject.parseObject(content);
      String title=o.getString("title");
      String  tit=o.getString("tit");
      String price=o.getString("price");
      String img=o.getString("image");
      String url="http://www.baidu.com";
      wxPublicUtils.sendWxMsg(openid, "shop", "商品:"+title+","+tit+","+"价格:"+price, null,title,tit,img,url);          
          }
    }
    
  } catch (WxErrorException e) {
   // TODO Auto-generated catch block
   flag="1";
   return flag;
   //e.printStackTrace();
  }
  return flag;
 }
 
 /**
  * 发送给所有客服
  */
 public void sendMessage(String openid, MsgData content,String roomid) {
  List<User> kfm = orderbyuser();
  for (User m : kfm) {
   try {
      int type= msg.getSource(roomid, m.getAccount());
      content.setSource(type);
     msg.sendChatMessage(openid, m.getAccount(), JSON.toJSONString(content));
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 
 }
 
 /**
  * 按排序获取客服
  */
 public List<User> orderbyuser() {
  EntityWrapper<User>  ew=new EntityWrapper<>();
  ew.in("roleid", "1");
  ew.eq("status", 1);
  List<User> list = userservice.selectList(ew);
  return list;
 }
 
 /**
  * 客服规则
  * 
  * @return
  */
 public String kfgz(int v) {
  Param param = paramService.selectById(1);
  List<User> kfm = orderbyuser();
  if (v == 1  ) {
   // 按照排序
  
   if (sort > kfm.size() - 1) {
    sort = 0;
   }
   kf = kfm.get(sort).getAccount();
   sort++;
 
  }
  //空闲度
  if( v == 2)
  {
   ChatGroup chatGroup=new ChatGroup();
   chatGroup.setTimeType("0");
   List<Map<String, Object>> list = chatgroupService.firstList(chatGroup);
   if(list.size()>0)
   {
    kf=list.get(0).get("account").toString();
   }
   
  }
  //随机
  if(v==3)
  {
   int random=(int) (Math.random()*kfm.size());
   kf = kfm.get(random).getAccount();
  }
  // 指定客服
  if (v == 4) {
   kf = param.getCustomerId();
  }
  return kf;
 }
 
 public File downUrlTxt(String fileName, String fileUrl, String downPath) {
  File savePath = new File(downPath);
  if (!savePath.exists()) {
   savePath.mkdir();
  }
  String[] urlname = fileUrl.split("/");
  int len = urlname.length - 1;
  String uname = urlname[len];// 获取文件名
  try {
   File file = new File(savePath + "/" + uname);// 创建新文件
   if (file != null && !file.exists()) {
    file.createNewFile();
   }
   OutputStream oputstream = new FileOutputStream(file);
   URL url = new URL(fileUrl);
   HttpURLConnection uc = (HttpURLConnection) url.openConnection();
   uc.setDoInput(true);// 设置是否要从 URL 连接读取数据,默认为true
   uc.connect();
   InputStream iputstream = uc.getInputStream();
//              System.out.println("file size is:"+uc.getContentLength());//打印文件长度  
   byte[] buffer = new byte[4 * 1024];
   int byteRead = -1;
   while ((byteRead = (iputstream.read(buffer))) != -1) {
    oputstream.write(buffer, 0, byteRead);
   }
   oputstream.flush();
   iputstream.close();
   oputstream.close();
   return file;
  } catch (Exception e) {
   System.out.println("读取失败!");
   e.printStackTrace();
  }
  return null;
 
 }
 
}

微信工具类

public class WXPublicUtils {
 
    @Resource
    private WxMpService wxMpService;
    @Autowired
    AliOSS oss;
    
    @Autowired
    private IOssService ossService;
    
 
    public String getAccessToken() {
        try {
            return wxMpService.getAccessToken();
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "";
    }
 
    /**
     * 获取用户基本信息(UnionID机制)
     *
     * @return 用户基本信息
     * @throws UnsupportedEncodingException 
     */
    public JSONObject findUserInfo(String token, String openid) throws UnsupportedEncodingException {
        String param = "access_token=" + token + "&openid=" + openid + "&lang=zh_CN";
        String jsonStirng = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/user/info", param);
        String encoderJson = URLEncoder.encode(jsonStirng, "UTF-8");
        return JSON.parseObject(encoderJson);
    }
 
    /**
     * 接收微信推送的消息
     */
    public Message receiveWxMsg(HttpServletRequest request, HttpServletResponse response, String token) throws IOException {
        //微信消息
        Message message = new Message();
 
        PrintWriter out = response.getWriter();
        
        Oss ofile=ossService.selectById(1);
        try {
            Map<String, String> map = xmlToMap(request);
            //从集合中,获取XML各个节点的内容
            String ToUserName = map.get("ToUserName");
            String FromUserName = map.get("FromUserName");
            String CreateTime = map.get("CreateTime");
            String MsgType = map.get("MsgType");
            String MsgId = map.get("MsgId");
            String Content = "";
      
            if (MsgType.equals("text")) {
                Content = map.get("Content");
                message.setContent(Content);
            } else {
                File file = wxMpService.getMaterialService().mediaDownload(map.get("MediaId"));
                String file_name = file.getName();
                if (MsgType.equals("voice")) {
                    String name = file_name.replace(".amr", ".mp3");
                    File target = new File(name);
//                    AmrToMp3.changeTemp(file, target);
                    AudioConvertUtils.changeLocalSourceToMp3(file, target);
                    oss.saveFileToOSS(target, name);
                    target.delete();
 
                    message.setContent(String.format("http://%s.%s/%s", ofile.getBucketName(), ofile.getEndpoint(), name));
                } else {
                 oss.saveFileToOSS(file, file_name);
                    message.setContent(String.format("http://%s.%s/%s", ofile.getBucketName(), ofile.getEndpoint(), file_name));
                }
                file.delete();
            }
 
            message.setFromUserName(FromUserName);
            message.setToUserName(ToUserName);
         
            message.setMsgId(MsgId);
            message.setMsgType(MsgType);
            message.setCreateTime(new Date(Long.parseLong(CreateTime)).getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        out.print("success");
        out.close();
        return message;
    }
 
    /**
     * 将xml格式转化为map
     */
    public Map<String, String> xmlToMap(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<>();
 
        SAXReader reader = new SAXReader();
        InputStream inputStream = request.getInputStream();
        Document doc = reader.read(inputStream);
        Element root = doc.getRootElement();//得到根节点
        List<Element> list = root.elements();//根节点下的所有的节点
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
 
        inputStream.close();
        return map;
    }
 
    /**
     * 发送微信消息
     *
     * @param openId  客户OpenID
     * @param msgType 消息主题(MsgType:文本-text;图片-image;语音-voice;视频-video;)
     * @param content 消息内容
     * @param file    消息文件
     */
    public void sendWxMsg(String openId, String msgType, String content, File file) throws WxErrorException {
        WxMpKefuMessage wxMpKefuMessage;
        if (msgType.equals("text")) {
            wxMpKefuMessage = WxMpKefuMessage
                    .TEXT()
                    .toUser(openId)
                    .content(content)
                    .build();
        }  
        else {
            //上传文件
            WxMediaUploadResult res = wxMpService.getMaterialService().mediaUpload(msgType, file);
 
            if (msgType.equals("image")) {
                wxMpKefuMessage = WxMpKefuMessage
                        .IMAGE()
                        .toUser(openId)
                        .mediaId(res.getMediaId())
                        .build();
 
            } else if (msgType.equals("voice")) {
                wxMpKefuMessage = WxMpKefuMessage
                        .VOICE()
                        .toUser(openId)
                        .mediaId(res.getMediaId())
                        .build();
            } else{
                wxMpKefuMessage = WxMpKefuMessage
                        .VIDEO()
                        .toUser(openId)
                        .mediaId(res.getMediaId())
                        .build();
            }
        }
 
        try {
            wxMpService.getKefuService().sendKefuMessage(wxMpKefuMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
    public void sendWxMsg(String openId, String msgType, String content, File file,String title,String desc,String picUrl,String url) 
      throws WxErrorException {
      WxMpKefuMessage wxMpKefuMessage; 
      List<WxArticle>list=new ArrayList<>();
      WxArticle model=new WxArticle();
      model.setTitle(title);
      model.setPicUrl(picUrl);
      model.setUrl(url);
      model.setDescription(desc);
      list.add(model);
     if (msgType.equals("shop")) {
            wxMpKefuMessage = WxMpKefuMessage
                    .NEWS()
                    .toUser(openId)
                    .articles(list)
                    .build();
        }else
        {
                 wxMpKefuMessage = WxMpKefuMessage
                   .TEXT()
                         .toUser(openId)
                         .content(content)
                         .build();
        }
       try {
              wxMpService.getKefuService().sendKefuMessage(wxMpKefuMessage);
          } catch (WxErrorException e) {
              e.printStackTrace();
          }
    }

本文使用 mdnice 排版