最近在搞小程序和微信公众号开发。 这章介绍token验证。公众号接入
废话不多说。
工具
1.需要一个公众号 私人订阅号 就行。
2.成为开发者
3.ngrok 这个主要用来 调试 作用是把你的内网 映射到公网中 使用方法本文会介绍。简单。
4.开发工具 我这eclispe
一.框架搭建。
这是项目结构图
需要注意的地方是 WxBbotApplication 在项目中位置尽量比你的controller级别包的位置 外层。
这样才能起作用。
其他的不注重介绍
我的是springboot , 都行
只要项目能运行就好!!(可以先用hello world 测试)
二.接下来我们来配置 与公众号关联的一步!!(就2个类)
public class WexinController {
@RequestMapping(value="/wexin" ,method=RequestMethod.GET)
protected void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get方法主要处理公众号接入部分
String signature=request.getParameter("signature");
String timestamp=request.getParameter("timestamp");
String nonce=request.getParameter("nonce");
String echostr=request.getParameter("echostr");
PrintWriter pWriter=response.getWriter();
if(CheckUtil.checkSignature(signature, timestamp, nonce)) {
pWriter.print(echostr);
pWriter.close();
}
}
@RequestMapping(value="/wexin" ,method=RequestMethod.POST)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//post方法 主要处理 一切消息的地方
比如文本消息 这个后面讲
}
}
public class CheckUtil {
public static final String token="weixin"; //这个记住
public static boolean checkSignature(String signature,String timestamp,String nonce) {
//根据微信的规则验证 是否接入成功
String[] arr=new String[] {token, timestamp,nonce};
Arrays.sort(arr);
StringBuffer content= new StringBuffer();
for(int i=0;i<arr.length;i++) {
content.append(arr[i]);
}
String temp=getSha1(content.toString());//加密
return temp.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;
}
}
}
好了。有了上面2个类。
看得出来 我只要访问localhost:8080/wexin
就可以访问我的get方法了。 准备关联公众号了
但是!!!微信访问不到。他只能访问公网的东西。所以。ngrok
来了。把我们的80放到公网上去。
- 去官网下载
- 用命令启动。(cd 到目标位置 运行 ngrok HTTP 8080)回车!
这样就启动成功了!! 上面的 http://6d29fb13.ngrok.io
就是 我的localhost:80
(我启动的是80)
自己可以测试下 能不能用 (hello world)
三. 关联
注意:weixin 是我的checkUtil
里面的那个token
需要一致!
然后提交 出现提交成功 就ok!!
到这步 意思是
微信的这个验证接口 调用的是你提供的 get 方法。
然后 根据一些信息或者规则(微信自己定义的规则 开发文档有) 返回一串东西。
他识别了,那就成功了。