微信公众号分享
2018-06-18 01:52:33来源:未知 阅读 ()
简单的写个微信分享的功能
aspx页面
引用
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<a href="javascript:wx_share()">分享</a>
js部分
$(function () { $.ajax({ type: "get", url: "后台路径", data: { url: location.href }, dataType: "json", success: function (data) { wx.config({ debug: false, appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: [ "onMenuShareTimeline", //分享到朋友圈 "onMenuShareAppMessage", //分享给好友 "onMenuShareQQ", //分享到QQ ] }); }, error: function (data) { //alert("连接失败!"); } }); }); function wx_share() { var sharehtml = "";//给予一个蒙城使用户只能点击微信右上角按钮 $("body").append(sharehtml); } var title, desc, img; title = ""; desc = ""; img = ""; var shareData = { title: title,//分享内容的标题 desc: desc,//这里请特别注意是要去除html link: window.location.href, //分享页的地址 imgUrl: img //分享中带有的图片 }; wx.ready(function () { wx.onMenuShareAppMessage(shareData);//分享给好友 wx.onMenuShareTimeline(shareData);//分享到朋友圈 wx.onMenuShareQQ(shareData);//分享到QQ });
C#后台接受部分
string url = Request.QueryString["url"]; var sign = GetSignPackage(url);//获取发送微信服务端的json数组字符串 var json = Common.NewJsonHelper.ObjectToJson<System.Collections.Hashtable>(sign);//就是将json字符串序列化一个json数组,每个公司用的不同,这个自己修改 Response.write(json);
获取json数组字符串
//得到数据包,返回使用页面 public static System.Collections.Hashtable GetSignPackage(string url) { string jsapiTicket = getJsApiTicket(); string timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now)); string nonceStr = createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url + ""; //得到签名 string signature = SHA1_Hash(rawstring); System.Collections.Hashtable signPackage = new System.Collections.Hashtable(); signPackage.Add("appId", "公众号appID"); signPackage.Add("nonceStr", nonceStr); signPackage.Add("timestamp", timestamp); signPackage.Add("url", url); signPackage.Add("signature", signature); signPackage.Add("rawString", rawstring); return signPackage; } //创建随机字符串 private static string createNonceStr() { int length = 16; string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string str = ""; Random rad = new Random(); for (int i = 0; i < length; i++) { str += chars.Substring(rad.Next(0, chars.Length - 1), 1); } return str; } //得到ticket 如果文件里时间 超时则重新获取 static string getJsApiTicket() { //这里我从数据库读取 string jticket = ""; string accessToken = getAccessToken();//获取系统的全局token string path = HttpContext.Current.Server.MapPath(@"/weixin/jsapi_ticket.json");//网上的都是写缓存,这个地方我是写一个全局json文件,最后会有说的 string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + accessToken; StreamReader sr = new StreamReader(path); string content = sr.ReadToEnd(); sr.Close(); JSTicket api = new JSTicket(); //未获取jsapi_ticket的情况 if (content.Length == 0) { Jsapi iden = JsonHelper.Deserialize<Jsapi>(RequestUrl(url, "get")); jticket = iden.ticket; if (jticket != "") { api.expire_time = ConvertDateTimeInt(DateTime.Now) + 7000; api.jsapi_ticket = jticket; string json = JsonHelper.GetJson<JSTicket>(api); StreamWriterMetod(json, path); } } else { var serializer = new DataContractJsonSerializer(typeof(JSTicket)); api = JsonHelper.Deserialize<JSTicket>(content); //时间过期重新获取 if (api.expire_time < ConvertDateTimeInt(DateTime.Now)) { Jsapi iden = JsonHelper.Deserialize<Jsapi>(RequestUrl(url, "get")); jticket = iden.ticket; if (jticket != "") { api.expire_time = ConvertDateTimeInt(DateTime.Now) + 7000; api.jsapi_ticket = jticket; string json = JsonHelper.GetJson<JSTicket>(api); StreamWriterMetod(json, path); } } else { jticket = api.jsapi_ticket; } } return jticket; } ////得到accesstoken 如果文件里时间 超时则重新获取 public static string getAccessToken() { // access_token 应该全局存储与更新,以下代码以写入到文件中做示例 string access_token = ""; string path = HttpContext.Current.Server.MapPath(@"/weixin/access_token.json");//我写的文件里面的,也可以自己写缓存 string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=123&secret=23";//appID自己修改,secret自己修改 StreamReader sr = new StreamReader(path); string content = sr.ReadToEnd(); sr.Close(); AccToken readJSTicket = new AccToken(); if (content.Length == 0) { AccToken iden = JsonHelper.Deserialize<AccToken>(RequestUrl(url, "get")); access_token = iden.access_token; if (access_token != "") { iden.expires_in = ConvertDateTimeInt(DateTime.Now) + 7000; iden.access_token = access_token; string json = JsonHelper.GetJson<AccToken>(iden); StreamWriterMetod(json, path); } } else { var serializer = new DataContractJsonSerializer(typeof(AccToken)); readJSTicket = JsonHelper.Deserialize<AccToken>(content); if (readJSTicket.expires_in < ConvertDateTimeInt(DateTime.Now)) { AccToken iden = JsonHelper.Deserialize<AccToken>(RequestUrl(url,"get")); access_token = iden.access_token; if (access_token != "") { iden.expires_in = ConvertDateTimeInt(DateTime.Now) + 7000; iden.access_token = access_token; string json = JsonHelper.GetJson<AccToken>(iden); StreamWriterMetod(json, path); } } else { access_token = readJSTicket.access_token; } } return access_token; } //发起一个http请球,返回值 private static string httpGet(string url) { try { WebClient MyWebClient = new WebClient(); MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据 Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据 string pageHtml = System.Text.Encoding.Default.GetString(pageData); //如果获取网站页面采用的是GB2312,则使用这句 return pageHtml; } catch (WebException webEx) { Console.WriteLine(webEx.Message.ToString()); return null; } } public static string RequestUrl(string url, string method) { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; } //SHA1哈希加密算法 public static string SHA1_Hash(string str_sha1_in) { //建立SHA1对象 SHA1 sha = new SHA1CryptoServiceProvider(); //将mystr转换成byte[] ASCIIEncoding enc = new ASCIIEncoding(); byte[] dataToHash = enc.GetBytes(str_sha1_in); //Hash运算 byte[] dataHashed = sha.ComputeHash(dataToHash); //将运算结果转换成string string hash = BitConverter.ToString(dataHashed).Replace("-", "").ToLower(); return hash; } /// <summary> /// StreamWriter写入文件方法 /// </summary> private static void StreamWriterMetod(string str, string patch) { try { StreamWriter swWriter = new StreamWriter(patch, false); swWriter.WriteLine(str); swWriter.Close(); } catch (Exception e) { throw e; } } /// <summary> /// 将c# DateTime时间格式转换为Unix时间戳格式 /// </summary> /// <param name="time">时间</param> /// <returns>double</returns> public static int ConvertDateTimeInt(System.DateTime time) { int intResult = 0; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); intResult = Convert.ToInt32((time - startTime).TotalSeconds); return intResult; }
json类
//创建Json序列化 及反序列化类目 #region //创建JSon类 保存文件 jsapi_ticket.json public class JSTicket { public string jsapi_ticket { get; set; } public double expire_time { get; set; } } //创建 JSon类 保存文件 access_token.json public class AccToken { public string access_token { get; set; } public double expires_in { get; set; } } //创建从微信返回结果的一个类 用于获取ticket public class Jsapi { public int errcode { get; set; } public string errmsg { get; set; } public string ticket { get; set; } public string expires_in { get; set; } } #endregion
前面会有说我定义的全局access_token和Ticket,网上大多写缓存,我这里写的全局文件
access_token.json
{"access_token":"","expires_in":0}
jsapi_ticket.json
{"expire_time":0,"jsapi_ticket":""}
差不多就这些了,记得点赞。
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:来份ASP.NET Core尝尝
下一篇:如何动态反射程序集
- 分享一个自己项目中用到的c++版的日志类(对初学者十分有用的 2020-05-22
- PC微信获取登录二维码 2020-05-18
- 游戏终端服务器分享(1.2版) 2020-02-11
- 分享一个Linux C++消息通信框架TCPSHM 2019-11-25
- QCustomplot使用分享(九) 绘制图表-多功能游标 2019-10-28
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash