1. 程式人生 > >微信開放實戰--掃一掃功能(詳細)

微信開放實戰--掃一掃功能(詳細)

public static Map<String, String> sign(String url) { String appId="wxcc42f613dbf7299f"; String appSecret="e59e10c74c70b1c042b5ecaf454052ac"; String access_token=getTokenTool(appId, appSecret).getString("access_token"); JSONObject ticketJson=getTicketTool(access_token); System.out.println(ticketJson.toString()); String jsapi_ticket = ticketJson.getString("ticket"); Map<String, String> ret = new HashMap<String, String>(); //這裡的jsapi_ticket是獲取的jsapi_ticket。 String nonce_str = create_nonce_str(); String timestamp = create_timestamp(); String string1; String signature = ""; System.out.println(2); //注意這裡引數名必須全部小寫,且必須有序 string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url; try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(string1.getBytes("UTF-8")); signature = byteToHex(crypt.digest()); System.out.println("crypt="+crypt.toString()); System.out.println("string1="+string1); System.out.println("signature="+signature); } 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); }