第二篇 微信开发者接入

参考接入指南:http://mp.weixin.qq.com/wiki/17/2d4265491f12608cd170a95559800f2d.html

登录微信公众平台官网后,在公众平台后台管理页面 - 开发者中心页,点击“修改配置”按钮,填写服务器地址(URL)、Token和EncodingAESKey,其中URL是开发者用来接收微信消息和事件的接口URL。Token可由开发者可以任意填写,用作生成签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性)。EncodingAESKey由开发者手动填写或随机生成,将用作消息体加解密密钥。

同时,开发者可选择消息加解密方式:明文模式、兼容模式和安全模式。模式的选择与服务器配置在提交后都会立即生效,请开发者谨慎填写及选择。加解密方式的默认状态为明文模式,选择兼容模式和安全模式需要提前配置好相关加解密代码,详情请参考消息体签名及加解密部分的文档。 


第二篇 微信开发者接入_第1张图片
 这里主要是一个url配置,丢与Java来说可以配置一个servlet如下:

1.在web.xml中

 <servlet>
    <servlet-name>WeChatCoreServlet</servlet-name>
    <servlet-class>com.ll.wechart.WeChatCoreServlet</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>WeChatCoreServlet</servlet-name>
     <url-pattern>/WeChatCoreServlet</url-pattern>
  </servlet-mapping>

2.配置一个servlet  WeChatCoreServlet.java

 

package com.ll.wechart;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ll.tools.pubfun.PubFun;
import com.ll.wechart.bean.WechartBackMessageBean;
import com.ll.wechart.bean.WechartMessageBean;
import com.ll.wechart.util.BackWeChartFunction;
import com.ll.wechart.util.GetWeChartFunction;

/**
 * 微信核心请求处理类 -接入请求
 *
 * @author liuli
 *
 */
public class WeChatCoreServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 private Log log = LogFactory.getLog(this.getClass().getName());
 private String Token = "liuli472732787";
 private String echostr;
 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
  connect(request, response);
 }
 
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
  message(request, response);
 }

 /***
  * <p>接入链接生效验证</p>
  */
 private void connect(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
  log.info("RemoteAddr: "+request.getRemoteAddr());
  log.info("QueryString: "+request.getQueryString());
  if(!accessing(request, response)){
   log.info("服务器接入失败....");
   return;
  }
  String echostr = getEchostr();
  if(!"".equals(echostr) && echostr != null ){
   log.info("服务器接入成功....");
   response.getWriter().print(echostr);//完成相互认证
  }
 }
 /***
  * <p>用来接收微信公共平台的验证</p>
  */
 protected boolean accessing(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
  String signature = request.getParameter("signature");
  String timestamp = request.getParameter("timestamp");
  String nonce = request.getParameter("nonce");
  String echostr = request.getParameter("echostr");
  /*System.out.println("==signature=="+signature);
  System.out.println("==timestamp=="+timestamp);
  System.out.println("==nonce=="+nonce);
  System.out.println("==echostr=="+echostr);
  System.out.println("==Token=="+Token);*/
  if(isEmpty(signature)){
   return false;
  }
  if(isEmpty(timestamp)){
   return false;
  }
  if(isEmpty(nonce)){
   return false;
  }
  if(isEmpty(echostr)){
   return false;
  }
  String[] ArrTmp = { Token, timestamp, nonce};
  Arrays.sort(ArrTmp);
  StringBuffer sb = new StringBuffer();
  for(int i = 0;i < ArrTmp.length;i++){
   sb.append(ArrTmp[i]);
  }
  String pwd = Encrypt(sb.toString()); 
  if(trim(pwd).equals(trim(signature))){
   this.echostr = echostr;
   return true;
  }else{
   return false;
  }
 }

 private String Encrypt(String strSrc) {
  MessageDigest md = null;
  String strDes = null; 
  byte[] bt = strSrc.getBytes();
  try{
   md = MessageDigest.getInstance("SHA-1");
   md.update(bt);
   strDes = bytes2Hex(md.digest());// to HexString
  } catch(NoSuchAlgorithmException e){
   log.error(e);
   return null;
  }
  return strDes;
 }

 private String bytes2Hex(byte[] bts) {
  String dec = "";
  String tmp = null;
  for(int i=0;i<bts.length;i++){
   tmp = Integer.toHexString(bts[i] & 0xFF);
   if(tmp.length() ==1){
    dec +="0";
   }
   dec += tmp;
  }
  return dec;
 }
 public String getEchostr() {
  return echostr;
 }
 /***
  * <p>获取用户发送方的消息</p>
  */
 private void message(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
  InputStream is = request.getInputStream();
  int size = request.getContentLength();
  byte[] buffer = new byte[size];
  byte[] xmldataByte = new byte[size];
  int count = 0;
  int rbyte = 0;
  while(count<size){
   rbyte = is.read(buffer);
   for(int i=0;i<rbyte;i++){
    xmldataByte[count+i] = buffer[i];
   }
   count += rbyte;
  }
  is.close();
  String requestStr = new String(xmldataByte, "UTF-8");
  GetWeChartFunction mGetWeChartFunction = new GetWeChartFunction();
  WechartMessageBean mWechartMessageBean= mGetWeChartFunction.getMessgeUtil(requestStr);
     log.info("====="+requestStr);
  log.info("消息类型:"+mWechartMessageBean.getMsgType());
  String responseStr = "Hello!";//默认返回消息
  try {
   responseStr = getBackMsg(mWechartMessageBean);    
   OutputStream os = response.getOutputStream();
   os.write(responseStr.getBytes("UTF-8"));
  } catch (Exception e) {
   OutputStream os = response.getOutputStream();
   os.write(responseStr.getBytes("UTF-8"));
  }
 }

