最近接触到微信公众号开发,在此记录一下。
由于微信公众号开发需要一个公众号来帮助我们进行测试,而注册公众号有太过麻烦,且功能过于简单,还好微信提供了供开发人员使用的测试号。
用微信扫一扫即可登陆
登陆后页面为
URL就是你的服务器地址,这里为了开发方便,我选择外网映射工具,这样可以随时的测试我的公众号,Sunny-Ngrok,可自行百度搜索使用方法。Token是你自定义的一个字符串。
填写URL,Token后,微信服务器会通过get请求访问你的URL。
我们在本地服务器上写URL的处理信息,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下图所示。
获取参数进行分析,将token、timestamp、nonce三个参数进行字典序排序然后将三个参数字符串拼接成一个字符串进行sha1加密 ,开发者获得加密后的字符串可与signature对比,相同就返回echostr随机字符串。
package Server; import java.io.IOException; 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 Tools.CheckUtil; /** * Servlet implementation class Text */ @WebServlet("/Text") public class Text extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Text() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(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"); PrintWriter out = response.getWriter(); if(CheckUtil.checkSignature(signature, timestamp, nonce)){ out.print(echostr); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
检查字符串的类
package Tools; import java.security.MessageDigest; import java.util.Arrays; public class CheckUtil { private static final String token = "hometao"; 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]); } //sha1加密 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; } } }
点击提交,测试成功!!
注意token值和代码中的token值一定要相同。