分享到微信朋友圈页面

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}&timestamp={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);
    wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
      appId: blogMng.WeiXinJsMng.WeiXinJsSignature.AppId, // 必填,公众号的唯一标识
      timestamp: blogMng.WeiXinJsMng.WeiXinJsSignature.Timestamp, // 必填,生成签名的时间戳
      nonceStr: blogMng.WeiXinJsMng.WeiXinJsSignature.Noncestr, // 必填,生成签名的随机串
      signature: blogMng.WeiXinJsMng.WeiXinJsSignature.Signature,// 必填,签名,见附录1
      jsApiList: ["previewImage"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    });
  }
}
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链接列表
        });
      });
    }
  });
}

  

  

分享到微信朋友圈页面

上一篇:微信公众号菜单添加小程序,miniprogram,pagepath参数详解,php开发公众号


下一篇:一,微信公众号配置