调用微信摄像头扫码

前台页面:

引用微信js : 

页面扫码按钮:

调用摄像头js:

View Code

 

后台代码:

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();
        }
View Code

获取签名:

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
{
    /// 
    /// 调用微信扫码积分
    /// 
    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(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(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(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(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; }
    }


}
View Code

 

转载于:https://www.cnblogs.com/SmilePastaLi/p/6878107.html

你可能感兴趣的:(调用微信摄像头扫码)