利用JS-SDK微信分享接口调用(后端.NET)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LYTIT/article/details/72454148

一直都想研究一下JS-SDK微信分享的接口调用,由于最近工作需要,研究了一下,目前只是实现了部分接口的调用;其他接口调用也是类似的;
在开发之前,需要提前准备一个微信公众号,并且域名JSAPI 配置接口正确,微信只能在部署在外网才能正常使用和测试;
闲话不多少说直接上代码 :

第一步:首先我们的有前端调用前端调用(实例代码)

<% if (IsWeiXinBrower)  <%--这里是后端写的一个判断是否为微信浏览器的方法判断--%>
            { %>
        <script src="/Scripts/jweixin-1.0.0.js?t=2016060160945"></script> <%--这个JS很重要,是微信官网的JS接口--%>
        <script src="/Scripts/weixincommon.js?t=2016060160945"></script><%--这个JS就是我自己写的一个方法封装了--%>
        <script type="text/javascript">
            if (wx){
                $(document).ready(function(){
                    WeiXinCommon2.WeiXinConfig();
                    var title = '<%= DtProductBasicInfo.Rows[0]["Productname"].ToString("") %>';
                    var content = title;
                    var link ='<%= WeiXinShareUrl %>';
                    var imgUrl = '<%= ShareImageUrl %>';//<%--<%= QRImageUrl %>--%>
                    wx.ready(function () {
                        WeiXinCommon2.ShareToFriend(title, content, link, imgUrl);
                        WeiXinCommon2.ShareToTimeLine(title, link, imgUrl);
                    });            
                });            
            }          
        </script>
   <% } %>

第二步:创建JS文件,例如:weixincommon.js,将下面的JS复制到封装的JS代码就可以了

