创建一个保存accesstoken的表,内有accesstoken(nchar),timee(datetime)两字段
public static string Getaccestoken()//获取可用的accesstoken
{
string f2=null;
SqlConnection myconnection = new SqlConnection(ConfigurationManager.AppSettings["tosql"]);
SqlDataAdapter sda = new SqlDataAdapter("select * from 保存accesstoken的表", myconnection);
//myconnection.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
DateTime timee =(DateTime)ds.Tables[0].Rows[0]["timee"];
DateTime n = DateTime.Now;
double s2 = (n - timee).TotalHours;
//myconnection.Close();
ds.Dispose();
if (s2 >= 1.9)
{
string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的secret";
f2= Get(url);
string[] step2 = f2.Split('"');
string acctoken = step2[3];//所需的accesstokne
SqlCommand addtoken = new SqlCommand("update 保存accesstoken的表 set accesstoken='" + acctoken + "',timee='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"'",myconnection);
myconnection.Open();
addtoken.ExecuteNonQuery();
myconnection.Close();
return acctoken;
}
else
{
string acctoken = (string)ds.Tables[0].Rows[0]["accesstoken"];
return acctoken;
}
}