收藏
回答

微信客服自动回复图片?

在调试微信客服自动回复图片时,所有都是按照文档要求开发,但是无法自动回复

首先:自动回复配置如下:


第二:验证加密(通过):

boolean isGet = request.getMethod().toLowerCase().equals("get");
       if (isGet) {
           // 微信加密签名
           String signature = request.getParameter("signature");
           // 时间戳
           String timestamp = request.getParameter("timestamp");
           // 随机数
           String nonce = request.getParameter("nonce");
           // 随机字符串
           String echostr = request.getParameter("echostr");
 
           // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
           if (signature != null && WeChatUtil.checkSignature(signature, timestamp, nonce)) {
               logger.debug("signature == " + signature);
               try {
                   PrintWriter print = response.getWriter();
                   print.write(echostr);
                   print.flush();
               } catch (IOException e) {
                   logger.error("微信消息接收和token验证异常", e);
               }
           }
       }

第三:自动回复

自动回复先上传临时素材到回信服务,并获取mediaId

//先上传临时素材到微信服务
 
       String mediaId = uploadFileToWeChat(WeChatUtil.REQ_MESSAGE_TYPE_IMAGE);
 
  /**
    * 上传图片到微信服务
    *
    * @param
    * @return
    */
   @Override
   public String uploadFileToWeChat(String type) {
       String accessToken = weiXinToken.getAccessToken();
       System.out.println("token == " + accessToken);
       RestTemplate restTemplate = new RestTemplate();
       HttpHeaders headers = new HttpHeaders();
       headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
       File file = new File(IMAGE_PATH);
       if (!file.exists() || !file.isFile()) {
           return null;
       }
       StringBuilder sb = new StringBuilder();
       sb.append(weixinImageUpload)
               .append("access_token=")
               .append(accessToken)
               .append("&type=")
               .append(type);
 
       String mediaId = WeChatUtil.httpRequest(sb.toString(), file);
 
       return mediaId;
   }


    获取到mediaId后,然后自动回复开发

/**
        * 此处自动回复文本
        */
       TextMessageResponseVo textMessageResponseVo = new TextMessageResponseVo();
       textMessageResponseVo.setFromUserName(requestMessageMap.get("ToUserName"));
       textMessageResponseVo.setToUserName(requestMessageMap.get("FromUserName"));
       textMessageResponseVo.setMsgType("text");
       textMessageResponseVo.setCreateTime(System.currentTimeMillis() / 1000);
       textMessageResponseVo.setContent("你好");
 
 
       /**
        * 此处自动回复图片
        */
       ImageMessageResponseVo imageMessageResponseVo = new ImageMessageResponseVo();
       imageMessageResponseVo.setFromUserName(requestMessageMap.get("FromUserName"));
       imageMessageResponseVo.setToUserName(requestMessageMap.get("ToUserName"));
       imageMessageResponseVo.setMsgType("image");
       imageMessageResponseVo.setCreateTime(System.currentTimeMillis() / 1000);
       AutoAnswer autoAnswer = new AutoAnswer();
       autoAnswer.setMediaId(mediaId);
       imageMessageResponseVo.setImage(autoAnswer);
       System.out.println("textMessageResponseVo>>>>>>>>"+imageMessageResponseVo.toString());
       String result = WeChatUtil.messageToXml(textMessageResponseVo);
       System.out.println("result XML CDATA +++++++++++++++++++++++++" + result);
       return result;
 
 
 /**
    * 文本消息转换成xml
    */
   public static String messageToXml(TextMessageResponseVo textMessageResponseVo) {
       xstream.alias("xml", textMessageResponseVo.getClass());
       return xstream.toXML(textMessageResponseVo);
 
 
   }
 
   /**
    * 图片
    * @param imageMessageResponseVo
    * @return
    */
   public static String messageToXml(ImageMessageResponseVo imageMessageResponseVo) {
       xstream.alias("xml", imageMessageResponseVo.getClass());
       return xstream.toXML(imageMessageResponseVo);
 
 
   }
 
 
   /**
    * 扩展xstream使其支持CDATA
    */
   private static XStream xstream = new XStream(new XppDriver() {
       @Override
       public HierarchicalStreamWriter createWriter(Writer out) {
           return new PrettyPrintWriter(out) {
               // 对所有xml节点的转换都增加CDATA标记
               boolean cdata = true;
 
               @Override
               @SuppressWarnings("unchecked")
               public void startNode(String name, Class clazz) {
                   super.startNode(name, clazz);
               }
 
               @Override
               protected void writeText(QuickWriter writer, String text) {
                   if (cdata) {
                       writer.write("<![CDATA[");
                       writer.write(text);
                       writer.write("]]>");
                   } else {
                       writer.write(text);
                   }
               }
           };
       }
   });


