前台页面:
引用微信js : <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
页面扫码按钮:<a href="#" id="scanCode" ><img src="~/img/btn.png" alt=""></a>
调用摄像头js:
<script> $(function () { //扫码 var hidtimestamp = '@ViewBag.hidtimestamp'; var hidsignature = '@ViewBag.hidsignature'; wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: '@ViewBag.appId', // 必填,公众号的唯一标识 timestamp: hidtimestamp, // 必填,生成签名的时间戳 nonceStr: '@ViewBag.appId', // 必填,生成签名的随机串 signature: hidsignature, // 必填,签名,见附录1 jsApiList: [ 'checkJsApi', 'scanQRCode' ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2 }); document.querySelector('#scanCode').onclick = function () { wx.scanQRCode({ needResult: 1, desc: 'scanCode desc', success: function (res) { //扫码后获取结果参数:htpp://xxx.com/c/?6123,截取到url中的防伪码后,赋值给Input var url = res.resultStr; var tempArray = url.substring(url.lastIndexOf("/") + 1); if (tempArray.length > 20) { tempArray = url.substring(url.length - 20); } location.href = "需要回传的页面地址" + tempArray; } }); } }) </script>
后台代码:
public ActionResult ScanCodeDraw() { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); int timestamp = (int)(DateTime.Now - startTime).TotalSeconds; string url = ScanCode.webUrl + ViewBag.UrlPath + "/ScanCodeAntifake/Home/ScanCodeDraw"; ViewBag.hidtimestamp = timestamp.ToString(); ScanCode sc = new ScanCode(); ViewBag.hidsignature = sc.jsapi_ticket(timestamp, url, ViewBag.UrlPath);//计算签名 return View(); }
获取签名:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net; using System.Xml.Linq; using System.Text; using System.IO; using Newtonsoft.Json; using System.Configuration; namespace Maticsoft.WebShop.Components { /// <summary> /// 调用微信扫码积分 /// </summary> public class ScanCode { public ScanCode() { Maticsoft.WeChat.BLL.Core.Config.ClearCache(); } public static string webUrl = ConfigurationManager.AppSettings["WebUrl"]; public string AppId = Maticsoft.WeChat.BLL.Core.Config.GetValueByCache("WeChat_AppId", -1, "AA"); public string AppSecret = Maticsoft.WeChat.BLL.Core.Config.GetValueByCache("WeChat_AppSercet", -1, "AA"); public string jsapi_ticket(int timestamp, string url, string bsname = "user") { try { string nonceStr = AppId; string jsapiticket = GetJsapiTicket(bsname); string str = "jsapi_ticket=" + jsapiticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url; string signature = SHA1(str).ToLower(); return signature; } catch (Exception ex) { LogHelp.AddErrorLog("微信扫码error:", ex.Message + ex.StackTrace, System.Web.HttpContext.Current.Request); return ""; } } private string GetTaken(string bsname = "user") { var xmlPath = AppDomain.CurrentDomain.BaseDirectory + "taken.xml"; var doc = XDocument.Load(xmlPath); if (doc.Element("person").Element(bsname) == null) { doc.Element("person").Add(new XElement(bsname, new XElement("access_token"), new XElement("access_time"))); doc.Save(xmlPath); } //读取 var actak = doc.Element("person").Element(bsname).Element("access_token").Value; var actime = doc.Element("person").Element(bsname).Element("access_time").Value; if (!string.IsNullOrEmpty(actak)) { if (Convert.ToDateTime(actime) < DateTime.Now) { HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret); //postData = ASCIIEncoding encoding = new ASCIIEncoding(); requestScore.Method = "Get"; requestScore.ContentType = "application/x-www-form-urlencoded"; requestScore.KeepAlive = true; HttpWebResponse responseSorce = (HttpWebResponse)requestScore.GetResponse(); StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); requestScore = null; responseSorce.Close(); responseSorce = null; reader = null; AccessEntity accessToken = new AccessEntity(); accessToken = JsonConvert.DeserializeObject<AccessEntity>(content); //写入 doc.Element("person").Element(bsname).Element("access_token").Value = accessToken.access_token; doc.Element("person").Element(bsname).Element("access_time").Value = DateTime.Now.AddHours(2).ToString(); doc.Save(xmlPath); //doc.Element("").Add(new XElement("","")); return accessToken.access_token; } else { return actak; } } else { HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret); //postData = ASCIIEncoding encoding = new ASCIIEncoding(); requestScore.Method = "Get"; requestScore.ContentType = "application/x-www-form-urlencoded"; requestScore.KeepAlive = true; HttpWebResponse responseSorce = (HttpWebResponse)requestScore.GetResponse(); StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); requestScore = null; responseSorce.Close(); responseSorce = null; reader = null; AccessEntity accessToken = new AccessEntity(); accessToken = JsonConvert.DeserializeObject<AccessEntity>(content); //写入 doc.Element("person").Element(bsname).Element("access_token").Value = accessToken.access_token; doc.Element("person").Element(bsname).Element("access_time").Value = DateTime.Now.AddHours(2).ToString(); doc.Save(xmlPath); return accessToken.access_token; } } private string GetJsapiTicket(string bsname = "user") { var xmlPath = AppDomain.CurrentDomain.BaseDirectory + "JsapiTicket.xml"; var doc = XDocument.Load(xmlPath); // XElement provinceElement = doc.Element("person").Elements("user").Where(e => ((string)e.Attribute("Name")).Equals(bsname)).FirstOrDefault(); if (doc.Element("person").Element(bsname) == null) { doc.Element("person").Add(new XElement(bsname, new XElement("jsapi_ticket"), new XElement("jsapi_time"))); doc.Save(xmlPath); } //读取 var jsticket = doc.Element("person").Element(bsname).Element("jsapi_ticket").Value; var jstime = doc.Element("person").Element(bsname).Element("jsapi_time").Value; if (!string.IsNullOrEmpty(jsticket)) { if (Convert.ToDateTime(jstime) < DateTime.Now) { HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + GetTaken(bsname) + "&type=jsapi"); ASCIIEncoding encoding = new ASCIIEncoding(); requestScore.Method = "Get"; requestScore.ContentType = "application/x-www-form-urlencoded"; requestScore.KeepAlive = true; HttpWebResponse responseSorce = (HttpWebResponse)requestScore.GetResponse(); StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); requestScore = null; responseSorce.Close(); responseSorce = null; reader = null; jsapiTicketEntity jticket = new jsapiTicketEntity(); jticket = JsonConvert.DeserializeObject<jsapiTicketEntity>(content); //写入 doc.Element("person").Element(bsname).Element("jsapi_ticket").Value = jticket.ticket; doc.Element("person").Element(bsname).Element("jsapi_time").Value = DateTime.Now.AddHours(2).ToString(); doc.Save(xmlPath); return jticket.ticket; } else { return jsticket; } } else { HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + GetTaken(bsname) + "&type=jsapi"); ASCIIEncoding encoding = new ASCIIEncoding(); requestScore.Method = "Get"; requestScore.ContentType = "application/x-www-form-urlencoded"; requestScore.KeepAlive = true; HttpWebResponse responseSorce = (HttpWebResponse)requestScore.GetResponse(); StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); requestScore = null; responseSorce.Close(); responseSorce = null; reader = null; jsapiTicketEntity jticket = new jsapiTicketEntity(); jticket = JsonConvert.DeserializeObject<jsapiTicketEntity>(content); //写入 doc.Element("person").Element(bsname).Element("jsapi_ticket").Value = jticket.ticket; doc.Element("person").Element(bsname).Element("jsapi_time").Value = DateTime.Now.AddHours(2).ToString(); doc.Save(xmlPath); return jticket.ticket; } } private static string SHA1(string text) { byte[] cleanBytes = Encoding.Default.GetBytes(text); byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes); return BitConverter.ToString(hashedBytes).Replace("-", ""); } public static string GetPromoterCode(string p) { Maticsoft.BLL.CRM.TC_AntiFakeCode tcbll = new BLL.CRM.TC_AntiFakeCode(); if (p.Length != 20) { int s = p.IndexOf('|'); int ind = p.Length; string IndexCode = ""; if (s != -1) { IndexCode = p.Substring(s + 1, 4); p = p.Substring(0, s); } p = tcbll.GetPromoterCode(p); } return p; } public static string GetFAntiFakeBarCode(string p) { Maticsoft.BLL.CRM.TC_AntiFakeCode tcbll = new BLL.CRM.TC_AntiFakeCode(); if (p.Length != 20) { int s = p.IndexOf('|'); int ind = p.Length; string IndexCode = ""; if (s != -1) { IndexCode = p.Substring(s + 1, 4); p = p.Substring(0, s); } p = tcbll.GetFAntiFakeBarCode(p); } return p; } } public class AccessEntity { public string access_token { get; set; } public int expires_in { get; set; } } public class jsapiTicketEntity { public string ticket { get; set; } public int expires_in { get; set; } } }