码迷,mamicode.com
首页 > 微信 > 详细

微信分享自定义设置Title与Desc

时间:2016-07-13 19:42:53      阅读:4056      评论:0      收藏:0      [点我收藏+]

标签:

前端Js引用:

  1 <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
  2 <script>
  3     function wxconfig(data) {
  4         wx.config({
  5             // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  6             debug: false,
  7             // 必填,公众号的唯一标识
  8             appId: data.appId,
  9             // 必填,生成签名的时间戳
 10             timestamp: data.timestamp,
 11             // 必填,生成签名的随机串
 12             nonceStr: data.nonceStr,
 13             // 必填,签名
 14             signature: data.signature,
 15             // 必填,需要使用的JS接口列表
 16             jsApiList: [
 17                 ‘checkJsApi‘,
 18                 ‘onMenuShareTimeline‘,
 19                 ‘onMenuShareAppMessage‘,
 20                 ‘onMenuShareQQ‘,
 21                 ‘onMenuShareWeibo‘
 22             ]
 23         });
 24     }
 25     // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
 26     wx.ready(function () {
 27         wx.checkJsApi({
 28             jsApiList: [
 29                 ‘onMenuShareTimeline‘,
 30                 ‘onMenuShareAppMessage‘,
 31                 ‘onMenuShareQQ‘,
 32                 ‘onMenuShareWeibo‘
 33             ]
 34         });
 35         var title = "上海长宽神游戏“神龟不掉线”,千万别小看它!";
 36         var des = "我玩过了上海长宽的游戏神作“神龟不掉线”,真的比想象中更难,你快来试试并领取电影红包吧!";
 37         wx.onMenuShareTimeline({
 38             title: title, //分享标题
 39             link: ‘http://m.gwbnsh.net.cn/sgbdx/‘, //分享链接
 40             desc: des, //分享描述
 41             imgUrl: ‘http://m.gwbnsh.net.cn/sgbdx/img/logo.png‘,//分享图片地址
 42             trigger: function (res) {
 43                 //alert(‘用户点击分享到朋友圈‘);
 44             },
 45             success: function (res) {
 46                 $.ajax({
 47                     type: "POST",
 48                     url: "User.ashx",   //处理页的相对地址
 49                     data: { isshare: 1 },
 50                     async: true,
 51                     success: function (data) {
 52                         location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF";
 53                     }
 54                 });
 55             },
 56             cancel: function (res) {
 57                 //alert(‘已取消‘);
 58             }
 59         });
 60         wx.onMenuShareAppMessage({
 61             title: title, //分享标题
 62             link: ‘http://m.gwbnsh.net.cn/sgbdx/‘, //分享链接
 63             desc: des, //分享描述
 64             imgUrl: ‘http://m.gwbnsh.net.cn/sgbdx/img/logo.png‘,//分享图片地址
 65             trigger: function (res) {
 66                 //alert(‘用户点击分享到朋友圈‘);
 67             },
 68             success: function (res) {
 69                 $.ajax({
 70                     type: "POST",
 71                     url: "User.ashx",   //处理页的相对地址
 72                     data: { isshare: 1 },
 73                     async: true,
 74                     success: function (data) {
 75                         location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF";
 76                     }
 77                 });
 78             },
 79             cancel: function (res) {
 80                 //alert(‘已取消‘);
 81             }
 82         });
 83         wx.onMenuShareQQ({
 84             title: title, //分享标题
 85             link: ‘http://m.gwbnsh.net.cn/sgbdx/‘, //分享链接
 86             desc: des, //分享描述
 87             imgUrl: ‘http://m.gwbnsh.net.cn/sgbdx/img/logo.png‘,//分享图片地址
 88             trigger: function (res) {
 89                 //alert(‘用户点击分享到朋友圈‘);
 90             },
 91             success: function (res) {
 92                 $.ajax({
 93                     type: "POST",
 94                     url: "User.ashx",   //处理页的相对地址
 95                     data: { isshare: 1 },
 96                     async: true,
 97                     success: function (data) {
 98                         location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF";
 99                     }
100                 });
101             },
102             cancel: function (res) {
103                 //alert(‘已取消‘);
104             }
105         });
106         wx.onMenuShareQZone({
107             title: title, //分享标题
108             link: ‘http://m.gwbnsh.net.cn/sgbdx/‘, //分享链接
109             desc: des, //分享描述
110             imgUrl: ‘http://m.gwbnsh.net.cn/sgbdx/img/logo.png‘,//分享图片地址
111             trigger: function (res) {
112                 //alert(‘用户点击分享到朋友圈‘);
113             },
114             success: function (res) {
115                 $.ajax({
116                     type: "POST",
117                     url: "User.ashx",   //处理页的相对地址
118                     data: { isshare: 1 },
119                     async: true,
120                     success: function (data) {
121                         location = "http://m.maizuo.com/act/lucky-package/?__locate=false#!/active/NUxySmNbvQFF";
122                     }
123                 });
124             },
125             cancel: function (res) {
126                 //alert(‘已取消‘);
127             }
128         });
129     });
130 </script>
131 <script type="text/javascript">
132     var data = ‘<%=JsApiirray %>‘;
133     data = eval("(" + data + ")");//实例化
134     wxconfig(data);
135 </script>

 

