| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web.Script.Serialization;
- namespace SiteCore
- {
- public class JSAPI
- {
- public static string appid = "wxec9d729c4e1b1af3";
- public static string appsec = "11870bcbff21b21f27be06b99e3aa7c8";
- static string tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
- static string jsapiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi";
- static object jsObj = new Object();
- private static object getAt(HttpHelper http)
- {
- object cat = WebCache.GetRunCache("jsAt");
- if (cat == null)
- {
- lock (jsObj)
- {
- //http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = string.Format(tokenUrl, appid, appsec)
- };
- HttpResult hResult = http.GetHtml(item);
- string html = hResult.Html;
- JavaScriptSerializer jss = new JavaScriptSerializer();
- Dictionary<string, object> jObj = jss.Deserialize<Dictionary<string, object>>(html);
- if (!jObj.ContainsKey("errcode"))
- {
- string at = jObj["access_token"].ToString();
- WebCache.AddRunCacheTime("jsAt", at, 100);
- cat = at;
- }
- }
- }
- return cat;
- }
- /// <summary>
- /// 获取jsapi_ticket
- /// jsapi_ticket是公众号用于调用微信JS接口的临时票据。
- /// 正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。
- /// 由于获取jsapi_ticket的api调用次数非常有限,频繁刷新jsapi_ticket会导致api调用受限,影响自身业务,开发者必须在自己的服务全局缓存jsapi_ticket 。
- /// </summary>
- /// <param name="access_token">BasicAPI获取的access_token,也可以通过TokenHelper获取</param>
- /// <returns></returns>
- public static dynamic GetTickect()
- {
- HttpHelper http = new HttpHelper();
- object acc = getAt(http);
- if (acc == null)
- {
- return "";
- }
- string access_token = getAt(http).ToString();
- HttpItem item = new HttpItem()
- {
- URL = string.Format(jsapiUrl, access_token)
- };
- HttpResult hResult = http.GetHtml(item);
- string html = hResult.Html;
- string jsapi_ticket = "";
- JavaScriptSerializer serializer = new JavaScriptSerializer();
- Dictionary<string, object> json = (Dictionary<string, object>)serializer.DeserializeObject(html);
- object value;
- if (json.TryGetValue("ticket", out value))
- {
- jsapi_ticket = value.ToString();
- }
- return jsapi_ticket;
- }
- #region 获取时间戳
- public static string GetTimeStamp()
- {
- TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
- return Convert.ToInt64(ts.TotalSeconds).ToString();
- }
- #endregion
- #region 生成随机字符串nonceStr
- ///<summary>
- ///生成随机字符串
- ///</summary>
- ///<param name="length">目标字符串的长度</param>
- ///<param name="useNum">是否包含数字,1=包含,默认为包含</param>
- ///<param name="useLow">是否包含小写字母,1=包含,默认为包含</param>
- ///<param name="useUpp">是否包含大写字母,1=包含,默认为包含</param>
- ///<param name="useSpe">是否包含特殊字符,1=包含,默认为不包含</param>
- ///<param name="custom">要包含的自定义字符,直接输入要包含的字符列表</param>
- ///<returns>指定长度的随机字符串</returns>
- public static string GetRnd(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
- {
- byte[] b = new byte[4];
- new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
- Random r = new Random(BitConverter.ToInt32(b, 0));
- string s = null, str = custom;
- if (useNum == true) { str += "0123456789"; }
- if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
- if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
- if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
- for (int i = 0; i < length; i++)
- {
- s += str.Substring(r.Next(0, str.Length - 1), 1);
- }
- return s;
- }
- #endregion
- #region SHA1加密
- private static string GetPwd(string str)
- {
- byte[] cleanBytes = Encoding.Default.GetBytes(str);
- byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes);
- return BitConverter.ToString(hashedBytes).Replace("-", "");
- }
- #endregion
- /// <summary>
- /// 签名算法
- /// </summary>
- /// <param name="jsapi_ticket">jsapi_ticket</param>
- /// <param name="noncestr">随机字符串(必须与wx.config中的nonceStr相同)</param>
- /// <param name="timestamp">时间戳(必须与wx.config中的timestamp相同)</param>
- /// <param name="url">当前网页的URL,不包含#及其后面部分(必须是调用JS接口页面的完整URL)</param>
- /// <returns></returns>
- public static string GetSignature(string jsapi_ticket, string noncestr, long timestamp, string url, out string string1)
- {
- var string1Builder = new StringBuilder();
- string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
- .Append("noncestr=").Append(noncestr).Append("&")
- .Append("timestamp=").Append(timestamp).Append("&")
- .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
- string1 = string1Builder.ToString();
- return GetPwd(string1);
- }
- //public static string GetSignature()
- //{
- // int nonceStrLength = 16;
- // string timestamp = GetTimeStamp();
- // string nonceStr = GetRnd(nonceStrLength, true, true, true, false, "");
- // string url = Request.Url.AbsoluteUri.ToString() + "?params=value";
- // string jsapi_ticket = GetTickect();
- // //拼接字符串
- // string string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + url;
- // //进行SHA1加密
- // return GetPwd(string1);
- //}
- }
- }
|