欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信js-sdk+JAVA实现“分享到朋友圈”和“发送给朋友”功能详解

程序员文章站 2023-01-15 08:12:37
主要为以下实现步骤: 1.绑定域名 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“js接口安全域名”。(特别提示不需要加上http或者https,吃过亏)...

主要为以下实现步骤:

1.绑定域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“js接口安全域名”。(特别提示不需要加上http或者https,吃过亏)

2.页面引入js文件

   <script src=">
   <script src=">

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可以直接在平台下载。