當(dāng)前位置:首頁(yè) > IT技術(shù) > 微信平臺(tái) > 正文

微信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>
        /// 獲取當(dāng)前時(shí)間戳
        /// </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 + "有效時(shí)間:" + re.expires_in);
                            return re.access_token;
                        }
                    }
                }
                else
                {
                    throw new Exception("響應(yīng)結(jié)果編碼不正常");
                }
            }
            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

開(kāi)通會(huì)員,享受整站包年服務(wù)立即開(kāi)通 >