java微信測試公衆號實現文本、圖片消息回覆

微信測試公衆號實現文本、圖片消息回覆

學習記錄:
源碼地址:https://gitee.com/jack_liujilong/WeiXin.git
1.申請微信測試公衆號https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421137522
在這裏插入圖片描述
2.配置測試公衆號
URL:能夠讓微信服務器請求到的網址也就是提供一個外網給微信服務器,後面這個wx_check就是微信服務器請求你的校驗Token的請求(如不知道或沒有外網端口的可以參考我上面的的文章"使用ngrok實現外網穿透(一)"地址:https://blog.csdn.net/csdn_ljl/article/details/94234532
,我用的是ngrok實現的外網映射
Token:隨便寫什麼,只要與後臺一致就行
在這裏插入圖片描述
微信校驗接口:

Controller:
/**
     * 校驗
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wx_check",method = {RequestMethod.GET})
    public void wxCheck(HttpServletRequest request, HttpServletResponse response) throws  Exception{
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        System.out.print(echostr);
        PrintWriter out = response.getWriter();
        if (WeiXinCheck.weiXinCheckSignature(signature,timestamp,nonce)){
            out.print(echostr);
        }
    }
    WeiXinCheck:
		private static final  String token = "admin";
    /**
     * 簽名校驗
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean weiXinCheckSignature(String signature,String timestamp,String nonce){
        String[] arr = new String[]{token,timestamp,nonce};
        //排序
        Arrays.sort(arr);

        //生成字符串
        StringBuffer content = new StringBuffer();
        for (int i =0; i<arr.length;i++){
            content.append(arr[i]);
        }

        //sha1加密
        String temp = getSha1(content.toString());
        return temp.equals(signature);
    }
    /**
     * sha1加密
     * @param str
     * @return
     */
    public static String getSha1(String str) {
        if (null == str || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

3.微信請求格式、及後臺響應代碼
1.文本消息回覆
微信請求格式:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140453

文本消息格式:
<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[text]]></MsgType>
  <Content><![CDATA[this is a test]]></Content>
  <MsgId>1234567890123456</MsgId>
</xml>

參數				描述
ToUserName		開發者微信號
FromUserName	發送方帳號(一個OpenID)
CreateTime		消息創建時間 (整型)
MsgType			消息類型,文本爲text
Content			文本消息內容
MsgId			消息id,64位整型

Controller:
/**
     * 文本消息回覆
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wx_check",method = {RequestMethod.POST})
    public void wxCheck2(HttpServletRequest request, HttpServletResponse response)throws Exception{
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        try {
            Map<String, String> map = MessageUtil.xmlToMap(request);
            String toUserName = map.get("ToUserName");
            String fromUserName = map.get("FromUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");

            String message = null;
            if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {

             

                /**
                 * 文本消息回覆
                 */
                TextMessage text = new TextMessage();
                text.setFromUserName(toUserName);
                text.setToUserName(fromUserName);
                text.setCreateTime(new Date().getTime()+"");
                text.setMsgType("text");
                text.setContent("您發送的消息是:"+ content);
                message = MessageUtil.textMessageToxml(text);
            }
            System.out.print(message);
            printWriter.print(message);
        }catch (DocumentException e){
            e.printStackTrace();
        }finally {
            printWriter.close();
        }
    }
MessageUtil:
/**
     * xml轉換爲map集合
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();

        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);
        Element root = doc.getRootElement();

        List<Element> list = root.elements();
        for (Element element : list) {
            map.put(element.getName(), element.getText());
        }
        ins.close();
        return map;
    }

文本消息實體類:
package com.jl.controller.po;

public class TextMessage {
    private String ToUserName;
    private String FromUserName;
    private String CreateTime;
    private String MsgType;
    private String Content;
    private String MsgId;

    public String getToUserName() {
        return ToUserName;
    }

    public void setToUserName(String toUserName) {
        ToUserName = toUserName;
    }

    public String getFromUserName() {
        return FromUserName;
    }

    public void setFromUserName(String fromUserName) {
        FromUserName = fromUserName;
    }

    public String getCreateTime() {
        return CreateTime;
    }

    public void setCreateTime(String createTime) {
        CreateTime = createTime;
    }

    public String getMsgType() {
        return MsgType;
    }

    public void setMsgType(String msgType) {
        MsgType = msgType;
    }

    public String getContent() {
        return Content;
    }

    public void setContent(String content) {
        Content = content;
    }

    public String getMsgId() {
        return MsgId;
    }

    public void setMsgId(String msgId) {
        MsgId = msgId;
    }
}

MessageUtil:
/**
     * 將文本對象轉換爲xml
     *
     * @param textMessage
     * @return
     */
    public static String textMessageToxml(TextMessage textMessage) {
        XStream xStream = new XStream();
        xStream.alias("xml", textMessage.getClass());
        return xStream.toXML(textMessage);
    }
   

