微信公众号链接分享开发和遇到的问题

1.先看前端代码。

网上查了很多资料,前端代码是这样的

<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js" type="text/javascript"></script>
 <script type="text/javascript">

     $(function () {
        var obj = eval({"appId":"wx","timestamp":"1542958275","nonceStr":"qTYROSQLAkmXXK","signature":"E2BC1DE5481D2479927C87BE5734F"});
         wx.config({
             debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。  
             appId: obj.appId, // 必填,公众号的唯一标识  
             timestamp: obj.timestamp, // 必填,生成签名的时间戳  
             nonceStr: obj.nonceStr, // 必填,生成签名的随机串  
             signature: obj.signature, // 必填,签名,见附录1  
             jsApiList: [
                              'checkJsApi',
                              'onMenuShareTimeline',
                              'onMenuShareAppMessage',
                              'onMenuShareQQ',
                              'onMenuShareWeibo',
                              'chooseWXPay',
                              'hideOptionMenu',
                              'showMenuItems'
                          ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2  
         });
     })

     wx.ready(function () {
         wx.hideOptionMenu();
         wx.showMenuItems({
             menuList: ["menuItem:share:appMessage", "menuItem:share:timeline"] // 要显示的菜单项,所有menu项见附录3
         });

         //分享到朋友圈
         wx.onMenuShareTimeline({
             title: 'xxxxxx', // 分享标题
             desc: 'xxxxxxx',
             link: '<%=Url %>/Pages/HealthAnnualBill/IndexAnnualBill.aspx', // 分享链接,将当前登录用户转为puid,以便于发展下线  
             imgUrl: '<%=Url %>/Pages/HealthAnnualBill/img/分享图.jpg', // 分享图标  
             success: function () {
                 // 用户确认分享后执行的回调函数  
             },
             cancel: function () {
                 // 用户取消分享后执行的回调函数  
             }
         });
         wx.error(function (res) {
             // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。  
             alert("errorMSG:" + res);
         });
         //分享给朋友
         wx.onMenuShareAppMessage({
             title: 'xxxxxx', // 分享标题
             desc: 'xxxxxx', // 分享描述
             link: '<%=Url %>/Pages/HealthAnnualBill/IndexAnnualBill.aspx', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
             imgUrl: '<%=Url %>/Pages/HealthAnnualBill/img/分享图.jpg', // 分享图标
             type: 'link', // 分享类型,music、zvideo或link,不填默认为link
             dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
             success: function () {
                
                 // 用户确认分享后执行的回调函数
             },
             cancel: function () {
                 // 用户取消分享后执行的回调函数
             }
         });
     });
 
 </script>

(1)需要引用官方的js文件: <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js" type="text/javascript"></script>

(2)相信查过其它资料的大兄弟们都能看的懂,这里唯一要点是微信签名怎么生成

2.接下去我们来看微信签名怎么生成

(1)先取到“access_token” ,注意这里的access_token和“https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code” 授权后用code获取的access_token是不一样的,这里需要用“https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}”这个接口获取。

BaseAccessTokenDTO BaseAccessTokenDTO = this.Post<BaseAccessTokenDTO>(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appID, appsecret));
                       

(2)接着通过access_token获取“ticket”

ticketDTO ticketDTO = this.Post<ticketDTO>(string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", BaseAccessTokenDTO.access_token)); 
JSApiTicket = CreateSignature(appID, ticketDTO.ticket, Request.Url.AbsoluteUri);

“JSApiTicket”是一个json变量,会赋值给前台,“CreateSignature(appID, ticketDTO.ticket, Request.Url.AbsoluteUri)” 是一个拼接签名的方法

  /// <summary>
        /// 生成微信签名
        /// </summary>
        /// <returns></returns>
        public string CreateSignature(string APPID, string Ticket, string url)
        {

            var ticket = Ticket;
            string noncestr = CreatenNonce_str();
            long timestamp = CreatenTimestamp();

            var string1Builder = new StringBuilder();
            string1Builder.Append("jsapi_ticket=").Append(ticket).Append("&")
                          .Append("noncestr=").Append(noncestr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
            string string1 = string1Builder.ToString();

            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();
            //将mystr转换成byte[]
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(string1);
            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);
            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");

            FileWrite.WriteTextLog("签名jsapi_ticket:" + ticket);
            FileWrite.WriteTextLog("签名signature:" + string1);

            return "{\"appId\":\"" + APPID + "\",\"timestamp\":\"" + timestamp + "\",\"nonceStr\":\"" + noncestr + "\",\"signature\":\"" + hash + "\"}";
        }

        private static string[] strs = new string[]
        {
            "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"
        };

        /// <summary>
        /// 创建随机字符串
        ///本代码来自开源微信SDK项目:https://github.com/night-king/weixinSDK
        /// </summary>
        /// <returns></returns>
        public string CreatenNonce_str()
        {
            Random r = new Random();
            var sb = new StringBuilder();
            var length = strs.Length;
            for (int i = 0; i < 15; i++)
            {
                sb.Append(strs[r.Next(length - 1)]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 创建时间戳
        ///本代码来自开源微信SDK项目:https://github.com/night-king/weixinSDK
        /// </summary>
        /// <returns></returns>
        public long CreatenTimestamp()
        {
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }

 

开发过程中遇到的问题:“config:invalid url donmain” 。  wx.config中报错

开始以为是签名生成的不对,后来发现还需要在公众号平台上面配置“JS接口域名

下图

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值