1. 程式人生 > >微網站-掃一掃

微網站-掃一掃

自己的 開啟 設置 returns sync mat ict () gets

技術分享圖片

第一步,擁有自己的測試微信公眾號,調用掃一掃功能,不需要從測試公眾號中進入網頁,只需要微信瀏覽器即可然後,這裏配置完成,就可以通過後臺的調用,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>

最後的呈現效果,手機微信瀏覽器:(如果有問題,可以多多交流)

技術分享圖片

微網站-掃一掃