第一步:首先登陆官方微信公众平台,选择基本配置界面,如下图:
在这里配置好URL,TOKEN,AppSecert,记住AppID,这四个参数在下一步搭建环境的时候会用的到。
第二步:编写环境搭建测试方法,注意这里会用到SHA1签名,签名工具类我会一并贴出
public static final String token = "weifengchuanmei"; /** * 微信环境搭建检测 * @param signature * @param timestamp * @param nonce * @return */ 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); } /** * SHA1加密工具 * @param str * @return */ 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) { // TODO: handle exception return null; } }
第三步:编写servlet做测试,代码如下:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp){ //测试与微信环境是否搭建成功 String signature = req.getParameter("signature"); String timestamp = req.getParameter("timestamp"); String nonce = req.getParameter("nonce"); String echostr = req.getParameter("echostr"); //保存在session中 req.setAttribute("signature", signature); req.setAttribute("timestamp", timestamp); req.setAttribute("nonce", nonce); req.setAttribute("appid", WeixinUtil.APPID); PrintWriter out; try { out = resp.getWriter(); if(UtilNet.checkSignature(signature, timestamp, nonce)){ out.print(echostr); } out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
这里用到的检查方法就是第二步中的方法
第四步:在web.xml注册该servlet,这里注意写的路径为第一步在微信公众平台中配置的URL
<!-- 配置微信测试Servlet --> <servlet> <servlet-name>weixinServlet</servlet-name> <servlet-class>com.net.servlet.WeixinServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>weixinServlet</servlet-name> <url-pattern>/wx.do</url-pattern> </servlet-mapping>
至此微信公众号与第三方网站的环境搭建就完成了