zoukankan      html  css  js  c++  java
  • .NET微信自定义分享标题、缩略图、超链接及描述的设置方法

    前端Js引用:

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

    或者

     1 <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
     2     <script type="text/javascript">
     3         var data = '<%=JsApiirray %>';
     4         data = eval("(" + data + ")");//实例化
     5         wxconfig(data);
     6     </script>
     7     <script>
     8         function wxconfig(data) {
     9             wx.config({
    10                 // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    11                 debug: false,
    12                 // 必填,公众号的唯一标识
    13                 appId: data.appId,
    14                 // 必填,生成签名的时间戳
    15                 timestamp: data.timestamp,
    16                 // 必填,生成签名的随机串
    17                 nonceStr: data.nonceStr,
    18                 // 必填,签名
    19                 signature: data.signature,
    20                 // 必填,需要使用的JS接口列表
    21                 jsApiList: [
    22                      'checkJsApi',
    23                  'onMenuShareTimeline',
    24                'onMenuShareAppMessage',
    25                'onMenuShareQQ',
    26                  'onMenuShareWeibo'
    27                 ]
    28             });
    29         }
    30         /*
    31  * 注意:
    32  * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
    33  * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。
    34  * 3. 完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/1c97470084b73f8e224fe6d9bab1625b.html
    35  * 如有问题请通过以下渠道反馈:
    36  * 邮箱地址:weixin-open@qq.com
    37  * 邮件主题:【微信JS-SDK反馈】具体问题
    38  * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。
    39  *config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
    40  */
    41         wx.ready(function () {
    42             wx.checkJsApi({
    43                 jsApiList: [
    44                 'onMenuShareTimeline',
    45                    'onMenuShareAppMessage',
    46                     'onMenuShareQQ',
    47                     'onMenuShareWeibo'
    48                 ],
    49                 success: function (res) {
    50                     alert(JSON.stringify(res));
    51                 }
    52             });
    53             var shareData = {
    54                 title: '标题',
    55                 desc: '描述',
    56                 link: '链接',
    57                 imgUrl: '图片',
    58                 trigger: function (res) {
    59                     alert('用户点击发送给朋友');
    60                 },
    61                 success: function (res) {
    62                     alert('已分享');
    63                 },
    64                 cancel: function (res) {
    65                     alert('已取消');
    66                 },
    67                 fail: function (res) {
    68                     alert(JSON.stringify(res));
    69                 }
    70             };
    71             wx.onMenuShareAppMessage(shareData);
    72             wx.onMenuShareTimeline(shareData);
    73             wx.onMenuShareQQ(shareData);
    74             wx.onMenuShareWeibo(shareData);
    75         });
    76         wx.error(function (res) {
    77             // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
    78             alert("errorMSG:" + res);
    79         });
    80     </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 }

    附件为源码:微信分享Demo

  • 相关阅读:
    javaweb毕业设计
    Maven入门----MyEclipse创建maven项目(二)
    Maven入门----介绍及环境搭建(一)
    SpringMvc入门五----文件上传
    SpringMvc入门四----rest风格Url
    SpringMvc入门三----控制器
    SpringMvc入门二----HelloWorld
    SpringMvc入门一----介绍
    分析setup/hold电气特性从D触发器内部结构角度
    33. Search in Rotated Sorted Array
  • 原文地址:https://www.cnblogs.com/soulmate/p/5666957.html
Copyright © 2011-2022 走看看