验证JsAPI权限配置:

 1 #region 验证JsApi权限配置
 2     /// <summary>
 3     /// 获取JsApi权限配置的数组/四个参数
 4     /// </summary>
 5     /// <returns></returns>
 6     public string GetJsApiInfo(string Appid, string Appsecret)
 7     {
 8         string timestamp = CommonMethod.ConvertDateTimeInt(DateTime.Now).ToString();//生成签名的时间戳
 9         string nonceStr = CommonMethod.GetRandCode(16);//生成签名的随机串
10         string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.ToString();//当前的地址
11         string jsapi_ticket = "";
12         //ticket 缓存7200秒
13         if (System.Web.HttpContext.Current.Session["jsapi_ticket"] == null)
14         {
15             jsapi_ticket = CommonMethod.WebRequestPostOrGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + BasicApi.GetTokenSession(Appid, Appsecret) + "&type=jsapi", "");
16             System.Web.HttpContext.Current.Session["jsapi_ticket"] = jsapi_ticket;
17             System.Web.HttpContext.Current.Session.Timeout = 7200;
18         }
19         else
20         {
21             jsapi_ticket = System.Web.HttpContext.Current.Session["jsapi_ticket"].ToString();
22         }
23         Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(jsapi_ticket);
24         jsapi_ticket = respDic["ticket"].ToString();//获取ticket
25         string[] ArrayList = { "jsapi_ticket=" + jsapi_ticket, "timestamp=" + timestamp, "noncestr=" + nonceStr, "url=" + url };
26         Array.Sort(ArrayList);
27         string signature = string.Join("&", ArrayList);
28         signature = Md5Hash(signature).ToLower();
29         return "{\"appId\":\"" + Appid + "\", \"timestamp\":" + timestamp + ",\"nonceStr\":\"" + nonceStr + "\",\"signature\":\"" + signature + "\"}";
30     }
31     /// <summary>
32     /// 32位MD5加密
33     /// </summary>
34     /// <param name="input"></param>
35     /// <returns></returns>
36     private string Md5Hash(string input)
37     {
38         MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
39         byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
40         StringBuilder sBuilder = new StringBuilder();
41         for (int i = 0; i < data.Length; i++)
42         {
43             sBuilder.Append(data[i].ToString("x2"));
44         }
45         return sBuilder.ToString();
46     }
47 
48     #endregion

基础接口BasicApi.cs:

 1 using System.Collections.Generic;
 2 using System.Net;
 3 using System.Text;
 4 using System.Web;
 5 using System.Web.Script.Serialization;
 6 using Newtonsoft.Json.Linq;
 7 using Newtonsoft.Json;
 8 namespace Web
 9 {// <summary>
10     /// 基础接口
11     /// </summary>
12     public class BasicApi
13     {
14         public static string SessionAccessToken = "";//access_token缓存 其他接口的通行证
15 
16         public BasicApi() { }
17 
18         #region 获取access_token缓存
19         public static string GetTokenSession(string AppID, string AppSecret)
20         {
21             string TokenSession = "";
22 
23             if (System.Web.HttpContext.Current.Session[SessionAccessToken] == null)
24             {
25                 TokenSession = AddTokenSession(AppID, AppSecret);
26             }
27             else
28             {
29                 TokenSession = System.Web.HttpContext.Current.Session[SessionAccessToken].ToString();
30             }
31 
32             return TokenSession;
33         }
34         /// <summary>
35         /// 添加AccessToken缓存
36         /// </summary>
37         /// <param name="AppID"></param>
38         /// <param name="AppSecret"></param>
39         /// <returns></returns>
40         public static string AddTokenSession(string AppID, string AppSecret)
41         {
42             //获取AccessToken
43             string AccessToken = GetAccessToken(AppID, AppSecret);
44             HttpContext.Current.Session[SessionAccessToken] = AccessToken;
45             HttpContext.Current.Session.Timeout = 7200;
46             return AccessToken;
47         }
48 
49         /// <summary>
50         /// 获取AccessToken
51         /// </summary>
52         /// <param name="AppID"></param>
53         /// <param name="AppSecret"></param>
54         /// <returns></returns>
55         public static string GetAccessToken(string AppID, string AppSecret)
56         {
57             JavaScriptSerializer Jss = new JavaScriptSerializer();
58             string respText = CommonMethod.WebRequestPostOrGet(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret), "");
59             Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
60             string accessToken = respDic["access_token"].ToString();
61             return accessToken;
62         }
63         /// <summary>
64         /// 用code换取获取用户信息(包括非关注用户的)
65         /// </summary>
66         /// <param name="openid"></param>
67         /// <param name="access_token"></param>
68         /// <returns></returns>
69         public static JObject GetUserInfo(string openid, string access_token)
70         {
71             JavaScriptSerializer Jss = new JavaScriptSerializer();
72             string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);
73             WebClient wc = new WebClient();
74             byte[] bytes = wc.DownloadData(url);
75             wc.Encoding = Encoding.UTF8;
76             string jsonText = Encoding.UTF8.GetString(bytes);
77             JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
78             return jo;
79         }
80         #endregion
81     }
82 }

