当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA实现 springMVC方式的微信接入、实现消息自动回复实例

JAVA实现 springMVC方式的微信接入、实现消息自动回复实例

2019年07月22日  | 移动技术网IT编程  | 我要评论
前段时间小忙了一阵,微信公众号的开发,从零开始看文档,踩了不少坑,也算是熬过来了,最近考虑做一些总结,方便以后再开发的时候回顾,也给正在做相关项目的同学做个参考。 1.思

前段时间小忙了一阵,微信公众号的开发,从零开始看文档,踩了不少坑,也算是熬过来了,最近考虑做一些总结,方便以后再开发的时候回顾,也给正在做相关项目的同学做个参考。

1.思路

微信接入:用户消息和开发者需要的事件推送都会通过微信方服务器发起一个请求,转发到你在公众平台配置的服务器url地址,微信方将带上signature,timestamp,nonce,echostr四个参数,我们自己服务器通过拼接公众平台配置的token,以及传上来的timestamp,nonce进行sha1加密后匹配signature,返回ture说明接入成功。

消息回复:当用户给公众号发送消息时,微信服务器会将用户消息以xml格式通过post请求到我们配置好的服务器对应的接口,而我们要做的事情就是根据消息类型等做相应的逻辑处理,并将最后的返回结果也通过xml格式return给微信服务器,微信方再传达给用户的这样一个过程。 

1.公众平台配置

2.controller

@controller
@requestmapping("/wechat")
publicclass wechatcontroller {
  @value("${dnbx_token}")
  private string dnbx_token;
  
  private static final logger logger = loggerfactory.getlogger(wechatcontroller.class);
  
  @resource
  wechatservice wechatservice;
  
  /**
   * 微信接入
   * @param wc
   * @return
   * @throws ioexception 
   */
  @requestmapping(value="/connect",method = {requestmethod.get, requestmethod.post})
  @responsebody
  publicvoid connectweixin(httpservletrequest request, httpservletresponse response) throws ioexception{
    // 将请求、响应的编码均设置为utf-8(防止中文乱码) 
    request.setcharacterencoding("utf-8"); //微信服务器post消息时用的是utf-8编码,在接收时也要用同样的编码,否则中文会乱码;
    response.setcharacterencoding("utf-8"); //在响应消息(回复消息给用户)时,也将编码方式设置为utf-8,原理同上;boolean isget = request.getmethod().tolowercase().equals("get"); 
   
    printwriter out = response.getwriter();
     
    try {
      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 (signutil.checksignature(dnbx_token, signature, timestamp, nonce)) { 
          logger.info("connect the weixin server is successful.");
          response.getwriter().write(echostr); 
        } else { 
          logger.error("failed to verify the signature!"); 
        }
      }else{
        string respmessage = "异常消息!";
        
        try {
          respmessage = wechatservice.weixinpost(request);
          out.write(respmessage);
          logger.info("the request completed successfully");
          logger.info("to weixin server "+respmessage);
        } catch (exception e) {
          logger.error("failed to convert the message from weixin!"); 
        }
        
      }
    } catch (exception e) {
      logger.error("connect the weixin server is error.");
    }finally{
      out.close();
    }
  }
}

3.签名验证 checksignature

从上面的controller我们可以看到,我封装了一个工具类signutil,调用了里面的一个叫checksignature,传入了四个值,dnbx_token, signature, timestamp, nonce。这个过程非常重要,其实我们可以理解为将微信传过来的值进行一个加解密的过程,很多大型的项目所有的接口为保证安全性都会有这样一个验证的过程。dnbx_token我们在微信公众平台配置的一个token字符串,主意保密哦!其他三个都是微信服务器发送get请求传过来的参数,我们进行一层sha1加密:

public class signutil { 
 
  /** 
   * 验证签名 
   * 
   * @param token 微信服务器token,在env.properties文件中配置的和在开发者中心配置的必须一致 
   * @param signature 微信服务器传过来sha1加密的证书签名
   * @param timestamp 时间戳
   * @param nonce 随机数 
   * @return 
   */ 
  public static boolean checksignature(string token,string signature, string timestamp, string nonce) { 
    string[] arr = new string[] { token, timestamp, nonce }; 
    // 将token、timestamp、nonce三个参数进行字典序排序 
    arrays.sort(arr); 
    
    // 将三个参数字符串拼接成一个字符串进行sha1加密 
    string tmpstr = sha1.encode(arr[0] + arr[1] + arr[2]); 
    
    // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信 
    return tmpstr != null ? tmpstr.equals(signature.touppercase()) : false; 
  } 
  
}

sha1:

/** 
 * 微信公众平台(java) sdk 
 * 
 * sha1算法
 * 
 * @author helijun 2016/06/15 19:49
 */ 
