ASP. net mvc WeChat JS-SDK certification, mvcjs-sdk

Source: Internet
Author: User
Tags subdomain name

ASP. net mvc JS-SDK certification, mvcjs-sdk

ASP. NET MVCJS-SDK authentication, specific content:

Preface

A while ago, because there was a project that needed to do the custom sharing function, so I studied the JS-SDK related knowledge.

This article makes a simple note (tu) Record (cao )...

Start
Everything starts from the document: JSSDK instructions

Project needs to use is sharing interface but before using JS-SDK, need to do JS interface authentication.

The authentication is as follows:

Step 1: bind a domain name

Step 2: Introduce the JS File

Step 3: inject the permission verification configuration through the config Interface

Step 4: Verify the processing by using the ready interface

Step 5: handle failure verification through the error Interface

Explanation:

In step 1, the domain name/subdomain name can be used, as long as xx.com/xxx.txt?xx.com/mp/xxx.txtcan be used. After the domain name passes authentication, all the ports under the domain name can use JS-SDK.

Step 2: No problem. skip this step.

Step 3 is the most refined, which will be explained separately below.

Config interface injection permission verification Configuration

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. deleetask[ "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 = "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 <dynamic> (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 all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.