投递文章投递文章 投稿指南 RSS订阅RSS订阅

微信js-sdk实现“分享到朋友圈”和“发送给朋友”

来源:未知 IT堂 发布时间:2017-05-24 收藏 投稿 字体:【

微信接口文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN

实现步骤:

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){});

详细页面代码

[html] view plain copy
 
  1. <script>  
  2. //微信分享朋友圈  
  3. $(function(){  
  4.   /***用户点击分享到微信圈后加载接口接口*******/  
  5.     var url=window.location.href.split('#')[0];  
  6.      url = url.replace(/&/g, '%26');  
  7.     console.log("url:"+url);  
  8.     $.ajax({  
  9.         url: "<%=basePath%>/lottery/shareToFriend.action?url="+url,  
  10.         type: "POST",  
  11.         async:true,  
  12.         cache: false,  
  13.         dataType: "json",  
  14.         success: function(data){  
  15.             wx.config({  
  16.               debug: false,  
  17.               appId: 'wx2948dfef9ef421ee',  
  18.               timestamp:data.timeStamp,  
  19.               nonceStr:data.nonceStr,  
  20.               signature:data.signature,  
  21.               jsApiList: [  
  22.                   'checkJsApi',  
  23.                   'onMenuShareTimeline',  
  24.                   'hideOptionMenu',  
  25.                   'onMenuShareAppMessage'  
  26.               ]  
  27.           });  
  28.               
  29.           wx.ready(function(){  
  30.              //wx.hideOptionMenu();/***隐藏分享菜单****/   
  31.              wx.checkJsApi({  
  32.               jsApiList: [  
  33.                 'getLocation',  
  34.                 'onMenuShareTimeline',  
  35.                 'onMenuShareAppMessage'  
  36.               ],  
  37.               success: function (res) {  
  38.                 //alert(res.errMsg);  
  39.               }  
  40.             });  
  41.                
  42.             wx.onMenuShareAppMessage({  
  43.                   title: '刮刮乐',  
  44.                   desc: '刮刮乐开始啦',  
  45.                   link: '<%=basePath%>/lottery/lottery.action?lottery.id=${lottery.id}',  
  46.                   imgUrl: '<%=basePath%>/resources/qjc/img/start.png',  
  47.                   trigger: function (res) {  
  48.                     //alert('用户点击发送给朋友');  
  49.                   },  
  50.                   success: function (res) {  
  51.                     alert('您已获得抽奖机会,赶紧去赢大奖吧~~');  
  52.                     //分享之后增加游戏次数  
  53.                     $.ajax({  
  54.                         url: "<%=basePath%>/lottery/rewardPlayCount.action?openId=${openId}&lotteryId=${lottery.id}&shareType=friend",  
  55.                         type: "POST",  
  56.                         async:true,  
  57.                         cache: false,  
  58.                         dataType: "json",  
  59.                         success: function(data){  
  60.                               
  61.                         }  
  62.                      });  
  63.                   },  
  64.                   cancel: function (res) {  
  65.                     //alert('已取消');  
  66.                   },  
  67.                   fail: function (res) {  
  68.                     alert(res.errMsg);  
  69.                   }  
  70.                });  
  71.               
  72.               // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口  
  73.               wx.onMenuShareTimeline({  
  74.                   title: '刮刮乐',  
  75.                   desc: '刮刮乐开始啦',  
  76.                   link: '<%=basePath%>/lottery/lottery.action?lottery.id=${lottery.id}',  
  77.                   imgUrl: '<%=basePath%>/resources/qjc/img/start.png',  
  78.                   trigger: function (res) {  
  79.                     //alert('用户点击分享到朋友圈');  
  80.                   },  
  81.                   success: function (res) {  
  82.                     alert('您已获得抽奖机会,赶紧去赢大奖吧~~');  
  83.                     //分享之后增加游戏次数  
  84.                     $.ajax({  
  85.                         url: "<%=basePath%>/lottery/rewardPlayCount.action?openId=${openId}&lotteryId=${lottery.id}&shareType=friendCircle",  
  86.                         type: "POST",  
  87.                         async:true,  
  88.                         cache: false,  
  89.                         dataType: "json",  
  90.                         success: function(data){  
  91.                               
  92.                         }  
  93.                      });  
  94.                   },  
  95.                   cancel: function (res) {  
  96.                     //alert('已取消');  
  97.                   },  
  98.                   fail: function (res) {  
  99.                     alert(res.errMsg);  
  100.                   }  
  101.             });  
  102.                
  103.             wx.error(function (res) {  
  104.                    alert(res.errMsg);  
  105.                });  
  106.            });    
  107.         },  
  108.         error: function() {  
  109.             alert('ajax request failed!!!!');  
  110.             return;  
  111.         }   
  112.     });  
  113.   });  
  114.   
  115. </script>  
java后台action代码:

 

 