public final class sha1 { 
 
  private static final char[] hex_digits = {'0', '1', '2', '3', '4', '5', 
              '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 
 
  /** 
   * takes the raw bytes from the digest and formats them correct. 
   * 
   * @param bytes the raw bytes from the digest. 
   * @return the formatted bytes. 
   */ 
  private static string getformattedtext(byte[] bytes) { 
    int len = bytes.length; 
    stringbuilder buf = new stringbuilder(len * 2); 
    // 把密文转换成十六进制的字符串形式 
    for (int j = 0; j < len; j++) { 
      buf.append(hex_digits[(bytes[j] >> 4) & 0x0f]); 
      buf.append(hex_digits[bytes[j] & 0x0f]); 
    } 
    return buf.tostring(); 
  } 
 
  public static string encode(string str) { 
    if (str == null) { 
      return null; 
    } 
    try { 
      messagedigest messagedigest = messagedigest.getinstance("sha1"); 
      messagedigest.update(str.getbytes()); 
      return getformattedtext(messagedigest.digest()); 
    } catch (exception e) { 
      throw new runtimeexception(e); 
    } 
  } 
}

当你在公众平台提交保存,并且看到绿色的提示“接入成功”之后,恭喜你已经完成微信接入。这个过程需要细心一点,注意加密算法里的大小写,如果接入不成功,大多数情况都是加密算法的问题,多检查检查。

4. 实现消息自动回复service

/**
   * 处理微信发来的请求
   * 
   * @param request
   * @return
   */
  public string weixinpost(httpservletrequest request) {
    string respmessage = null;
    try {

      // xml请求解析
      map<string, string> requestmap = messageutil.xmltomap(request);

      // 发送方帐号(open_id)
      string fromusername = requestmap.get("fromusername");
      // 公众帐号
      string tousername = requestmap.get("tousername");
      // 消息类型
      string msgtype = requestmap.get("msgtype");
      // 消息内容
      string content = requestmap.get("content");
      
      logger.info("fromusername is:" + fromusername + ", tousername is:" + tousername + ", msgtype is:" + msgtype);

      // 文本消息
      if (msgtype.equals(messageutil.req_message_type_text)) {
        //这里根据关键字执行相应的逻辑,只有你想不到的,没有做不到的
        if(content.equals("xxx")){
          
        }
        
        //自动回复
        textmessage text = new textmessage();
        text.setcontent("the text is" + content);
        text.settousername(fromusername);
        text.setfromusername(tousername);
        text.setcreatetime(new date().gettime() + "");
        text.setmsgtype(msgtype);
        
        respmessage = messageutil.textmessagetoxml(text);
        
      } /*else if (msgtype.equals(messageutil.req_message_type_event)) {// 事件推送
        string eventtype = requestmap.get("event");// 事件类型
        
        if (eventtype.equals(messageutil.event_type_subscribe)) {// 订阅
          respcontent = "欢迎关注xxx公众号!";
          return messageresponse.gettextmessage(fromusername , tousername , respcontent);
        } else if (eventtype.equals(messageutil.event_type_click)) {// 自定义菜单点击事件
          string eventkey = requestmap.get("eventkey");// 事件key值,与创建自定义菜单时指定的key值对应
          logger.info("eventkey is:" +eventkey);
          return xxx;
        }
      }
      //开启微信声音识别测试 2015-3-30
      else if(msgtype.equals("voice"))
      {
        string recvmessage = requestmap.get("recognition");
        //respcontent = "收到的语音解析结果:"+recvmessage;
        if(recvmessage!=null){
          respcontent = tulingapiprocess.gettulingresult(recvmessage);
        }else{
          respcontent = "您说的太模糊了,能不能重新说下呢?";
        }
        return messageresponse.gettextmessage(fromusername , tousername , respcontent); 
      }
      //拍照功能
      else if(msgtype.equals("pic_sysphoto"))
      {
        
      }
      else
      {
        return messageresponse.gettextmessage(fromusername , tousername , "返回为空"); 
      }*/
      // 事件推送
      else if (msgtype.equals(messageutil.req_message_type_event)) {
        string eventtype = requestmap.get("event");// 事件类型
        // 订阅
        if (eventtype.equals(messageutil.event_type_subscribe)) {
          
          textmessage text = new textmessage();
          text.setcontent("欢迎关注,xxx");
          text.settousername(fromusername);
          text.setfromusername(tousername);
          text.setcreatetime(new date().gettime() + "");
          text.setmsgtype(messageutil.resp_message_type_text);
          
          respmessage = messageutil.textmessagetoxml(text);
        } 
        // todo 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
        else if (eventtype.equals(messageutil.event_type_unsubscribe)) {// 取消订阅
          
          
        } 
        // 自定义菜单点击事件
        else if (eventtype.equals(messageutil.event_type_click)) {
          string eventkey = requestmap.get("eventkey");// 事件key值,与创建自定义菜单时指定的key值对应
          if (eventkey.equals("customer_telephone")) {
            textmessage text = new textmessage();
            text.setcontent("0755-86671980");
            text.settousername(fromusername);
            text.setfromusername(tousername);
            text.setcreatetime(new date().gettime() + "");
            text.setmsgtype(messageutil.resp_message_type_text);
            
            respmessage = messageutil.textmessagetoxml(text);
          }
        }
      }
    }
    catch (exception e) {
      logger.error("error......")
    }
    return respmessage;
  }

先贴代码如上,大多都有注释,读一遍基本语义也懂了不需要多解释。

