环境搭建
实现内网穿透
如果腾讯服务器需要访问本地电脑,需要用本机运行穿透软件,
步骤1:在www.ngrok.cc官网注册一个自己的隧道
步骤2:ngrok客户端
步骤3:在客户端打开 Sunny-Ngrok启动工具.bat 这个文件
2.申请微信测试号以获得更多接口权限
步骤1:打开https://mp.weixin.qq.com/
步骤2:点开服务号,点开开发者文档
步骤3:开始开发,接口测试号申请
注意:申请成功之后,需要扫描测试号二维码进行测试和开发,
步骤4:填写接口配置信息:
URL:Ngrok给的URl地址
Token:自定义,需要和程序后台一致
步骤5:编写后台程序:
@WebServlet(urlPatterns = "/wx")
public class WxServlet extends HttpServlet {
@Override
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");
if (WxService.check(timestamp,nonce,signature)){
System.out.println("接入成功");
PrintWriter out = resp.getWriter();
out.print(echostr);
out.flush();
out.close();
}else{
System.out.println("接入失败");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("psot");
}
}
public class WxService {
private final static String TOKEN = "token";
public static boolean check(String timestamp,String nonce,String signature){
String[] strs = new String[] {TOKEN,timestamp,nonce};
System.out.println("字典排序之前:"+strs.toString());
Arrays.sort(strs);
System.out.println("字典排序之后:"+strs.toString());
String str = strs[0]+strs[1]+strs[2];
System.out.println("拼成得到字符串:"+str);
String mysig = sha1(str);
System.out.println("mysig:"+mysig);
System.out.println("signature:"+signature);
return mysig.equals(signature);
}
private static String sha1(String str) {
try {
MessageDigest md = MessageDigest.getInstance("sha1");
byte[] digest = md.digest(str.getBytes());
char[] chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
StringBuilder sb = new StringBuilder();
for (byte b : digest){
sb.append(chars[(b>>4)&15]);
sb.append(chars[b&15]);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
}