/**
 * 返回给用户的信息
 * @param mWechartMessageBean
 * @return
 */
 private String getBackMsg(WechartMessageBean mWechartMessageBean) {
  BackWeChartFunction mBackWeChartFunction = new BackWeChartFunction();
  WechartBackMessageBean mWechartBackMessageBean = new WechartBackMessageBean();
  String responseStr = "";//默认返回消息
  String type =mWechartMessageBean.getMsgType();
   if ("event".equals(type)) {//事件消息  subscribe(订阅)、unsubscribe(取消订阅)
    log.info("Event:"+type +"||EventKey:"+mWechartMessageBean.getEventKey());
    String mEvent = mWechartMessageBean.getEvent();
    if ("subscribe".equals(mEvent)) {
     mWechartBackMessageBean.setContent("欢迎关注:QYXXHSYB 有事找我请留言!");  
     log.info("有用户关注我了 哈哈 !");
   }else  if ("unsubscribe".equals(mEvent)) {
     mWechartBackMessageBean.setContent("Goodbye by !!!"); 
     log.info("用户取消关注我了 郁闷!");
   }else{
    mWechartBackMessageBean.setContent("欢迎关注:QYXXHSYB  By liuli");      
   }
  }else if ("text".equals(type)) {
   mWechartBackMessageBean.setContent("感谢你的留言 /:gift"+PubFun.getCurrentDateTime()+" By liuli !");   
  }else{
   mWechartBackMessageBean.setContent("Sorry 你发送的消息类型:"+type+" 请文本消息!");
  }
  responseStr = mBackWeChartFunction.backText(mWechartMessageBean, mWechartBackMessageBean);
  return responseStr;
 }

 @Override
 public void init() throws ServletException {
  Token = "liuli472732787";
 }
 private boolean isEmpty(String str){
  return null == str || "".equals(str)? true:false;
 }
 private String trim(String str){
  return null != str? str.trim():str;
 }
}

之后启动配置,关注微信公众号:


第二篇 微信开发者接入_第2张图片
 


第二篇 微信开发者接入_第3张图片
 

你可能感兴趣的:(微信开发)