1、准備工作
官方文檔:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111
必須是認證過的公眾號才可以,先登錄微信公眾平台進入“公眾號設置”的“功能設置”里填寫“js接口安全域名”、“網頁授權域名”
然后在開發設置中獲取AppID和AppSecret,並設置ip白名單
2、前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>https://www.cnblogs.com/webapi/</title> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <meta name="description" content="https://www.cnblogs.com/webapi/" /> <meta name="keywords" content="https://www.cnblogs.com/webapi/" /> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="Pragma" content="no-cache"> <script src="https://cdn.bootcss.com/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script> <script type="text/javascript"> var pagetUrl = window.location.href; $(function () { //--微信JS配置 if (wx != null && wx != undefined) { if (pagetUrl.indexOf("#") > 0) { pagetUrl = str.substring(0, pagetUrl.indexOf("#")); }
$.ajax({
url: "weixinshare.aspx",
type: "post",
data: { purl: pagetUrl },
dataType: "json",
success: function (data) {
wx.config({
debug: false, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。
appId: data.appid, // 必填,公眾號的唯一標識
timestamp: data.timestamp, // 必填,生成簽名的時間戳
nonceStr: data.nonceStr, // 必填,生成簽名的隨機串
signature: data.signature, // 必填,簽名,見附錄1
jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
});
}
});
wx.ready(function () { //自定義“分享給朋友”及“分享到QQ”按鈕的分享內容(1.4.0) wx.ready(function () { //需在用戶可能點擊分享按鈕前就先調用 wx.updateAppMessageShareData({ title: '微信分享測試-分享標題', // 分享標題 desc: '微信分享測試-分享描述,微信分享測試-分享描述', // 分享描述 link: pagetUrl, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 imgUrl: 'https://www.baidu.com/img/bd_logo1.png', // 分享圖標 success: function () { // 設置成功 } }) }); //自定義“分享到朋友圈”及“分享到QQ空間”按鈕的分享內容(1.4.0) wx.ready(function () { //需在用戶可能點擊分享按鈕前就先調用 wx.updateTimelineShareData({ title: '微信分享測試-分享標題,微信分享測試-分享描述', // 分享標題 link: pagetUrl, // 分享鏈接,該鏈接域名或路徑必須與當前頁面對應的公眾號JS安全域名一致 imgUrl: 'https://www.baidu.com/img/bd_logo1.png', // 分享圖標 success: function () { // 設置成功 } }) }); }); } }); </script> </head> <body> <h1>微信分享測試</h1> <div> 微信JS-SDK是微信公眾平台 面向網頁開發者提供的基於微信內的網頁開發工具包。通過使用微信JS-SDK,網頁開發者可借助微信高效地使用拍照、選圖、語音、位置等手機系統的能力,同時可以直接使用微信分享、掃一掃、卡券、支付等微信特有的能力,為微信用戶提供更優質的網頁體驗。此文檔面向網頁開發者介紹微信JS-SDK如何使用及相關注意事項 </div> </body> </html>
3、后台
using LitJson; using System; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; public partial class weixin_weixin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111 string url = Request.Form["purl"]; string appid = "wxd111111111111"; string appSecret = "8888888888888888888888888888"; string jsapiTicket = getJsApiTicket(appid, appSecret); // 獲取時間戳 string timestamp = Convert.ToString(GetTimeStamp()); // 獲取隨機字符串 string nonceStr = createNonceStr(); // 獲取簽名signature string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url + ""; string signature = SHA1_Hash(rawstring); // 返回的json string json = "{\"appid\":\"" + appid + "\",\"timestamp\":\"" + timestamp + "\",\"nonceStr\":\"" + nonceStr + "\",\"signature\":\"" + signature + "\"}"; Response.Write(json); Response.End(); } //創建隨機字符串 public string createNonceStr() { int length = 16; string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string str = ""; Random rad = new Random(); for (int i = 0; i < length; i++) { str += chars.Substring(rad.Next(0, chars.Length - 1), 1); } return str; } public string GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } public string SHA1_Hash(string str_sha1_in) { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in); byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in); string str_sha1_out = BitConverter.ToString(bytes_sha1_out); str_sha1_out = str_sha1_out.Replace("-", "").ToLower(); return str_sha1_out; } // 獲取Token public string GetToken(string appid, string secret) { //獲取token,有效期7200秒,需要cache string strJson = string.Empty; if (GetCache("token") != null) { strJson = GetCache("token").ToString(); } else { strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret)); SetCache("token", strJson, 119); } JsonData jd = JsonMapper.ToObject(strJson); return jd["access_token"].ToString(); } //獲取ticket public string getJsApiTicket(string appid, string appSecret) { //獲取ticket,有效期7200秒,需要cache string token = GetToken(appid, appSecret); string strJson = string.Empty; if (GetCache("ticket") != null) { strJson = GetCache("ticket").ToString(); } else { strJson = RequestUrl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + token); SetCache("ticket", strJson, 119); } JsonData jd = JsonMapper.ToObject(strJson); return jd["ticket"].ToString(); }//公共方法,request網絡獲取 public string RequestUrl(string url) { // 設置參數 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "get"; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); string content = sr.ReadToEnd(); return content; } /// <summary> /// 創建緩存項過期 /// </summary> /// <param name="key">緩存Key</param> /// <param name="obj">object對象</param> /// <param name="expires">過期時間(分鍾)</param> public void SetCache(string key, object obj, int expires) { Cache.Insert(key, obj, null, DateTime.UtcNow.AddMinutes(expires), TimeSpan.Zero); } public object GetCache(string key) { if (string.IsNullOrEmpty(key)) { return null; } return Cache.Get(key); } }