C#——企业微信一般操作之一
1.获取微信访问凭证
public 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("https://qyapi.weixin.qq.com/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((double)en.expires_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,图片保存在项目下
//获取图片路径 var t1 = retString.IndexOf("http://"); 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 + ""); //wc.DownloadFile(retString, @"d:\mobile.gif");//保存到本地的文件名和路径,请自行更改 }
3.获取图片路径,使用WebClient类来上传文件,并读取返回值media_id
//图片处理 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);
//下面是获取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("https://qyapi.weixin.qq.com/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.使用using,定义范围,在该范围结束时回收资源
备注:代码暂不完美,只是学习记录一下,欢迎大佬提意见,请勿喷,谢谢!