結果如圖:
在這裏插入圖片描述
2.圖片消息回覆

微信圖片回覆格式:
圖片消息

```<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType><![CDATA[image]]></MsgType>
  <PicUrl><![CDATA[this is a url]]></PicUrl>
  <MediaId><![CDATA[media_id]]></MediaId>
  <MsgId>1234567890123456</MsgId>
</xml>

參數					描述
ToUserName		開發者微信號
FromUserName	發送方帳號(一個OpenID)
CreateTime		消息創建時間 (整型)
MsgType			消息類型,圖片爲image
PicUrl			圖片鏈接(由系統生成)
MediaId			圖片消息媒體id,可以調用獲取臨時素材接口拉取數據。
MsgId			消息id,64位整型
```j
校驗簽名必須要的哦別忘了
Controller:
/**
     * 圖片消息回覆
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "wx_check",method = {RequestMethod.POST})
    public void wxCheck2(HttpServletRequest request, HttpServletResponse response)throws Exception{
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        try {
            Map<String, String> map = MessageUtil.xmlToMap(request);
            String toUserName = map.get("ToUserName");
            String fromUserName = map.get("FromUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");

            String message = null;
            if (MessageUtil.MESSAGE_TEXT.equals(msgType)) {

                /**
                 * 圖片消息回覆
                 */
                message= MessageUtil.initNewsMessage(toUserName,fromUserName);

               
            }
            System.out.print(message);
            printWriter.print(message);
        }catch (DocumentException e){
            e.printStackTrace();
        }finally {
            printWriter.close();
        }
    }
MessageUtil:
	public static final String MESSAGE_TEXT = "text";//文本消息
    public static final String MESSAGE_IMAGE = "image";//圖片消息
    public static final String MESSAGE_VOICE = "voice";//語音消息
    public static final String MESSAGE_VIDEO = "video";//視頻
    public static final String MESSAGE_SHORTVIDEO = "shortvideo";//小視屏
    public static final String MESSAGE_LOCATION = "location";//地理位置
    public static final String MESSAGE_LINK = "link";//鏈接
    public static final String MESSAGE_EVENT = "event";//事件推送
    public static final String MESSAGE_SUBSCRIBE = "subscribe";//被關注
    public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";//取消關注
    public static final String MESSAGE_CLICK = "CLICK";//點擊
    public static final String MESSAGE_VIEW = "VIEW";//

    /**
     * 圖片消息組裝
     * @param toUserName
     * @param fromUserName
     * @return
     */
        public static String initNewsMessage (String toUserName, String fromUserName)throws  Exception{
            String message = null;
            Image image = new Image();

            AccessToken token = WeiXinUtil.getAccessToken();
            System.out.print("票據:"+token.getToken());
            System.out.print("有效時間:"+token.getExpiresIn());
            image.setMediaId(WeiXinUtil.upload("img/0.jpg",token.getToken(),"image"));

            ImageMessage imageMessage = new ImageMessage();
            imageMessage.setFromUserName(toUserName);
            imageMessage.setToUserName(fromUserName);
            imageMessage.setMsgType(MESSAGE_IMAGE);
            imageMessage.setCreateTime(new Date().getTime()+"");
            imageMessage.setImage(image);
            message = imageMessageToxml(imageMessage);
            return message;
        }

Image:
package com.jl.controller.po;

public class Image {
    private String MediaId;

    public String getMediaId() {
        return MediaId;
    }

    public void setMediaId(String mediaId) {
        MediaId = mediaId;
    }
}
ImageMessage:
package com.jl.controller.po;

public class ImageMessage extends BaseMessage {
    private Image Image;

    public com.jl.controller.po.Image getImage() {
        return Image;
    }

