This article mainly introduces the ASP.NETMVCJS-SDK certification for everyone, has a certain reference value, interested friends can refer to ASP. NET MVCJS-SDK certification, the specific content:
Here is a description:
All pages that require JS-SDK must first inject configuration information, otherwise it will not be called (the same url only needs to be called once, the SPA web app that changes the url can be called every time the url changes. Currently, the Android client does not support the new H5 feature of pushState, therefore, using pushState to implement web app pages will cause signature failure, which will be fixed in Android6.2 ).
Wx. config ({debug: true, // enable the debugging mode. The Returned values of all called APIs are displayed on the alert client. // to view the input parameters, open the api on the pc, the parameter information is output through log and printed only on the pc end. AppId: '', // required. the unique identifier timestamp:, // required. the timestamp of the generated signature is nonceStr:''. // required, sign the random string signature: '', // required. for details, see Appendix 1 jsApiList: [] // required. list of JS interfaces to be used, for a list of all JS interfaces, see Appendix 2 });
It must have been awesome to see here. how can this be done.
Remind us to go to Appendix 1... after reading it, we will summarize as follows:
1. use the config interface to inject the permission verification configuration, with emphasis on generating valid signatrue
2. to generate signature, you must obtain the token through appid and secret.
3. the timestamp and the URL of the called interface are indispensable.
4. this operation must be completed by the server and cannot be implemented by the client.
The entire process becomes:
1. get access_token through appid and secret, and then use token to get jsapi_ticket;
2. after obtaining jsapi_ticket, splice the jsapi_ticket, timestamp, random string, and interface call page URL into a complete string and use the sha1 algorithm to encrypt and obtain signature.
3. return to the page, and fill in appid in wx. config. the timestamp in the previous step, the random string in the previous step, the signature obtained by sha1, and the JS interface to be used.
Let's talk about the code.
Code Time
Public class WeiXinController: Controller {public static readonly string appid = System. web. configuration. webConfigurationManager. deleetask[ "wxappid"]; public static readonly string secret = System. web. configuration. webConfigurationManager. deleetask[ "wxsecret"]; public static readonly bool isDedug = System. web. configuration. webConfigurationManager. appSettings ["IsDebug"] = "true"; public stati C 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
(ResultString); if (resultValue = null | resultValue. access_token = null | resultValue. access_token.Value = null) {return Json (new {issuccess = false, error = "failed to get 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
(ResultString); if (ticketValue = null | ticketValue. errcode = null | ticketValue. errcode. Value! = 0 | ticketValue. ticket = null) return Json (new {issuccess = false, error = "failed to get 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), timesta Mp = 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 stat Ic 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 (); // Obtain the encoding format of the target website, string contentype = webResponse. headers ["Content-Type"]; Regex regex = new Regex ("charset \ s * = \ s * [\ W]? \ S * ([\ w-] +) ", RegexOptions. ignoreCase); if (webResponse. contentEncoding. toLower () = "gzip") // If GZip is used, decompress {using (System. IO. stream streamReceive = webResponse. getResponseStream () {using (var zipStream = new System. IO. compression. GZipStream (streamReceive, System. IO. compression. compressionMode. decompress) {// match the encoding format 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: pay attention to cache the _ ticket (access_token). according to the document, the access_token is valid within two hours and does not need to be called frequently. In addition, the interface for obtaining access_token has a limit on the number of calls. if the number of calls exceeds the limit, it is not allowed to be called.
PPS: it is recommended that noncestr and URL be imported from the foreground. use var theWebUrl = window. location. href. split ('#') [0] to get the URL. noncestr is free of choice.
PPPS: when encountering a strange invalid signature, first check the url parameters, then check noncestr, and then restart the program to get a new token and continue playing.
The above is ASP. net mvc JS-SDK authentication instance tutorial details, more please pay attention to php other related articles!