C#微信网页开发---JSSDK使用 通过config接口注入权限验证配置

 1:   我们来看,下面的这个是开发需要配置的东西,我们通过开发文档来一个一个的配置

wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,公众号的唯一标识
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名
    jsApiList: [] // 必填,需要使用的JS接口列表
});

签名算法见文末的附录1,所有JS接口列表见文末的附录2

这个地方AppID,时间戳,随机字符串和js接口列表都很好得到,唯一比较难的就是签名

2:获取签名

    (1):获取签名的第一步,需要获得jsapi_ticket

  

 
 这个地方需要使用到access_token,access_token获取方法:http://blog.csdn.net/weixin_39462109/article/details/79438922

private static void  Getjsapi_ticket()
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi",Access_token);
            string backStr=Common.Get_Request(url);
            //string backStr = "{ \"errcode\":0,\"errmsg\":\"ok\",\"ticket\":\"kgt8ON7yVITDhtdwci0qeZWDYY9llY5RrKsWxKD--zOUIRYqJ1XwMo305bwZhG22b5hOl-TZ-gZAXCbMMHwvCw\",\"expires_in\":7200}";
            string str_ticket = backStr.Split(',')[2].Split(':')[1];
            Jsapi_ticket= str_ticket.Substring(1,str_ticket.Length-2);
        }
/// 
        /// 发送Get请求,并且得到返回结果
        /// 
        /// 
        /// 
        public static string Get_Request(string url)
        {
            System.Net.WebRequest wrq = System.Net.WebRequest.Create(url);
            wrq.Method = "GET";
            System.Net.WebResponse wrp = wrq.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(wrp.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8"));
            return sr.ReadToEnd();
        }
3:创建一个WX_Web_Config类,类中封装签名方法

     

 public class WX_Web_Config
    {
        private bool debug;
        private string appId;
        private string timestamp;
        private string nonceStr;
        private string signature;
        private List jsApiList=new List();
        private string url;


        public WX_Web_Config(bool debug, string appId, string timestamp, string nonceStr, string url)
        {
            this.debug = debug;
            this.appId = appId;
            this.timestamp = timestamp;
            this.nonceStr = nonceStr;
            this.url = url;
            this.signature = GetSignature();
        }

        /// 
        /// 是否开启调试模式
        /// 
        public bool Debug
        {
            get
            {
                return debug;
            }

            set
            {
                debug = value;
            }
        }

        /// 
        /// 必填,公众号的唯一标识
        /// 
        public string AppId
        {
            get
            {
                return appId;
            }

            set
            {
                appId = value;
            }
        }

        /// 
        /// 必填,生成签名的时间戳
        /// 
        public string Timestamp
        {
            get
            {
                return timestamp;
            }

            set
            {
                timestamp = value;
            }
        }

        /// 
        /// 必填,生成签名的随机串
        /// 
        public string NonceStr
        {
            get
            {
                return nonceStr;
            }

            set
            {
                nonceStr = value;
            }
        }

        /// 
        /// 必填,签名
        /// 
        public string Signature
        {
            get
            {
                return signature;
            }

            set
            {
                signature = value;
            }
        }
        /// 
        /// 必填,需要使用的JS接口列表
        /// 
        public List JsApiList
        {
            get
            {
                return jsApiList;
            }

            set
            {
                jsApiList = value;
            }
        }

        public string Url
        {
            get
            {
                return url;
            }

            set
            {
                url = value;
            }
        }

        /// 
        /// 得到签名
        /// 
        /// 
        private string GetSignature()
        {
            Hashtable hs = new Hashtable();
            hs.Add("jsapi_ticket", MvcApplication.Jsapi_ticket);//获取的
            hs.Add("noncestr", NonceStr);
            hs.Add("timestamp", Timestamp);
            hs.Add("url", Url);
            //得到string1
            string string1= formatParameters(hs);
            //对string1进行sha1签名
            Signature = HashCode(string1);
            return Signature;
        }

        /// 
        /// 参数名ASCII码从小到大排序(字典序)
        /// 
        /// 
        /// 
        private string formatParameters(Hashtable parameters)
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList(parameters.Keys);
            akeys.Sort();
            foreach (string k in akeys)
            {
                string v = (string)parameters[k];//防止参数不是字符串
                sb.Append(k.ToLower() + "=" + v + "&");
            }
            //去掉最后一个&
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }

        /// 
        /// 进行sha1签名
        /// 
        /// 
        /// 
        public static string HashCode(string str)
        {
            string rethash = "";
            try
            {

                System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
                System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
                byte[] combined = encoder.GetBytes(str);
                hash.ComputeHash(combined);
                rethash = Convert.ToBase64String(hash.Hash);
            }
            catch (Exception ex)
            {
                string strerr = "Error in HashCode : " + ex.Message;
            }
            return rethash;
        }


    }

4:创建一个枚举,用来存储所有的js接口名称

 

 public enum WX_Web_Js_Interface
    {
        onMenuShareTimeline,

        onMenuShareAppMessage,

        onMenuShareQQ,

        onMenuShareWeibo,

        onMenuShareQZone,

        startRecord,

        stopRecord,

        onVoiceRecordEnd,

        playVoice,

        pauseVoice,

        stopVoice,

        onVoicePlayEnd,

        uploadVoice,

        downloadVoice,

        chooseImage,

        previewImage,

        uploadImage,

        downloadImage,

        translateVoice,

        getNetworkType,

        openLocation,

        getLocation,

        hideOptionMenu,

        showOptionMenu,

        hideMenuItems,

        showMenuItems,

        hideAllNonBaseMenuItem,

        showAllNonBaseMenuItem,

        closeWindow,

        scanQRCode,

        chooseWXPay,

        openProductSpecificView,

        addCard,

        chooseCard,

        openCard


    }

6:在加载页面的时候调用WX_Web_Config构造函数

namespace 微信开发2018.Controllers
{
    public class WebController : Controller
    {
        // GET: Web
        public ActionResult Index()
        {
            WX_Web_Config config = new WX_Web_Config(true,WebConfigurationManager.AppSettings.Get("AppID"),DateTime.Now.ToLongDateString(),"tangjie", "http://116.21.25.73/Web/Index");
            config.JsApiList.Add(WX_Web_Js_Interface.addCard.ToString());
            config.JsApiList.Add(WX_Web_Js_Interface.chooseCard.ToString());
            return View(config);
        }
    }
}

7:前端界面显示

 @model  微信开发2018.WxCode.WX_Web.WX_Web_Config
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/Menu_LayoutPage.cshtml";
    
}

加载JSSDK


8:结果

C#微信网页开发---JSSDK使用 通过config接口注入权限验证配置_第1张图片





你可能感兴趣的:(C#,微信开发)