微信&java 开发7 js sdk 获取签名 signature

在前面的章节 如果全局缓存了 access_token和 jsapi_ticket的话 这里直接获取

springmvc 中

@RequestMapping(value = "/gotoWtjb")
	public ModelAndView  gotoWtjb(HttpServletRequest request,
            HttpServletResponse response, ModelMap modelMap) {
		Map map=SignatureUtil.get(request);
        modelMap.addAllAttributes(map);
        return new ModelAndView("index",modelMap);
	}

看SignatureUtil.get(request);方法 签名算法请看官方文档

public static Map get(HttpServletRequest request) {
		JsApiTicket jsApiTicket = (JsApiTicket)ServletContextUtil.get().getAttribute(Contants.JSAPI_TICKET);
		if(null != jsApiTicket) {
			String ticket = jsApiTicket.getTicket();
			String url = request.getRequestURL().toString();
			System.out.println(url);
			Map ret = sign(ticket, url);
			ret.put("appId", WeiXinPropUtil.APPID);
			ret.put("doMain", WeiXinPropUtil.WebDomain);
			return ret;
		}
		return null;
	};

public static Map sign(String jsapi_ticket, String url) {
		Map ret = new HashMap();
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str+ "×tamp=" + timestamp + "&url=" + url;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		return ret;
	}

private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}


你可能感兴趣的:(微信公众平台)