使用demo签名代码,客户端最终还是返回签名失败,示例代码如下,返回结果如图片,谢谢。
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
imort java.io.UnsupportedEncodingException;
class Sign {
public static void main(String[] args) {
String jsapi_ticket = "jsapi_ticket";
String url = "http://example.com";
Map<String, String> ret = sign(jsapi_ticket, url);
for (Map.Entry entry : ret.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
};
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();
String timestamp = create_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());
}
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);
}
}
我也用java demo代码,没问题,这是咋回事呢
难道是前端写法有问题?请指教,谢谢。getJsSignature 方法是调用后端Java签名的方法
var url = window.location.origin + '/';
getJsSignature({url}).then(res => {
var signature = res.data;
this.setShare(signature);
});
感谢再次回复,个人感觉java代码大概率没有问题,如下步骤:
1、AccessToken 通过地址 https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s 正常获取到了
2、Ticket 通过地址 https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi 正常获取到了
3、getJsSignature 简单到不能再简单了,其中 SHA1Util.sign 就是上面的示例代码,一摸一样
public SignatureInfo getJsSignature(String url) throws IOException {
JSONObject jsonObject = getJsapiTicket();
Map<String, String> map = SHA1Util.sign(jsonObject.get("ticket").toString(), url);
SignatureInfo signatureInfo = new SignatureInfo();
signatureInfo.setNoncestr(map.getOrDefault("nonceStr", ""));
signatureInfo.setTimestamp(map.getOrDefault("timestamp", ""));
signatureInfo.setSignature(map.getOrDefault("signature", ""));
signatureInfo.setTicket(map.getOrDefault("jsapi_ticket", ""));
return signatureInfo;
}