微信js-sdk+JAVA实现“分享到朋友圈”和“发送给朋友”功能详解
作者:wdc 时间:2021-10-20 23:13:51
主要为以下实现步骤:
1.绑定域名
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。(特别提示不需要加上http或者https,吃过亏)
2.页面引入js文件
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
3.通过config接口注入权限验证配置
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '', // 必填,公众号的唯一标识
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名,见附录1
jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
4.通过ready接口处理成功验证
wx.ready(function(){
//详细代码
});
5.通过error接口处理失败验证
wx.error(function(res){});
详细页面代码
<script>
//微信分享朋友圈
$(function(){
/***用户点击分享到微信圈后加载接口接口*******/
var url=window.location.href.split('#')[0];
url = url.replace(/&/g, '%26');
console.log("url:"+url);
$.ajax({
url: "<%=basePath%>/lottery/shareToFriend.action?url="+url,
type: "POST",
async:true,
cache: false,
dataType: "json",
success: function(data){
wx.config({
debug: false,
appId: 'wx2948dfef9ef421ee',
timestamp:data.timeStamp,
nonceStr:data.nonceStr,
signature:data.signature,
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'hideOptionMenu',
'onMenuShareAppMessage'
]
});
wx.ready(function(){
//wx.hideOptionMenu();/***隐藏分享菜单****/
wx.checkJsApi({
jsApiList: [
'getLocation',
'onMenuShareTimeline',
'onMenuShareAppMessage'
],
success: function (res) {
//alert(res.errMsg);
}
});
wx.onMenuShareAppMessage({
title: '刮刮乐',
desc: '刮刮乐开始啦',
link: '<%=basePath%>/lottery/lottery.action?lottery.id=${lottery.id}',
imgUrl: '<%=basePath%>/resources/qjc/img/start.png',
trigger: function (res) {
//alert('用户点击发送给朋友');
},
success: function (res) {
alert('您已获得抽奖机会,赶紧去赢大奖吧~~');
//分享之后增加游戏次数
$.ajax({
url: "<%=basePath%>/lottery/rewardPlayCount.action?openId=${openId}&lotteryId=${lottery.id}&shareType=friend",
type: "POST",
async:true,
cache: false,
dataType: "json",
success: function(data){
}
});
},
cancel: function (res) {
//alert('已取消');
},
fail: function (res) {
alert(res.errMsg);
}
});
// 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
wx.onMenuShareTimeline({
title: '刮刮乐',
desc: '刮刮乐开始啦',
link: '<%=basePath%>/lottery/lottery.action?lottery.id=${lottery.id}',
imgUrl: '<%=basePath%>/resources/qjc/img/start.png',
trigger: function (res) {
//alert('用户点击分享到朋友圈');
},
success: function (res) {
alert('您已获得抽奖机会,赶紧去赢大奖吧~~');
//分享之后增加游戏次数
$.ajax({
url: "<%=basePath%>/lottery/rewardPlayCount.action?openId=${openId}&lotteryId=${lottery.id}&shareType=friendCircle",
type: "POST",
async:true,
cache: false,
dataType: "json",
success: function(data){
}
});
},
cancel: function (res) {
//alert('已取消');
},
fail: function (res) {
alert(res.errMsg);
}
});
wx.error(function (res) {
alert(res.errMsg);
});
});
},
error: function() {
alert('ajax request failed!!!!');
return;
}
});
});
</script>
java后台action代码:
//微信分享
public void shareToFriend(){
HttpServletRequest request = ServletActionContext.getRequest();
String timeStamp = Sha1Util.getTimeStamp();//时间戳
String nonceStr = WxConfig.getUUID();//随机字符串,不长于32位
String url=request.getParameter("url");
String signature = WxConfig.getSignature("APPId", "APP_secret", url, timeStamp, nonceStr);
request.setAttribute("timeStamp", timeStamp);
request.setAttribute("nonceStr", nonceStr);
request.setAttribute("url", url);
request.setAttribute("signature", signature);
WXjssdk result = new WXjssdk(timeStamp,nonceStr,signature,url);
CommonUtil.returnMsg(ServletActionContext.getResponse(), new Gson().toJson(result));
}
WxConfig.java代码
">//jsapi_ticket
public final static String WEIXIN_JSAPI_TICKET_URL ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
//access_token
public static String getAccessToken(String appId,String appSecret){
String access_token;
access_token = mapToken.get("accessToken");
if(access_token==null){
String url = HttpUtil.WEIXIN_HOST_API + "/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
String menuJsonStr = HttpUtil.get(url);
final Type type = new TypeToken<Map<String, Object>>() {}.getType();
final Map<Object, Object> accessTokenInfo = new Gson().fromJson(menuJsonStr, type);
try{
access_token = accessTokenInfo.get("access_token").toString();
Object expires_in = accessTokenInfo.get("expires_in");
mapToken.put("accessToken", access_token);
logger.info("access_token:"+access_token+";expires_in:"+expires_in);
}catch (JSONException e) {
access_token = null;
e.printStackTrace();
logger.error("errcode:{}:"+accessTokenInfo.get("errcode")+"errmsg:{}:"+accessTokenInfo.get("errmsg"));
}
}
return access_token;
}
//jsapi_ticket
public static String getJsapiTicket(String accessToken){
String ticket;
ticket = mapTicket.get("ticket");
if(ticket==null){
String url = HttpUtil.WEIXIN_HOST_API + "/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
String menuJsonStr = HttpUtil.get(url);
final Type type = new TypeToken<Map<String, Object>>() {}.getType();
final Map<Object, Object> ticketInfo = new Gson().fromJson(menuJsonStr, type);
try{
ticket = ticketInfo.get("ticket").toString();
String expires_in = ticketInfo.get("expires_in").toString();
mapTicket.put("ticket", ticket);
logger.info("jsapi_ticket:"+ticket+";expires_in:"+expires_in);
}catch (JSONException e) {
ticket = null;
e.printStackTrace();
logger.error("ticket errcode:{}:"+ticketInfo.get("errcode")+"errmsg:{}:"+ticketInfo.get("errmsg"));
}
}
return ticket;
}
//生成随机字符串UUID
public static String getUUID(){
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
//JS-SDK Signature
public static String getSignature(String appId,String appSecret,String url,String timeStamp,String nonceStr){
String accessToken = getAccessToken(appId,appSecret);
String jsapi_ticket = getJsapiTicket(accessToken);
logger.info("accessToken==="+accessToken);
String signValue = "jsapi_ticket="+jsapi_ticket+"&noncestr="+nonceStr+"×tamp="+timeStamp+"&url="+url;
logger.info("微信JS-SDK权限验证的签名串:"+signValue);
//这个签名.主要是给加载微信js使用.别和上面的搞混了.
String signature = Sha1Util.getSha1((signValue));
logger.info("微信JS-SDK权限验证的签名:"+signature);
return signature;
}
另外项目用到的Sha1Util.java和MD5Util.java可以直接在平台下载。
标签:微信,js-sdk
0
投稿
猜你喜欢
Spring boot配置文件加解密详解
2023-11-12 00:17:29
详解jvm对象的创建和分配
2022-01-27 13:39:41
利用C语言实现一个最简单的飞机游戏
2022-12-11 15:17:22
Android之沉浸式状态栏的实现方法、状态栏透明
2022-01-02 17:49:21
C#泛型约束的深入理解
2023-02-21 09:32:19
java加载properties文件的六种方法总结
2023-09-20 05:24:54
浅谈Android View绘制三大流程探索及常见问题
2022-03-02 00:01:26
Android如何判断一个点在不在多边形区域内
2023-07-06 14:06:13
Java深入浅出掌握SpringBoot之MVC自动配置原理篇
2022-04-16 02:14:34
Android编程中File文件常见存储与读取操作demo示例
2021-11-24 18:33:20
Android TextView控件文字添加下划线的实现方法
2022-03-11 06:01:43
Android 将网络的Url资源转换为Drawable资源方式
2023-06-23 03:06:19
Java设计模式中的桥接模式
2023-11-10 08:42:25
利用Kotlin Tools如何快速添加Kotlin依赖详解
2021-06-24 05:43:52
Spring Security基于散列加密方案实现自动登录功能
2022-09-19 01:10:22
关于C#连接SQL Server时提示用户登录失败的解决方法
2021-10-03 21:21:58
Seata AT模式TM处理流程图文示例详解
2022-05-03 02:28:39
C#实现XML与实体类之间相互转换的方法(序列化与反序列化)
2022-05-14 03:39:32
深入浅析Spring 的aop实现原理
2023-01-10 00:00:10
Java封装的实现访问限定符、包
2023-03-20 07:08:48