当前位置:首页 > IT技术 > 微信平台 > 正文

微信jaapi签名
2021-07-28 12:41:29

public WeiXinJsSignature(string weixinUrl)
        {
            //string url = ConfigurationManager.AppSettings["UrlAddress"] + "/Home/Index";
            //string url = "http://mweb.zhijiaxing.net/circlerelationblog/Home/Index?type=11&id=5ea5b237-6ae5-49af-b7e5-64a583b1a321&ck=Zl8P3aQsTP36bskInAqlxL6p_yl9Z_emxvL8eTZsUiabYh22MoIVQw%3d%3d&from=singlemessage&isappinstalled=0";
            Timestamp = GetTimeStamp();
            Noncestr = Guid.NewGuid().ToString().Replace("-", "");
            string jsapiTicket = GetTicket();
            string sourceStr = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsapiTicket, Noncestr, Timestamp, weixinUrl);
            Signature = GetSHA1(sourceStr);
        }

  

/// <summary>
        /// 获取当前时间戳
        /// </summary>
        /// <returns></returns>
        private string GetTimeStamp()
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return ((int)(DateTime.Now - startTime).TotalSeconds).ToString();
        }

  

/// <summary>
        /// SHA1加密
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        private string GetSHA1(string source)
        {
            string rethash = "";
            try
            {

                System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
                System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
                byte[] combined = encoder.GetBytes(source);
                hash.ComputeHash(combined);

                var sb = new StringBuilder();
                foreach (var t in hash.Hash)
                {
                    sb.Append(t.ToString("x2"));
                }

                rethash = sb.ToString();
                //rethash = Convert.ToBase64String(hash.Hash);
            }
            catch (Exception ex)
            {
                LogWriter.ToError("加密失败 : " + ex.Message);
            }
            return rethash;
        }

  

public class HttpClientHelper
    {
        private static readonly HttpClient _httpClient;

        static HttpClientHelper()
        {
            _httpClient = new HttpClient();
        }
        public static string GetAccessToken()
        {
            var res = _httpClient.GetAsync(WChartConfig.Url).Result;
            try
            {
                if (res.IsSuccessStatusCode)
                {
                    string resCont = res.Content.ReadAsStringAsync().Result;
                    //{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    if (resCont.Contains("errcode"))
                    {
                        throw new Exception(resCont);
                    }
                    else
                    {
                        AccessTokenFromWChat re = JsonConvert.DeserializeObject<AccessTokenFromWChat>(resCont);
                        if (re != null && !string.IsNullOrWhiteSpace(re.access_token))
                        {
                            LogWriter.ToInfo("从微信获取:AccessToken:" + re.access_token + "有效时间:" + re.expires_in);
                            return re.access_token;
                        }
                    }
                }
                else
                {
                    throw new Exception("响应结果编码不正常");
                }
            }
            catch (Exception ex)
            {
                LogWriter.ToError(ex);
            }
            return null;
        }

        internal static string GetJsApiTicket(string token)
        {
            //{"errcode":0,"errmsg":"ok","ticket":"kgt8ON7yVITDhtdwci0qeb-gNJDxgAfi5m4ENt9ATtHvcqJU1OpSNrW4imnqjxOiXJDEvxemmRAsnclfGSPhiQ","expires_in":7200}
            string url = ConfigurationLoader.JsApiTicketUrl.Replace("ACCESS_TOKEN", token);
            var res = _httpClient.GetAsync(url).Result;
            try
            {
                if (res.IsSuccessStatusCode)
                {
                    string resCont = res.Content.ReadAsStringAsync().Result;
                    LogWriter.ToInfo("[GetJsApiTicket]获取到Ticket信息:" + resCont);
                    JsApiTicketFromWChat re = JsonConvert.DeserializeObject<JsApiTicketFromWChat>(resCont);
                    if (re.errcode == 0)
                        return re.ticket;
                }
            }
            catch (Exception ex)
            {
                LogWriter.ToError(ex);
            }
            return null;
        }
    }

  

 

public class WChartConfig
    {
        private static readonly string GrantType = "client_credential";
        public static readonly string AppId = ConfigurationManager.AppSettings.Get("AppId");
        private static readonly string AppSecret = ConfigurationManager.AppSettings.Get("AppSecret"); 
        public static readonly string Url =
         string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", GrantType, AppId, AppSecret);
    }

  

public class ConfigurationLoader
    {

        public static readonly string JsApiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; 
    }

  

本文摘自 :https://blog.51cto.com/u

开通会员,享受整站包年服务立即开通 >