通用方法CommonMethod.cs:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Net;
  5 using System.Web;
  6 
  7 namespace Web
  8 {
  9     /// <summary>
 10     /// 通用方法类
 11     /// </summary>
 12     public class CommonMethod
 13     {
 14         #region Post/Get提交调用抓取
 15         /// <summary>
 16         /// Post/get 提交调用抓取
 17         /// </summary>
 18         /// <param name="url">提交地址</param>
 19         /// <param name="param">参数</param>
 20         /// <returns>string</returns>
 21         public static string WebRequestPostOrGet(string sUrl, string sParam)
 22         {
 23             byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam);
 24 
 25             Uri uriurl = new Uri(sUrl);
 26             HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param);
 27             req.Method = "Post";
 28             req.Timeout = 120 * 1000;
 29             req.ContentType = "application/x-www-form-urlencoded;";
 30             req.ContentLength = bt.Length;
 31 
 32             using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存
 33             {
 34                 reqStream.Write(bt, 0, bt.Length);
 35                 reqStream.Flush();
 36             }
 37             try
 38             {
 39                 using (WebResponse res = req.GetResponse())
 40                 {
 41                     //在这里对接收到的页面内容进行处理 
 42 
 43                     Stream resStream = res.GetResponseStream();
 44 
 45                     StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8);
 46 
 47                     string resLine;
 48 
 49                     System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder();
 50 
 51                     while ((resLine = resStreamReader.ReadLine()) != null)
 52                     {
 53                         resStringBuilder.Append(resLine + System.Environment.NewLine);
 54                     }
 55 
 56                     resStream.Close();
 57                     resStreamReader.Close();
 58 
 59                     return resStringBuilder.ToString();
 60                 }
 61             }
 62             catch (Exception ex)
 63             {
 64                 return ex.Message;//url错误时候回报错
 65             }
 66         }
 67         #endregion Post/Get提交调用抓取
 68 
 69         #region unix/datatime 时间转换
 70         /// <summary>
 71         /// unix时间转换为datetime
 72         /// </summary>
 73         /// <param name="timeStamp"></param>
 74         /// <returns></returns>
 75         public static DateTime UnixTimeToTime(string timeStamp)
 76         {
 77             DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
 78             long lTime = long.Parse(timeStamp + "0000000");
 79             TimeSpan toNow = new TimeSpan(lTime);
 80             return dtStart.Add(toNow);
 81         }
 82 
 83         /// <summary>
 84         /// datetime转换为unixtime
 85         /// </summary>
 86         /// <param name="time"></param>
 87         /// <returns></returns>
 88         public static int ConvertDateTimeInt(System.DateTime time)
 89         {
 90             System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
 91             return (int)(time - startTime).TotalSeconds;
 92         }
 93         #endregion
 94 
 95         #region 记录bug,以便调试
 96         /// <summary>
 97         /// 记录bug,以便调试
 98         /// </summary>
 99         public static bool WriteTxt(string str)
100         {
101             try
102             {
103                 string LogPath = HttpContext.Current.Server.MapPath("/err_log/");
104                 if (!Directory.Exists(LogPath))
105                 {
106                     Directory.CreateDirectory(LogPath);
107                 }
108                 FileStream FileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("/err_log//lwf_" + DateTime.Now.ToLongDateString() + "_.txt"), FileMode.Append);
109                 StreamWriter StreamWriter = new StreamWriter(FileStream);
110                 //开始写入
111                 StreamWriter.WriteLine(str);
112                 //清空缓冲区
113                 StreamWriter.Flush();
114                 //关闭流
115                 StreamWriter.Close();
116                 FileStream.Close();
117             }
118             catch (Exception)
119             {
120                 return false;
121             }
122             return true;
123         }
124         #endregion
125 
126         #region 生成随机字符
127         /// <summary>
128         /// 生成随机字符
129         /// </summary>
130         /// <param name="iLength">生成字符串的长度</param>
131         /// <returns>返回随机字符串</returns>
132         public static string GetRandCode(int iLength)
133         {
134             string sCode = "";
135             if (iLength == 0)
136             {
137                 iLength = 4;
138             }
139             string codeSerial = "0,1,2,3,4,5,6,7,8,9,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";
140             string[] arr = codeSerial.Split(,);
141             int randValue = -1;
142             Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
143             for (int i = 0; i < iLength; i++)
144             {
145                 randValue = rand.Next(0, arr.Length - 1);
146                 sCode += arr[randValue];
147             }
148             return sCode;
149         }
150         #endregion
151     }
152 }

 

微信分享自定义设置Title与Desc

标签:

原文地址:http://www.cnblogs.com/soulmate/p/5666957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!