@Component
@ConfigurationProperties(prefix = "weixin")
@Data
public class WXUnitl {
private String weixinAppId;
private String weixinSecret;
public static WinXinEntity getWinXinEntity(String url) {
WinXinEntity wx = new WinXinEntity();
String access_token = getAccessToken();
String ticket = getTicket(access_token);
Map<String, String> ret = sign(ticket, url);
wx.setTicket(ret.get("jsapi_ticket"));
wx.setSignature(ret.get("signature"));
wx.setNoncestr(ret.get("nonceStr"));
wx.setTimestamp(ret.get("timestamp"));
return wx;
}
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 getTicket(String access_token) {
String ticket = null;
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.parseObject(message);
System.out.println("获取ticket:"+demoJson);
ticket = demoJson.getString("ticket");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ticket:"+ticket);
return ticket;
}
private static String getAccessToken() {
String access_token = "";
String grant_type = "client_credential";
String AppId=weixinAppId;
String secret=weixinSecret;
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes);
JSONObject demoJson = JSONObject.parseObject(message);
System.out.println("获取token:"+demoJson);
access_token = demoJson.getString("access_token");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return access_token;
}
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:"+string1);
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
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 create_nonce_str() {
return UUID.randomUUID().toString();
}
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
@ApiOperation("获取微信签名")
@RequestMapping(value = "/getWxSg", method = RequestMethod.GET)
public Map<String, Object> sgture(HttpServletRequest request) {
String strUrl=request.getParameter("url");
logger.info("===前====url========="+strUrl);
WinXinEntity wx = WXUnitl.getWinXinEntity(strUrl);
Map<String, Object> map = new HashMap<String, Object>();
map.put("signature", wx.getSignature().trim());
map.put("timestamp", wx.getTimestamp().trim());
map.put("noncestr", wx.getNoncestr().trim());
map.put("appId","wxdb3337d1f8618294");
return map;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket-demo</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js" type="text/javascript"></script>
</head>
<body>
<div style="font-size: 100px; background-color: yellow;" onclick="getShareConfig()">
点击开始分享
</div>
</body>
<script type="text/javascript" charset="utf-8">
function getShareConfig() {
$.get("http://www.lifeiyu.icu:9055/video/video/getWxSg", {url: window.location.href}, function (res) {
jWeixin.config({
debug: true,
appId: res.appId,
timestamp: res.timestamp,
nonceStr: res.noncestr,
signature: res.signature,
jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"]
});
jWeixin.showMenuItems({
menuList: ['updateAppMessageShareData', 'updateTimelineShareData']
});
jWeixin.error((err) => {
console.error('Config error:', err);
});
jWeixin.ready(() => {
jWeixin.updateAppMessageShareData({
title: "分享标题",
desc: "分享描述",
link: window.location.href,
imgUrl: "http://www.lifeiyu.icu:9000/video/images/2024/08/03/17226921293788661.jpeg",
success() {
alert("分享给朋友成功");
},
cancel() {
alert("分享给朋友取消");
}
});
});
});
}
</script>
</html>
updateAppMessageShareData 接口仅用于设置分享内容,是不能唤起分享的,目前是只能点击右上角菜单操作分享。