接收消息优化--微信企业号

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_27912569/article/details/79287855

微信企业号接收消息处理优化

优化点:

  • 1.所有接收消息的返回全部调用主动发送消息,因为接收消息的返回需要在5s内,且还需要加密,我对于自己的网络等不太放心,所以使用稳妥的办法,只返回成功标示200;
  • 2.更新秘钥access_token,本来是想在web工程中使用子进程定时更新,但是代码出现异常了,所以用了简单的办法,若返回码错误类型是access_token的过期或者异常,就去更新且写入到配置文件中;
  • 3.将固定参数写入到配置文件中;
  • 4.整个项目war

废话太多,上代码

接收消息调用主动发送

PrintWriter out = response.getWriter();
        String sRespData = "";
        if (("text").equals(Content)) {
            sRespData = "<xml><ToUserName><![CDATA[" + FromUserName
                    + "]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>"
                    + System.currentTimeMillis() + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA["
                    + "response news -- test,type:text" + "]]></Content><MsgId>" + MsgId + "</MsgId><AgentID>"
                    + sAgentId + "</AgentID></xml>";

        } else if (("image").equals(Content)) {

            sRespData = "200";
            /**
             * 在这里调用主动发送信息,发送除了文本信息之外的数据
             */
            String access_token = cUtils.getPorp("access_token");
            System.out.println("access_token:" + access_token);
            String result = MediaUploadUtil.uploadMedia(cUtils.getPorp("access_token"), "image",
                    "http://img15.3lian.com/2015/c1/83/d/29.jpg");
            System.out.println("result---media_id:" + result);

            jsparam2 = WxworkNewsType.imageType(WxworkUtil.getReturn(result).get("media_id"), FromUserName, "",
                    Integer.parseInt(cUtils.getPorp("AgentId")));
        } else if (("active-text").equals(Content)) {
            sRespData = "200";
            System.out.println(cUtils.getPorp("access_token"));
            jsparam2 = WxworkNewsType.textType(
                    "主动测试信息:\n  xxxx连接信息<a href=\"https://mp.weixin.qq.com/debug/wxadoc/dev/framework/MINA.html \">微信小程序pai文档</a>\n <a href=\"http://www.importnew.com/18769.html \">InportNew</a>\n",
                    FromUserName, "", Integer.parseInt(cUtils.getPorp("AgentId")));
        } else if (("active-news").equals(Content)) {
            sRespData = "200";
            jsparam2 = WxworkNewsType.newsType(FromUserName, "", Integer.parseInt(cUtils.getPorp("AgentId")),
                    "请求异步发送图文信息", "主动请求,设置成功,主动发送图文信息",
                    "href=\"https://mp.weixin.qq.com/debug/wxadoc/dev/framework/MINA.html",
                    "http://img15.3lian.com/2015/c1/83/d/29.jpg", "更多信息");

        } else {
            sRespData = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA["
                    + sCorpID + "]]></FromUserName><CreateTime>" + System.currentTimeMillis()
                    + "</CreateTime><MsgType><![CDATA[" + "text" + "]]></MsgType><Content><![CDATA[" + Content
                    + "]]></Content><MsgId>" + MsgId + "</MsgId><AgentID>" + sAgentId + "</AgentID></xml>";

        }
        // String sRespData = ToXmlString("response news -- test ",ToUserName);
        try {
            String sEncryptMsg = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce);
            // 加密成功
            System.out.println("相应消息加密结果--after encrypt sEncrytMsg: " + sEncryptMsg);
            out.println(sEncryptMsg);
            if (null != jsparam2 && sRespData == "200") {
                String sendruslt = WxworkUtil.sendData(cUtils.getPorp("access_token"), jsparam2).toString();
                System.out.println("主动发送消息返回结果---第一次执行:" + sendruslt);
                String errcode = WxworkUtil.getRuslt(sendruslt).get("errcode");
                if (!"0".equals(errcode)) {
                    // 当发送小时失败时,根据返回码的access_token异常,更新access_toke的值,再次重新发送
                    // System.out.println("返回结果:"+WxworkUtil.getRuslt(sendruslt).toString());
                    // System.out.println("判断返回结果:"+"ok".equals(WxworkUtil.getRuslt(sendruslt).get("errmsg"))
                    // );
                    switch (errcode) {
                    case "40014":
                    case "42001":
                        System.out.println("access_token,不合法或者过期,正在更新");
                        cUtils.setPorp("access_token", WxworkUtil
                                .GetForAT(cUtils.getPorp("CorpID"), cUtils.getPorp("corpsecret")).get("access_token"));
                        if (("image").equals(Content)) {
                            String result = MediaUploadUtil.uploadMedia(cUtils.getPorp("access_token"), "image",
                                    "http://img15.3lian.com/2015/c1/83/d/29.jpg");
                            jsparam2 = WxworkNewsType.imageType(WxworkUtil.getReturn(result).get("media_id"),
                                    FromUserName, "", Integer.parseInt(cUtils.getPorp("AgentId")));
                        }
                        sendruslt = WxworkUtil.sendData(cUtils.getPorp("access_token"), jsparam2).toString();
                        System.out.println("主动发送消息返回结果---二次执行:" + sendruslt);
                        break;
                    default:
                        System.out.println("返回码错误,根据返回码,查找问题:微信企业号文档--全局错误码:" + errcode);
                        ;
                    }

                } else if ("pwu-null" != WxworkUtil.getRuslt(sendruslt).get("invaliduser")) {
                    System.out.println(
                            "主动发送消息的请求,异常需要核对参数 invaliduser:" + WxworkUtil.getRuslt(sendruslt).get("invaliduser"));
                } else if ("0".equals(errcode)) {
                    System.out.println("调用接口成功!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 加密失败
        }

    }

配置文件工具类


package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class ConfigUtils {
    private Properties prop = new Properties();
    private File file=null;

    /** 
     * @param proName
     */
    public  ConfigUtils(String proName){
            init(proName);

    }
    /**
     * @param proName
     */
    private void init(String proName){
        //String dir=System.getProperty("user.dir")+"/resource/"+proName+".properties";
        //GetResource.class.getClassLoader().getResource("xx/xx.txt").getPath();
        String dir=ConfigUtils.class.getClassLoader().getResource(proName+".properties").getPath();
        file = new File(dir);
        try {
            prop.load(new FileInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @param key
     * @return
     */
    public String getPorp(String key){
        return (String)prop.getProperty(key);
    }
    /**
     * @param key
     * @param val
     */
    public void  setPorp(String key,String val){
        prop.setProperty(key, val);
        FileOutputStream fos=null;
        try {
            fos = new FileOutputStream(file);
            prop.store(fos, null);      
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fos!=null){
                try {
                    fos.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_27912569/article/details/79287855