标签:
微信开发-微信一般帮助类
public class CommonUtil { #region 微信相关帮助 /// <summary> /// 生成指定长度的签名的随机串 /// </summary> /// <param name="length"></param> /// <returns></returns> public static String CreateNoncestr(int length) { String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String res = ""; Random rd = new Random(); for (int i = 0; i < length; i++) { res += chars[rd.Next(chars.Length - 1)]; } return res; } /// <summary> /// 生成签名的随机串 /// </summary> /// <returns></returns> public static String CreateNoncestr() { String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String res = ""; Random rd = new Random(); for (int i = 0; i < 16; i++) { res += chars[rd.Next(chars.Length - 1)]; } return res; } /// <summary> /// 生成签名的时间戳 /// </summary> /// <returns></returns> public static String CreateTimeStamp() { return ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); } /// <summary> /// 获取微信JS接口的临时票据 /// </summary> /// <param name="jsTicketUrl">js ticket url</param> /// <param name="accessToken">微信的accesstoken</param> /// <returns></returns> public static String CreateJsTicket(string jsTicketUrl, string accessToken) { string ticketUrl = string.Format(jsTicketUrl, accessToken); string result =WebHttpHelper.CreateWebrequest(ticketUrl); IHashObject obj = Carpa.Web.Ajax.JavaScriptSerializer.CreateInstance().DeserializeObject(result) as IHashObject; if (obj.Count > 0) { if (obj.GetValue("errcode", "").Equals("0")) { return obj.GetValue("ticket", ""); } } return ""; } /// <summary> /// 生成 wx config签名;参与签名的参数如下(jsapi_ticket,noncestr,×tamp,url-当前请求的url) /// </summary> /// <param name="dic"></param> /// <returns></returns> public static String CreateSignature(Dictionary<string, string> dic) { //字典排序 var dictemp = dic.OrderBy(d => d.Key); #region 生成url字符串 StringBuilder str = new StringBuilder(); foreach (var item in dictemp) { str.AppendFormat("{0}={1}&", item.Key, item.Value); } #endregion var temp = str.ToString().Trim(‘&‘); return Util.Sha1(temp); } /// <summary> /// 网页授权认证获取用户的opneid /// </summary> /// <param name="url">授权地址</param> /// <param name="appId">appid</param> /// <param name="appKey">appid</param> /// <param name="code">授权获取的code</param> /// <returns></returns> public static String GetOpenIdByOauth(string url, string appId, string appKey, string code) { string aUrl = string.Format(url, appId, appKey, code); string result = WebHttpHelper.CreateWebrequest(aUrl); IHashObject obj = Carpa.Web.Ajax.JavaScriptSerializer.CreateInstance().DeserializeObject(result) as IHashObject; if (obj.Count > 0) { if (obj.GetValue("openid", "") != "") { return obj.GetValue("openid", ""); } } return ""; } #endregion }
标签:
原文地址:http://www.cnblogs.com/tiggerinchengdu/p/4511974.html