Asp.Net微信js分享
1、准备工作
官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111
必须是认证过的公众号才可以,先登录微信公众平台进入“公众号设置”的“功能设置”里填写“js接口安全域名”、“网页授权域名”
然后在开发设置中获取AppID和AppSecret,并设置ip白名单
2、前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>https://www.cnblogs.com/webapi/</title> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <meta name="description" content="https://www.cnblogs.com/webapi/" /> <meta name="keywords" content="https://www.cnblogs.com/webapi/" /> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="Pragma" content="no-cache"> <script src="https://cdn.bootcss.com/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script> <script type="text/javascript"> var pagetUrl = window.location.href; $(function () { //--微信JS配置 if (wx != null && wx != undefined) { if (pagetUrl.indexOf("#") > 0) { pagetUrl = str.substring(0, pagetUrl.indexOf("#")); }
$.ajax({
url: "weixinshare.aspx",
type: "post",
data: { purl: pagetUrl },
dataType: "json",
success: function (data) {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: data.appid, // 必填,公众号的唯一标识
timestamp: data.timestamp, // 必填,生成签名的时间戳
nonceStr: data.nonceStr, // 必填,生成签名的随机串
signature: data.signature, // 必填,签名,见附录1
jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}
});
wx.ready(function () { //自定义“分享给朋友”及“分享到QQ”按钮的分享内容(1.4.0) wx.ready(function () { //需在用户可能点击分享按钮前就先调用 wx.updateAppMessageShareData({ title: '微信分享测试-分享标题', // 分享标题 desc: '微信分享测试-分享描述,微信分享测试-分享描述', // 分享描述 link: pagetUrl, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: 'https://www.baidu.com/img/bd_logo1.png', // 分享图标 success: function () { // 设置成功 } }) }); //自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容(1.4.0) wx.ready(function () { //需在用户可能点击分享按钮前就先调用 wx.updateTimelineShareData({ title: '微信分享测试-分享标题,微信分享测试-分享描述', // 分享标题 link: pagetUrl, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: 'https://www.baidu.com/img/bd_logo1.png', // 分享图标 success: function () { // 设置成功 } }) }); }); } }); </script> </head> <body> <h1>微信分享测试</h1> <div> 微信JS-SDK是微信公众平台 面向网页开发者提供的基于微信内的网页开发工具包。通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照、选图、语音、位置等手机系统的能力,同时可以直接使用微信分享、扫一扫、卡券、支付等微信特有的能力,为微信用户提供更优质的网页体验。此文档面向网页开发者介绍微信JS-SDK如何使用及相关注意事项 </div> </body> </html>
3、后台
using LitJson; using System; using System.IO; using System.Net; using System.Security.Cryptography; using System.Text; public partial class weixin_weixin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#111 string url = Request.Form["purl"]; string appid = "wxd111111111111"; string appSecret = "8888888888888888888888888888"; string jsapiTicket = getJsApiTicket(appid, appSecret); // 获取时间戳 string timestamp = Convert.ToString(GetTimeStamp()); // 获取随机字符串 string nonceStr = createNonceStr(); // 获取签名signature string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url + ""; string signature = SHA1_Hash(rawstring); // 返回的json string json = "{\"appid\":\"" + appid + "\",\"timestamp\":\"" + timestamp + "\",\"nonceStr\":\"" + nonceStr + "\",\"signature\":\"" + signature + "\"}"; Response.Write(json); Response.End(); } //创建随机字符串 public 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; } public string GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } public string SHA1_Hash(string str_sha1_in) { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in); byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in); string str_sha1_out = BitConverter.ToString(bytes_sha1_out); str_sha1_out = str_sha1_out.Replace("-", "").ToLower(); return str_sha1_out; } // 获取Token public string GetToken(string appid, string secret) { //获取token,有效期7200秒,需要cache string strJson = string.Empty; if (GetCache("token") != null) { strJson = GetCache("token").ToString(); } else { strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret)); SetCache("token", strJson, 119); } JsonData jd = JsonMapper.ToObject(strJson); return jd["access_token"].ToString(); } //获取ticket public string getJsApiTicket(string appid, string appSecret) { //获取ticket,有效期7200秒,需要cache string token = GetToken(appid, appSecret); string strJson = string.Empty; if (GetCache("ticket") != null) { strJson = GetCache("ticket").ToString(); } else { strJson = RequestUrl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + token); SetCache("ticket", strJson, 119); } JsonData jd = JsonMapper.ToObject(strJson); return jd["ticket"].ToString(); }//公共方法,request网络获取 public string RequestUrl(string url) { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "get"; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); string content = sr.ReadToEnd(); return content; } /// <summary> /// 创建缓存项过期 /// </summary> /// <param name="key">缓存Key</param> /// <param name="obj">object对象</param> /// <param name="expires">过期时间(分钟)</param> public void SetCache(string key, object obj, int expires) { Cache.Insert(key, obj, null, DateTime.UtcNow.AddMinutes(expires), TimeSpan.Zero); } public object GetCache(string key) { if (string.IsNullOrEmpty(key)) { return null; } return Cache.Get(key); } }
//成功一定有方法,失败一定有原因。