原创

关于微信分享的注意事项

注意自定义分享时,获取url必须是动态的,如果不是,签名正确的情况下,前端在使用签名后的参数时也会报签名错误,具体看代码

public Map<String, String> share(String url) throws Exception {
url = URLDecoder.decode(url, "UTF-8");
String accessToken = getToken().get("access_token");
String jsapi_ticket = getTicket("https://api.weixin.qq.com/cgi-bin/ticket/getticket",accessToken);//jsapi_ticket
Map<String, String> map = sign(jsapi_ticket, url);
return map;
}
public static Map<String, String> sign(String jsapi_ticket, String url) {
Map<String, String> ret = new HashMap<String, String>();
String nonce_str = create_nonce_str();
System.out.println("随机字符串===="+nonce_str);
String timestamp = create_timestamp();
System.out.println("时间戳===="+timestamp);
String string1;
String signature = "";

//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
System.out.println(string1);

try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
System.out.println("最后签名为===="+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);
}


正文到此结束