C#——企业⼀般操作之⼀1.获取访问凭证
1
2
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50public static string GetAccessToken()
{
string_AccessToken = "";//存储访问凭证
DateTime _lastGetTimeOfAccessToken;//ACCESS_TOKEN最后⼀次更新时间
string corpId = "XXXXX";// 填⼊企业的corpId
string corpsecret = "XXXX";// 填⼊Secret
try
{
string sqlstring = "SELECT count(*)  FROM [Booking].[dbo].[WX_GetAccessCredentials] "
+ " WHERE WX_LastGetTimeOfAccessToken> GETDATE(); ";
DataTable dt = DBUtility.DbHelperSQL.Query(sqlstring);
if(dt.Rows[0][0].ToString() == "0") //_lastGetTimeOfAccessToken < DateTime.Now
{
string serviceAddress = string.Format("qyapi.weixin.qq/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpId, corpsecret);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
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();
myStreamReader.Close();
myResponseStream.Close();
var rsEntity = new{ access_token = "", expires_in = 0, errcode = 0, errmsg = ""};
dynamic en = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType<object>(retString, rsEntity); // Newtonsoft.Json提供的匿名类反序列化
_lastGetTimeOfAccessToken = DateTime.Now.AddSeconds((pires_in - 300);
_AccessToken = en.access_token;//GetAccessToken
string sqlstring1 = "insert into [Booking].[dbo].[WX_GetAccessCredentials] ([WX_LastGetTimeOfAccessToken],[WX_AccessToken],[Create_Date])"
+ "VALUES('"+ _lastGetTimeOfAccessToken + "','"+ _AccessToken + "',GETDATE())";
var result = DBUtility.DbHelperSQL.ExecuteSql(sqlstring1);
}
string sqlstring3 = "SELECT [WX_LastGetTimeOfAccessToken],[WX_AccessToken],[Create_Date]  FROM [Booking].[dbo].[WX_GetAccessCredentials] "            + " WHERE WX_LastGetTimeOfAccessToken> GETDATE(); ";
DataTable dt3 = DBUtility.DbHelperSQL.Query(sqlstring3);
_AccessToken = dt3.Rows[0][1].ToString();
return_AccessToken;
}
catch(Exception ex)
{
throw ex;
}
}
2.将某成员信息⽤GET请求⽅式导出,抓取avatar属性值——头像url,图⽚保存在项⽬下
1 2 3 4 5 6 7 8 9 10 11//获取图⽚路径
var t1 = retString.IndexOf("");
var t2 = retString.IndexOf("\",\"status\"");
retString = retString.Substring(t1, t2 - t1);
//下载图⽚
string newname = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
string datePath = System.Web.HttpContext.Current.Server.MapPath("/") + "Upload/Test/"+ newname; using(System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Headers.Add("User-Agent", "Chrome");
wc.DownloadFile(retString, @""+ datePath + "");
11 12 13 14    wc.DownloadFile(retString, @""+ datePath + "");
//wc.DownloadFile(retString, @"d:\mobile.gif");//保存到本地的⽂件名和路径,请⾃⾏更改}
3.获取图⽚路径,使⽤WebClient类来上传⽂件,并读取返回值media_id 1
2
3
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54            //图⽚处理
string PhotoName = "1.jpg";
string filepath= System.Web.HttpContext.Current.Server.MapPath("/") + "Upload/Test/"+ PhotoName;
MediaType mt = MediaType.image;
string media_id = WxUpLoad(filepath, mt);<br>
//下⾯是获取media_id的⽅法
/// <summary>
/// topic:⽤WebClient类来上传⽂件,并读出返回值media_id
/// </summary>
/// <param name="filepath">⽂件绝对路径</param>
/// <param name="mt">⽂件类型</param>
public string WxUpLoad(string filepath, MediaType mt)
{
string media_id = "";
string token = GetAccessToken();
using(WebClient client = new WebClient())
{
byte[] b = client.UploadFile(string.Format("qyapi.weixin.qq/cgi-bin/media/upload?access_token={0}&type={1}", token, mt.ToString()), filepath);//调⽤接⼝上传⽂件
string retdata = Encoding.Default.GetString(b);//获取返回值
if(retdata.Contains("media_id"))//判断返回值是否包含media_id,包含则说明上传成功,然后将返回的json字符串转换成json
{
media_id=JsonConvert.DeserializeObject<UpLoadInfo>(retdata).media_id;
return media_id;
}
else
{return null;}
}
}
//⾥⾯有枚举
/// <summary>
/// topic:媒体⽂件的类型定义为枚举
/// </summary>
public enum MediaType
{
/// <summary>
/// 图⽚(image):2MB,⽀持JPG,PNG格式
/
// </summary>
image,
/// <summary>
/// 语⾳(voice):2MB,播放长度不超过60s,仅⽀持AMR格式
代码转换
/// </summary>
voice,
/// <summary>
/// 视频(video):10MB,⽀持MP4格式
/// </summary>
video,
/// <summary>
/
// 普通⽂件(file):20MB
/// </summary>
file
}
4.using的三种⽤法:
1 2 3//1.在⽂件顶部引⽤命名空间
//2.为命名空间或类型定义别名
//3.使⽤using,定义范围,在该范围结束时回收资源
备注:代码暂不完美,只是学习记录⼀下,欢迎⼤佬提意见,请勿喷,谢谢!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。