关闭

html(h5)页面实现微信js分享

标签: 微信微信分享接口
12288人阅读 评论(2) 收藏 举报
分类:

html(h5)页面实现微信js分享

注:并非所有代码原创

服务端实现签名等


因为引用了第三方dll,所以需先添加nuget包,这个包直接在nuget管理器中搜索不到,在pm控制台输入如下内容:也
Install-Package Senparc.Weixin.MP -Version 14.3.5
但安装包时也会报错,找不到包,
可以从 https://www.nuget.org/packages/Senparc.Weixin.MP/14.3.5 左下方直接下载本地包,放到pm窗口提示的找不到包自动在本地找包的路径中,再执行该命令,即可安装成功

以下是利用该接口获取时间戳,签名的方法

using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Helpers;
using Utility;

namespace Mobile.App_Codes
{
    /// <summary>
    /// 微信分享接口封装
    /// </summary>
    public class WeiXin
    {
        /// <summary>
        /// 获取微信分享配置信息
        /// </summary>
        /// <param name="url">当前请求url</param>
        /// <returns></returns>
        public static WxConfig GetConfig(string url)
        {
            var key = "Mobile_Wxconfig" + url;
            var wxConfig = Cache.GetCache<WxConfig>(key.Md5());
            if (wxConfig != null && wxConfig.Signature.Length > 0)
            {
                return wxConfig;
            }
            else
            {
                wxConfig = new WxConfig();
                wxConfig.Timestamp = JSSDKHelper.GetTimestamp();
                wxConfig.NonceStr = JSSDKHelper.GetNoncestr();


                wxConfig.AppId = "wxe62testestetewtstest";
                wxConfig.AppSecret = "8b213499dtestesetrtestesteserewtest";
                wxConfig.Ticket = JsApiTicketContainer.TryGetJsApiTicket(wxConfig.AppId, wxConfig.AppSecret);

                wxConfig.Signature = JSSDKHelper.GetSignature(wxConfig.Ticket, wxConfig.NonceStr, wxConfig.Timestamp,
                    url);

                Cache.SetCache(key.Md5(), wxConfig, 60*60);
                return wxConfig;
            }
        }
    }
}

当然也可以自己代码实现这个, 具体的实现可以下这个项目的源码看下


下面列出是sha1计算签名的方法

        /// <summary>
        /// 获取JS-SDK权限验证的签名Signature
        /// </summary>
        /// <param name="ticket"></param>
        /// <param name="noncestr"></param>
        /// <param name="timestamp"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetSignature(string ticket, string noncestr, string timestamp, string url)
        {
            var parameters = new Hashtable();
            parameters.Add("jsapi_ticket", ticket);
            parameters.Add("noncestr", noncestr);
            parameters.Add("timestamp", timestamp);
            parameters.Add("url", url);
            return CreateSha1(parameters);
        }

        /// <summary>
        /// sha1加密
        /// </summary>
        /// <returns></returns>
        private static string CreateSha1(Hashtable parameters)
        {
            var sb = new StringBuilder();
            var akeys = new ArrayList(parameters.Keys);
            akeys.Sort();

            foreach (var k in akeys)
            {
                if (parameters[k] != null)
                {
                    var v = (string)parameters[k];

                    if (sb.Length == 0)
                    {
                        sb.Append(k + "=" + v);
                    }
                    else
                    {
                        sb.Append("&" + k + "=" + v);
                    }
                }
            }
            return SHA1UtilHelper.GetSha1(sb.ToString()).ToLower();
        }
        /// <summary>
        /// 签名算法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetSha1(string str)
        {
            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();
            //将mystr转换成byte[] 
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(str);
            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");
            return hash;
        }



签名,appid,AppSecret,这些放在服务端实现,不要放在js里,不安全,


下面主要讲前端如何调用实现分享


1 首先添加js引用 

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

2 在你要分享的页面合适的地方添加如下的js代码

var shareData = {};
shareData.imgUrl = window.ImgPrex + result.PicUrls;
shareData.link = window.location.href;
shareData.content = delHtmlTag($("#Contents").html());
shareData.title = document.title;
Share(shareData);

3 分享实现的代码

function Share(shareData) {

        var data = {};
        var wxdata = {};
        data.method = "GetConfig";
        data.url = window.location.href.split('#')[0];
        //这里是ajax向后台请求签名,appid等的方法
        ajaxProcess("/h5/share.aspx?", data, function callSuccess(oRet) {
            //var data = oRet;
            var result = oRet;
            if (result != null) {
                wx.config({
                    debug: false,
                    appId: result.AppId,
                    timestamp: result.Timestamp,
                    nonceStr: result.NonceStr,
                    signature: result.Signature,
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']
                });


            }
        }, function callError(e) {
            alert(e);
        });


        wxdata.imgUrl = shareData.imgUrl;
        wxdata.link = shareData.link;
        var content = shareData.content;
        content = delHtmlTag(content);
        if (content.length > 100) {
            wxdata.desc = content.substring(0, 100);
        } else {
            wxdata.desc = content;
        }
        wxdata.title = shareData.title;


        var friendcallback = function(res) {
            //alert("分享成功");
        };


        wx.ready(function() {
            wx.onMenuShareTimeline({
                title: wxdata.title,
                desc: wxdata.desc,
                link: wxdata.link,
                imgUrl: wxdata.imgUrl,
                img_width: 200,
                img_height: 200,
                trigger: function(res) {
                },
                success: function(res) {
                    friendcallback(res);
                },
                cancel: function(res) {
                },
                fail: function(res) {
                    alert(JSON.stringify(res));
                }
            });
        });


        wx.ready(function() {
            wx.onMenuShareAppMessage({
                title: wxdata.title,
                desc: wxdata.desc,
                link: wxdata.link,
                imgUrl: wxdata.imgUrl,
                img_width: 200,
                img_height: 200,
                trigger: function(res) {
                },
                success: function(res) {
                    friendcallback(res);
                },
                cancel: function(res) {
                },
                fail: function(res) {
                    alert(JSON.stringify(res));
                }
            });
        });


        wx.ready(function() {
            wx.onMenuShareQQ({
                title: wxdata.title,
                desc: wxdata.desc,
                link: wxdata.link,
                imgUrl: wxdata.imgUrl,
                img_width: 200,
                img_height: 200,
                trigger: function(res) {
                },
                success: function(res) {
                    friendcallback(res);
                },
                cancel: function(res) {
                },
                fail: function(res) {
                    alert(JSON.stringify(res));
                }
            });
        });


        wx.ready(function() {
            wx.onMenuShareWeibo({
                title: wxdata.title,
                desc: wxdata.desc,
                link: wxdata.link,
                imgUrl: wxdata.imgUrl,
                img_width: 200,
                img_height: 200,
                trigger: function(res) {
                },
                success: function(res) {
                    friendcallback(res);
                },
                cancel: function(res) {
                },
                fail: function(res) {
                    alert(JSON.stringify(res));
                }
            });
        });


        wx.ready(function() {
            wx.onMenuShareQZone({
                title: wxdata.title,
                desc: wxdata.desc,
                link: wxdata.link,
                imgUrl: wxdata.imgUrl,
                img_width: 200,
                img_height: 200,
                trigger: function(res) {
                },
                success: function(res) {
                    friendcallback(res);
                },
                cancel: function(res) {
                },
                fail: function(res) {
                    alert(JSON.stringify(res));
                }


            });


        });
    }

分享音频视频

如果想分享音频或视频,设置如下两个属性
type: 'link', // 分享类型,music、video或link,不填默认为link【必填】
dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空


以上就是实现的主要代码了

具体接口的说明文档可参考: 点击 https://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html

--- end ---


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2139232次
    • 积分:21032
    • 等级:
    • 排名:第355名
    • 原创:245篇
    • 转载:474篇
    • 译文:0篇
    • 评论:263条
    文章分类
    最新评论