微信公众号开发(开发模式-Java)
环境搭建
- 微信公众号申请步骤
https://kf.qq.com/faq/120911VrYVrA151009eIrYvy.html- 微信公众号与后台调通
java后台搭建
1.创建Dynamic Web Project
2.创建类WechatServlet继承HttpServlet
//主要重写doGet方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr");
PrintWriter out = resp.getWriter();
if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
}
//工具类CheckUtil
//定义TOKEN 此处命名随意(后续会用到,一致即可)
private static final String TOKEN = "miya";
public static Boolean checkSignature(String signature, String timestamp, String nonce) {
String array[] = new String[] {TOKEN, timestamp, nonce };
//排序
Arrays.sort(array);
//生成字符串
StringBuffer content = new StringBuffer();
for (int i=0;i<array.length;i++) {
content.append(array[i]);
}
//sha1加密
String tempStr = getSha1(content.toString());
//返回比较结果
return tempStr.equals(signature);
}
public static String getSha1(String str){
if(str==null||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) {
return null;
}
}
web.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="false" version="3.0">
<display-name>
wechat
</display-name>
<servlet>
<servlet-name>wechatServlet</servlet-name>
<servlet-class>com.miya.wechat.base.WechatServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>wechatServlet</servlet-name>
<url-pattern>/wechat.do</url-pattern>
/* 名称随意,后续一致即可*/
</servlet-mapping>
</web-app>
项目结构:
uploading-image-431716.png
现在即可运行项目。
- 配置微信公众平台开发模式配置
服务器地址:
若本地测试则 ip+端口号+项目名称+url
url的配置实在web.xml里面的(名称可随意)
uploading-image-950650.png
- 下载内网穿刺工具
有很多,我用的是ngork
同样访问成功