導(dǎo)讀微信(WeChat)是騰訊公司于2011年1月21日推出的一個(gè)為智能終端提供即時(shí)通訊服務(wù)的免費(fèi)應(yīng)用程序,由張小龍所帶領(lǐng)的騰訊廣州研發(fā)中心產(chǎn)品團(tuán)隊(duì)打造 [2] 。微信支持跨通信運(yùn)營(yíng)商、跨操作系統(tǒng)平臺(tái)... 微信(WeChat)是騰訊公司于2011年1月21日推出的一個(gè)為智能終端提供即時(shí)通訊服務(wù)的免費(fèi)應(yīng)用程序,由張小龍所帶領(lǐng)的騰訊廣州研發(fā)中心產(chǎn)品團(tuán)隊(duì)打造 [2] 。微信支持跨通信運(yùn)營(yíng)商、跨操作系統(tǒng)平臺(tái)通過網(wǎng)絡(luò)快速發(fā)送免費(fèi)(需消耗少量網(wǎng)絡(luò)流量)語音短信、視頻、圖片和文字,同時(shí),也可以使用通過共享流媒體內(nèi)容的資料和基于位置的社交插件“搖一搖”、“漂流瓶”、“朋友圈”、”公眾平臺(tái)“、”語音記事本“等服務(wù)插件。 本篇文章給大家分享的內(nèi)容是關(guān)于微信自定義分享功能的實(shí)現(xiàn)代碼,內(nèi)容很詳細(xì),有需要的朋友可以參考一下,希望可以幫助到你們.前端時(shí)間,開發(fā)了一個(gè)資訊類的項(xiàng)目,但銷售部門進(jìn)行微信推廣時(shí),分享的鏈接直接是網(wǎng)頁鏈接加分享符號(hào),即難看又不正規(guī),于是研究了一下微信自定義的分享功能 前期準(zhǔn)備工作: 1.認(rèn)證公眾號(hào)的appId,appSecret 2.各種獲取微信信息鏈接(此部分查找微信自定義分享API,地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115) # 獲取access_token請(qǐng)求地址 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 # 獲取用戶基本信息請(qǐng)求地址 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層 /** * 微信配置信息實(shí)體 */ @Autowired private WeiXinProperties weiXinProperties; //微信參數(shù) private String accessToken; private String jsApiTicket; //獲取參數(shù)的時(shí)刻 private Long getTiketTime = 0L; private Long getTokenTime = 0L; //參數(shù)的有效時(shí)間,單位是秒(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) { //當(dāng)前時(shí)間 long now = System.currentTimeMillis(); //判斷accessToken是否已經(jīng)存在或者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的時(shí)間 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是否已經(jīng)存在或者是否過期 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~"); } } //生成微信權(quán)限驗(yàn)證的參數(shù) 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 = JSON.parseObject(result); return jsonObject; } //生成微信權(quán)限驗(yàn)證的參數(shù) 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 = ""; //注意這里參數(shù)名必須全部小寫,且必須有序 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; } /** * 發(fā)送請(qǐng)求 * * @param url * @return * @throws Exception */ String send(String url) { return HttpClientTools.post(url); } //字節(jié)數(shù)組轉(zhuǎn)換為十六進(jìn)制字符串 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; } //生成隨機(jī)字符串 private static String createNonceStr() { return UUID.randomUUID().toString(); } //生成時(shí)間戳 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,////生產(chǎn)環(huán)境需要關(guān)閉debug模式 appId: data.appid,//appId通過微信服務(wù)號(hào)后臺(tái)查看 timestamp: data.timestamp,//生成簽名的時(shí)間戳 nonceStr: data.nonceStr,//生成簽名的隨機(jī)字符串 signature: data.signature,//簽名 jsApiList: [//需要調(diào)用的JS接口列表 'checkJsApi',//判斷當(dāng)前客戶端版本是否支持指定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> <script type="text/javascript" src="/resources/js/share.js"></script> 6.在當(dāng)前頁面<script>中,此部分可以直接寫到share.js中 /*分享代碼*/ wx.ready(function() { // config信息驗(yàn)證后會(huì)執(zhí)行ready方法,所有接口調(diào)用都必須在config接口獲得結(jié)果之后,config是一個(gè)客戶端的異步操作,所以如果需要在頁面加載時(shí)就調(diào)用相關(guān)接口,則須把相關(guān)接口放在ready函數(shù)中調(diào)用來確保正確執(zhí)行。對(duì)于用戶觸發(fā)時(shí)才調(diào)用的接口,則可以直接調(diào)用,不需要放在ready函數(shù)中。 console.log('weixin 驗(yàn)證成功'); // 分享到朋友圈 wx.onMenuShareTimeline({ title: detail_title, // 分享標(biāo)題 link: link, // 分享鏈接,該鏈接域名或路徑必須與當(dāng)前頁面對(duì)應(yīng)的公眾號(hào)JS安全域名一致 imgUrl: 'http://develop.fangxinyuesao.com/resources/images/logo.png', // 分享圖標(biāo) success: function() { // 用戶確認(rèn)分享后執(zhí)行的回調(diào)函數(shù) }, cancel: function() { // 用戶取消分享后執(zhí)行的回調(diào)函數(shù) } }); // 分享給朋友 wx.onMenuShareAppMessage({ title: detail_title, // 分享標(biāo)題 desc: '來自婦幼頭條的分享', // 分享描述 link: link, // 分享鏈接,該鏈接域名或路徑必須與當(dāng)前頁面對(duì)應(yīng)的公眾號(hào)JS安全域名一致 imgUrl: 'http://develop.fangxinyuesao.com/resources/images/logo.png', // 分享圖標(biāo) type: '', // 分享類型,music、video或link,不填默認(rèn)為link dataUrl: '', // 如果type是music或video,則要提供數(shù)據(jù)鏈接,默認(rèn)為空 success: function() { // 用戶確認(rèn)分享后執(zhí)行的回調(diào)函數(shù) }, cancel: function() { // 用戶取消分享后執(zhí)行的回調(diào)函數(shù) } }); }); wx.error(function(res) { // config信息驗(yàn)證失敗會(huì)執(zhí)行error函數(shù),如簽名過期導(dǎo)致驗(yàn)證失敗,具體錯(cuò)誤信息可以打開config的debug模式查看,也可以在返回的res參數(shù)中查看,對(duì)于SPA可以在這里更新簽名。 console.log('weixin 驗(yàn)證失敗'); console.log(res); }); 注意事項(xiàng):分享要設(shè)置網(wǎng)站白名單,電腦端調(diào)試時(shí),推薦使用微信WEB開發(fā)工具 相關(guān)推薦: 以上就是關(guān)于微信自定義分享功能的實(shí)現(xiàn)代碼的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章! 微信提供公眾平臺(tái)、朋友圈、消息推送等功能,用戶可以通過“搖一搖”、“搜索號(hào)碼”、“附近的人”、掃二維碼方式添加好友和關(guān)注公眾平臺(tái),同時(shí)微信將內(nèi)容分享給好友以及將用戶看到的精彩內(nèi)容分享到微信朋友圈。 |
溫馨提示:喜歡本站的話,請(qǐng)收藏一下本站!