C#
1.获取签名
public class WeiXinJsSignature { /// <summary> /// 构造函数 /// </summary> public WeiXinJsSignature() { string url = ConfigurationManager.AppSettings["UrlAddress"] + "/Home/Index";//分享的页面地址 Timestamp = GetTimeStamp(); Noncestr = Guid.NewGuid().ToString().Replace("-", ""); string jsapiTicket = GetTicket(); string sourceStr = string.Format("jsapi_ticket={0}&noncestr={1}×tamp={2}&url={3}", jsapiTicket, Noncestr, Timestamp, url); Signature = GetSHA1(sourceStr); } /// <summary> /// 公众号的唯一标识 /// </summary> public string AppId { get; set; } /// <summary> /// 生成签名的时间戳 /// </summary> public string Timestamp { get; set; } /// <summary> /// 生成签名的随机串 /// </summary> public string Noncestr { get; set; } /// <summary> /// 签名 /// </summary> public string Signature { get; set; } /// <summary> /// 获取JsApiTicket /// </summary> /// <returns></returns> public string GetTicket() { string ticket = string.Empty; try { string JsApiTicketUrl = System.Configuration.ConfigurationManager.AppSettings["JsApiTicket"]; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(JsApiTicketUrl); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string JsApiTicketString = string.Empty; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { JsApiTicketString = reader.ReadToEnd(); LogWriter.ToTrace(string.Format("获取JSAPITicke 结果:{0}", JsApiTicketString)); } var jsApiTicketObj = new { Code = "", ErrorMessage = "", AppId = "", JsApiTicket = "" }; var ticketObj = JsonConvert.DeserializeAnonymousType(JsApiTicketString, jsApiTicketObj); ticket = ticketObj.JsApiTicket; AppId = ticketObj.AppId; LogWriter.ToTrace(string.Format("获取JsApiTicket成功:{0} Appid:{1}", ticket, AppId)); } catch (Exception ex) { LogWriter.ToError(string.Format("获取JsApiTicket失败:{0}", ex.ToString())); } return ticket; } /// <summary> /// 获取当前时间戳 /// </summary> /// <returns></returns> private string GetTimeStamp() { DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return ((int)(DateTime.Now - startTime).TotalSeconds).ToString(); } /// <summary> /// SHA1加密 /// </summary> /// <param name="source"></param> /// <returns></returns> private string GetSHA1(string source) { 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(source); hash.ComputeHash(combined); var sb = new StringBuilder(); foreach (var t in hash.Hash) { sb.Append(t.ToString("x2")); } rethash = sb.ToString(); //rethash = Convert.ToBase64String(hash.Hash); } catch (Exception ex) { LogWriter.ToError("加密失败 : " + ex.Message); } return rethash; } }
2.配置
appsettings配置 <add key="JsApiTicket" value="http://IP:port/api/JsApiTicket" /> <add key="UrlAddress" value="http://localhost:5876" /> 这个是部署的分享页面服务的地址
3.返回给前端签名
private WeiXinJsSignature GetSignature() { WeiXinJsSignature WXJsSign = new WeiXinJsSignature(); return WXJsSign; }
ViewData["WeiXinJsSignature"] = JsonConvert.SerializeObject(GetSignature());
html
html <input type="hidden" id="WeiXinJsSignature" value="@ViewData["WeiXinJsSignature"]" /> js 引入<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> WeiXinJsMng: { WeiXinJsSignature: {}, init: function () {
var WeiXinJsSignature = $("#WeiXinJsSignature").val(); blogMng.WeiXinJsMng.WeiXinJsSignature = JSON.parse(WeiXinJsSignature); var apiList = ['previewImage', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']; //初始化配置 wx.config({ debug: false, appId: blogMng.WeiXinJsMng.WeiXinJsSignature.AppId, timestamp: blogMng.WeiXinJsMng.WeiXinJsSignature.Timestamp, nonceStr: blogMng.WeiXinJsMng.WeiXinJsSignature.Noncestr, signature: blogMng.WeiXinJsMng.WeiXinJsSignature.Signature, jsApiList: apiList }); window.share_config = { "share": { "imgUrl": "http://mweb.zhijiaxing.net/rvmeventshare/Content/Img/icon120.png",//分享图,默认当相对路径处理,所以使用绝对路径的的话,“http://”协议前缀必须在。 "desc": "车生活的美好瞬间尽在智驾行,快到碗里来...",//摘要,如果分享到朋友圈的话,不显示摘要。 "title": '智驾行-圈子日志分享',//分享卡片标题 "link": window.location.href,//分享出去后的链接,这里可以将链接设置为另一个页面。 "success": function () {//分享成功后的回调函数 }, 'cancel': function () { // 用户取消分享后执行的回调函数 } } }; wx.ready(function () { wx.onMenuShareAppMessage(share_config.share); wx.onMenuShareQQ(share_config.share); wx.onMenuShareWeibo(share_config.share); wx.onMenuShareQZone(share_config.share); wx.onMenuShareTimeline(share_config.share); });
} }
WeiXinJsMng.init();
这个是点击查看大图的js代码:你可以了解一下 imgPreview: function () { var imgs = $("#BlogImgList").children("img"); var srcList = []; $.each(imgs, function (i, item) { if ($(item).attr("originalsrc").length > 0) { srcList.push($(item).attr("originalsrc")); $(item).click(function (e) { // 通过这个API就能直接调起微信客户端的图片播放组件了 wx.previewImage({ current: $(this).attr("originalsrc"), // 当前显示图片的http链接 urls: srcList // 需要预览的图片http链接列表 }); }); } }); }
微信H5页面再分享到朋友圈,朋友,qq,qq空间,qq微博不显示图表描述 原因: 获取微信签名需要四个参数 jsapi_ticket 调用http://172.31.240.5:9017/api/JsApiTicket获取,无需参数 noncestr 随机字符串 timestamp 时间戳 url 分享的h5页面地址(nginx域名+文件夹代理配置+控制器+方法+参数) 例如:http://mweb.zhijiaxing.net/circlerelationblog/Home/Index?type=11&id=5ea5b237-6ae5-49af-b7e5-64a583b1a321&ck=Zl8P3aQsTP36bskInAqlxL6p_yl9Z_emxvL8eTZsUiabYh22MoIVQw%3d%3d&from=singlemessage&isappinstalled=0 url错误导致签名报错 invalid signature