function IsWeiXinBrowser() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    }
    else {
        return false;
    }
}
var WeiXinCommon2 = ({
    //配置
    WeiXinConfig: function () {
        $.ajax({
            async: false,
            url: '/WeiXinInterface/WeixinInterface.ashx',//调用的一般处理程序
            type: 'POST',
            dataType: "json",
            data: {
                type: "GetWeiXinJSApiConfig",
                url: window.location.href
            },
            error: function (xhr, status, err) {
            },
            success: function (json) {
                if (json.IsSuccess) {
                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                        appId: json.appId, // 必填,公众号的唯一标识
                        timestamp: json.timestamp, // 必填,生成签名的时间戳
                        nonceStr: json.noncestr, // 必填,生成签名的随机串
                        signature: json.signature,// 必填,签名,见附录1
                        jsApiList: [
                            'onMenuShareTimeline',
                            'onMenuShareAppMessage',
                            'onMenuShareQQ',
                            'onMenuShareWeibo',
                            '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'
                        ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
                    });
                }
                else {
                    //alert(json.Message);
                }
            }
        });
    },
    //分享给朋友
    ShareToFriend: function (title, desc, link, imgUrl, successFn, cancelFn, failFn) {
        wx.onMenuShareAppMessage({
            title: title,
            desc: desc,
            link: link,
            imgUrl: imgUrl,
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
                //alert('用户点击发送给朋友');
            },
            success: function (res) {
                if (typeof (successFn) == "function") {
                    successFn();
                }
            },
            cancel: function (res) {
                if (typeof (cancelFn) == "function") {
                    cancelFn();
                }
            },
            fail: function (res) {
                if (typeof (failFn) == "function") {
                    failFn();
                }
            }
        });
    },
    //分享至朋友圈
    ShareToTimeLine: function (title, link, imgUrl, successFn, cancelFn, failFn) {
        wx.onMenuShareTimeline({
            title: title,
            link: link,
            imgUrl: imgUrl,
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
                //alert('用户点击分享到朋友圈');
            },
            success: function (res) {
                if (typeof (successFn) == "function") {
                    successFn();
                }
            },
            cancel: function (res) {
                if (typeof (cancelFn) == "function") {
                    cancelFn();
                }
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
                if (typeof (failFn) == "function") {
                    failFn();
                }
            }
        });
    },
    //分享至QQ
    ShareToQQ: function (title, desc, link, imgUrl, completeFn, successFn, cancelFn, failFn) {
        wx.onMenuShareQQ({
            title: title,
            desc: desc,
            link: link,
            imgUrl: imgUrl,
            trigger: function (res) {
                alert('用户点击分享到QQ');
            },
            complete: function (res) {
                if (typeof (completeFn) == "function") {
                    completeFn();
                }
            },
            success: function (res) {
                if (typeof (successFn) == "function") {
                    successFn();
                }
            },
            cancel: function (res) {
                if (typeof (cancelFn) == "function") {
                    cancelFn();
                }
            },
            fail: function (res) {
                if (typeof (failFn) == "function") {
                    failFn();
                }
            }
        });
    },
    //分享至微博
    ShareToWeiBo: function (title, desc, link, imgUrl, completeFn, successFn, cancelFn, failFn) {
        wx.onMenuShareWeibo({
            title: title,
            desc: desc,
            link: link,
            imgUrl: imgUrl,
            trigger: function (res) {
                alert('用户点击分享到微博');
            },
            complete: function (res) {
                if (typeof (completeFn) == "function") {
                    completeFn();
                }
            },
            success: function (res) {
                if (typeof (successFn) == "function") {
                    successFn();
                }
            },
            cancel: function (res) {
                if (typeof (cancelFn) == "function") {
                    cancelFn();
                }
            },
            fail: function (res) {
                if (typeof (failFn) == "function") {
                    failFn();
                }
            }
        });
    },
    //隐藏菜单
    HideOptionMenu: function () {
        wx.hideOptionMenu();
    },
    //显示菜单
    ShowOptionMenu: function () {
        wx.showOptionMenu();
    },
    //批量隐藏菜单项
    HideMenuItems: function (menuList) {
        wx.hideMenuItems({
            menuList: menuList,
            //[
            //  'menuItem:readMode', // 阅读模式
            //  'menuItem:share:timeline', // 分享到朋友圈
            //  'menuItem:copyUrl' // 复制链接
            //],
            success: function (res) {
                //alert('已隐藏“阅读模式”,“分享到朋友圈”,“复制链接”等按钮');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        });
    },
    //批量显示菜单项
    ShowMenuItems: function (menuList) {
        wx.showMenuItems({
            menuList: menuList,
            //[
            //  'menuItem:readMode', // 阅读模式
            //  'menuItem:share:timeline', // 分享到朋友圈
            //  'menuItem:copyUrl', // 复制链接
            //  'menuItem:profile', // 查看公众号(已添加)
            //  'menuItem:addContact' // 查看公众号(未添加)
            //],
            success: function (res) {
                //alert('已显示“阅读模式”,“分享到朋友圈”,“复制链接”等按钮');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        });
    },
    //隐藏所有非基本菜单项
    HideAllNonBaseMenuItems: function(){
        wx.hideAllNonBaseMenuItem({
            success: function () {
                alert('已隐藏所有非基本菜单项');
            }
        });
    },
    //显示所有被隐藏的非基本菜单项
    ShowAllNonBaseMenuItems: function () {
        wx.showAllNonBaseMenuItem({
            success: function () {
                alert('已显示所有非基本菜单项');
            }
        });
    },
    //关闭当前窗口
    CloseWindow: function () {
        wx.closeWindow();
    }
});

第三步:后端代码(.NET)

      /// <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);
            DataRow dr = DevInfoBLL.LoadDeveloperInfo();//这是获取数据保存的配置信息,这个需要自定义
            string appId = dr != null ? dr["AppId"].ToString("") : "";
            string appSecret = dr != null ? dr["AppSecret"].ToString("") : "";
            if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(appSecret)) {
                result = new {
                    IsSuccess = false,
                    Message = "未录入开发者信息!",
                };
            }
            else {
                long timestamp = DateTime.Now.ToTimestamp();
                string noncestr = GetNonceStr();
                string signature = "";          
                if (!string.IsNullOrEmpty(appId) && !string.IsNullOrEmpty(appSecret)) {
                    signature = WeiXinMenuHelper.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 result.ToJson();
        }
        /// <summary>
        /// 取得微信JSApi签名
        /// </summary>
        /// <returns></returns>
        public static string GetJSApiTicketSignature(string appId, string appSecret, string noncestr, long timesStamp, string url)
        {
            string jsApiTicket = GetJSApiTicket(appId, appSecret);
            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();
        }

以上是实现的关键代码,可以根据自己的理解适当封装,来满足自己的需求,后续会有更多的微信JS-SDK接口实现陆续更新,请持续关注。。。

猜你喜欢

转载自blog.csdn.net/LYTIT/article/details/72454148