--微信分享首先要从后台传签名算法,后台方法 /// <summary> /// 签名算法 /// </summary> /// <param name="jsapi_ticket">jsapi_ticket</param> /// <param name="noncestr">随机字符串(必须与wx.config中的nonceStr相同)</param> /// <param name="timestamp">时间戳(必须与wx.config中的timestamp相同)</param> /// <param name="url">当前网页的URL,不包含#及其后面部分(必须是调用JS接口页面的完整URL)</param> /// <returns></returns> public string GetSignature(string noncestr, long timetamp, string url, string accessToken, out string string1) { string jsapi_ticket = GetTickect(accessToken); var string1Builder = new StringBuilder(); string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&") .Append("noncestr=").Append(noncestr).Append("&") .Append("timestamp=").Append(timetamp).Append("&") .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url); string1 = string1Builder.ToString(); return Sha1(string1); } private static string[] strs = new string[] { "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z", "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z" }; /// <summary> /// 创建随机字符串 /// </summary> /// <returns></returns> private string CreatenNonce_str() { Random r = new Random(); var sb = new StringBuilder(); var length = strs.Length; for (int i = 0; i < 15; i++) { sb.Append(strs[r.Next(length - 1)]); } return sb.ToString(); } /// <summary> /// 创建时间戳 /// </summary> /// <returns></returns> private long CreatenTimestamp() { return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000; } /// <summary> /// Sha1 /// </summary> /// <param name="orgStr"></param> /// <param name="encode"></param> /// <returns></returns> public static string Sha1(string orgStr, string encode = "UTF-8") { var sha1 = new SHA1Managed(); var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr); byte[] resultHash = sha1.ComputeHash(sha1bytes); string sha1String = BitConverter.ToString(resultHash).ToLower(); sha1String = sha1String.Replace("-", ""); return sha1String; } /// <summary> /// 获取AccessToken /// </summary> /// <returns></returns> public string GetAccessToken() { string cacheKey = string.Format(ModelCacheEventConsumer.TOKENNAME_PATTERN_KEY); var cacheModel = _cacheManager.Get(cacheKey, () => { string grant_type = "client_credential"; string appid = "wx76a637f31faef786"; string secret = "02ff8a2030305730c9f75b2335b7ce17"; ; string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret); string strReturn = Get(tokenUrl); strReturn = GetTokenStr(strReturn); return strReturn; }); return cacheModel; } public static string GetTokenStr(string tokenJsonStr) { //if(string.IsNullOrEmpty(tokenJsonStr) var strArray = tokenJsonStr.Split(','); var tokenArray = strArray[0].Split(':'); var tokenStr = tokenArray[1]; tokenStr = tokenStr.Replace("\"", string.Empty); return tokenStr; } public string GetJSAPIStr(string jsapiJsonStr) { //if(string.IsNullOrEmpty(tokenJsonStr) var strArray1 = jsapiJsonStr.Split(','); var strArray2 = strArray1[2].Split(':'); var tokenStr = strArray2[1]; tokenStr = tokenStr.Replace("\"", string.Empty); return tokenStr; } public string GetTickect(string accessToken) { string cacheKey = string.Format(ModelCacheEventConsumer.JSAPINAME_PATTERN_KEY); var cacheModel = _cacheManager.Get(cacheKey, () => { string type = "jsapi"; string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}", accessToken, type); string jsapi = Get(tokenUrl); jsapi = GetJSAPIStr(jsapi); return jsapi; }); //记录操作日志 //_logger.InsertLog(LogLevel.Debug, cacheModel); return cacheModel; } public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { //直接确认,否则打不开 return true; } public static string Get(string url) { System.GC.Collect(); string result = ""; HttpWebRequest request = null; HttpWebResponse response = null; //请求url以获取数据 try { //设置最大连接数 ServicePointManager.DefaultConnectionLimit = 200; //设置https验证方式 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } /*************************************************************** * 下面设置HttpWebRequest的相关属性 * ************************************************************/ request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; //获取服务器返回 response = (HttpWebResponse)request.GetResponse(); //获取HTTP返回数据 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = sr.ReadToEnd().Trim(); sr.Close(); } catch (Exception e) { throw new Exception(e.ToString()); } finally { //关闭连接和流 if (response != null) { response.Close(); } if (request != null) { request.Abort(); } } return result; } ---微信分享的前台js代码 <script> function getBasePath() { var curWwwPath = window.document.location.href; var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); var localhostPaht = curWwwPath.substring(0, pos); var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); return (localhostPaht + projectName); } //此处是使用了百度分享的插件 window._bd_share_config = { common: { bdText: "@Model.Name",//标题 bdUrl: '@Model.ProductSharlFPlusUrl?pro=@Model.PromoterInfo',//链接 bdMini: '2', bdMiniList: ['weixin', 'sqq'], bdPic: '@(Model.PictureModels.Any()?Model.PictureModels[0].ImageUrl:"")',//图片 data_track_clickback: true, onAfterClick: function (cmd) { if (cmd == 'sqq') { sucesscallback(3);//点击了qq分享后的回执方法 } } }, share: { "tag": 'share_1', "bdSize": 24 } }; //插件的JS加载部分,这是使用百度分享插件必须引用的js with (document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src ='@Url.Content("~/Content/BaiduShare/api/js/share.js?cdnversion=")' + ~(-new Date() / 36e5)]; if (isWeiXin()) { $('#shareesc').addClass('isdisplay'); $('#fenxiang').addClass('isdisplay'); wx.config({ debug: false, appId: 'wx76a637f31faef786', timestamp: '@ViewBag.timestamp',//这些值就是从后台获取的时间戳、数字签名、随机串 nonceStr: '@ViewBag.nonceStr', signature: '@ViewBag.signature', jsApiList: [ 'onMenuShareTimeline',//分享到朋友圈 'onMenuShareAppMessage'//分享到好友 ] }); var imgUrl = "@(Model.PictureModels.Any()?Model.PictureModels[0].ImageUrl:"")"; //图片LOGO注意必须是绝对路径 var lineLink = "@Model.ProductSharlFPlusUrl?pro=@Model.PromoterInfo"; //网站网址,必须是绝对路径 var descContent = '@Model.SubTitle'; //分享给朋友或朋友圈时的文字简介 var shareTitle = '@Model.Name'; //分享title var appid = 'wx76a637f31faef786'; //apiID,可留空,这个是注册了微信公众平台之后平台给的appid和secret //分享给好友 function shareFriend() { WeixinJSBridge.invoke('sendAppMessage', { "appid": appid, "img_url": imgUrl, "img_width": "200", "img_height": "200", "link": lineLink, "desc": descContent, "title": shareTitle, }, function (res) { if (res.err_msg == 'send_app_msg:ok') { sucesscallback(1); } }); } //分享到朋友圈 function shareTimeline() { WeixinJSBridge.invoke('shareTimeline', { "img_url": imgUrl, "img_width": "200", "img_height": "200", "link": lineLink, "desc": descContent, "title": shareTitle }, function (res) { if (res.err_msg == 'share_timeline:ok') { sucesscallback(2); } }); } // 当微信内置浏览器完成内部初始化后会触发WeixinJSBridgeReady事件。 document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { // 发送给好友 WeixinJSBridge.on('menu:share:appmessage', function (argv) { shareFriend(); }); // 分享到朋友圈 WeixinJSBridge.on('menu:share:timeline', function (argv) { shareTimeline(); }); }, false); wx.ready(function () { // 1 判断当前版本是否支持指定 JS 接口,支持批量判断 document.querySelector('#checkJsApi').onclick = function () { wx.checkJsApi({ jsApiList: [ 'onMenuShareTimeline', 'onMenuShareAppMessage' ], success: function (res) { alert(JSON.stringify(res)); } }); }; }); wx.error(function (res) { alert(res.errMsg); }); } //}; //判断是否是微信浏览器,因为qq 分享的时候点击微信都是在微信浏览器中打开当前页面,然后在微信浏览器中进行分享 function isWeiXin() { var ua = window.navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == 'micromessenger') { return true; } else { return false; } } //这是分享成功之后的回调函数,可以用来保存分享历史记录之类的 function sucesscallback(stype) { @if (WorkContext.CurrentCustomer.IsRegistered()) { <text> $.ajax({ cache: false, type: "GET", dataType: "json", contentType: "application/json;charset=utf-8", url: "@(Url.Action("BuildShareHistory", "Product"))", data: { productid: "@Model.Id", sharetype: stype, customerId: "@WorkContext.CurrentCustomer.Id" }, complete: function (data) { //返回根据文件名查询的值; var result = data.responseText.toString(); if (result == "1") { //分享成功; return false; } } }); </text> } else { <text> ; </text> } }; </script> <script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>//这个是调用微信分享官方接口必须的引用js