asp.net MVC micro-Letter Js-sdk Certification _ Practical Skills

Source: Internet
Author: User
Tags datetime hash sha1 ticket

asp.net MVC micro-letter JS-SDK certification, specific content:

It's written in front.

Because there is a project need to do a micro-letter custom sharing function, so to study the next micro-letter JS-SDK related knowledge.

This article makes a simple (TU) record (Cao) ...

Begin
everything starts with the document: micro-letter Jssdk documentation

The project needs to use is the sharing interface, but before using micro-letter js-sdk, you need to do JS interface certification.

Certification is as follows:

Step one: Bind the domain name

Step Two: The introduction of JS file

Step three: Inject permission validation configuration via config interface

Step four: Successfully validate with Ready interface

Step five: Process failure validation through the error interface

Specific explanation:

The domain name/subdomain is allowed in step one, as long as Xx.com/xxx.txt or xx.com/mp/xxx.txt can access it. After the domain name authentication is passed, the website of all ports under this domain name can use JS-SDK.

Step two no problem, skip.

Step three is the most torture, explained separately below.

Config interface injection permission validation configuration

First come to a description:

All pages that need to use JS-SDK must first inject the configuration information, otherwise it will not be able to invoke (the same URL needs to be invoked only once, and the Web app for the spa that changes the URL can be invoked each time the URL changes. At present, the Android micro-trust client does not support the new H5 feature of Pushstate, so using Pushstate to implement the Web app's page will cause the signature to fail and the problem will be fixed in Android6.2.

Wx.config ({
 debug:true,//Open debug mode, the return value of all invoked APIs will be on the client alert,
 //To view incoming parameters, can be opened on the PC side, and the parameter information will be typed on the PC side only.)
 appId: ',//must fill, public number unique identification
 timestamp:,//required, generate signature timestamp
 noncestr: ',//must fill, generate signed random string
 signature: ',//must fill, sign Name, see Appendix 1
 jsapilist: []//must fill in, need to use the JS interface list, all JS interface list see Appendix 2
});

See here must be Meng, this is what ghost ... How to play AH.

Prompt us to see Appendix 1 ... After reading the summary is as follows:

1. Use config interface to inject permission authentication configuration, the focus is to generate legitimate signatrue
2. Generating signature needs to be obtained through AppID and secret token
3. Time stamp and call interface URL are essential
4. This operation requires service-side completion and cannot be implemented using the client

The whole process becomes:

1. Obtain Access_token through AppID and secret, then use token to obtain jsapi_ticket;

2. After getting jsapi_ticket, jsapi_ticket, timestamp, random string, interface call page URL stitching into a complete string, using the SHA1 algorithm to encrypt signature.

3. Finally return to the page, fill in the Wx.config inside the AppID, the last step of the time stamp timestamp, on a random string, SHA1 get signature, want to use the JS interface.

Less nonsense, directly on the code.

Code time

 public class Weixincontroller:controller {public static readonly string AppID = System.Web.Configuration.WebConfig

 urationmanager.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_t
  Ype=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 = "Get token failed"}); } 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 = "Get Ticketvalue Failed"});
  _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 (); The 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 ();
  Gets the encoding format of the target Web site 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 first extract the {using (System.IO.Stream streamreceive = Webresp Onse. GetResponseStream ()) {using (var ZIPstream = new System.IO.Compression.GZipStream (streamreceive, System.IO.Compress Ion. 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 (StreamReadersr = new System.IO.StreamReader (ZIPstream, Encoding.UTF8)) {Htmlcode = Sr.
    ReadToEnd (); }}}} else {using (System.IO.Stream streamreceive = WebResponse.GetResponseStream ()) {var E
   ncoding = 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 to pay attention to the cache _ticket (ie access_token), according to the micro-letter documents, Access_token two hours of effective, do not require frequent calls. And the interface that gets the Access_token has the limit of the number of calls, if it exceeds the number of times, it is not allowed to call.

PPS: Recommended Noncestr and URLs from the foreground to be more appropriate, using the var Theweburl = window.location.href.split (' # ') [0] to get the URL,NONCESTR is random.

PPPS: Encounter Strange Invalid signature, first check the URL parameters, and then check noncestr, no longer restart the program to get a new token back to play.

This article has been sorted out to the ASP. NET micro-Credit Development tutorial Summary, you are welcome to learn to read.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.