前端時間,開發了一個資訊類的項目,但銷售部門進行微信推廣時,分享的連接直接是網頁連接加分享符號,即難看又不正規,因而研究了一下微信自定義的分享功能javascript
未配置自義定分享時,分享的頁面:前端
成功配置後: java
前期準備工做:ajax
1.認證公衆號的appId,appSecretjson
2.各類獲取微信信息連接,封裝在配置文件裏(此部分查找微信自定義分享API,地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115)api
# 獲取access_token請求地址 getAccessTokenUrl: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s #獲取accessToken getAccessTokenOAuthUrl: https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code # 獲取用戶基本信息請求地址 getUserInfoUrl: https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN #獲取code getCodeUrl: https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=%s&scope=%s&state=%s#wechat_redirect #獲取ticket getTicketUrl: https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi
3.controller層數組
/** * 微信配置信息實體 */ @Autowired private WeiXinProperties weiXinProperties; //微信參數 private String accessToken; private String jsApiTicket; //獲取參數的時刻 private Long getTiketTime = 0L; private Long getTokenTime = 0L; //參數的有效時間,單位是秒(s) private Long tokenExpireTime = 0L; private Long ticketExpireTime = 0L; /** * 微信自定義分享 */ @RequestMapping(value = "/getShareInfo", method = RequestMethod.POST) public Map<String, String> getShareInfo(HttpServletRequest request, HttpServletResponse response, String url) { //當前時間 long now = System.currentTimeMillis(); //判斷accessToken是否已經存在或者token是否過時 if (StringUtils.isBlank(accessToken) || (now - getTokenTime > tokenExpireTime * 1000)) { JSONObject tokenInfo = getAccessToken(); if (tokenInfo != null) { accessToken = tokenInfo.getString("access_token"); tokenExpireTime = tokenInfo.getLongValue("expires_in"); //獲取token的時間 getTokenTime = System.currentTimeMillis(); log.info("accessToken====>" + accessToken); log.info("tokenExpireTime====>" + tokenExpireTime + "s"); log.info("getTokenTime====>" + getTokenTime + "ms"); } else { log.info("====>tokenInfo is null~"); log.info("====>failure of getting tokenInfo,please do some check~"); } } //判斷jsApiTicket是否已經存在或者是否過時 if (StringUtils.isBlank(jsApiTicket) || (now - getTiketTime > ticketExpireTime * 1000)) { JSONObject ticketInfo = getJsApiTicket(accessToken); if (ticketInfo != null) { log.info("ticketInfo====>" + ticketInfo.toJSONString()); jsApiTicket = ticketInfo.getString("ticket"); ticketExpireTime = ticketInfo.getLongValue("expires_in"); getTiketTime = System.currentTimeMillis(); log.info("jsApiTicket====>" + jsApiTicket); log.info("ticketExpireTime====>" + ticketExpireTime + "s"); log.info("getTiketTime====>" + getTiketTime + "ms"); } else { log.info("====>ticketInfo is null~"); log.info("====>failure of getting tokenInfo,please do some check~"); } } //生成微信權限驗證的參數 Map<String, String> wechatParam = makeWXTicket(jsApiTicket, url); return wechatParam; } //獲取accessToken private JSONObject getAccessToken() { //String accessTokenUrl = https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET //獲取微信端的accessToken String requestUrl = String.format(weiXinProperties.getGetAccessTokenUrl(), weiXinProperties.getAppId(), weiXinProperties.getAppSecret()); String result = send(requestUrl); JSONObject jsonObject = JSON.parseObject(result); return jsonObject; } //獲取ticket private JSONObject getJsApiTicket(String access_token) { //String apiTicketUrl = https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi // 經過acessToken 獲取ticket String requestUrl = String.format(weiXinProperties.getGetTicketUrl(), access_token); String result = send(requestUrl); //此部分用到了咱們項目的工具類,整段複製本代碼時,能夠用如下代替
//JSONObject jsonObject = httpUtils.doGet(requestUrl) JSONObject jsonObject = JSON.parseObject(result); return jsonObject; } //生成微信權限驗證的參數 public Map<String, String> makeWXTicket(String jsApiTicket, String url) { Map<String, String> ret = new HashMap<String, String>(); String nonceStr = createNonceStr(); String timestamp = createTimestamp(); String string1; String signature = ""; //注意這裏參數名必須所有小寫,且必須有序 string1 = "jsapi_ticket=" + jsApiTicket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url; log.info("String1=====>" + string1); try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(string1.getBytes("UTF-8")); signature = byteToHex(crypt.digest()); log.info("signature=====>" + signature); } catch (NoSuchAlgorithmException e) { log.error("WeChatController.makeWXTicket=====Start"); log.error(e.getMessage(), e); log.error("WeChatController.makeWXTicket=====End"); } catch (UnsupportedEncodingException e) { log.error("WeChatController.makeWXTicket=====Start"); log.error(e.getMessage(), e); log.error("WeChatController.makeWXTicket=====End"); } ret.put("url", url); ret.put("jsapi_ticket", jsApiTicket); ret.put("nonceStr", nonceStr); ret.put("timestamp", timestamp); ret.put("signature", signature); ret.put("appid", weiXinProperties.getAppId()); return ret; } /** * 發送請求 * * @param url * @return * @throws Exception */ String send(String url) { return HttpClientTools.post(url); } //字節數組轉換爲十六進制字符串 private static String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; } //生成隨機字符串 private static String createNonceStr() { return UUID.randomUUID().toString(); } //生成時間戳 private static String createTimestamp() { return Long.toString(System.currentTimeMillis() / 1000); }
4.引入share.js.要分享的頁面安全
$(function(){ var url = location.href.split('#').toString();//url不能寫死 $.ajax({ type : "post", url : "/user/login/getShareInfo", dataType : "json", async : false, data:{url:url}, success : function(data) { wx.config({ debug: false,////生產環境須要關閉debug模式 appId: data.appid,//appId經過微信服務號後臺查看 timestamp: data.timestamp,//生成簽名的時間戳 nonceStr: data.nonceStr,//生成簽名的隨機字符串 signature: data.signature,//簽名 jsApiList: [//須要調用的JS接口列表 'checkJsApi',//判斷當前客戶端版本是否支持指定JS接口 'onMenuShareTimeline',//分享給好友 'onMenuShareAppMessage'//分享到朋友圈 ] }); }, error: function(xhr, status, error) { //alert(status); //alert(xhr.responseText); } }) });
5.在要分享的頁面中引入,微信分享的核心js和share.js微信
<script type="text/javascript" src="/resources/js/jweixin-1.2.0.js"></script>app
<script type="text/javascript" src="/resources/js/share.js"></script>
6.在當前頁面<script>中,此部分能夠直接寫到share.js中
/*分享代碼*/ wx.ready(function() { // config信息驗證後會執行ready方法,全部接口調用都必須在config接口得到結果以後,config是一個客戶端的異步操做,因此若是須要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則能夠直接調用,不須要放在ready函數中。 console.log('weixin 驗證成功'); // 分享到朋友圈 wx.onMenuShareTimeline({ title: detail_title, // 分享標題 link: link, // 分享連接,該連接域名或路徑必須與當前頁面對應的公衆號JS安全域名一致 imgUrl: 'http://develop.fangxinyuesao.com/resources/images/logo.png', // 分享圖標 success: function() { // 用戶確認分享後執行的回調函數 }, cancel: function() { // 用戶取消分享後執行的回調函數 } }); // 分享給朋友 wx.onMenuShareAppMessage({ title: detail_title, // 分享標題 desc: '來自婦幼頭條的分享', // 分享描述 link: link, // 分享連接,該連接域名或路徑必須與當前頁面對應的公衆號JS安全域名一致 imgUrl: 'http://develop.fangxinyuesao.com/resources/images/logo.png', // 分享圖標 type: '', // 分享類型,music、video或link,不填默認爲link dataUrl: '', // 若是type是music或video,則要提供數據連接,默認爲空 success: function() { // 用戶確認分享後執行的回調函數 }, cancel: function() { // 用戶取消分享後執行的回調函數 } }); }); wx.error(function(res) { // config信息驗證失敗會執行error函數,如簽名過時致使驗證失敗,具體錯誤信息能夠打開config的debug模式查看,也能夠在返回的res參數中查看,對於SPA能夠在這裏更新簽名。 console.log('weixin 驗證失敗'); console.log(res); });
注意事項:分享要設置網站白名單,電腦端調試時,推薦使用微信WEB開發工具