 有一个地方格外需要注意:

上面标红的fromusername和tousername刚好相反,这也是坑之一,还记得我当时调了很久,明明都没有问题就是不通,最后把这两个一换消息就收到了!其实回过头想也对,返回给微信服务器这时本身角色就变了,所以发送和接收方也肯定是相反的。

5.messageutil

public class messageutil {
  
  /** 
   * 返回消息类型:文本 
   */ 
  public static final string resp_message_type_text = "text"; 
 
  /** 
   * 返回消息类型:音乐 
   */ 
  public static final string resp_message_type_music = "music"; 
 
  /** 
   * 返回消息类型:图文 
   */ 
  public static final string resp_message_type_news = "news"; 
 
  /** 
   * 请求消息类型:文本 
   */ 
  public static final string req_message_type_text = "text"; 
 
  /** 
   * 请求消息类型:图片 
   */ 
  public static final string req_message_type_image = "image"; 
 
  /** 
   * 请求消息类型:链接 
   */ 
  public static final string req_message_type_link = "link"; 
 
  /** 
   * 请求消息类型:地理位置 
   */ 
  public static final string req_message_type_location = "location"; 
 
  /** 
   * 请求消息类型:音频 
   */ 
  public static final string req_message_type_voice = "voice"; 
 
  /** 
   * 请求消息类型:推送 
   */ 
  public static final string req_message_type_event = "event"; 
 
  /** 
   * 事件类型:subscribe(订阅) 
   */ 
  public static final string event_type_subscribe = "subscribe"; 
 
  /** 
   * 事件类型:unsubscribe(取消订阅) 
   */ 
  public static final string event_type_unsubscribe = "unsubscribe"; 
 
  /** 
   * 事件类型:click(自定义菜单点击事件) 
   */ 
  public static final string event_type_click = "click"; 
}

这里为了程序可读性、扩展性更好一点,我做了一些封装,定义了几个常量,以及将微信传过来的一些参数封装成java bean持久化对象,核心代码如上。重点讲下xml和map之间的转换

其实这个问题要归咎于微信是用xml通讯,而我们平时一般是用json,所以可能短时间内会有点不适应

1.引入jar包

<!-- 解析xml -->
    <dependency>
      <groupid>dom4j</groupid>
      <artifactid>dom4j</artifactid>
      <version>1.6.1</version>
    </dependency>
    
    <dependency>
      <groupid>com.thoughtworks.xstream</groupid>
      <artifactid>xstream</artifactid>
      <version>1.4.9</version>
    </dependency>

2.xml转map集合对象

/**
   * xml转换为map
   * @param request
   * @return
   * @throws ioexception
   */
  @suppresswarnings("unchecked")
  public static map<string, string> xmltomap(httpservletrequest request) throws ioexception{
    map<string, string> map = new hashmap<string, string>();
    saxreader reader = new saxreader();
    
    inputstream ins = null;
    try {
      ins = request.getinputstream();
    } catch (ioexception e1) {
      e1.printstacktrace();
    }
    document doc = null;
    try {
      doc = reader.read(ins);
      element root = doc.getrootelement();
      
      list<element> list = root.elements();
      
      for (element e : list) {
        map.put(e.getname(), e.gettext());
      }
      
      return map;
    } catch (documentexception e1) {
      e1.printstacktrace();
    }finally{
      ins.close();
    }
    
    return null;
  }

3.文本消息对象转换成xml

/** 
   * 文本消息对象转换成xml 
   * 
   * @param textmessage 文本消息对象 
   * @return xml 
   */ 
  public static string textmessagetoxml(textmessage textmessage){
    xstream xstream = new xstream();
    xstream.alias("xml", textmessage.getclass());
    return xstream.toxml(textmessage);
  }

到此为止已经大功告成了,这个时候可以在公众号里尝试发送“测试”,你会收到微信回复的“the text is 测试”,这也是上面代码里做的回复处理,当然你也可以发挥你的想象用他做所有你想做的事了,比如回复1查天气,2查违章等等....

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网