微信分享相關的能夠查看相關的微信文檔,這裏給出個人代碼,能夠參考。javascript
首先微信有默認的分享,他分享的是當前頁面。html
可是有不少微信web,不管哪一個頁面分享的都是同一個連接,這個,就須要代碼實現前端
首先,須要ticket,ticket是分享必須的一個參數,可是獲取他,就必須先要獲取tocken,這裏給出代碼。java
//獲取tocken
public void getAccessToken() { String urlNameString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + WalletUtils.GRANT_TYPE + "&appid=" + WalletUtils.APPID + "&secret=" + WalletUtils.SECRET; //微信的url String str = sendGet(urlNameString); // get請求 JSONObject json = JSONObject.parseObject(str);// 返回值封裝 String access_token = String.valueOf(json.get("access_token")); if (access_token != null) { try { memcachedClient.set("ACCESS_TOKEN", 0, access_token); //我這裏吧tockne放到了memcached裏了,大家能夠自行存儲 log.info("memcached存儲的數據爲:" + access_token); String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi"; getTicket(url); } catch (Exception e) { log.info("memcachedClient獲取數據異常" + e); throw new BusinessException("memcachedClient獲取數據異常"); } }else{ String errcode = String.valueOf(json.get("errcode")); if(errcode!=null){ log.info("獲取access_token錯誤,錯誤碼爲:"+errcode); throw new BusinessException("獲取access_token錯誤"); }else{ log.info("訪問微信接口無響應"); throw new BusinessException("訪問微信接口無響應"); } } } //同上,只不過,這個須要tocken來獲取ticket,這裏一樣放到memcached裏 public void getTicket(String url){ String jsonstr = sendGet(url); JSONObject json = JSONObject.parseObject(jsonstr); String ticket = String.valueOf(json.get("ticket")); if (ticket != null) { try { memcachedClient.set("TICKET", 0, ticket); log.info("memcached存儲的數據爲:" + ticket); } catch (Exception e) { log.info("memcachedClient獲取數據異常" + e); throw new BusinessException("memcachedClient獲取數據異常"); } }else{ log.info("獲取ticket錯誤,錯誤碼爲:"); throw new BusinessException("獲取ticket錯誤"); } } public String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打開和URL之間的鏈接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 創建實際的鏈接 connection.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { log.info("發送Get請求異常:"+e); throw new BusinessException("發送Get請求異常"); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { log.info("關閉流異常:"+e2); throw new BusinessException("關閉流異常"); } } return result; }
以上,我放到了定時任務裏,由於tocken和ticket的有效期爲7200秒,重複獲取可能引發衝突,因此我這是一個專門跑批的任務。jquery
一下是分享的前端部分web
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html lang="zh-CN"> <script type="text/javascript" src="./js/jweixin-1.0.0.js"></script> <script type="text/javascript" src="./js/jquery-1.7.2.min.js"></script> <script type="text/javascript"> var title = ''; var desc = ''; var imgUrl = ''; var link = ''; wx.ready(function(){ wx.onMenuShareAppMessage({ title: title, // 分享標題 desc: desc,// 分享描述 link: link,// 分享連接 imgUrl: imgUrl }); wx.onMenuShareTimeline({ title: title, // 分享標題 link: link,// 分享連接 imgUrl: imgUrl }); wx.onMenuShareQQ({ title: title, // 分享標題 desc: desc, // 分享描述 link: link, // 分享連接 imgUrl: imgUrl }); wx.onMenuShareWeibo({ title: title, // 分享標題 desc: desc, // 分享描述 link: link, // 分享連接 imgUrl: imgUrl }); wx.onMenuShareQZone({ title: title, // 分享標題 desc: desc, // 分享描述 link: link, imgUrl: imgUrl }); }); $(document).ready(function(){ var url = window.location.href; $.ajax({ url:'<%=basePath%>rest/walletFxController/fxIndex',// 跳轉到 action data : { url : url }, type : 'get', dataType : 'json', success : function(data) { var obj = eval(data); title = obj.title; desc = obj.desc; imgUrl = '<%=basePath%>'+obj.imgUrl; link = obj.link; wx.config({ debug: false, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。 appId: obj.appId, // 必填,公衆號的惟一標識 timestamp: obj.timestamp, // 必填,生成簽名的時間戳 nonceStr: obj.nonceStr, // 必填,生成簽名的隨機串 signature: obj.signature,// 必填,簽名,見附錄1 jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填,須要使用的JS接口列表,全部JS接口列表見附錄2 }); } }); }); </script> <head> <meta charset="UTF-8"> <body> <h1>404</h1> </body> </html>
我這裏試了下,不能放在includ裏和js文件裏,只能直接放在jsp,你們能夠本身測試下。ajax
下面是java部分。json
@Controller @RequestMapping("/walletFxController") public class WalletFxController { @Autowired private MemcachedClient memcachedClient; @RequestMapping("/fxIndex") public void fxIndex(HttpServletRequest request,HttpServletResponse response){ String ticket = ""; try { ticket = memcachedClient.get("TICKET"); } catch (Exception e) { e.printStackTrace(); } String strBackUrl = request.getParameter("url"); String time = WeixinUtil.getTimestamp(); String noncestr = WeixinUtil.getNoncestr(12); // String signature = WeixinUtil.Getsignature(strBackUrl,"wxa916d2eaf629ac6c", "d4624c36b6795d1d99dcf0547af5443d",noncestr,time, ticket); String signature = WeixinUtil.getSignature(strBackUrl,noncestr,time,ticket); Map<String,Object> map = new HashMap<String, Object>(); map.put("appId", WeiXinConfig.APPID); map.put("link", strBackUrl); map.put("title", WeiXinConfig.TITLE); map.put("desc", WeiXinConfig.DESC); map.put("imgUrl", WeiXinConfig.IMGURL); // map.put("appId", "wxa916d2eaf629ac6c"); map.put("timestamp", time); map.put("nonceStr", noncestr); map.put("signature", signature); String json = JSONObject.fromObject(map).toString(); try { PrintWriter pw = response.getWriter(); pw.write(json); pw.flush(); pw.close(); } catch (IOException e) { e.printStackTrace(); } } }
微信要求的參數有:api
分享url,這裏我只是簡單的用js獲取了下當前的。數組
隨機字符串:能夠混合數字,貌似是不長於32爲
時間戳:1970年到如今的秒數,注意:不是毫秒
ticket:剛纔有獲取。
他要求,把這些參數按照ACSII排序並組合,再進行SHA1加密。
能夠查看代碼。
/** * 生成singature,須要把全部參數ACSII排序後,用SHA1加密 * @param strBackUrl 請求的url * @param noncestr 隨機字符串 * @param time 時間戳 * @param ticket 從微信官方請求來的參數 * @return */ public static String getSignature(String strBackUrl, String noncestr, String time, String ticket) { String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "×tamp=" + time + "&url=" + strBackUrl; System.out.println("url:"+str); String singature = getSHA1(str); System.out.println("singature:"+singature); String ss = singature; return ss; }
/** * SHA1加密 * @param decript * @return */ public static String getSHA1(String decript) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(decript.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); // 字節數組轉換爲 十六進制 數 for (int i = 0; i < messageDigest.length; i++) { String shaHex = Integer.toHexString(messageDigest[i] & 0xFF); if (shaHex.length() < 2) { hexString.append(0); } hexString.append(shaHex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
public static String getTimestamp(){ Date date = new Date(); return date.getTime()/1000+""; } public static String getNoncestr(int length){ String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); }
測試這個須要耐心,微信官方有提供各類測試工具,能夠測試。
須要配置js安全域名,這個不能加http,二級域名須要把第一個點前面都去掉。