微信分享获取signatrue

作者:outlela  来源:本站原创   发布时间:2021-6-21 19:57:50

[Skip]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WxShareController : ControllerBase
    {
        [EnableCors("ShareCors")]
        public ActionResult GetShareConfig(string url)
        {
            try
            {
                string appid = AppSettings.GetObject<string>("WechatDev:AppId");//appid
                string appSecret = AppSettings.GetObject<string>("WechatDev:AppSecret");//secret
                string jsapiTicket = GetJsApiTicket(appid, appSecret);
                // 获取时间戳
                string timestamp = Convert.ToString(GetTimeStamp());
                // 获取随机字符串
                string nonceStr = CreateNonceStr();
                // 获取签名signature
                string rawstring = $"jsapi_ticket={jsapiTicket}&noncestr={nonceStr}&timestamp={timestamp}&url={url}";
                string signature = SHA1_Hash(rawstring);
                var json = new { appid, timestamp, nonceStr, signature };
                var jsonstr = json.ToJson();
                Log4Helper.Info($"jsapiTicket:{jsapiTicket},URL:{url},{jsonstr}");
                return Content(jsonstr);
            }
            catch (Exception e)
            {
                Log4Helper.Error($"{e.Message}{e.InnerException?.Message}");
                return null;
            }

        }
        //创建随机字符串  
        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;
        }
        public string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        public string SHA1_Hash(string str_sha1_in)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = Encoding.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;
        }
        // 获取Token
        public string GetToken(string appid, string secret)
        {
            //获取token,有效期7200秒,需要cache
            string strJson = string.Empty;
            if (GetCache("sharetoken") != null)
            {
                strJson = GetCache("sharetoken").ToString();
            }
            else
            {
                strJson = RequestUrl($"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}");
                SetCache("sharetoken", strJson, 119);
            }


            var jd = strJson.ToObject<dynamic>();
            return jd.access_token.ToString();
        }
        //获取ticket
        public string GetJsApiTicket(string appid, string appSecret)
        {
            //获取ticket,有效期7200秒,需要cache
            string token = GetToken(appid, appSecret);

            string strJson = string.Empty;
            if (GetCache("shareticket") != null)
            {
                strJson = GetCache("shareticket").ToString();
            }
            else
            {
                strJson = RequestUrl($"https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={token}");
                SetCache("shareticket", strJson, 119);
            }


            var jd = strJson.ToObject<dynamic>();
            return jd.ticket.ToString();
        }//公共方法,request网络获取
        public string RequestUrl(string url)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "get";
            request.ContentType = "text/html";
            request.Headers.Add("charset", "utf-8");

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            return content;
        }
        /// <summary>
        /// 创建缓存项过期
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="obj">object对象</param>
        /// <param name="expires">过期时间(分钟)</param>
        public void SetCache(string key, object obj, int expires)
        {
            MemoryCacheHelper.Set(key, obj, TimeSpan.FromMinutes(expires));
        }
        public object GetCache(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }
            return MemoryCacheHelper.Get(key);
        }
    }

此方法适用于在微信内部打开的网页,点击右上角分享到朋友圈或好友!


注意事项:需要在公众号后台设置jssdk,安全域名及白名单IP。

页面js代码将在下一篇分享,不然篇幅太长,影响阅读。

*本文最后修改于:2021-6-21 20:6:29
本文标签: 微信 分享 signatrue .net c# 好友 朋友圈
本文由本站原创发布, 本文链接地址:https://outlela.com/Code/120.html
转载或引用请保留地址并注明出处:outlela.com