    public void setImage(com.jl.controller.po.Image image) {
        Image = image;
    }
}
AccessToken:
package com.jl.controller.po;

public class AccessToken {
	private String token;
	private int expiresIn;
	public String getToken() {
		return token;
	}
	public void setToken(String token) {
		this.token = token;
	}
	public int getExpiresIn() {
		return expiresIn;
	}
	public void setExpiresIn(int expiresIn) {
		this.expiresIn = expiresIn;
	}
}
BaseMessage:
package com.jl.controller.po;

public class BaseMessage {

    private String ToUserName;
    private String FromUserName;
    private String CreateTime;
    private String MsgType;
    private String MediaId;

    public String getToUserName() {
        return ToUserName;
    }

    public void setToUserName(String toUserName) {
        ToUserName = toUserName;
    }

    public String getFromUserName() {
        return FromUserName;
    }

    public void setFromUserName(String fromUserName) {
        FromUserName = fromUserName;
    }

    public String getCreateTime() {
        return CreateTime;
    }

    public void setCreateTime(String createTime) {
        CreateTime = createTime;
    }

    public String getMsgType() {
        return MsgType;
    }

    public void setMsgType(String msgType) {
        MsgType = msgType;
    }

    public String getMediaId() {
        return MediaId;
    }

    public void setMediaId(String mediaId) {
        MediaId = mediaId;
    }
}


    
 WeiXinUtil:
				private static final String APPID = "寫自己的";
			    private static final String APPSECRET = "寫自己的";
			
			    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
			
			    private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
			
			    private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
			
			    private static final String QUERY_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
			
			    private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

/**
     * get請求
     * @param url
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static JSONObject doGetStr(String url) throws ParseException, IOException{
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        HttpResponse httpResponse = client.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = JSONObject.fromObject(result);
        }
        return jsonObject;
    }
    /**
     * POST請求
     * @param url
     * @param outStr
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static JSONObject doPostStr(String url,String outStr) throws ParseException, IOException{
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpost = new HttpPost(url);
        JSONObject jsonObject = null;
        httpost.setEntity(new StringEntity(outStr,"UTF-8"));
        HttpResponse response = client.execute(httpost);
        String result = EntityUtils.toString(response.getEntity(),"UTF-8");
        jsonObject = JSONObject.fromObject(result);
        return jsonObject;
    }

        (下載圖片獲得mediaid)
        /**
     * 文件下載
     * @param filePath
     * @param accessToken
     * @param type
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws KeyManagementException
     */
    public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IOException("文件不存在");
        }

        String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);

        URL urlObj = new URL(url);
        //連接
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);

        //設置請求頭信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");

        //設置邊界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        StringBuilder sb = new StringBuilder();
        sb.append("--");
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");

        byte[] head = sb.toString().getBytes("utf-8");

        //獲得輸出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        //輸出表頭
        out.write(head);

        //文件正文部分
        //把文件已流文件的方式 推入到url中
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();

        //結尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定義最後數據分隔線

        out.write(foot);

        out.flush();
        out.close();

        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        try {
            //定義BufferedReader輸入流來讀取URL的響應
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        JSONObject jsonObj = JSONObject.fromObject(result);
        System.out.println(jsonObj);
        String typeName = "media_id";
        if(!"image".equals(type)){
            typeName = type + "_media_id";
        }
        String mediaId = jsonObj.getString(typeName);
        return mediaId;
    }
 
    /**
     * 獲取accessToken
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static AccessToken getAccessToken() throws ParseException, IOException{
        AccessToken token = new AccessToken();
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        JSONObject jsonObject = doGetStr(url);
        if(jsonObject!=null){
            token.setToken(jsonObject.getString("access_token"));
            token.setExpiresIn(jsonObject.getInt("expires_in"));
        }
        return token;
    }
    MessageUtil:
/**
     * 將圖片對象轉換爲xml
     *
     * @param imageMessage
     * @return
     */
    public static String imageMessageToxml(ImageMessage imageMessage) {
        XStream xStream = new XStream();
        xStream.alias("xml", imageMessage.getClass());
        return xStream.toXML(imageMessage);
    }


結果如圖:在這裏插入圖片描述
如不成功請上碼雲下載源碼覈對,地址:https://gitee.com/jack_liujilong/WeiXin.git

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章