这位怪蜀黍 中午的时光真难熬!还好有你在!

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接口。

前端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//分享公众号
    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令牌

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//获取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");
      }

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 返回时间戳
               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

1
2
3
4
5
6
7
8
9
10
11
12
13
        // 返回签名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;
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
      }

  祝各位能用着开心

 

posted @   蟾宝  阅读(215)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示