java实现微信小程序客服功能开发,后台接受用户发送消息实现关键词自动回复

最近做了一个小程序中间用到了小程序客服功能,主要实现采集用户提问,并且针对关键词自动回复及手动回复。中间踩过很多坑,所也现在记录下来提供给大家。

准备

首先准备一个小程序,配置好域名,左边菜单栏目点击开发-->找到推送(然后这是服务器地址,此地址会接收用户发送消息)设置好后点击启用。

小程序实现 

小程序打开客服功能很简单只需要加入如下代码就可以直接打开客服界面,然后直接发送消息就完事

<button open-type='contact'>联系客服</button>

 后台功能实现

/**
     * 微信接口配置信息认证接口<br>
     * 需要正确响应微信发送的Token验证。 加密/校验流程如下:<br>
     * 1. 将token、timestamp、nonce三个参数进行字典序排序<br>
     * 2. 将三个参数字符串拼接成一个字符串进行sha1加密<br>
     * 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
     */
    @RequestMapping("/cgi")
    public void cgi(HttpServletRequest request, HttpServletResponse response) {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        // 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        try {
            if (isGet) {
                String signature = request.getParameter("signature");
                // 时间戳
                String timestamp = request.getParameter("timestamp");
                // 随机数
                String nonce = request.getParameter("nonce");
                // 随机字符串
                String echostr = request.getParameter("echostr");
                logger.info("signature = "+signature+" , timestamp = "+timestamp+ " , nonce = "+nonce+ " , echostr = "+echostr);
                String[] strArray = new String[] { hmh_token, timestamp, nonce };
                Arrays.sort(strArray);
                StringBuilder sb = new StringBuilder();
                for (String str : strArray) {
                    sb.append(str);
                }
                String encrypt = SHA1.getDigestOfString(sb.toString().getBytes());
                if (encrypt.equals(signature)) {
                    response.getOutputStream().write(echostr.getBytes());
                }
            }else{
                // 进入POST聊天处理
                // 将请求、响应的编码均设置为UTF-8(防止中文乱码)
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                // 接收消息并返回消息
                String result = acceptMessage(request, response);

                // 响应消息
                PrintWriter out = response.getWriter();
                out.print(result);
                out.close();
            }
        } catch (Exception ex) {
            logger.error("微信帐号接口配置失败!", ex);
            ex.printStackTrace();
        }
    }


    /**
     * 接受到微信接口数据
     * @param request
     * @param response
     * @return
     */
    private String acceptMessage(HttpServletRequest request, HttpServletResponse response) {
//        {CreateTime=1548042266, Event=user_enter_tempsession, ToUserName=gh_e6198220cbff,
//                FromUserName=oZvme4q2Oi7Dz3FChXc43kqw28, MsgType=event, SessionFrom=wxapp}
        String respMessage = "";
        try {
            // xml请求解析
            Map<String, String> requestMap = MessageUtil.parseXml(request);
            logger.info(">>>>>>>>>>>>>"+requestMap);
            // 发送方帐号(open_id)
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            String Event = requestMap.get("Event");  //SCAN 为扫描信息  VIEW 公众号底部点击事件
            logger.info("fromUserName = "+fromUserName+" , ToUserName = "+toUserName+ " , msgType = "+msgType);

            HmhWxTokenEntity tokenEntity = hmhWxTokenService.getHmhWxTokenInfoById(Long.parseLong(String.valueOf(1)));

            StringBuffer contentMsg = new StringBuffer();
            String html = "https://xxxxx.cn/index/wechat/index.html?oid="+fromUserName;
            String url = "☞ <a href=\""+html+"\">点击跳转</a>";
            //公众号关注事件消息
            if(msgType.equals("event")){
                contentMsg.append("↓↓您的专属充值链接↓↓").append("\n");
                contentMsg.append(url);
                if(tokenEntity!=null){
                    WxUtil.sendKfMessage(fromUserName,contentMsg.toString(),tokenEntity.getWxToken()); //把封装好的信息推送给用户
                }
            }else if(msgType.equals("text")){
                logger.info("公众号接受文字..........");
                contentMsg.append("↓↓您的专属充值链接↓↓").append("\n");
                contentMsg.append(url);
                if(tokenEntity!=null){
                    WxUtil.sendKfMessage(fromUserName,contentMsg.toString(),tokenEntity.getWxToken());
                }
            }else if(msgType.equals("image")){
                logger.info("公众号接受图片..........");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respMessage;
    }
 //客服消息推送地址
    public final static String kf_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send";

    public static String  getToken() throws Exception{
        String accessToken = HttpUtils.doGet(url);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(accessToken);
        return String.valueOf(jsonObject.get("access_token"));
    }

    public static String sendKfMessage(String openid,String text,String access_token)throws Exception{
        Map<String,Object> map_content = new HashMap<>();
        map_content.put("content",text);
        Map<String,Object> map = new HashMap<>();
        map.put("touser",openid);
        map.put("msgtype","text");
        map.put("text",map_content);
        String content =  JSONUtils.toJSONString(map);
        return HttpUtils.doPost(kf_url+"?access_token="+access_token,content);

    }

小程序客服消息官方文档:

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/customer-message/receive.html

有啥问题直接点击博客左边 wx +我注明问题 。

猜你喜欢

转载自blog.csdn.net/love468092550/article/details/87801662