Sweep the micro-channel features to achieve - with all the code

 First, when you call micro-channel JS-SDK interface need to carefully read the official notes, or it may be less effective. Here is probably the first major overview of the process, first of all, the use of micro-channel sweep the needs of the public have been through a number of certification; secondly, the public needs to know the number of APPID and APPSecrect, in order to obtain Access_Token and Ticket; then there is the need to understand the internal .NET the SHA1 encryption class; the last reference to official JS, on it.

VIEW Code

It should be noted that the number of public domain must be binding

Copy the code
<! DOCTYPE HTML> 

<HTML> 
<head> 
    <Meta name = "the viewport" Content = "Device-width width =" /> 
    <title> Index </ title> 
    <Script the src = "HTTP: //res.wx. qq.com/open/js/jweixin-1.1.0.js "> </ Script> 
    <Script the src =" http://libs.baidu.com/jquery/2.0.0/jquery.js "> </ Script > 
    <Script the src = "~ / Script / WxScanQRCode.js"> </ Script> 
    <Script> 
        wx.config ({ 
        debug: to true, // debug mode is turned on, all calls will return values api out alert client , to see the incoming parameters, you can open the pc side, will play parameter information through log, will be printed only when the pc.   
        appId: '@ ViewBag.appid', // required, the public unique identification number   
        timestamp: '@ ViewBag.timestamp',  // required, generating a signature stamp 
        nonceStr: '@ ViewBag.noncestr', // Required, generating a signature random string   
        signature: '@ ViewBag.sinature', // required signatures  
        jsApiList: [ 'checkJsApi', 
        // where the interfaces are involved in the official document, we only need to call micro-channel can sweep the 
                    // 'chooseImage', 
                    // 'previewImage', 
                    // 'uploadImage', 
                    // 'DownloadImage', 
                    // 'getNetworkType', the state of the network interfaces // 
                    // 'openLocation', // use the built-in map view location micro-channel interfaces 
                    // 'getLocation', // obtain the geographic location Interface 
                    // 'hideOptionMenu', / / operator interface interface. 1 
                    // 'showOptionMenu', operator interface interface // 2 
                    // 'closeWindow', //// interface user interface. 3 
                    // 'hideMenuItems',//// interface user interface. 4 
                    // 'showMenuItems', //// interface operation interface 5
                    // 'hideAllNonBaseMenuItem', //// interface operation interfaces. 6 
                    // 'showAllNonBaseMenuItem', //// interface operation interfaces. 7 
                      'scanQRCode' sweep the micro-channel interfaces // 
        ]   
        }); 
        <! - start scanning - > 
        function Scan () { 
            wx.ready (function () { 
                var _scan = document.getElementById ( "URL"); 
                _scan.value = window.location.href; 
                wx.scanQRCode ({ 
                    needResult:. 1, 
                    desc: 'scanQRCode desc ', 
                    Success: function (RES) { 
                        Alert (the JSON.stringify (RES));
                    }
                }); 
            }) 
        } 
    </ Script> 
</head>

<body>
    <div>
        <input type="text" name ="url" id="url">
        <button id="scanbutton" type="button" onclick="scan()">click here to scan</button>
    </div>
</body>
</html>
Copy the code

 

Controller Code

 

First, we need to get Access_Token according to APPID and APPSecrect, after acquiring jsapi_ticket according to AccessToken. Finally, internally generated time stamp Controller, a random string, after the first two and the ticket signature according to SHA1 encryption, the server sends the micro channel, after authentication by so that it can sweep the interface of the call.

Copy the code
Index ActionResult public () 
        { 
            // Get ACCESS_TOKEN 
            String Request.Url.ToString the _url = (); 
            // Get Ticket 
            String _ticket = Requestjsapi_ticket (request_url ()); 
            // Get Ticket 
            String _finalticket = _ticket; 
            // Get noncestr 
            String _noncestr CreatenNonce_str = (); 
            // get timestamp 
            Long the _TimeStamp = CreatenTimestamp (); 
            // get sinature 
            String _sinature = GetSignature (_finalticket, _noncestr, the _TimeStamp, _url) .ToLower (); 

            ViewBag.appid = "here to fill your APPID"; 
            ViewBag.timestamp = _timestamp; 
            ViewBag.noncestr = _noncestr;
            ViewBag.sinature = _sinature;
            return View();

        }

