JsAPI.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Web.Script.Serialization;
  7. namespace SiteCore
  8. {
  9. public class JSAPI
  10. {
  11. public static string appid = "wxec9d729c4e1b1af3";
  12. public static string appsec = "11870bcbff21b21f27be06b99e3aa7c8";
  13. static string tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
  14. static string jsapiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";
  15. static object jsObj = new Object();
  16. private static object getAt(HttpHelper http)
  17. {
  18. object cat = WebCache.GetRunCache("jsAt");
  19. if (cat == null)
  20. {
  21. lock (jsObj)
  22. {
  23. //http = new HttpHelper();
  24. HttpItem item = new HttpItem()
  25. {
  26. URL = string.Format(tokenUrl, appid, appsec)
  27. };
  28. HttpResult hResult = http.GetHtml(item);
  29. string html = hResult.Html;
  30. JavaScriptSerializer jss = new JavaScriptSerializer();
  31. Dictionary<string, object> jObj = jss.Deserialize<Dictionary<string, object>>(html);
  32. if (!jObj.ContainsKey("errcode"))
  33. {
  34. string at = jObj["access_token"].ToString();
  35. WebCache.AddRunCacheTime("jsAt", at, 100);
  36. cat = at;
  37. }
  38. }
  39. }
  40. return cat;
  41. }
  42. /// <summary>
  43. /// 获取jsapi_ticket
  44. /// jsapi_ticket是公众号用于调用微信JS接口的临时票据。
  45. /// 正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。
  46. /// 由于获取jsapi_ticket的api调用次数非常有限,频繁刷新jsapi_ticket会导致api调用受限,影响自身业务,开发者必须在自己的服务全局缓存jsapi_ticket 。
  47. /// </summary>
  48. /// <param name="access_token">BasicAPI获取的access_token,也可以通过TokenHelper获取</param>
  49. /// <returns></returns>
  50. public static dynamic GetTickect()
  51. {
  52. HttpHelper http = new HttpHelper();
  53. object acc = getAt(http);
  54. if (acc == null)
  55. {
  56. return "";
  57. }
  58. string access_token = getAt(http).ToString();
  59. HttpItem item = new HttpItem()
  60. {
  61. URL = string.Format(jsapiUrl, access_token)
  62. };
  63. HttpResult hResult = http.GetHtml(item);
  64. string html = hResult.Html;
  65. string jsapi_ticket = "";
  66. JavaScriptSerializer serializer = new JavaScriptSerializer();
  67. Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(html);
  68. object value;
  69. if (json.TryGetValue("ticket", out value))
  70. {
  71. jsapi_ticket = value.ToString();
  72. }
  73. return jsapi_ticket;
  74. }
  75. #region 获取时间戳
  76. public static string GetTimeStamp()
  77. {
  78. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  79. return Convert.ToInt64(ts.TotalSeconds).ToString();
  80. }
  81. #endregion
  82. #region 生成随机字符串nonceStr
  83. ///<summary>
  84. ///生成随机字符串
  85. ///</summary>
  86. ///<param name="length">目标字符串的长度</param>
  87. ///<param name="useNum">是否包含数字,1=包含,默认为包含</param>
  88. ///<param name="useLow">是否包含小写字母,1=包含,默认为包含</param>
  89. ///<param name="useUpp">是否包含大写字母,1=包含,默认为包含</param>
  90. ///<param name="useSpe">是否包含特殊字符,1=包含,默认为不包含</param>
  91. ///<param name="custom">要包含的自定义字符,直接输入要包含的字符列表</param>
  92. ///<returns>指定长度的随机字符串</returns>
  93. public static string GetRnd(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
  94. {
  95. byte[] b = new byte[4];
  96. new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
  97. Random r = new Random(BitConverter.ToInt32(b, 0));
  98. string s = null, str = custom;
  99. if (useNum == true) { str += "0123456789"; }
  100. if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
  101. if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  102. if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
  103. for (int i = 0; i < length; i++)
  104. {
  105. s += str.Substring(r.Next(0, str.Length - 1), 1);
  106. }
  107. return s;
  108. }
  109. #endregion
  110. #region SHA1加密
  111. private static string GetPwd(string str)
  112. {
  113. byte[] cleanBytes = Encoding.Default.GetBytes(str);
  114. byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes);
  115. return BitConverter.ToString(hashedBytes).Replace("-", "");
  116. }
  117. #endregion
  118. /// <summary>
  119. /// 签名算法
  120. /// </summary>
  121. /// <param name="jsapi_ticket">jsapi_ticket</param>
  122. /// <param name="noncestr">随机字符串(必须与wx.config中的nonceStr相同)</param>
  123. /// <param name="timestamp">时间戳(必须与wx.config中的timestamp相同)</param>
  124. /// <param name="url">当前网页的URL,不包含#及其后面部分(必须是调用JS接口页面的完整URL)</param>
  125. /// <returns></returns>
  126. public static string GetSignature(string jsapi_ticket, string noncestr, long timestamp, string url, out string string1)
  127. {
  128. var string1Builder = new StringBuilder();
  129. string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
  130. .Append("noncestr=").Append(noncestr).Append("&")
  131. .Append("timestamp=").Append(timestamp).Append("&")
  132. .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
  133. string1 = string1Builder.ToString();
  134. return GetPwd(string1);
  135. }
  136. //public static string GetSignature()
  137. //{
  138. // int nonceStrLength = 16;
  139. // string timestamp = GetTimeStamp();
  140. // string nonceStr = GetRnd(nonceStrLength, true, true, true, false, "");
  141. // string url = Request.Url.AbsoluteUri.ToString() + "?params=value";
  142. // string jsapi_ticket = GetTickect();
  143. // //拼接字符串
  144. // string string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
  145. // //进行SHA1加密
  146. // return GetPwd(string1);
  147. //}
  148. }
  149. }