In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of Wechat JS-SDK certification in ASP.NET MVC, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
ASP.NET MVC Wechat JS-SDK certification, specific content:
Write at the front
Not long ago, because there was a project that needed to do the custom sharing function of Wechat, I went to study the relevant knowledge of Wechat JS-SDK.
This article makes a simple tu recording (cao).
Start
Everything starts with documentation: Wechat JSSDK documentation
What the project needs to use is the sharing interface, but before using Wechat JS-SDK, you need to verify the JS interface.
The certification is as follows:
Step 1: bind the domain name
Step 2: introduce the JS file
Step 3: verify the configuration by injecting permissions through the config interface
Step 4: successfully verify through the ready interface
Step 5: handle failure verification through error interface
Specific explanation:
Domain name / subdomain name is allowed in step 1, as long as xx.com/xxx.txt or xx.com/mp/xxx.txt can access it. After the domain name authentication is passed, all websites under this domain name can use JS-SDK.
Step two is fine. Skip it.
Step 3 is the most exhausting, which will be explained separately below.
Config interface injection permission verification configuration
Let's start with a paragraph:
All pages that need to use JS-SDK must first inject configuration information, otherwise they cannot be called (the same url only needs to be called once. The web app of the SPA that changes the url can be called each time the url changes. Currently, the Android Wechat client does not support the new H5 feature of pushState, so using pushState to implement web app pages will cause signature failure, which will be fixed in Android6.2).
Wx.config ({debug: true, / / enable debug mode, and the returned values of all api called will be displayed in the client alert. / / if you want to view the passed parameters, you can open them on the PC side, and the parameter information will be typed out through log and printed only on the PC side. AppId:'', / / required, unique identification of official account timestamp:, / / required, timestamp nonceStr:'', / / required to generate signature, random string signature:'', / / required, signature generated, see Appendix 1 jsApiList: [] / / required, list of JS APIs to be used, list of all JS APIs see Appendix 2})
You must be confused to see here. What the heck is this? How to play.
Remind us to look at Appendix 1. After reading it, it is summarized as follows:
1. Use the config interface to inject permissions to verify the configuration, focusing on generating legitimate signatrue
two。 To generate signature, you need to obtain token through appid and secret.
3. Timestamp and call interface URL are essential
4. This operation needs to be completed by the server and cannot be implemented by the client.
The whole process becomes:
1. Get access_token through appid and secret, and then use token to get jsapi_ticket
two。 After getting the jsapi_ticket, assemble the jsapi_ticket, timestamp, random string, and URL of the API call page into a complete string, and encrypt the signature using the sha1 algorithm.
3. Finally, return to the page, enter appid in the wx.config, the timestamp timestamp in the previous step, the random string in the previous part, the signature obtained by sha1, and the JS API you want to use.
Cut the crap and go straight to the code.
Code time
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 (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), 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 (); / / get 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, extract {using (System.IO.Stream streamReceive = webResponse.GetResponseStream ()) {using (var zipStream = new System.IO.Compression.GZipStream (streamReceive)) first System.IO.Compression.CompressionMode.Decompress) {/ / match 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: here, pay attention to caching _ ticket (that is, access_token). According to Wechat documentation, access_token is valid for two hours and does not need to be called frequently. Moreover, the API for obtaining access_token has a limit on the number of calls. If the number of calls is exceeded, the call is not allowed.
PPS: it is recommended that noncestr and URL be passed in from the foreground. Use var theWebUrl = _ window.location.href.split ('#') [0] to get URL,noncestr at will.
PPPS: when you encounter a weird invalid signature, first check the url parameters, then check the noncestr, and then restart the program to get a new token to continue playing.
Thank you for reading this article carefully. I hope the article "sample Analysis of Wechat JS-SDK Certification in ASP.NET MVC" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.