1.绑定域名
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“js接口安全域名”。(特别提示不需要加上http或者https,吃过亏)
2.设置白名单
3.前端:
//引用js
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
//若是分享的是https的,则引入:
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
var title = "";//分享标题
var desc = "";//分享描述
var link = window.location.href;//分享链接
var imgUrl = "";//图片图标的路径
$(document).ready(function() {
var urls = window.location.href;
$.ajax({
type:"POST",
url:"${mobilePath}/yikang/ContentController/wxshare?urls="+urls,
success:function(data){
wx.config({
debug: false, //调试模式,需要调试就改成true
appId: data.appId,// 必填,公众号的唯一标识
timestamp:data.timestamp,// 必填,生成签名的时间戳
nonceStr:data.noncestr,// 必填,生成签名的随机串
signature:data.signature,// 必填,签名
jsApiList: [// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage'
]
});
}
});
});
wx.ready(function () {
wx.onMenuShareTimeline({
title: title, // 分享标题
desc: desc, // 分享描述
link: link, // 分享链接
imgUrl: imgUrl, // 分享图标
success: function () {
// 用户确认分享后执行的回调函数
console.log("test");
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
wx.onMenuShareAppMessage({
title: title, // 分享标题
desc: desc, // 分享描述
link: link, // 分享链接
imgUrl: imgUrl, // 分享图标
//type: '', // 分享类型,music、video或link,不填默认为link
//dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
success: function () {
// 用户确认分享后执行的回调函数
console.log("test");
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
});
</script>
4.后台:
@RequestMapping(value = "wxshare")
@ResponseBody
public Map<String, String> wxshare(HttpServletRequest request, HttpServletResponse response, Model model) {
String urls = request.getParameter("urls"); //获取签名页面的链接
System.out.println(urls);
String timestamp = (String)CacheUtils.get("FrontWeixin.timestamp");
String jsapiTicket=(String)CacheUtils.get("FrontWeixin.jsapiTicket");
if( timestamp == null || (System.currentTimeMillis()-Long.parseLong(timestamp)) >= 7100*1000 )
{
//1. 获取Accesstoken
String accessToken="";
accessToken= getAccessToken();
System.out.println("accessToken=========="+accessToken);
// 2、获取Ticket
jsapiTicket = getTicket(accessToken);
System.out.println("jsapiTicket========="+jsapiTicket);
CacheUtils.put("FrontWeixin.accessToken",accessToken);
CacheUtils.put("FrontWeixin.timestamp",Long.toString(System.currentTimeMillis()));
CacheUtils.put("FrontWeixin.jsapiTicket",jsapiTicket);
System.out.println("propertyRepair.accessToken ===================重新获取accesstoken:" + accessToken);
}
String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);// 随机字符串
timestamp = String.valueOf(System.currentTimeMillis() / 1000);// 时间戳
String str = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + urls;
// 6、将字符串进行sha1加密
String signature = SHA1(str);
System.out.println("propertyRepair.jsapiTicket ===================" + jsapiTicket);
System.out.println("propertyRepair.noncestr ===================" + noncestr);
System.out.println("propertyRepair.timestamp ===================" + timestamp);
System.out.println("propertyRepair.signature ===================" + signature);
String appId = "";
Map<String,String> map = new HashMap<String,String>();
map.put("appId", appId);
map.put("jsapiTicket", jsapiTicket);
map.put("noncestr", noncestr);
map.put("timestamp", timestamp);
map.put("signature", signature);
return map;
}
//加密
public static String SHA1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取access_token
*
* @return
*/
public static String getAccessToken() {
String access_token = "";
String grant_type = "client_credential";// 获取access_token填写client_credential
String AppId = "";// 第三方用户唯一凭证
String secret = "";// 第三方用户唯一凭证密钥,即appsecret
// 这个url链接地址和参数皆不能变
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"); // 必须是get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
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("getAccessToken------------------JSON字符串:" + demoJson);
access_token = demoJson.getString("access_token");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return access_token;
}
/**
* 获取jsapi_ticket
*
* @param access_token
* @return
*/
public 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";// 这个url链接和参数不能变
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
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("getTicket--------====-------JSON字符串:" + demoJson);
ticket = demoJson.getString("ticket");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return ticket;
}
到此为止就可以了,下面是效果图