• C# 点击按钮分享公众号给好友


    最近客户提了个需求,在移动端首页加一个按钮,点击按钮实现分享给好友。
    啥也没说,先看了一篇微信开发文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

    接着配置了微信公众号开发平台域名和黑白名单,引用微信js:http://res.wx.qq.com/open/js/jweixin-1.6.0.js,获取参数,调用wx接口。

    前端代码:

    //分享公众号
        function wx_fx() {
            wx.config({
                debug: true, // 是否开启调试模式
                appId: "{$:#.appid}",
                timestamp: '{$:#.timestamp}', //时间戳
                nonceStr: '{$:#.nonceStr}', // 随机字符串
                signature: "{$:#.signature}",//签名
                jsApiList: [
    					'onMenuShareAppMessage'
    				] // 需要使用的JS接口列表
            })
           wx.ready(function(){
    
            //分享给朋友
            wx.onMenuShareAppMessage({
              title:'分享测试', // 分享标题
                desc:'测试分享', // 分享描述
                link: 'http://xxxx.com', // 分享链接
                imgUrl: 'http://xxxx.com/templets/mobile/images/index_101.png', // 分享图标
                type:'link', // 分享类型,music、video或link,不填默认为link
                dataUrl:'', // 如果type是music或video,则要提供数据链接,默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                     alert('分享成功');
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                      alert('取消了分享');
                }
            });
        });
    
     }
       
    </script>
    

     后台第一步:根据Appid和秘钥appSecret获取ticket令牌

      //获取ticket
            public string getJsApiTicket(string appid, string appSecret)
            {
                string ticket = string.Empty;
                if (!string.IsNullOrEmpty(appid) && !string.IsNullOrEmpty(appSecret))
                {
                    //这里开始从微信API获取ticket
                    string token = GetToken(appid, appSecret);
                
                    string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token=" + token + "";
                    Jsapi api = JsonConvert.DeserializeObject<Jsapi>(httpGet(url));
                    //FsLog.CreateLog("api:" + api, true);
                    ticket = api.ticket;
                    //FsLog.CreateLog("api.ticket:" + api.ticket, true);
                }
                return ticket;
            }
    
    
    
    
            // 获取access_token
            public string GetToken(string appid, string secret)
            {
                string strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret), "post");
                return GetJsonValue(strJson, "access_token");
            }
    

      第二步:生成时间戳获取随机字符串

     // 返回时间戳
                    string timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
     // 返回创建随机字符串
                    string nonceStr = createNonceStr();
    
            //创建随机字符串  
            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;
            }
    

      第三步:获取签名signature,可以写错误日志在ftp上查看问题,微信js接口签名效验:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign

                    // 返回签名signature
                    string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + pathurl + "";
                    string signature = SHA1_Hash(rawstring);
    
            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;
            }
    

      

      public string Keyword(string Appid, string appSecret)
            {
                string json = "";
                if (!string.IsNullOrEmpty(Appid)&&!string.IsNullOrEmpty(appSecret))
                {
                    //获取ticket
                    string jsapiTicket = getJsApiTicket(Appid, appSecret);
                    //FsLog.CreateLog("jsapiTicket:" + jsapiTicket, true);
    
                    // 返回时间戳
                    string timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
    
                    //FsLog.CreateLog("timestamp:" + timestamp, true);
    
                    // 返回创建随机字符串
                    string nonceStr = createNonceStr();
    
                    //FsLog.CreateLog("nonceStr:" + nonceStr, true);
    
                    // 返回签名signature
                    string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + pathurl + "";
                    string signature = SHA1_Hash(rawstring);
    
                    //FsLog.CreateLog("signature:" + signature, true);
    
                    json = timestamp + "," + nonceStr + "," + signature + "," + jsapiTicket;    
                }
                return json;
            }
    

      祝各位能用着开心

  • 相关阅读:
    Oozie简介
    ASP.NET Redis 开发
    迁移到 Express 4.x
    vim文本编辑器
    【Shell常用命令二】管道符 通配符
    【Shell常用命令一】echo bash alias history 输出重定向 快捷键
    【linux学习笔记八】常用命令
    【linux学习笔记七】关机重启命令
    【linux学习笔记六】压缩 解压缩命令
    【linux学习笔记五】帮助命令
  • 原文地址:https://www.cnblogs.com/jstblog/p/15090827.html
Copyright © 2020-2023  润新知