编程那点事编程那点事

专注编程入门及提高
探究程序员职业规划之道!

Net获取微信JS-SDK的signature签名

具体文档看这里:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

我没做任何封装,功能是实现了。

页面引用jweixin

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

页面ajax获取签名

url = location.href.split('#')[0];
            //alert(url);
            $.ajax({
                type: "post",
                url: "weixininterface.ashx?url=" + url,
                dataType: "json",
                async: false,
                success: function (data, textStatus) {
                    //salert(data.timestamp);
                    wx.config({
                        // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                        debug: false,
                        // 必填,公众号的唯一标识
                        appId: data.appId,
                        // 必填,生成签名的时间戳
                        timestamp: data.timestamp,
                        // 必填,生成签名的随机串
                        nonceStr: data.noncestr,
                        // 必填,签名
                        signature: data.signature,
                        // 必填,需要使用的JS接口列表
                        jsApiList: ['scanQRCode']
                    });

                    wx.error(function (res) {
                        alert("出错了:" + res.errMsg);//这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
                    });

                    wx.ready(function () {
                        wx.checkJsApi({
                            jsApiList: ['scanQRCode', 'chooseImage', 'uploadImage', 'downloadImage'],
                            success: function (res) {

                            }
                        });


                    });
                }
            });

weixininterface.ashx代码

public class weixininterface : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(GetWeiXinJSApiConfig(context));
            context.Response.End();
        }

        /// <summary>
        /// 取得JSApi配置
        /// </summary>
        /// <returns></returns>
        protected string GetWeiXinJSApiConfig(HttpContext context)
        {
            object result;

            string url = context.Request["url"].ToString();
            int lastIndexOfSharpChar = url.LastIndexOf('#');
            if (lastIndexOfSharpChar >= 0)
                url = url.Remove(lastIndexOfSharpChar);

            BLL.weixin_account bll = new BLL.weixin_account();
            Model.weixin_account model = bll.GetModel(1);
                
            string appId = model.appid;
            string appSecret = model.appsecret;
            if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(appSecret))
            {
                result = new
                {
                    IsSuccess = false,
                    Message = "未录入开发者信息!",
                };
            }
            else
            {
                long timestamp = ConvertDateTimeToInt(DateTime.Now);
                string noncestr = GetNonceStr();
                string signature = "";
                if (!string.IsNullOrEmpty(appId) && !string.IsNullOrEmpty(appSecret))
                {
                    signature = GetJSApiTicketSignature(appId, appSecret, noncestr, timestamp, url);//获取签名
                    result = new
                    {
                        IsSuccess = true,
                        Message = "",
                        appId = appId,
                        appSecret = appSecret,
                        timestamp = timestamp,
                        noncestr = noncestr,
                        signature = signature
                    };
                }
                else
                {
                    result = new
                    {
                        IsSuccess = false,
                        Message = "未取得微信配置信息!",
                    };
                }
            }

            return JsonConvert.SerializeObject(result);
        }
        /// <summary>
        /// 取得微信JSApi签名
        /// </summary>
        /// <returns></returns>
        public static string GetJSApiTicketSignature(string appId, string appSecret, string noncestr, long timesStamp, string url)
        {
            BLL.weixin_account bll = new BLL.weixin_account();
            Model.weixin_account model = bll.GetModel(1);

            string jsApiTicket = model.js_api_ticket;
            string hashSource = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}",jsApiTicket, noncestr, timesStamp, url);

            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(hashSource);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
            str_sha1_out = str_sha1_out.Replace("-", "");
            return str_sha1_out;
        }
        /// <summary>
        /// 取得nonceStr
        /// </summary>
        /// <returns></returns>
        public string GetNonceStr()
        {
            string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            StringBuilder sbResult = new StringBuilder();
            Random random = new Random(chars.Length);
            for (int i = 0; i < 32; i++)
            {
                sbResult.Append(chars[random.Next(chars.Length)]);
            }
            return sbResult.ToString();
        }

        /// <summary>    
        /// 将c# DateTime时间格式转换为Unix时间戳格式    
        /// </summary>    
        /// <param name="time">时间</param>    
        /// <returns>long</returns>    
        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位        
            return t;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

另外获取token、js api ticket可以看这篇文章:Java获取微信JS-SDK的signature签名

因为老是开发类似的接口,我用java的quartz框架写了个平台专门执行定时任务的。

未经允许不得转载: Net获取微信JS-SDK的signature签名