ASP.NET MVC 微信JS-SDK認證_實用技巧

來源:互聯網
上載者:User

ASP.NET MVC微信JS-SDK認證,具體內容:

寫在前面

前陣子因為有個項目需要做微信自訂分享功能,因而去研究了下微信JS-SDK相關知識。

此文做個簡單的記(tu)錄(cao)...

開始
所有的東西都從文檔開始:微信JSSDK說明文檔

項目需要用到的是分享介面 不過使用微信JS-SDK之前,需要做JS介面認證。

認證如下:

步驟一:綁定網域名稱

步驟二:引入JS檔案

步驟三:通過config介面注入許可權驗證配置

步驟四:通過ready介面處理成功驗證

步驟五:通過error介面處理失敗驗證

具體解釋:

步驟一中允許使用網域名稱/子網域名稱,只要xx.com/xxx.txt或者xx.com/mp/xxx.txt能訪問就好。網域名稱認證通過之後,此網域名稱下的所有連接埠的網站都可以使用JS-SDK。

步驟二沒什麼問題,略過。

步驟三最磨人,下面單獨講解。

config介面注入許可權驗證配置

先來一段說明:

所有需要使用JS-SDK的頁面必須先注入配置資訊,否則將無法調用(同一個url僅需調用一次,對於變化url的SPA的web app可在每次url變化時進行調用,目前Android微信用戶端不支援pushState的H5新特性,所以使用pushState來實現web app的頁面會導致簽名失敗,此問題會在Android6.2中修複)。

