微网站-扫一扫

第一步,拥有自己的测试微信公众号,调用扫一扫功能,不需要从测试公众号中进入网页,只需要微信浏览器即可然后,这里配置完成,就可以通过后台的调用,token和tickes来完成扫一扫功能;

第二步,这里使用C#代码写的,详情如下:(代码从各个帮助页面拿过来,比较冗余,自己用,可以尽量优化)

private static string corpid = "你的appid";//在公众号里面点击设置
        private static string corpsecret = "你的secrect";      //通过得到的token,得到ticket       
        string url2 = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";
        //这个得到Ticket,使用get请求       
        public  Access_ticket accessTicket()
        {            
            Access_ticket atic = new Access_ticket();           
            var eigq=Convert.ToDateTime(Session["expires_in"]);
            //判断凭证是否过期;
           if (eigq >= DateTime.Now)            
            {
                atic.ticket = Session["ticket"].ToString();
                atic.expires_in = Session["expires_in"].ToString();   
            }
            else
            {
            //根据appid和secret,获取accesstoken
            AccessToken AccessToken = GetAccessToken(corpid, corpsecret);
            Session["expires_in"] = AccessToken.expires_in;
            //string json = GetHtml(string.Format(url2, AccessToken.access_token));
            string result = HttpGet(string.Format(url2, AccessToken.access_token));
            JavaScriptSerializer Se = new JavaScriptSerializer();
            Dictionary<string, string> _dic = Se.Deserialize<Dictionary<string, string>>(result);
            string errcode="";
            _dic.TryGetValue("errcode", out  errcode);
            //
            //为0获取拼争成功
            if (errcode=="0")
            {
                 string ticket = String.Empty;
                string expires_in = String.Empty;
                _dic.TryGetValue("ticket", out ticket);
                _dic.TryGetValue("expires_in", out expires_in);
                atic.ticket = ticket;
                atic.expires_in = expires_in;
                Session["ticket"] = ticket;
            }               
            }
            return atic;            
        }


        //获取签名
        [HttpGet]
        public  void Getsignature(string url)
        {
            Access_ticket Access_ticket = accessTicket();
            string ticket = Access_ticket.ticket;            
            //这个是所有得到的东西拼接成一个字符串,1.jsapi_ticket:上面得到的ticket 2.noncestr:这个是随机的字符串,必须和上面(3)的那个一样 3.timestamp:这个是随机的字符串,必须和上面(3)的那个一样,
            //4.url:地址一定要详细,比如:http://baidu.com/1.html  哪个页面需要调用 扫一扫,就使用哪个页面的地址
            string string1 = "jsapi_ticket=" + ticket + "&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=" + url + "";
            //使用sha1加密这个字符串           
            Response.Write(SHA1(string1));
            Response.End();
        }

       
        /// <summary>
        /// 32位小写
        /// </summary>
        /// <returns></returns>
        public static string SHA1(string s)
        {
            s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "SHA1").ToString();
            return s.ToLower();
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static AccessToken GetAccessToken(string appID, string secret)
        {
            AccessToken at = new AccessToken();
           string  token = String.Empty;
           DateTime  expressDate = DateTime.Now;
            string result = HttpGet(String.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appID, secret));
            if (result.Contains("errcode"))
            {
                at.expires_in = DateTime.Now;
                at.access_token = "";
            }
            else
            {
                JavaScriptSerializer Se = new JavaScriptSerializer();
                Dictionary<string, string> _dic = Se.Deserialize<Dictionary<string, string>>(result);
                string access_token = String.Empty;
                string expressTime = String.Empty;
                _dic.TryGetValue("access_token", out access_token);
                _dic.TryGetValue("expires_in", out expressTime);
                token = access_token;
                expressDate = DateTime.Now.AddSeconds(Convert.ToInt32(expressTime) - 100);
                at.expires_in = expressDate;
                at.access_token = token;
            }

            return at;
        }
       
        //后台get请求
        public static string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            WebResponse response = null;
            string responseStr = null;

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                response = null;
            }

            return responseStr;
        }

 

第三步,前台调用微信类库, wx.config,的配置,可以参考微信测试接口,如果提示签名无效,可以参考jsapsign,进行测试(jsapsign)

https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign

html代码:,核心js:  <script src='https://res.wx.qq.com/open/js/jweixin-1.2.0.js'></script> 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src='https://res.wx.qq.com/open/js/jweixin-1.2.0.js'></script> 
<script src="../Scripts/jquery/jquery-2.1.1.min.js"></script> <script type="text/JavaScript"> //初始化 $(document).ready(function () { scan(); }) function scan() { //alert(location.href.split('#')[0]); var signature = ""; //获取签名:通过后台方法; $.ajaxSetup({ async: false, }); $.get(你自己的域名url+ "/weixinclient/Getsignature?url=https://weixin.xxx.com/wx/Pages/Scan.html", function (res) { if (res != undefined) { signature = res; } }) wx.config({ debug:false, //是否调试,true,会弹窗 appId:'你自己的appid', //得到这个东西,首先必须有一个公众号,或者企业号,如果已经拥有了,你可以就知道AppId在哪里了。 timestamp:'1414587457',//生成签名的时间戳,随机数,之后会用这个生成一个签名 nonceStr: 'Wm3WZYTPz0wzccnW',//生成签名的随机串,随机串,之后会用这个生成一个签名 signature:signature,//这个就是签名了,在步骤4,我会详细讲解 jsApiList:['scanQRCode'] //开启扫一扫功能,这里还可以添加更多的功能,比如微信支付 }); wx.ready(function () { wx.scanQRCode({ desc:'scanQRCode desc', needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果, scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有 success: function (res) { //获得二维码内容; var guid = res.resultStr; } }); }); } </script> </head> <body> </body> </html>

最后的呈现效果,手机微信浏览器:(如果有问题,可以多多交流)

 

posted @ 2018-07-26 15:36  西平sir  阅读(508)  评论(0编辑  收藏  举报