最后,响应微信服务的是一串String的xml

//文本响应微信的xml
<xml>
  <ToUserName><![CDATA[onv1V4-zyxgliQlXbaBujrNT-ycs]]></ToUserName>
  <FromUserName><![CDATA[gh_dc0815388d0f]]></FromUserName>
  <CreateTime><![CDATA[1570614951]]></CreateTime>
  <MsgType><![CDATA[text]]></MsgType>
  <Content><![CDATA[你好]]></Content>
</xml>
  
  
//图片响应微信的xml
  
<xml>
 
  <ToUserName><![CDATA[onv1V4-zyxgliQlXbaBujrNT-ycs]]></ToUserName>
 
  <FromUserName><![CDATA[gh_dc0815388d0f]]></FromUserName>
 
  <CreateTime><![CDATA[1570670451]]></CreateTime>
 
  <MsgType><![CDATA[image]]></MsgType>
 
  <Image>
 
    <MediaId><![CDATA[ukM01FczEHwYUthTQ_Sf_6XNgI1_2lScqCFuIWOs8zQ8CGp0kgH98SS8B4SxdznU]]></MediaId>
 
  </Image>
 
</xml>
 



但是最后没有收到微信自动回复,请求各位大佬指教

最后一次编辑于  2019-10-10
回答关注问题邀请回答
收藏

2 个回答

  • Tyson Wu
    Tyson Wu
    2019-10-10

    这是httpRequest方法

    /**
     * @param requestUrl 微信上传临时素材的接口url
     * @param file       要上传的文件
     * @return String  上传成功后,微信服务器返回的消息
     * @desc :微信上传素材的请求方法
     */
    public static String httpRequest(String requestUrl, File file) {
        StringBuffer buffer = new StringBuffer();
     
        try {
            //1.建立连接
            URL url = new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  //打开链接
     
            //1.1输入输出设置
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false); // post方式不能使用缓存
            //1.2设置请求头信息
            httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Charset", "UTF-8");
            //1.3设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
     
            // 请求正文信息
            // 第一部分:
            //2.将文件头输出到微信服务器
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必须多两道线
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
                    + "\";filename=\"" + file.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            // 获得输出流
            OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
            // 将表头写入输出流中:输出表头
            outputStream.write(head);
     
            //3.将文件正文部分输出到微信服务器
            // 把文件以流文件的方式 写入到微信服务器中
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }
            in.close();
            //4.将结尾部分输出到微信服务器
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            outputStream.write(foot);
            outputStream.flush();
            outputStream.close();
     
     
            //5.将微信服务器返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
     
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
     
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
     
     
        } catch (IOException e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
        //4.json字符串转对象:解析返回值,json反序列化
        String result = buffer.toString().replaceAll("[\\\\]", "");
        System.out.println("result:" + result);
        JSONObject resultJSON = JSONObject.parseObject(result);
        return resultJSON.getString("media_id");
    }


    2019-10-10
    有用 1
    回复 2
  • 戏多多💎💎__________________
    戏多多💎💎__________________
    2019-10-09

    检查下有没有拼错的单词~

    2019-10-09
    有用
    回复 2
    • Tyson Wu
      Tyson Wu
      2019-10-10
      刚检查了一下,image写错,应该是Image,但是改过来后,还是不行;
      2019-10-10
      回复
    • 喂,快醒醒besos
      喂,快醒醒besos
      2019-12-19
      你解决了吗,我用python的也不行,文本消息可以
      2019-12-19
      回复
登录 后发表内容
问题标签