wx.config({ debug: true, // 開啟偵錯模式,調用的所有api的傳回值會在用戶端alert出來, //若要查看傳入的參數,可以在pc端開啟,參數資訊會通過log打出,僅在pc端時才會列印。 appId: '', // 必填,公眾號的唯一標識 timestamp: , // 必填,產生簽名的時間戳記 nonceStr: '', // 必填,產生簽名的隨機串 signature: '',// 必填,簽名,見附錄1 jsApiList: [] // 必填,需要使用的JS介面列表,所有JS介面列表見附錄2});

看到這裡肯定懵逼了,這是都什麼鬼...怎麼玩啊。

提示我們去看附錄1...看完之後總結如下:

1.使用config介面注入許可權驗證配置,重點是產生合法的signatrue
2.產生signature需要通過appid和secret擷取token
3.時間戳記和調用介面URL必不可少
4.此操作需要服務端完成,不能使用用戶端實現

整個過程變成:

1.通過appid和secret擷取access_token,接著使用token擷取jsapi_ticket;

2.拿到jsapi_ticket之後,把jsapi_ticket、時間戳記、隨機字串、介面調用頁面URL 拼接成完整字串,使用sha1演算法加密得到signature。

3.最後返回至頁面,在wx.config裡面填入appid,上一步的時間戳記timestamp,上一部的隨機字串、sha1拿到的signature,想要使用的JS介面。

廢話少說,直接上代碼吧。

代碼時間

 public class WeiXinController : Controller { public static readonly string appid = System.Web.Configuration.WebConfigurationManager.AppSettings["wxappid"]; public static readonly string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["wxsecret"]; public static readonly bool isDedug = System.Web.Configuration.WebConfigurationManager.AppSettings["IsDebug"] =="true"; public static string _ticket = ""; public static DateTime _lastTimestamp; public ActionResult Info(string url,string noncestr) {  if (string.IsNullOrEmpty(_ticket) ||   _lastTimestamp == null || (_lastTimestamp - DateTime.Now).Milliseconds > 7200)  {  var resultString = HTTPHelper.GetHTMLByURL("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="   + appid + "&secret=" + secret);  dynamic resultValue = JsonConvert.DeserializeObject<dynamic>(resultString);  if (resultValue == null || resultValue.access_token == null   || resultValue.access_token.Value == null)  {   return Json(new { issuccess = false,    error = "擷取token失敗" });  }  var token = resultValue.access_token.Value;  resultString = HTTPHelper.GetHTMLByURL  ("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" +   token + "&type=jsapi");  dynamic ticketValue = JsonConvert.DeserializeObject<dynamic>(resultString);  if (ticketValue == null || ticketValue.errcode == null  || ticketValue.errcode.Value != 0 || ticketValue.ticket == null)   return Json(new { issuccess = false,   error = "擷取ticketValue失敗" });  _ticket = ticketValue.ticket.Value;  _lastTimestamp = DateTime.Now;  var timestamp = GetTimeStamp();  var hexString = string.Format("jsapi_ticket={0}&noncestr={3}&timestamp={1}&url={2}",  _ticket, timestamp, url,noncestr);  return Json(new {   issuccess = true,    sha1value = GetSHA1Value(hexString),    timestamp = timestamp,    url = url,    appid = appid,    debug=isDedug,   tiket=_ticket  });    }  else  {  var timestamp = GetTimeStamp();  var hexString = string.Format("jsapi_ticket={0}&noncestr=1234567890123456&timestamp={1}&url={2}",   _ticket, timestamp, url);  return Json(new {    issuccess = true, sha1value = GetSHA1Value(hexString),   timestamp = timestamp, url = url,   appid = appid, debug = isDedug,tiket = _ticket  });  } } private string GetSHA1Value(string sourceString) {  var hash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(sourceString));  return string.Join("",   hash.Select(b => b.ToString("x2")).ToArray()); } private static string GetTimeStamp() {  TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);  return Convert.ToInt64(ts.TotalSeconds).ToString(); } }     public class HTTPHelper { public static string GetHTMLByURL(string url) {  string htmlCode = string.Empty;  try  {  HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);  webRequest.Timeout = 30000;  webRequest.Method = "GET";  webRequest.UserAgent = "Mozilla/4.0";  webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");  HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();  //擷取目標網站的編碼格式  string contentype = webResponse.Headers["Content-Type"];  Regex regex = new Regex("charset\\s*=\\s*[\\W]?\\s*([\\w-]+)", RegexOptions.IgnoreCase);  if (webResponse.ContentEncoding.ToLower() == "gzip")//如果使用了GZip則先解壓  {   using (System.IO.Stream streamReceive = webResponse.GetResponseStream())   {   using (var zipStream = new System.IO.Compression.GZipStream(streamReceive, System.IO.Compression.CompressionMode.Decompress))   {    //匹配編碼格式    if (regex.IsMatch(contentype))    {    Encoding ending = Encoding.GetEncoding    (regex.Match(contentype).Groups[1].Value.Trim());    using (StreamReader sr = new System.IO.StreamReader(zipStream, ending))    {     htmlCode = sr.ReadToEnd();    }    }    else    {    using (StreamReader sr = new System.IO.StreamReader(zipStream, Encoding.UTF8))    {     htmlCode = sr.ReadToEnd();    }    }   }   }  }  else  {   using (System.IO.Stream streamReceive = webResponse.GetResponseStream())   {   var encoding = Encoding.Default;   if (contentype.Contains("utf"))    encoding = Encoding.UTF8;   using (System.IO.StreamReader sr = new System.IO.StreamReader(streamReceive, encoding))   {    htmlCode = sr.ReadToEnd();   }   }  }  return htmlCode;  }  catch (Exception ex)  {  return "";  } } }

PS:這裡要注意緩衝一下_ticket(即access_token),照微信文檔說的,access_token兩個小時內有效,不需要頻繁調用。而且擷取access_token的介面有調用次數的限制,如果超過了次數,就不允許調用了。

PPS:建議noncestr和URL由前台傳入比較適合,使用 var theWebUrl = window.location.href.split('#')[0] 擷取URL,noncestr就隨意了。

PPPS:遇到詭異的invalid signature的時候,首先檢查url參數,然後檢查noncestr,再不行重啟一下程式擷取一個新的token回來繼續玩。

本文已被整理到了《ASP.NET微信開發教程匯總》,歡迎大家學習閱讀。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.