ASP.NET MVC 微信JS-SDK認(rèn)證
ASP.NET MVC微信JS-SDK認(rèn)證,具體內(nèi)容:

寫在前面
前陣子因為有個項目需要做微信自定義分享功能,因而去研究了下微信JS-SDK相關(guān)知識。
此文做個簡單的記(tu)錄(cao)...
開始
所有的東西都從文檔開始:微信JSSDK說明文檔

項目需要用到的是分享接口 不過使用微信JS-SDK之前,需要做JS接口認(rèn)證。
認(rèn)證如下:
步驟一:綁定域名
步驟二:引入JS文件
步驟三:通過config接口注入權(quán)限驗證配置
步驟四:通過ready接口處理成功驗證
步驟五:通過error接口處理失敗驗證
具體解釋:
步驟一中允許使用域名/子域名,只要xx.com/xxx.txt或者xx.com/mp/xxx.txt能訪問就好。域名認(rèn)證通過之后,此域名下的所有端口的網(wǎng)站都可以使用JS-SDK。
步驟二沒什么問題,略過。
步驟三最磨人,下面單獨講解。
config接口注入權(quán)限驗證配置
先來一段說明:
所有需要使用JS-SDK的頁面必須先注入配置信息,否則將無法調(diào)用(同一個url僅需調(diào)用一次,對于變化url的SPA的web app可在每次url變化時進行調(diào)用,目前Android微信客戶端不支持pushState的H5新特性,所以使用pushState來實現(xiàn)web app的頁面會導(dǎo)致簽名失敗,此問題會在Android6.2中修復(fù))。
wx.config({
debug: true, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會在客戶端alert出來,
//若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會通過log打出,僅在pc端時才會打印。
appId: '', // 必填,公眾號的唯一標(biāo)識
timestamp: , // 必填,生成簽名的時間戳
nonceStr: '', // 必填,生成簽名的隨機串
signature: '',// 必填,簽名,見附錄1
jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2
});
看到這里肯定懵逼了,這是都什么鬼...怎么玩啊。
提示我們?nèi)タ锤戒?...看完之后總結(jié)如下:
1.使用config接口注入權(quán)限驗證配置,重點是生成合法的signatrue
2.生成signature需要通過appid和secret獲取token
3.時間戳和調(diào)用接口URL必不可少
4.此操作需要服務(wù)端完成,不能使用客戶端實現(xiàn)
整個過程變成:
1.通過appid和secret獲取access_token,接著使用token獲取jsapi_ticket;
2.拿到j(luò)sapi_ticket之后,把jsapi_ticket、時間戳、隨機字符串、接口調(diào)用頁面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}×tamp={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×tamp={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();
//獲取目標(biāo)網(wǎng)站的編碼格式
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兩個小時內(nèi)有效,不需要頻繁調(diào)用。而且獲取access_token的接口有調(diào)用次數(shù)的限制,如果超過了次數(shù),就不允許調(diào)用了。
PPS:建議noncestr和URL由前臺傳入比較適合,使用 var theWebUrl = window.location.href.split('#')[0] 獲取URL,noncestr就隨意了。
PPPS:遇到詭異的invalid signature的時候,首先檢查url參數(shù),然后檢查noncestr,再不行重啟一下程序獲取一個新的token回來繼續(xù)玩。
本文已被整理到了《ASP.NET微信開發(fā)教程匯總》,歡迎大家學(xué)習(xí)閱讀。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 微信js-sdk上傳與下載圖片接口用法示例
- 微信js-sdk地理位置接口用法示例
- 微信JS-SDK自定義分享功能實例詳解【分享給朋友/分享到朋友圈】
- 解析微信JS-SDK配置授權(quán),實現(xiàn)分享接口
- 微信JS-SDK選取手機照片上傳功能
- 微信js-sdk預(yù)覽圖片接口及從拍照或手機相冊中選圖接口用法示例
- PHP實現(xiàn)微信JS-SDK接口選擇相冊及拍照并上傳的方法
- 微信 java 實現(xiàn)js-sdk 圖片上傳下載完整流程
- 微信js-sdk界面操作接口用法示例
- 最詳細的ASP.NET微信JS-SDK支付代碼
- php微信公眾號js-sdk開發(fā)應(yīng)用
- 微信JS-SDK坐標(biāo)位置如何轉(zhuǎn)換為百度地圖坐標(biāo)
- 詳解基于Node.js的微信JS-SDK后端接口實現(xiàn)代碼
- 微信js-sdk分享功能接口常用邏輯封裝示例
- 微信JS-SDK分享功能的.Net實現(xiàn)代碼
- php版微信js-sdk支付接口類用法示例
- 微信開發(fā) JS-SDK 6.0.2 經(jīng)常遇到問題總結(jié)
- 微信js-sdk+JAVA實現(xiàn)“分享到朋友圈”和“發(fā)送給朋友”功能詳解
相關(guān)文章
Visual Studio 2013如何使XML文件轉(zhuǎn)換成類
Visual Studio 2013如何使XML文件轉(zhuǎn)換成類?這篇文章主要介紹了Visual Studio2013輕松將你的XML文件轉(zhuǎn)換成類的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
Asp.net中DataTable導(dǎo)出到Excel的方法介紹
本篇文章介紹了,Asp.net中DataTable導(dǎo)出到Excel的方法。需要的朋友參考下2013-05-05
ASP.NET單選按鈕控件RadioButton常用屬性和方法介紹
RadioButton又稱單選按鈕,其在工具箱中的圖標(biāo)為 ,單選按鈕通常成組出現(xiàn),用于提供兩個或多個互斥選項,即在一組單選鈕中只能選擇一個2014-04-04
asp.net 獲取目錄下的文件數(shù)和文件夾數(shù)
遍歷一個文件夾中的文件,需要用到DirectoryInfo類中的一個重要的方法GetFileSystemInfos(),此方法返回指定的是與搜索條件相匹配的文件和子目錄的強類型 FileSystemInfo對象的數(shù)組。2010-07-07

