前端Js引用:javascript
1 <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> 2 <script type="text/javascript"> 3 var data = '<%=JsApiirray %>'; 4 data = eval("(" + data + ")");//實例化 5 wxconfig(data); 6 </script> 7 <script> 8 function wxconfig(data) { 9 wx.config({ 10 // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。 11 debug: false, 12 // 必填,公衆號的惟一標識 13 appId: data.appId, 14 // 必填,生成簽名的時間戳 15 timestamp: data.timestamp, 16 // 必填,生成簽名的隨機串 17 nonceStr: data.nonceStr, 18 // 必填,簽名 19 signature: data.signature, 20 // 必填,須要使用的JS接口列表 21 jsApiList: [ 22 'checkJsApi', 23 'onMenuShareTimeline', 24 'onMenuShareAppMessage', 25 'onMenuShareQQ', 26 'onMenuShareWeibo' 27 ] 28 }); 29 } 30 // config信息驗證後會執行ready方法,全部接口調用都必須在config接口得到結果以後,config是一個客戶端的異步操做,因此若是須要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則能夠直接調用,不須要放在ready函數中。 31 wx.ready(function () { 32 wx.checkJsApi({ 33 jsApiList: [ 34 'onMenuShareTimeline', 35 'onMenuShareAppMessage', 36 'onMenuShareQQ', 37 'onMenuShareWeibo' 38 ] 39 }); 40 var title = "上海長寬神遊戲「神龜不掉線」,千萬別小看它!"; 41 var des = "我玩過了上海長寬的遊戲神做「神龜不掉線」,真的比想象中更難,你快來試試並領取電影紅包吧!"; 42 wx.onMenuShareTimeline({ 43 title: title, //分享標題 44 link: 'http://m.gwbnsh.net.cn/sgbdx/', //分享連接 45 desc: des, //分享描述 46 imgUrl: 'http://m.gwbnsh.net.cn/sgbdx/img/logo.png',//分享圖片地址 47 trigger: function (res) { 48 //alert('用戶點擊分享到朋友圈'); 49 }, 50 success: function (res) { 51 $.ajax({ 52 type: "POST", 53 url: "User.ashx", //處理頁的相對地址 54 data: { isshare: 1 }, 55 async: true, 56 success: function (data) { 57 location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF"; 58 } 59 }); 60 }, 61 cancel: function (res) { 62 //alert('已取消'); 63 } 64 }); 65 wx.onMenuShareAppMessage({ 66 title: title, //分享標題 67 link: 'http://m.gwbnsh.net.cn/sgbdx/', //分享連接 68 desc: des, //分享描述 69 imgUrl: 'http://m.gwbnsh.net.cn/sgbdx/img/logo.png',//分享圖片地址 70 trigger: function (res) { 71 //alert('用戶點擊分享到朋友圈'); 72 }, 73 success: function (res) { 74 $.ajax({ 75 type: "POST", 76 url: "User.ashx", //處理頁的相對地址 77 data: { isshare: 1 }, 78 async: true, 79 success: function (data) { 80 location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF"; 81 } 82 }); 83 }, 84 cancel: function (res) { 85 //alert('已取消'); 86 } 87 }); 88 wx.onMenuShareQQ({ 89 title: title, //分享標題 90 link: 'http://m.gwbnsh.net.cn/sgbdx/', //分享連接 91 desc: des, //分享描述 92 imgUrl: 'http://m.gwbnsh.net.cn/sgbdx/img/logo.png',//分享圖片地址 93 trigger: function (res) { 94 //alert('用戶點擊分享到朋友圈'); 95 }, 96 success: function (res) { 97 $.ajax({ 98 type: "POST", 99 url: "User.ashx", //處理頁的相對地址 100 data: { isshare: 1 }, 101 async: true, 102 success: function (data) { 103 location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF"; 104 } 105 }); 106 }, 107 cancel: function (res) { 108 //alert('已取消'); 109 } 110 }); 111 wx.onMenuShareQZone({ 112 title: title, //分享標題 113 link: 'http://m.gwbnsh.net.cn/sgbdx/', //分享連接 114 desc: des, //分享描述 115 imgUrl: 'http://m.gwbnsh.net.cn/sgbdx/img/logo.png',//分享圖片地址 116 trigger: function (res) { 117 //alert('用戶點擊分享到朋友圈'); 118 }, 119 success: function (res) { 120 $.ajax({ 121 type: "POST", 122 url: "User.ashx", //處理頁的相對地址 123 data: { isshare: 1 }, 124 async: true, 125 success: function (data) { 126 location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF"; 127 } 128 }); 129 }, 130 cancel: function (res) { 131 //alert('已取消'); 132 } 133 }); 134 wx.error(function (res) { 135 // config信息驗證失敗會執行error函數,如簽名過時致使驗證失敗,具體錯誤信息能夠打開config的debug模式查看,也能夠在返回的res參數中查看,對於SPA能夠在這裏更新簽名。 136 alert("errorMSG:" + res); 137 }); 138 }); 139 </script>
或者html
1 <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> 2 <script type="text/javascript"> 3 var data = '<%=JsApiirray %>'; 4 data = eval("(" + data + ")");//實例化 5 wxconfig(data); 6 </script> 7 <script> 8 function wxconfig(data) { 9 wx.config({ 10 // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。 11 debug: false, 12 // 必填,公衆號的惟一標識 13 appId: data.appId, 14 // 必填,生成簽名的時間戳 15 timestamp: data.timestamp, 16 // 必填,生成簽名的隨機串 17 nonceStr: data.nonceStr, 18 // 必填,簽名 19 signature: data.signature, 20 // 必填,須要使用的JS接口列表 21 jsApiList: [ 22 'checkJsApi', 23 'onMenuShareTimeline', 24 'onMenuShareAppMessage', 25 'onMenuShareQQ', 26 'onMenuShareWeibo' 27 ] 28 }); 29 } 30 /* 31 * 注意: 32 * 1. 全部的JS接口只能在公衆號綁定的域名下調用,公衆號開發者須要先登陸微信公衆平臺進入「公衆號設置」的「功能設置」裏填寫「JS接口安全域名」。 33 * 2. 若是發如今 Android 不能分享自定義內容,請到官網下載最新的包覆蓋安裝,Android 自定義分享接口需升級至 6.0.2.58 版本及以上。 34 * 3. 完整 JS-SDK 文檔地址:http://mp.weixin.qq.com/wiki/7/1c97470084b73f8e224fe6d9bab1625b.html 35 * 若有問題請經過如下渠道反饋: 36 * 郵箱地址:weixin-open@qq.com 37 * 郵件主題:【微信JS-SDK反饋】具體問題 38 * 郵件內容說明:用簡明的語言描述問題所在,並交代清楚遇到該問題的場景,可附上截屏圖片,微信團隊會盡快處理你的反饋。 39 *config信息驗證後會執行ready方法,全部接口調用都必須在config接口得到結果以後,config是一個客戶端的異步操做,因此若是須要在頁面加載時就調用相關接口,則須把相關接口放在ready函數中調用來確保正確執行。對於用戶觸發時才調用的接口,則能夠直接調用,不須要放在ready函數中。 40 */ 41 wx.ready(function () { 42 wx.checkJsApi({ 43 jsApiList: [ 44 'onMenuShareTimeline', 45 'onMenuShareAppMessage', 46 'onMenuShareQQ', 47 'onMenuShareWeibo' 48 ], 49 success: function (res) { 50 alert(JSON.stringify(res)); 51 } 52 }); 53 var shareData = { 54 title: '標題', 55 desc: '描述', 56 link: '連接', 57 imgUrl: '圖片', 58 trigger: function (res) { 59 alert('用戶點擊發送給朋友'); 60 }, 61 success: function (res) { 62 alert('已分享'); 63 }, 64 cancel: function (res) { 65 alert('已取消'); 66 }, 67 fail: function (res) { 68 alert(JSON.stringify(res)); 69 } 70 }; 71 wx.onMenuShareAppMessage(shareData); 72 wx.onMenuShareTimeline(shareData); 73 wx.onMenuShareQQ(shareData); 74 wx.onMenuShareWeibo(shareData); 75 }); 76 wx.error(function (res) { 77 // config信息驗證失敗會執行error函數,如簽名過時致使驗證失敗,具體錯誤信息能夠打開config的debug模式查看,也能夠在返回的res參數中查看,對於SPA能夠在這裏更新簽名。 78 alert("errorMSG:" + res); 79 }); 80 </script>
驗證JsAPI權限配置:前端
1 #region 驗證JsApi權限配置 2 /// <summary> 3 /// 獲取JsApi權限配置的數組/四個參數 4 /// </summary> 5 /// <returns></returns> 6 public string GetJsApiInfo(string Appid, string Appsecret) 7 { 8 string timestamp = CommonMethod.ConvertDateTimeInt(DateTime.Now).ToString();//生成簽名的時間戳 9 string nonceStr = CommonMethod.GetRandCode(16);//生成簽名的隨機串 10 string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.ToString();//當前的地址 11 string jsapi_ticket = ""; 12 //ticket 緩存7200秒 13 if (System.Web.HttpContext.Current.Session["jsapi_ticket"] == null) 14 { 15 jsapi_ticket = CommonMethod.WebRequestPostOrGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + BasicApi.GetTokenSession(Appid, Appsecret) + "&type=jsapi", ""); 16 System.Web.HttpContext.Current.Session["jsapi_ticket"] = jsapi_ticket; 17 System.Web.HttpContext.Current.Session.Timeout = 7200; 18 } 19 else 20 { 21 jsapi_ticket = System.Web.HttpContext.Current.Session["jsapi_ticket"].ToString(); 22 } 23 Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(jsapi_ticket); 24 jsapi_ticket = respDic["ticket"].ToString();//獲取ticket 25 string[] ArrayList = { "jsapi_ticket=" + jsapi_ticket, "timestamp=" + timestamp, "noncestr=" + nonceStr, "url=" + url }; 26 Array.Sort(ArrayList); 27 string signature = string.Join("&", ArrayList); 28 signature = Md5Hash(signature).ToLower(); 29 return "{\"appId\":\"" + Appid + "\", \"timestamp\":" + timestamp + ",\"nonceStr\":\"" + nonceStr + "\",\"signature\":\"" + signature + "\"}"; 30 } 31 /// <summary> 32 /// 32位MD5加密 33 /// </summary> 34 /// <param name="input"></param> 35 /// <returns></returns> 36 private string Md5Hash(string input) 37 { 38 MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); 39 byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); 40 StringBuilder sBuilder = new StringBuilder(); 41 for (int i = 0; i < data.Length; i++) 42 { 43 sBuilder.Append(data[i].ToString("x2")); 44 } 45 return sBuilder.ToString(); 46 } 47 48 #endregion
基礎接口BasicApi.cs:java
1 using System.Collections.Generic; 2 using System.Net; 3 using System.Text; 4 using System.Web; 5 using System.Web.Script.Serialization; 6 using Newtonsoft.Json.Linq; 7 using Newtonsoft.Json; 8 namespace Web 9 {// <summary> 10 /// 基礎接口 11 /// </summary> 12 public class BasicApi 13 { 14 public static string SessionAccessToken = "";//access_token緩存 其餘接口的通行證 15 16 public BasicApi() { } 17 18 #region 獲取access_token緩存 19 public static string GetTokenSession(string AppID, string AppSecret) 20 { 21 string TokenSession = ""; 22 23 if (System.Web.HttpContext.Current.Session[SessionAccessToken] == null) 24 { 25 TokenSession = AddTokenSession(AppID, AppSecret); 26 } 27 else 28 { 29 TokenSession = System.Web.HttpContext.Current.Session[SessionAccessToken].ToString(); 30 } 31 32 return TokenSession; 33 } 34 /// <summary> 35 /// 添加AccessToken緩存 36 /// </summary> 37 /// <param name="AppID"></param> 38 /// <param name="AppSecret"></param> 39 /// <returns></returns> 40 public static string AddTokenSession(string AppID, string AppSecret) 41 { 42 //獲取AccessToken 43 string AccessToken = GetAccessToken(AppID, AppSecret); 44 HttpContext.Current.Session[SessionAccessToken] = AccessToken; 45 HttpContext.Current.Session.Timeout = 7200; 46 return AccessToken; 47 } 48 49 /// <summary> 50 /// 獲取AccessToken 51 /// </summary> 52 /// <param name="AppID"></param> 53 /// <param name="AppSecret"></param> 54 /// <returns></returns> 55 public static string GetAccessToken(string AppID, string AppSecret) 56 { 57 JavaScriptSerializer Jss = new JavaScriptSerializer(); 58 string respText = CommonMethod.WebRequestPostOrGet(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret), ""); 59 Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText); 60 string accessToken = respDic["access_token"].ToString(); 61 return accessToken; 62 } 63 /// <summary> 64 /// 用code換取獲取用戶信息(包括非關注用戶的) 65 /// </summary> 66 /// <param name="openid"></param> 67 /// <param name="access_token"></param> 68 /// <returns></returns> 69 public static JObject GetUserInfo(string openid, string access_token) 70 { 71 JavaScriptSerializer Jss = new JavaScriptSerializer(); 72 string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", access_token, openid); 73 WebClient wc = new WebClient(); 74 byte[] bytes = wc.DownloadData(url); 75 wc.Encoding = Encoding.UTF8; 76 string jsonText = Encoding.UTF8.GetString(bytes); 77 JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText); 78 return jo; 79 } 80 #endregion 81 } 82 }
通用方法CommonMethod.cs:ajax
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Net; 5 using System.Web; 6 7 namespace Web 8 { 9 /// <summary> 10 /// 通用方法類 11 /// </summary> 12 public class CommonMethod 13 { 14 #region Post/Get提交調用抓取 15 /// <summary> 16 /// Post/get 提交調用抓取 17 /// </summary> 18 /// <param name="url">提交地址</param> 19 /// <param name="param">參數</param> 20 /// <returns>string</returns> 21 public static string WebRequestPostOrGet(string sUrl, string sParam) 22 { 23 byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam); 24 25 Uri uriurl = new Uri(sUrl); 26 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param); 27 req.Method = "Post"; 28 req.Timeout = 120 * 1000; 29 req.ContentType = "application/x-www-form-urlencoded;"; 30 req.ContentLength = bt.Length; 31 32 using (Stream reqStream = req.GetRequestStream())//using 使用能夠釋放using段內的內存 33 { 34 reqStream.Write(bt, 0, bt.Length); 35 reqStream.Flush(); 36 } 37 try 38 { 39 using (WebResponse res = req.GetResponse()) 40 { 41 //在這裏對接收到的頁面內容進行處理 42 43 Stream resStream = res.GetResponseStream(); 44 45 StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8); 46 47 string resLine; 48 49 System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder(); 50 51 while ((resLine = resStreamReader.ReadLine()) != null) 52 { 53 resStringBuilder.Append(resLine + System.Environment.NewLine); 54 } 55 56 resStream.Close(); 57 resStreamReader.Close(); 58 59 return resStringBuilder.ToString(); 60 } 61 } 62 catch (Exception ex) 63 { 64 return ex.Message;//url錯誤時候回報錯 65 } 66 } 67 #endregion Post/Get提交調用抓取 68 69 #region unix/datatime 時間轉換 70 /// <summary> 71 /// unix時間轉換爲datetime 72 /// </summary> 73 /// <param name="timeStamp"></param> 74 /// <returns></returns> 75 public static DateTime UnixTimeToTime(string timeStamp) 76 { 77 DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 78 long lTime = long.Parse(timeStamp + "0000000"); 79 TimeSpan toNow = new TimeSpan(lTime); 80 return dtStart.Add(toNow); 81 } 82 83 /// <summary> 84 /// datetime轉換爲unixtime 85 /// </summary> 86 /// <param name="time"></param> 87 /// <returns></returns> 88 public static int ConvertDateTimeInt(System.DateTime time) 89 { 90 System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 91 return (int)(time - startTime).TotalSeconds; 92 } 93 #endregion 94 95 #region 記錄bug,以便調試 96 /// <summary> 97 /// 記錄bug,以便調試 98 /// </summary> 99 public static bool WriteTxt(string str) 100 { 101 try 102 { 103 string LogPath = HttpContext.Current.Server.MapPath("/err_log/"); 104 if (!Directory.Exists(LogPath)) 105 { 106 Directory.CreateDirectory(LogPath); 107 } 108 FileStream FileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("/err_log//lwf_" + DateTime.Now.ToLongDateString() + "_.txt"), FileMode.Append); 109 StreamWriter StreamWriter = new StreamWriter(FileStream); 110 //開始寫入 111 StreamWriter.WriteLine(str); 112 //清空緩衝區 113 StreamWriter.Flush(); 114 //關閉流 115 StreamWriter.Close(); 116 FileStream.Close(); 117 } 118 catch (Exception) 119 { 120 return false; 121 } 122 return true; 123 } 124 #endregion 125 126 #region 生成隨機字符 127 /// <summary> 128 /// 生成隨機字符 129 /// </summary> 130 /// <param name="iLength">生成字符串的長度</param> 131 /// <returns>返回隨機字符串</returns> 132 public static string GetRandCode(int iLength) 133 { 134 string sCode = ""; 135 if (iLength == 0) 136 { 137 iLength = 4; 138 } 139 string codeSerial = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; 140 string[] arr = codeSerial.Split(','); 141 int randValue = -1; 142 Random rand = new Random(unchecked((int)DateTime.Now.Ticks)); 143 for (int i = 0; i < iLength; i++) 144 { 145 randValue = rand.Next(0, arr.Length - 1); 146 sCode += arr[randValue]; 147 } 148 return sCode; 149 } 150 #endregion 151 } 152 }
附件爲源碼:微信分享Demojson