java 代码
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 获取签名算法
*/
public void jsapiTicket(){
String url = getPara("url");
Map<Object,Object> map = new HashMap<>();
HttpServletRequest request = getRequest();
Cookie[] cookies = request.getCookies();
boolean flag = true;
String access_token = "";
//如果cookie 不等于空
System.out.println("11111111111111111111111111111");
if(null!=cookies){
//先判断cookie中的access_token 过期没有
for( int i=0; i<cookies.length; i++ ) {
Cookie cookie = cookies[i];
System.out.println( "Cookie name:"+cookie.getName() );
System.out.println( "Cookie value:"+cookie.getValue() );
System.out.println( "Max Age: "+cookie.getMaxAge()+"<br>" );
if(cookie.getName().equals("access_token")) {
flag = false;
access_token = cookie.getValue();
}
}
}
System.out.println("33333333333333333333333333");
String body = "";
HttpClientUtil httpClientUtil = new HttpClientUtil();
System.out.println("4444444444444444444444444444");
//如果过期了就重新获取access_token
if(flag){
//获取access_token
body = HttpKit.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret);
System.out.println(body);
JSONObject jsonObject = JSONObject.fromObject(body);
System.out.println(jsonObject.containsKey("access_token"));
if(jsonObject.containsKey("access_token")){
access_token = jsonObject.getString("access_token");
System.out.println(access_token);
Cookie cookie = new Cookie("access_token", access_token);
cookie.setMaxAge(7200);
}else{
map.put("msg", "获取失败");
map.put("code", 0);
renderJson(map);
return;
}
}
//获取到jsapi_ticket 并返回
String doGet = HttpKit.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi");
System.out.println(doGet);
JSONObject jsonObject = JSONObject.fromObject(doGet);
if(jsonObject.containsKey("ticket")){
String jsapi_ticket = jsonObject.getString("ticket");
Record record = new Record();
//jsapi_ticket
record.set("jsapi_ticket", jsapi_ticket);
//appId
record.set("appId", appId);
//时间戳
long timestamp = System.currentTimeMillis() / 1000;
record.set("timestamp", timestamp);
//随机字符串
String nonceStr = UUID.randomUUID().toString();
record.set("nonceStr", nonceStr);
String signature = "jsapi_ticket="+jsapi_ticket+"&noncestr="+nonceStr+"×tamp="+timestamp+"&url="+url;
System.out.println("22222222222222222222222222222222");
signature = encode(signature);
//签名
record.set("signature", signature);
record.set("url", url);
map.put("msg", "获取成功");
map.put("code", 1);
map.put("data", record);
}else{
map.put("msg", "获取失败");
map.put("code", 0);
}
renderJson(map);
}
/**
* 首字母排序
*/
public static void sortStringArray() {
String[] arrayToSort = new String[] { "jsapi_ticket", "appId", "timestamp",
"nonceStr", "url"};
System.out.println();
System.out.println("字符型数组排序,排序前:");
for (int i = 0; i < arrayToSort.length; i++){
System.out.print(arrayToSort[i]+",");
}
System.out.println();
System.out.println("排序后:");
// 调用数组的静态排序方法sort,且不区分大小写
Arrays.sort(arrayToSort,String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < arrayToSort.length; i++){
System.out.print(arrayToSort[i]+"=&");
}
}
public static String encode(String string1) {
String signature = "";
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();
}
return signature;
}
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;
}
js 代码
var imgUrl = 'http://xxx'; // 分享后展示的一张图片
var lineLink = 'http://xxx'; // 点击分享后跳转的页面地址
var descContent = "描述信息描述信息描述信息描述信息描述信息描述信息"; // 分享后的描述信息
var shareTitle = '标题标题标题标题'; // 分享后的标题
var appid = ''; // 应用id,如果有可以填,没有就留空
$(function(){
$.ajax({
type:"POST",
dataType:"json",
data:{"url":window.location.href},
url:"${base}/jsapiTicket",
success:function(res){
//通过config接口注入权限验证配置
var data = res.data;
console.log(res);
if(res.code==1){
wx.config({
debug: false,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。移动端会通过弹窗来提示相关信息。如果分享信息配置不正确的话,可以开了看对应报错信息
appId: data.appId,
timestamp: data.timestamp,
nonceStr: data.nonceStr,
signature: data.signature,
jsApiList: [//需要使用的JS接口列表,分享默认这几个,如果有其他的功能比如图片上传之类的,需要添加对应api进来
'updateAppMessageShareData',//
'updateTimelineShareData',
'checkJsApi'
]
});
wx.checkJsApi({
jsApiList: ['updateAppMessageShareData','updateAppMessageShareData'], // 需要检测的JS接口列表,所有JS接口列表见附录2,
success: function(res) {
console.log(res);
}
});
wx.ready(function () {
wx.updateAppMessageShareData({
title: shareTitle, // 分享标题
desc: descContent, // 分享描述
link: lineLink, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: imgUrl, // 分享图标
success: function () {
// 设置成功
}
})
wx.updateTimelineShareData({
title: shareTitle, // 分享标题
link: lineLink, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: imgUrl, // 分享图标
success: function () {
// 设置成功
}
})
});
wx.error(function(res) {
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
alert('error');
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.readyState);
console.log(textStatus);
}
});
});