微信JSSDK开发第一步的重要的config验证

这是一篇 16年没法出去的文章,忘记哪来的了。也许是自己写的,也许是复制。有知道的告诉我啊。

首先这上一篇适合刚开始搞微信网页开发的萌新。老鸟请飞走。

最近公司业务上需要,做微信的支付分享什么的等等等..总之是需要微信开发。

============先BB一下==================

微信JS-SDK是微信公众平台面向网页开发者提供的基于微信内的网页开发工具包。

通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力,为微信用户提供更优质的网页体验。

此文档面向网页开发者介绍微信JS-SDK如何使用及相关注意事项。 

============节奏跟上================== 

要使用微信的JSSDK,就必须通过验证config接口注入权限验证配置

1.先注册个微信公众号,JS接口安全域名

2. 通过appid和secret(在公众帐号里面找到)获取 token令牌

3通过token获取jsapi_ticket票据

4.获取到:signature签名=(1.jsapi_ticket票据,2.nonceStr签名的随机串,3.timestamp时间戳,4.url )

对流程就这这样子的。。。话不多说,直接上干货比较实在。

============节奏跟上================== 

  #region 微信
//需要引入一个Newtonsoft.Json.dll
//jssdk.css
        //令牌
        public string access_token_key = "access_token";
        public string access_token = "";
        //票据
        public string jsapi_ticket_key = "jsapi_ticket";
        public string jsapi_ticket = "";


        public string appid = "写入自己的";
        public string secret = "写入自己的";


        public void ProcessRequest()
        {
            Cache cache = HttpContext.Current.Cache;
            //cache.Remove(access_token_key);
            access_token = CacheHelper.GetVals(access_token_key); //读取内存access_token凭证
            //当access_token凭证过期时
            if (string.IsNullOrEmpty(access_token))
            {
                Get_token();
            }


            GetJsApi();
        }
  

 

//签名
        public string GetSignature(string jsapi_ticket, string noncestr, string timestamp, string url)
        {
            string tmpStr = "";
            //  return Common.JSAPI.GetSignature(CacheHelper.GetVals(jsapi_ticket_key), noncestr, timestamp, url);
            SortedList<string, string> SLString = new SortedList<string, string>();
            SLString.Add("noncestr", noncestr);
            SLString.Add("url", url);
            SLString.Add("timestamp", timestamp);
            SLString.Add("jsapi_ticket", jsapi_ticket);
            foreach (KeyValuePair<string, string> des in SLString) 
            {
                tmpStr += des.Key + "=" + des.Value + "&";
            }
            if (tmpStr.Length > 0)
                tmpStr = tmpStr.Substring(0, tmpStr.Length - 1);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            return tmpStr.ToLower();
        }


        // 第一步:获取access token 令牌
        public string Get_token()
        {
            string token = null;
            string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret + "";
            string str = Common.JSAPI.GetInfo(url);//这个 getinfo方法下面有
            token = jsonk(str, "access_token");
            if (token != null)
            {
                CacheHelper.Insert(access_token_key, token, 7200, 0); //这个微信那边只有7200有效时间
                jsapi_ticket = Get_ticket(token);  //请求获取 access_ticket 票据
            }
            return token;
        }


        //第二步:请求获取 access_ticket 票据
        public string Get_ticket(string token)
        {
            string ticket = null;
            string js = Common.JSAPI.GetInfo("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi");
            JObject jo = JObject.Parse(js);
            if (jo["errcode"].ToString() == "0")
            {
                ticket = jo["ticket"].ToString();
                CacheHelper.Insert(jsapi_ticket_key, ticket, 7200, 0);


            }
            return ticket;
        }

     //第三步:验证JsApi权限配置
        public void GetJsApi()
        {
             string url = Request.Url.AbsoluteUri.ToString();
            string timestamp = Common.JSAPI.CreatenTimestamp().ToString(); //时间戳
            string nonceStr = Common.JSAPI.getNoncestr(); //签名的随机串
            jsapi_ticket = CacheHelper.GetVals(jsapi_ticket_key);
            string signature = GetSignature(jsapi_ticket, nonceStr, timestamp, url);//签名
            //string data = "{\"appId\":\"" + appid + "\", \"timestamp\":" + timestamp + ",\"nonceStr\":\"" + nonceStr + "\",\"signature\":\"" + signature + "\"" + "\",\"jsapi_ticket\":\"" + jsapi_ticket + "\"}";     
        }

 
        //解析json
        public string jsonk(string str, string key)
        {
            try
            {
                JObject jo = JObject.Parse(str);
                string msg = jo[key].ToString();
                return msg;
            }
            catch (Exception)
            {
                return null;
            }
        }

  #endregion

//Common.JSAPI 类的方法

   /// <summary>     
        /// /// 生成时间戳 timespan     
        /// /// </summary>     
        /// /// <returns></returns>    
        public static string getTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        /// <summary>    
        /// /// 生成随机字符串nonceStr      
        /// /// </summary>      
        /// /// <returns></returns>      
        public static string getNoncestr()
        {
            Random random = new Random();
            return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK");
        }

        /// <summary>
        /// 这种方法懒得写,强行复制上的。获取url的返回值
        /// </summary>
        /// <param name="url"></param>
        public static string GetInfo(string url)
        {
            string strBuff = "";
            Uri httpURL = new Uri(url);
            ///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法 建立,并进行强制的类型转换 
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
            ///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换 
            HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
            ///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容 
            ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理 
            Stream respStream = httpResp.GetResponseStream();
            ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以 
            //StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8) 
            StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
            strBuff = respStreamReader.ReadToEnd();
            return strBuff;
        }

//CacheHelper 类的方法

  //根据key读取内存
    public static string GetVals(string key)
    {
        try
        {
            return cache.Get(key).ToString();
        }
        catch (Exception)
        {


            return null;
        }
    }

//存入缓存
 public static void Insert(string key, object obj, int Seconds,int i)
    {
        if (obj != null)
        {
            cache.Insert(key, obj, null, DateTime.MaxValue, TimeSpan.FromSeconds(Seconds), CacheItemPriority.High, null);
            //文件权重级别
            //_cache.Add("MyData", "缓存重要级别", null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30), CacheItemPriority.High, null);
            //30秒后就到期,立即移除,没商量
           // _cache.Insert("DD", "绝对过期测试", null, DateTime.Now.AddSeconds(5), System.Web.Caching.Cache.NoSlidingExpiration);
           // _cache.Insert(key, obj, null, DateTime.Now.AddSeconds(Seconds), System.Web.Caching.Cache.NoSlidingExpiration);
            //弹性过期时间,当缓存没使用10秒就过期
            //_cache.Insert("DD", "滑动过期测试", null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10));
         
        }
    }

=====================有问题没...项目里面代码太多,应该都完全了的

接下来就是网页前端的东西了

<script src="//cdn.bootcss.com/jquery/3.1.0/jquery.min.js" type="text/javascript"></script>

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: "", // 必填,公众号的唯一标识
                timestamp: "", // 必填,生成签名的时间戳
                nonceStr: "", // 必填,生成签名的随机串
                signature: ",// 必填,签名,见附录1
                jsApiList: [
                'checkJsApi',
                'onMenuShareAppMessage',
                'onMenuShareTimeline',
                'onMenuShareQQ'
                ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });
       
        wx.ready(function () {
            //当验证成功后,就会执行这里面的。要写到这里面才有作用

 wx.onMenuShareAppMessage({...............});

   });

==============================结束了===========应该还简单吧,我把方法都拆开了放上去的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值