.NET POST方式获取微信JSSDK的wx.config配置

最近公司微信扫一扫不能用,原来的是通过<script src="连接"></script>的方式获取wx.config配置。这种GET请求的方式没搞定,就通过下面方式解决了。

调用扫一扫页面代码,复制一下代码就可以了,注意一点URL地址要填写对,我这里是在同一项目下,所以不需要添加项目名

var linkUlr= location.href; // 获取当前扫一扫页面地址
  $.ajax({
    url: "jssdk.aspx/getInfoMation",//后台给你提供的接口
    type: "Post",
    data: "{'url':'"+linkUlr+"'}",
    async: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
      var datad = JSON.parse(data.d); //转译为Json字符串
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来
        appId: datad.appid, // 必填,公众号的唯一标识
        timestamp: datad.timestamp, // 必填,生成签名的时间戳
        nonceStr: datad.noncestr, // 必填,生成签名的随机串
        jsapi_ticket: datad.jsapi_ticket, //选填 调用微信JS的临时票据
        url: linkUlr,// 选填 当前扫一扫页面地址
        signature: datad.signature,// 必填,签名,见附录1
        jsApiList: ["scanQRCode"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
      });
      wx.error(function (res) {
        layer.msg(res);
      });
    },
    error: function (error) {
      layer.msg(error)
    }
 });   

 服务器端代码 

步1、创建WebFrom1.aspx文件,将其重命名为JsSdk.aspx

步2、在JsSdk.aspx.cs 添加一下代码  、

  需要注意的是一定要在getInfoMation方法上面添加[WebMethod] 至于其用法可以度娘看下

     /// <summary>
        /// 初始化微信接口返回参数
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [WebMethod] //此处如果不添加WebMethod,则页面调用不到
        public static string getInfoMation(string url) {
            try {
                string appid = System.Configuration.ConfigurationManager.AppSettings["appid"];
                string jsapiTicket = getJsApiTicket();
                //string url = HttpContext.Current.Request.Url.ToString();
                long timestamp = ConvertDateTimeInt();
                string nonceStr = createNonceStr();

                // 这里参数的顺序要按照 key 值 ASCII 码升序排序  
                //string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url + "";

                string signature = GetSignature(jsapiTicket, nonceStr, timestamp, url);
               
                //拼接json串返回前台
                string rtn = "{\"appid\":\"" + appid + "\",\"jsapi_ticket\":\"" + jsapiTicket + "\",\"noncestr\":\"" + nonceStr + "\",\"timestamp\":\"" + timestamp + "\",\"signature\":\"" + signature + "\"}";

                return rtn;
            } catch (Exception e) {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取jsapi_ticket微信公众号调用微信JS接口的临时票据
        /// </summary>
        private static string getJsApiTicket()
        {
            string accessToken = getAccessToken();
            string content = "";
            try
            {
                //TODO:注意api_ticket 是用于调用微信卡券JS API的临时票据,有效期为7200 秒,通过access_token 来获取。
                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;
                Stream responseStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
                //获取返回过来的结果
                content = sr.ReadToEnd();
                dynamic resultStr = JsonConvert.DeserializeObject(content, new { errcode = "", errmsg = "", ticket = "", expires_in = "" }.GetType());

                //请求成功
                if (resultStr.errcode == "0" && resultStr.errmsg == "ok")
                {
                    content = resultStr.ticket;
                }
                else
                {
                    content = "";
                }

                return content;
            }
            catch (Exception ex)
            {
                content = ex.Message;
                return content;
            }
        }

        /// <summary>
        /// 得到accesstoken 如果文件里时间 超时则重新获取 
        /// </summary>
        /// <returns></returns>        
        private static string getAccessToken()
        {
            // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
            string appid = System.Configuration.ConfigurationManager.AppSettings["appid"];
            string appsecret = System.Configuration.ConfigurationManager.AppSettings["appsecret"];
            //请求接口获取
            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();
            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;
            Stream responseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
            //获取返回过来的结果
            string content = sr.ReadToEnd();
            dynamic resultContent = JsonConvert.DeserializeObject(content, new { access_token = "", expires_in = "", errcode = "", errmsg = "" }.GetType());
            if (resultContent != null && !string.IsNullOrWhiteSpace(resultContent.access_token)) //注意:请求成功时是不会有errcode=0返回,判断access_token是否有值即可
            {
                return resultContent.access_token;//返回请求唯一凭证
            }
            else
            {
                //请求失败,返回为空
                return "";
            }

        }

        /// <summary>
        /// 获取当前时间戳
        /// </summary>
        /// <returns></returns>
        public static long ConvertDateTimeInt()
        {
            DateTime currentDate = DateTime.Now;//当前时间
            //转化为时间戳
            DateTime localTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return long.Parse((currentDate - localTime).TotalSeconds.ToString().Split('.')[0]);
        }

        /// <summary>
        /// 创建随机字符串  
        /// </summary>
        /// <returns></returns>
        private static string createNonceStr()
        {
            int length = 16;
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str = "";
            Random rad = new Random();
            for (int i = 0; i < length; i++)
            {
                str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
            }
            return str;
        }

        /// <summary>
        /// 获取签名
        /// </summary>
        /// <param name="jsapi_ticket">微信公众号调用微信JS临时票据</param>
        /// <param name="nonceStr">随机串</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="url">当前网页URL</param>
        /// <returns></returns>
        public static string GetSignature(string jsapi_ticket, string nonceStr, long timestamp, string url)
        {

            var string1Builder = new StringBuilder();
            //注意这里参数名必须全部小写,且必须有序
            string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
                          .Append("noncestr=").Append(nonceStr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);

            return Sha1(string1Builder.ToString(), Encoding.UTF8);
        }

        /// <summary>
        /// 签名加密,使用SHA加密所得
        /// </summary>
        /// <param name="content">签名加密参数</param>
        /// <param name="encode">编码UTF-8</param>
        /// <returns></returns>
        public static string Sha1(string content, Encoding encode)
        {
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                byte[] bytesIn = encode.GetBytes(content);
                byte[] bytesOut = sha1.ComputeHash(bytesIn);
                sha1.Dispose();
                string result = BitConverter.ToString(bytesOut);
                result = result.Replace("-", "");
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密出错:" + ex.Message);
            }
        }

   发布后,运行调用测试,已亲测没问题,已搞定扫一扫功能,当然,如果你想要调用微信地图等API只需要在wx.config里的jsApiList中添加地图接口标识即可。

  仅供参考,有改进的地方可以交流。

 

posted @ 2020-08-27 15:00  小温2597  阅读(659)  评论(0编辑  收藏  举报