WeChat js-sdk + JAVA implements the "share to friends" and "send to friends" functions, and js-sdk sends to friends

Source: Internet
Author: User
Tags openid

Js-sdk + JAVA implements the "share to friends" and "send to friends" functions, and js-sdk sends to friends

Follow these steps:

1. Bind a domain name

Log on to the public platform and go to "function Settings" of "public account settings" and enter "JS interface security domain name ". (Especially if you do not need to add http or https, you have suffered a loss)

2. Introduce js files to 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 the permission verification configuration through the config Interface

Wx. config ({debug: true, // enable the debugging mode. The returned values of all called APIs are displayed in the client alert. To view the input parameters, you can open them on the pc, the parameter information is output through log and printed only on the pc end. AppId: '', // required. The unique identifier timestamp:, // required. The timestamp of the generated signature is nonceStr:''. // required, sign the random string signature: '', // required. For details, see Appendix 1 jsApiList: [] // required. List of JS interfaces to be used, for a list of all JS interfaces, see Appendix 2 });

4. Verify the processing by using the ready interface

Wx. ready (function () {// detailed code });

5. Handle failure verification through the error Interface

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

Detailed Page code

<Script> // share the circle of friends $ (function () {/*** the user clicks share to the Circle and loads the interface ******/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 ();/*** hide the sharing menu ***/wx. checkJsApi ({jsA PiList: ['getlocation', 'onmenusharetimeline ', 'onmenushareappmessage'], success: function (res) {// alert (res. errMsg) ;}}); wx. onMenuShareAppMessage ({title: 'scratch ', desc: 'scratch start', link:' <% = basePath %>/lottery. action? Lottery. id =$ {lottery. id} ', imgUrl:' <% = basePath %>/resources/qjc/img/start.png ', trigger: function (res) {// alert ('user click to send to friends');}, success: function (res) {alert ~~ '); // Increase the number of games after sharing $. 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 ('canceled ') ;}, fail: function (res) {alert (res. errMsg) ;}}); // 2.2 listen to the "share to circle of friends" button, and customize the sharing content and the sharing result interface wx. onMenuShareTimeline ({title: 'scratch ', desc: 'scratch start', link:' <% = basePath %>/lottery. action? Lottery. id =$ {lottery. id} ', imgUrl:' <% = basePath %>/resources/qjc/img/start.png ', trigger: function (res) {// alert ('user click to share with your friends') ;}, success: function (res) {alert ~~ '); // Increase the number of games after sharing $. 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 ('canceled ') ;}, fail: function (res) {alert (res. errMsg) ;}}); wx. error (function (res) {alert (res. errMsg) ;}) ;}, error: function () {alert ('ajax request failed !!!! '); Return ;}}) ;}); </script>

Java background action code:

// Share public void shareToFriend () {HttpServletRequest request = ServletActionContext. getRequest (); String timeStamp = Sha1Util. getTimeStamp (); // timestamp String nonceStr = WxConfig. getUUID (); // random String, no longer than 32-Bit 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 code

"> // 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 ("access Token ", 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 accesen en) {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 ;}// generate a random String 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 ("signature string for JS-SDK permission verification:" + signValue); // this signature. it is mainly used for loading js. don't confuse with the above. string signature = Sha1Util. getSha1 (signValue); logger.info ("signature for JS-SDK permission verification:" + signature); return signature ;}

In addition, Sha1Util. java and MD5Util. java used in the project can be downloaded directly from the platform.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.