Wechat JS SDK implementation sharing to the circle of friends

Wechat interface document address: https://mp.weixin.qq.com/wiki? T = resource / res ˊ main & id = mp1421141115 & token = & lang = zh cn

Implementation steps:

1. Bind domain name

First login WeChat public platform into the "official account settings" function settings to fill in the "JS interface security domain name". (special tips: you don't need to add http or https. You have suffered losses)

2. Import js file into the page

   <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. Inject permission to verify configuration through config interface

wx.config({

debug: true, / / turn on the debugging mode. The return values of all the APIs you call will come out in the client alert. To view the parameters passed in, you can turn them on on the pc side. The parameter information will be printed out through the log, and will only be printed on the pc side.

appId: '/ / / required, official account number only identifier.

Timestamp:, / / required, generate signature timestamp

nonceStr: '', / / required, generate random string of signature

Signature: '', / / required, signature, see Appendix 1

jsApiList: [] / / required. Please refer to Appendix 2 for the list of JS interfaces to be used

});

4. Successful verification through the ready interface processing

   wx.ready(function(){

/ / detailed code

});

Handling failed validation through the error interface

wx.error(function(res){});

Detailed page code

  1. <script>  
  2. //Wechat sharing circle of friends
  3. $(function(){  
  4.   /***User clicks to share to wechat circle and then loads interface interface*******/  
  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(); / * * * hide sharing menu
  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: 'Squeegee',  
  44.                   desc: 'Scratch is on',  
  45.                   link: '<%=basePath%>/lottery/lottery.action?lottery.id=${lottery.id}',  
  46.                   imgUrl: '<%=basePath%>/resources/qjc/img/start.png',  
  47.                   trigger: function (res) {  
  48.                     //alert('users Click to send to friends')
  49.                   },  
  50.                   success: function (res) {  
  51.                     alert('You've got the chance to draw. Hurry to win the prize~~');  
  52.                     //Increase the number of games after sharing
  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('cancelled ')
  66.                   },  
  67.                   fail: function (res) {  
  68.                     alert(res.errMsg);  
  69.                   }  
  70.                });  
  71.               
  72.               //2.2 monitor the "share to friends" button click, customize the share content and share result interface
  73.               wx.onMenuShareTimeline({  
  74.                   title: 'Squeegee',  
  75.                   desc: 'Scratch is on',  
  76.                   link: '<%=basePath%>/lottery/lottery.action?lottery.id=${lottery.id}',  
  77.                   imgUrl: '<%=basePath%>/resources/qjc/img/start.png',  
  78.                   trigger: function (res) {  
  79.                     //alert('users Click to share to their friends circle ')
  80.                   },  
  81.                   success: function (res) {  
  82.                     alert('You've got the chance to draw. Hurry to win the prize~~');  
  83.                     //Increase the number of games after sharing
  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('cancelled ')
  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 background action code:

  1. //Wechat sharing  
  2.     public void shareToFriend(){  
  3.         HttpServletRequest request = ServletActionContext.getRequest();  
  4.         String timeStamp = Sha1Util.getTimeStamp();//time stamp  
  5.         String nonceStr = WxConfig.getUUID();//Random string, no longer than 32 bits  
  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.     }  
  1. WxConfig.java code
  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.      //Generate random string 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("WeChat JS-SDK Signature string for permission validation:"+signValue);  
  63.         //This signature is mainly used to load wechat js. Don't confuse it with the above one  
  64.         String signature = Sha1Util.getSha1((signValue));  
  65.         logger.info("WeChat JS-SDK Signature for permission validation:"+signature);  
  66.         return signature;  
  67.     }  

Other projects
  1. Sha1Util.java and MD5Util.java can be downloaded directly from the platform.   

Keywords: Java JSON SDK

Added by phpusers on Fri, 01 May 2020 10:04:40 +0300