//获取AccessToken
        public static string Request_Url()
        {
            // 设置参数
            string _appid = "这里写入你的APPID";
            string _appsecret = "这里写入你的APPSecrect";
            string _url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + _appid + "&secret=" + _appsecret;
            string method = "GET";
            HttpWebRequest request = WebRequest.Create(_url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            = CookieContainer request.CookieContainer; 
            // Since the micro channel JSON string returned by the server contains a lot of information, we only need to obtain AccessToken it is necessary to split the JSON 
            String [] str = content.Split ( ' " ');
            content = str[3];
            request.AllowAutoRedirect = true;
            request.Method = method;
            = request.ContentType "text / HTML"; 
            request.Headers.Add ( "charset", "UTF-. 8"); 

            // send the request and obtain the appropriate response data is 
            the HttpWebResponse request.GetResponse Response = () AS the HttpWebResponse; 
            // until request.GetResponse () Post program started sending a request to the target page 
            Stream responseStream response.GetResponseStream = (); 
            the StreamReader the StreamReader new new SR = (responseStream, Encoding.UTF8); 
            // returns the results page (html) Code 
            string content = sr. the ReadToEnd (); 
            return Content; 
        } 

 // Get jsapi_ticket according to the accessToken 
        public static String Requestjsapi_ticket (String accessToken) 
        {

            string _accesstoken = accesstoken;
            string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + _accesstoken + "&type=jsapi";
            string method = "GET";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = method;
            request.ContentType = "text/html";
            request.Headers.Add("charset", "utf-8");
            HttpWebResponse response = request.GetResponse () as HttpWebResponse
            // send the request and obtain the corresponding response data 
            // until request.GetResponse () procedure started Post request is sent to the target page 
            Stream responseStream response.GetResponseStream = (); 
            the StreamReader the StreamReader new new SR = (responseStream , Encoding.UTF8); 
            // returns the results page (html) Code 
            String Content = sr.ReadToEnd (); 
            // Also, JSON returned information can be simply removed from the ticket 
            String [] str = content.Split ( ' " '); 
            Content STR = [. 9]; 
            return Content; 
        } 

// Next is an auxiliary tools, generate a random string 
#region random string CreatenNonce_str () 
        Private static string [] = STRs new new string [] 
                                    { 
                                    "A", "B", "C", "D", "E", " f "," g "," h ","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                                    "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
                                    };
        public static string CreatenNonce_str()
        {
            Random r = new Random();
            var sb = new StringBuilder();
            var length = strs.Length;
            for (int i = 0; i < 15; i++)
            {
                sb.Append(strs[r.Next(length - 1)]);
        {
        public static Long CreatenTimestamp ()
 #region stamp generator CreatenTimestamp ()
// generate a timestamp, spare
            }
            return sb.ToString();
        }
        #endregion

            return (DateTime.Now.ToUniversalTime () Ticks - 621355968000000000.) / 10000000; 
        } 
        #endregion 

// Get signature, where the three parameters are previously generated Ticket, and a time stamp random string 
#region acquired signature GetSignature () 
        GetSignature static String public (jsapi_ticket String, String noncestr, timestamp Long, String URL) 
        { 

            var = new new string1Builder the StringBuilder (); 
            . string1Builder.Append ( "jsapi_ticket =") the Append (jsapi_ticket) .Append the ( "&") 
                          .Append the ( "noncestr ="). Append (noncestr) .Append the ( "&") ;
            return SHA1(string1Builder.ToString()); 
                          .Append the (" timestamp = ").Append(timestamp).Append("&")
                          .Append ( "url =") Append. (Url.IndexOf ( "#")> = 0 url.substring (0, url.IndexOf ( "#")):? Url); 
        } 
        #endregion 


// The final step is SHA1 encryption algorithm tool 
 #region signature encryption algorithm SHAl (Content) 
        // signature algorithm encryption 
        public static String SHAl (String Content) 
        { 
            return SHAl (Content, Encoding.UTF8); 

        } 
        // encrypted signature 
        public static string SHA1 (string content, encode Encoding) 
        { 
            the try 
            { 
                SHAl new new SHA1CryptoServiceProvider = SHA1 (); 
                byte [] = bytes_in encode.GetBytes (Content); 
                byte [] = bytes_out sha1.ComputeHash (bytes_in); 
                sha1.Dispose (); 
                String Result = BitConverter.ToString (bytes_out); 
                result = result.Replace ( "-", "");
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密出错:" + ex.Message);
            }
        }  
        #endregion
Copy the code

to sum up

Copy the code can be used to note the number of certified public or binding, domain names, as well as the accuracy of the final encryption algorithm to generate the string, which step less, we will not get a proper return results.

Reprinted: https: //blog.csdn.net/SugaryoTT/article/details/78558105

Guess you like

Origin www.cnblogs.com/macT/p/11579449.html