{
private static string wxtonken;
private static string jsapi_ticket;
private static DateTime wxtonkentime;
private static string noncestr;
private static long timestamp;
private static string signature;
/// <summary>
/// 获取用户OPENID
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
[HttpGet]
public string UserOpenid(string code)
{
string appid = ConfigurationManager.AppSettings["appid"];
string secret = ConfigurationManager.AppSettings["secret"];
string httpurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(httpurl);
httpWebRequest.Method = "GET";
httpWebRequest.ContentType = "text/html;charset=UTF-8";
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string result = streamReader.ReadToEnd();
User_wx userInfo = JsonConvert.DeserializeObject<User_wx>(result);
return userInfo.openid;
}
/// <summary>
/// 微信发送模板消息
/// </summary>
/// <param name="data">发送模板消息内容</param>
/// <returns></returns>
[HttpGet]
public string SendTemplateMsg(string data)
{
string accessToken = Get_Tokento();
string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", accessToken);
HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
hwr.Method = "POST";
hwr.ContentType = "application/x-www-form-urlencoded";
byte[] payload = Encoding.UTF8.GetBytes(data);
hwr.ContentLength = (long)payload.Length;
Stream writer = hwr.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
HttpWebResponse result = hwr.GetResponse() as HttpWebResponse;
string strMsg = this.WebResponseGet(result);
return strMsg;
}
/// <summary>
/// 获取微信token
/// </summary>
/// <returns></returns>
[HttpGet]
public string Get_Tokento()
{
if (!string.IsNullOrEmpty(wxtonken))
{
TimeSpan ts = wxtonkentime - DateTime.Now;
if (ts.TotalMinutes > 0)
{
//token未过期
return wxtonken;
}
else
{
InsertToken();
return wxtonken;
}
}
else
{
InsertToken();
return wxtonken;
}
}
/// <summary>
/// 获取微信签名信息
/// </summary>
/// <returns>appId 公众号的唯一标识 timestamp 生成签名的时间戳 nonceStr 生成签名的随机串 signature 签名</returns>
[HttpGet]
public string Get_Sign()
{
Get_Tokento();
string appid = ConfigurationManager.AppSettings["appid"];
return "{\"appId\":\"" + appid + "\",\"timestamp\":\"" + timestamp + "\",\"nonceStr\":\"" + noncestr + "\",\"signature\":\"" + signature + "\"}";
}
{
string appid = ConfigurationManager.AppSettings["appid"];
string secret = ConfigurationManager.AppSettings["secret"];
string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
Access_TokenModel atm = JsonConvert.DeserializeObject<Access_TokenModel>(retString);
wxtonken = atm.access_token;
wxtonkentime = DateTime.Now.AddHours(1).AddMinutes(40);//重新生成时间
Log.WriteLog("微信token", wxtonken);//记录token
Insertjsapi_ticket(wxtonken);
}
private void Insertjsapi_ticket(string token)
{
string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
Access_TokenModel atm = JsonConvert.DeserializeObject<Access_TokenModel>(retString);
jsapi_ticket = atm.ticket;
timestamp = GetTimeStamp();
noncestr = GetRandomString(8, true, true, true, false, null);
Log.WriteLog("微信jsapi_ticket", jsapi_ticket);//记录jsapi_ticket
string content;//sha1加密字符串
signature = GetSignature(jsapi_ticket, noncestr, timestamp, "http://*********", out content);
}
/// <summary>
/// 获取请求返回内容
/// </summary>
/// <param name="webResponse"></param>
/// <returns></returns>
private string WebResponseGet(HttpWebResponse webResponse)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webResponse.GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webResponse.GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
///<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 GetRandomString(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;
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public static long GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds);
}
/// <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 Sha1(string1);
}
/// <summary>
/// Sha1加密
/// </summary>
/// <param name="orgStr"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string Sha1(string orgStr, string encode = "UTF-8")
{
var sha1 = new SHA1Managed();
var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr);
byte[] resultHash = sha1.ComputeHash(sha1bytes);
string sha1String = BitConverter.ToString(resultHash).ToLower();
sha1String = sha1String.Replace("-", "");
return sha1String;
}