[java] view plain copy
 
  1. //微信分享  
  2.     public void shareToFriend(){  
  3.         HttpServletRequest request = ServletActionContext.getRequest();  
  4.         String timeStamp = Sha1Util.getTimeStamp();//时间戳  
  5.         String nonceStr = WxConfig.getUUID();//随机字符串,不长于32位  
  6.         String url=request.getParameter("url");  
  7.         String signature = WxConfig.getSignature("APPId""APP_secret", url, timeStamp, nonceStr);  
  8.         request.setAttribute("timeStamp", timeStamp);  
  9.         request.setAttribute("nonceStr", nonceStr);  
  10.         request.setAttribute("url", url);  
  11.         request.setAttribute("signature", signature);  
  12.         WXjssdk result = new WXjssdk(timeStamp,nonceStr,signature,url);  
  13.         CommonUtil.returnMsg(ServletActionContext.getResponse(), new Gson().toJson(result));  
  14.     }  
[java] view plain copy
 
  1. WxConfig.java代码  
[java] view plain copy
 
  1. <pre name="code" class="java">//jsapi_ticket  
  2.     public final static String WEIXIN_JSAPI_TICKET_URL ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";  
  3.       
  4.     //access_token   
  5.     public static String getAccessToken(String appId,String appSecret){  
  6.         String access_token;  
  7.         access_token = mapToken.get("accessToken");  
  8.         if(access_token==null){  
  9.             String url = HttpUtil.WEIXIN_HOST_API + "/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;  
  10.             String menuJsonStr = HttpUtil.get(url);  
  11.             final Type type = new TypeToken<Map<String, Object>>() {}.getType();  
  12.             final Map<Object, Object> accessTokenInfo = new Gson().fromJson(menuJsonStr, type);  
  13.             try{  
  14.                 access_token = accessTokenInfo.get("access_token").toString();  
  15.                 Object expires_in = accessTokenInfo.get("expires_in");  
  16.                 mapToken.put("accessToken", access_token);  
  17.                 logger.info("access_token:"+access_token+";expires_in:"+expires_in);  
  18.             }catch (JSONException e) {  
  19.                 access_token = null;  
  20.                 e.printStackTrace();  
  21.                 logger.error("errcode:{}:"+accessTokenInfo.get("errcode")+"errmsg:{}:"+accessTokenInfo.get("errmsg"));  
  22.             }  
  23.         }  
  24.         return access_token;  
  25.     }  
  26.       
  27.     //jsapi_ticket  
  28.     public static String getJsapiTicket(String accessToken){  
  29.         String ticket;  
  30.         ticket = mapTicket.get("ticket");  
  31.         if(ticket==null){  
  32.             String url = HttpUtil.WEIXIN_HOST_API + "/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";  
  33.             String menuJsonStr = HttpUtil.get(url);  
  34.             final Type type = new TypeToken<Map<String, Object>>() {}.getType();  
  35.             final Map<Object, Object> ticketInfo = new Gson().fromJson(menuJsonStr, type);  
  36.             try{  
  37.                 ticket = ticketInfo.get("ticket").toString();  
  38.                 String expires_in = ticketInfo.get("expires_in").toString();  
  39.                 mapTicket.put("ticket", ticket);  
  40.                 logger.info("jsapi_ticket:"+ticket+";expires_in:"+expires_in);  
  41.             }catch (JSONException e) {  
  42.                 ticket = null;  
  43.                 e.printStackTrace();  
  44.                 logger.error("ticket  errcode:{}:"+ticketInfo.get("errcode")+"errmsg:{}:"+ticketInfo.get("errmsg"));  
  45.             }  
  46.         }  
  47.         return ticket;  
  48.     }  
  49.       
  50.      //生成随机字符串UUID  
  51.     public static String getUUID(){      
  52.           String uuid = UUID.randomUUID().toString().trim().replaceAll("-""");      
  53.           return uuid;      
  54.     }   
  55.       
  56.     //JS-SDK Signature  
  57.     public static String getSignature(String appId,String appSecret,String url,String timeStamp,String nonceStr){  
  58.         String accessToken = getAccessToken(appId,appSecret);  
  59.         String jsapi_ticket = getJsapiTicket(accessToken);  
  60.         logger.info("accessToken==="+accessToken);  
  61.         String signValue = "jsapi_ticket="+jsapi_ticket+"&noncestr="+nonceStr+"×tamp="+timeStamp+"&url="+url;  
  62.         logger.info("微信JS-SDK权限验证的签名串:"+signValue);  
  63.         //这个签名.主要是给加载微信js使用.别和上面的搞混了.  
  64.         String signature = Sha1Util.getSha1((signValue));  
  65.         logger.info("微信JS-SDK权限验证的签名:"+signature);  
  66.         return signature;  
  67.     }  

另外项目用到的
[java] view plain copy
 
  1. Sha1Util.java和MD5Util.java可以直接在平台下载。  

顶一下
(0)
0%
踩一下
(0)
0%
本文Tags: 微信 分享 朋友圈
  • 表情:
  •    
  • 评价:
用户名: 密码: 匿名 注册
最新评论 查看所有评论
About iTtang - 联系我们  - 专题列表 - 友情链接  -  高级搜索  -  帮助中心  -  您的意见