C# 微信JSSDK 获取配置信息
本内容部分内容是搬运来,并个人稍加改良完成。
////// 微信JSSDK基础信息 /// public class WechatJSSDKController : ApiController { private static string appid = ConfigurationManager.AppSettings["appID"]; private static string appsecret = ConfigurationManager.AppSettings["appsecret"]; /// /// 获取微信配置基础信息 /// /// [HttpPost] public WXShare GetWxShareInfo() { var context = HttpContext.Current; string url = Common.ObjectToString(context.Request["url"]); DateTime now = DateTime.Now; var timestamp = GetTimeStamp(now);//取十位时间戳 var guid = Guid.NewGuid().ToString("N");//随机串 var ticket = "";//签名密钥 try { WXShare s = new WXShare(); //取缓存中的Ticket,没有则重新生成Ticket值(也可以将Ticket值保存到文件中,此时从文件中读取Ticket) var Cache = CacheHelper.GetCache("ticket"); if (Cache == null) CacheHelper.SetCache("ticket", GetTicket(), 7000); ticket = CacheHelper.GetCache("ticket").ToString(); url = HttpUtility.UrlDecode(url);//url解码 string sign = GetSignature(ticket, guid, timestamp, url); s.appid = appid; s.noncestr = guid; s.timestamp = timestamp; s.signature = sign; //logger.Warn($"url:{url},时间戳:{timestamp},随机数:{guid},ticket:{ticket},sign值:{sign}");//记录日志 return s; } catch (Exception ex) { //logger.Warn(ex); throw ex; } } /// /// GetTicket 签名密钥 /// /// public static string GetTicket() { string token = ""; var Cache = CacheHelper.GetCache("token"); if (Cache == null) CacheHelper.SetCache("token", GetAccessToken(), 7000);//获取AccessToken token = CacheHelper.GetCache("token").ToString(); IDictionary<string, string> dic = new Dictionary<string, string>(); dic["access_token"] = token; dic["type"] = "jsapi"; FormUrlEncodedContent content = new FormUrlEncodedContent(dic); var response = Client.PostAsync("https://api.weixin.qq.com/cgi-bin/ticket/getticket", content).Result; if (response.StatusCode != HttpStatusCode.OK) return ""; var result = response.Content.ReadAsStringAsync().Result; JObject obj = JObject.Parse(result); string ticket = obj["ticket"]?.ToString() ?? ""; return ticket; } /// /// GetAccessToken /// /// public static string GetAccessToken() { IDictionary<string, string> dic = new Dictionary<string, string>(); dic["grant_type"] = "client_credential"; dic["appid"] = appid;//自己的appid dic["secret"] = appsecret;//自己的appsecret FormUrlEncodedContent content = new FormUrlEncodedContent(dic); var response = Client.PostAsync("https://api.weixin.qq.com/cgi-bin/token", content).Result; if (response.StatusCode != HttpStatusCode.OK) return ""; var result = response.Content.ReadAsStringAsync().Result; JObject obj = JObject.Parse(result); string token = obj["access_token"]?.ToString() ?? ""; return token; } /// /// 签名算法 /// /// ticket /// 随机字符串 /// 时间戳 /// /// public static string GetSignature(string ticket, string noncestr, long timestamp, string url) { var string1Builder = new StringBuilder(); //拼接字符串 string1Builder.Append("jsapi_ticket=").Append(ticket).Append("&") .Append("noncestr=").Append(noncestr).Append("&") .Append("timestamp=").Append(timestamp).Append("&") .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url); string str = string1Builder.ToString(); return SHA1(str);//加密 } public static string SHA1(string content) { return SHA1(content, Encoding.UTF8); } /// /// SHA1 加密 /// /// 需要加密字符串 /// 指定加密编码 /// 返回40位小写字符串 public static string SHA1(string content, Encoding encode) { try { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytes_in = encode.GetBytes(content); byte[] bytes_out = sha1.ComputeHash(bytes_in); sha1.Dispose(); string result = BitConverter.ToString(bytes_out); result = result.Replace("-", "").ToLower();//转小写 return result; } catch (Exception ex) { throw new Exception("SHA1加密出错:" + ex.Message); } } //请求基类 private static HttpClient _client = null; public static HttpClient Client { get { if (_client == null) { var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip, AllowAutoRedirect = false, UseCookies = false, }; _client = new HttpClient(handler); _client.Timeout = TimeSpan.FromSeconds(5); _client.DefaultRequestHeaders.Add("Accept", "application/json"); } return _client; } } /// /// 十位时间戳 /// /// /// public static int GetTimeStamp(DateTime dt) { DateTime dateStart = new DateTime(1970, 1, 1, 8, 0, 0); int timeStamp = Convert.ToInt32((dt - dateStart).TotalSeconds); return timeStamp; } /// /// 返回实体 /// public class WXShare { public string appid { get; set; } /// /// 随机码 /// public string noncestr { get; set; } /// /// 时间戳 /// public int timestamp { get; set; } /// /// 签名值 /// public string signature { get; set; } } public class CacheHelper { /// /// 获取数据缓存 /// /// 键 public static object GetCache(string cacheKey) { var objCache = HttpRuntime.Cache.Get(cacheKey); return objCache; } /// /// 设置数据缓存 /// public static void SetCache(string cacheKey, object objObject) { var objCache = HttpRuntime.Cache; objCache.Insert(cacheKey, objObject); } /// /// 设置数据缓存 /// public static void SetCache(string cacheKey, object objObject, int timeout = 7200) { try { if (objObject == null) return; var objCache = HttpRuntime.Cache; //相对过期 //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, new TimeSpan(0, 0, timeout), CacheItemPriority.NotRemovable, null); //绝对过期时间 objCache.Insert(cacheKey, objObject, null, DateTime.UtcNow.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null); } catch (Exception) { //throw; } } /// /// 移除指定数据缓存 /// public static void RemoveAllCache(string cacheKey) { var cache = HttpRuntime.Cache; cache.Remove(cacheKey); } /// /// 移除全部缓存 /// public static void RemoveAllCache() { var cache = HttpRuntime.Cache; var cacheEnum = cache.GetEnumerator(); while (cacheEnum.MoveNext()) { cache.Remove(cacheEnum.Key.ToString()); } } } }
微信页面调用:
//页面引用