微信公众号JSSDK获取signature签名,史上最全,没有之一
1.操作流程
1、通过appId和appSecret获取access_token;
2、使用access_token获取jsapi_ticket ;
3、用时间戳、随机数、jsapi_ticket和要访问的url按照签名算法拼接字符串;
4、对第三步得到的字符串进行SHA1加密,得到签名。
2.上代码
获取accessToken与jsapi_ticket代码
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* HTTPUtil get方法工具类
*
* @author javaNice
* @time 2023年10月08日
*/
@Slf4j
public class HttpUtils {
// 获取accesstoken
public final static String GetAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
// 获取ticket
public final static String GetTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
/**
* 传递请求url
* @param requestUrl
* @return
*/
public static String sendGet(String requestUrl) {
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(requestUrl);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
//获取返回结果
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
log.error("发送GET请求出现异常e2!" + e2);
e2.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
String appid="你自己的appid";
String secret="你自己的appSecret";
String accessTokenRequestUrl = GetAccessTokenUrl.replace("APPID", appid).replace("SECRET", secret);
//获取accessToken
String accessTokenResult = HttpUtils.sendGet(accessTokenRequestUrl);
JSONObject accessTokenJsonObject = JSON.parseObject(accessTokenResult);
String accessToken = String.valueOf(accessTokenJsonObject.get("access_token"));
System.out.println(accessToken);
String ticketRequestUrl = GetTicketUrl.replace("ACCESS_TOKEN", accessToken);
String ticketResult = HttpUtils.sendGet(ticketRequestUrl);
//获取ticket
JSONObject ticketResultJsonObject = JSON.parseObject(ticketResult);
String ticket = String.valueOf(ticketResultJsonObject.get("ticket"));
System.out.println(ticket);
}
}
加密获取sign代码
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class WxSign {
public static void main(String[] args) {
String jsapi_ticket = "获取到的ticket";
// 注意 URL 一定要动态获取,不能 hardcode
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);
}
}
整个流程官方文档地址
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#8
获取accesstoken官方文档
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
官方校验签名是否正确网址
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
官方获取加密签名代码示例代码包
https://www.weixinsxy.com/jssdk/sample.zip
备注:链接中包含php、java、nodejs以及python的示例代码供第三方参考,第三方切记要对获取的accesstoken以及jsapi_ticket进行缓存以确保不会触发频率限制。
常见错误40164
{"errcode":40164,"errmsg":"invalid ip 122.69.0.54 ipv6 ::ffff:122.69.0.54, not in whitelist rid: 65224c13-74f9b1e4-106f93ca"}
报此错误表示 需要将122.69.0.54 加入到app的白名单中