在使用企业微信中,如果需要接收到企业微信用户发送的消息或者监测通讯录是否发生改动时,就需要用到企业微信的回调模式。
回调模式接口地址:https://work.weixin.qq.com/api/doc/90000/90135/90930
调用回调模式需要事先准备一台有固定公网IP或者域名指向的服务器,这台服务器用于后面接收企业微信下发的各种数据。
第一步 创建应用
第二步 设置API配置
这边的参数说明:
URL为回调的服务器地址可以使用公网IP或者域名,要加上项目名称
Token用于计算签名可以自己设定也可以随机生成
EncodingAESKey用于消息内容加密同样可以自己设定或随机生成
将三个参数设置好,先不要点击保存,点击保存时企业微信就会下发验证消息,验证不成功会提示失败。
第三步 编写服务器端代码
企业微信提供了用于url验证的加解密库
大家可以根据自己的语言选择对应库,我这边使用的是Java
将加解密库文件放到自己项目里
回调模式首先会验证url有效性,这边企业微信会向之前填写的url发送一条xml信息,里面包含四个参数
验证步骤一共四步
解密验证的代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.Token;
import common.xml.XMLDeal;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import wwapi.WXDoMessage;
import wxutil.AesException;
import wxutil.WXBizMsgCrypt;
/**
* Servlet implementation class GetMassage
*/
@WebServlet("/GetUrlVerify")
public class GetUrlVerify extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetUrlVerify() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String msg_signature = request.getParameter("msg_signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
System.out.println("msg_signature:" + msg_signature);
System.out.println("timestamp:" + timestamp);
System.out.println("nonce:" + nonce);
System.out.println("echostr:" + echostr);
WXBizMsgCrypt wxmc;
try {
//解密
//corpid:wwcb74a7*******,Token:5N****,EncodingAESKey:48wJVcsQlHedUeiESoJMpWy*****************
wxmc = new WXBizMsgCrypt("5N****", "48wJVcsQlHedUeiESoJMpWy*****************", "wwcb74a7*******");
String newechostr = wxmc.VerifyURL(msg_signature, timestamp, nonce, echostr);
System.out.println(newechostr);
//返回明文
PrintWriter writer = response.getWriter();
writer.println(newechostr);
} catch (AesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
将项目放到服务器上运行,再配置页面点击保存
验证成功后,回调模式就可以开始使用了
更多腾讯接口开发可以关注本人微信公众号查看