/// <summary> /// 获取公众号中的在线客服接待信息列表 /// </summary> /// <param name="userName">公众号</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回在线客服接待信息列表;如果获取失败,返回null。</returns> public static List <CustomerServiceOnlineInfo> GetOnlineKfList(string userName, out ErrorMessage errorMessage) { List <CustomerServiceOnlineInfo> infos = null; string responseContent = HttpHelper.RequestResponseContent(urlForGettingOnlineKfList, userName, null, httpMethodForGettingOnlineKfList, null); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { var kf_online_list = new { kf_online_list = new List <CustomerServiceOnlineInfo>() }; var kfOnlineList = JsonConvert.DeserializeAnonymousType(responseContent, kf_online_list); infos = kfOnlineList.kf_online_list; errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "获取在线客服接待信息成功。"); } return(infos); }
/// <summary> /// 获取值类型的结果 /// </summary> /// <typeparam name="T">返回结果的类型</typeparam> /// <param name="responseContent">响应内容</param> /// <param name="propertyNameInJson">返回结果在json中的键名</param> /// <param name="errorMessage">返回请求是否成功</param> /// <returns>返回结果;如果请求失败,或者发生错误,返回default(T)。</returns> private static T ConvertValueTypeResult <T>(string responseContent, string propertyNameInJson, out ErrorMessage errorMessage) where T : struct { if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); return(default(T)); } if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); } JObject jo = JObject.Parse(responseContent); JToken jt; if (jo.TryGetValue(propertyNameInJson, out jt)) { return(ConvertValueTypeResult <T>((string)jt)); } else { return(default(T)); } }
/// <summary> /// 获取自定义菜单配置 /// </summary> /// <param name="userName">公众号</param> /// <param name="isOpened">返回是否开启了菜单;如果获取失败,返回false。</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回是菜单数组;如果获取失败,或者尚未开启菜单,返回null。</returns> public static BaseMenu[] GetSelfMenuInfo(string userName, out bool isOpened, out ErrorMessage errorMessage) { isOpened = false; BaseMenu[] menus = null; string responseContent = HttpHelper.RequestResponseContent(urlForGettingSelfMenuInfo, userName, null, httpMethodForGettingSelfMenuInfo, null); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "查询菜单成功"); JObject jo = JObject.Parse(responseContent); isOpened = (int)jo["is_menu_open"] == 1; if (isOpened) { menus = Parse(responseContent); } } return(menus); }
/// <summary> /// 获取用户列表 /// </summary> /// <param name="userName">公众号</param> /// <param name="nextOpenId">第一个拉取的OPENID,不填默认从头开始拉取</param> /// <param name="total">返回关注该公众账号的总用户数;如果获取失败,返回-1。</param> /// <param name="newNextOpenId">返回获取用户列表后,后一个用户的id</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回这次获取的用户列表;如果获取失败,返回null。</returns> public static string[] GetUserList(string userName, string nextOpenId, out int total, out string newNextOpenId, out ErrorMessage errorMessage) { string[] users = null; total = -1; newNextOpenId = string.Empty; if (nextOpenId == null) { nextOpenId = string.Empty; } string responseContent = HttpHelper.RequestResponseContent(urlForGettingUserList, userName, new object[] { nextOpenId }, httpMethodForGettingUserList, null); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { var result = JsonConvert.DeserializeAnonymousType(responseContent, new { total = 2, count = 2, data = new { openid = new string[1] }, next_openid = "NEXT_OPENID" }); if (result.count > 0 && result.data != null && result.data.openid != null && result.data.openid.Length > 0) { users = result.data.openid; } total = result.total; newNextOpenId = result.next_openid; errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); } return(users); }
/// <summary> /// 查询用户所在分组 /// </summary> /// <param name="userName">公众号</param> /// <param name="openId">用户id</param> /// <param name="errorMessage">返回查询是否成功</param> /// <returns>返回用户所在的分组id;如果查询失败,返回-1。</returns> public static int GetGroupId(string userName, string openId, out ErrorMessage errorMessage) { int id = -1; if (string.IsNullOrWhiteSpace(openId)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "用户id不能为空。"); return(id); } string json = JsonConvert.SerializeObject(new { openid = openId }); string responseContent = HttpHelper.RequestResponseContent(urlForGettingGroupId, userName, null, httpMethodForGettingGroupId, json); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); var result = JsonConvert.DeserializeAnonymousType(responseContent, new { groupid = 0 }); id = result.groupid; } return(id); }
/// <summary> /// 获取永久素材(图片(image)、语音(voice)、缩略图(thumb)) /// </summary> /// <param name="userName">公众号</param> /// <param name="mediaId">素材的id</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回素材数据;如果获取失败,返回null。</returns> public static byte[] Get(string userName, string mediaId, out ErrorMessage errorMessage) { byte[] responseData = Get(userName, mediaId); string error = "{\"errcode\":40007,\"errmsg\":\"invalid media_id\"}"; byte[] errorData = HttpHelper.ResponseEncoding.GetBytes(error); if (responseData == null || responseData.Length == 0) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "获取永久素材失败。"); return(null); } else if (responseData.Length > errorData.Length * 3) { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "获取永久素材成功。"); return(responseData); } else { try { string responseContent = HttpHelper.ResponseEncoding.GetString(responseData); errorMessage = ErrorMessage.Parse(responseContent); } catch { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "获取永久素材失败。"); } return(null); } }
/// <summary> /// 创建用户分组 /// </summary> /// <param name="userName">公众号</param> /// <param name="groupName">分组名称</param> /// <param name="errorMessage">返回是否创建成功</param> /// <returns>返回分组id;如果创建失败,返回-1。</returns> public static int CreateGroup(string userName, string groupName, out ErrorMessage errorMessage) { int id = -1; if (string.IsNullOrWhiteSpace(groupName)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "分组名称不能为空。"); return(id); } string json = JsonConvert.SerializeObject(new { group = new { name = groupName } }); string responseContent = HttpHelper.RequestResponseContent(urlForCreatingGroup, userName, null, httpMethodForCreatingGroup, json); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { JObject jo = JObject.Parse(responseContent); id = (int)jo["group"]["id"]; errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); } return(id); }
/// <summary> /// 校验网页access token的有效性 /// </summary> /// <param name="accessToken">网页许可令牌</param> /// <param name="openId">用户id</param> /// <returns>返回网页access token是否有效</returns> public static ErrorMessage CheckValidate(string accessToken, string openId) { if (string.IsNullOrWhiteSpace(accessToken)) { return(new ErrorMessage(ErrorMessage.ExceptionCode, "网页access token不能为空。")); } if (string.IsNullOrWhiteSpace(openId)) { return(new ErrorMessage(ErrorMessage.ExceptionCode, "用户id不能为空。")); } string url = string.Format(urlForCheckingValidate, accessToken, openId); string responseContent; if (!HttpHelper.Request(url, out responseContent, httpMethod, (string)null)) { return(new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。")); } else if (ErrorMessage.IsErrorMessage(responseContent)) { return(ErrorMessage.Parse(responseContent)); } else { return(new ErrorMessage(ErrorMessage.ExceptionCode, "解析结果失败。")); } }
/// <summary> /// 解析响应字符串 /// </summary> /// <param name="responseContent">响应字符串</param> /// <param name="errorMessage">返回错误消息</param> /// <returns>返回多媒体上传结果</returns> private static MultiMediaUploadResult ParseResult(string responseContent, out ErrorMessage errorMessage) { MultiMediaUploadResult result = null; if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "上传失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { if (MultiMediaUploadResult.TryParse(responseContent, out result)) { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "上传成功。"); } else { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "解析多媒体上传结果失败。"); } } return(result); }
/// <summary> /// 从响应中获取媒体id /// </summary> /// <param name="responseContent">响应内容</param> /// <param name="errorMessage">返回是否成功</param> /// <returns>返回媒体id;如果失败,返回null。</returns> private static string GetMediaId(string responseContent, out ErrorMessage errorMessage) { if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); return(null); } else { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "新增永久图文素材成功。"); return(responseContent); } }
/// <summary> /// 获取公众号中的客服聊天记录列表 /// </summary> /// <param name="userName">公众号</param> /// <param name="openId">普通用户的标识</param> /// <param name="startTime">查询开始时间</param> /// <param name="endTime">查询结束时间</param> /// <param name="pageSize">每页大小,每页最多拉取1000条</param> /// <param name="pageIndex">查询第几页,从1开始</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回在线客服接待信息列表;如果获取失败,返回null。</returns> public static List <CustomerServiceRecord> GetRecord(string userName, string openId, DateTime startTime, DateTime endTime, int pageSize, int pageIndex, out ErrorMessage errorMessage) { List <CustomerServiceRecord> records = null; errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, ""); if (startTime > endTime) { errorMessage.errmsg = "查询开始时间不能大于查询结束时间。"; return(null); } if (pageSize <= 0 || pageSize > 1000) { errorMessage.errmsg = "每页大小错误。"; return(null); } if (pageIndex < 1) { errorMessage.errmsg = "查询页码错误。"; return(null); } var postData = new { starttime = Utility.ToWeixinTime(startTime), endtime = Utility.ToWeixinTime(endTime), openid = openId ?? string.Empty, pagesize = pageSize, pageindex = pageIndex }; string json = JsonConvert.SerializeObject(postData); string responseContent = HttpHelper.RequestResponseContent(urlForGettingRecord, userName, null, json); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage.errmsg = "从微信服务器获取响应失败。"; } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { var recordlist = new { recordlist = new List <CustomerServiceRecord>() }; var recordList = JsonConvert.DeserializeAnonymousType(responseContent, recordlist); records = recordlist.recordlist; errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); } return(records); }
/// <summary> /// 获取统计数据 /// </summary> /// <param name="userName">公众号</param> /// <param name="beginDate">起始日期</param> /// <param name="endDate">结束日期</param> /// <param name="url">获取统计数据的地址</param> /// <param name="timeSpan">最大时间跨度</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回包含统计数据的JArray对象</returns> private static T[] Get <T>(string userName, DateTime beginDate, DateTime endDate, string url, int timeSpan, out ErrorMessage errorMessage) where T : IParsable, new() { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, ""); if (!CheckTimeSpan(beginDate, endDate, timeSpan)) { errorMessage.errmsg = "起止日期不正确或者超过范围。"; return(null); } string json = JsonConvert.SerializeObject(new { begin_date = beginDate.ToString("yyyy-MM-dd"), end_date = endDate.ToString("yyyy-MM-dd") }); string responseData = HttpHelper.RequestResponseContent(url, userName, null, httpMethod, json); if (string.IsNullOrWhiteSpace(responseData)) { errorMessage.errmsg = "请求失败。"; return(null); } else if (ErrorMessage.IsErrorMessage(responseData)) { errorMessage = ErrorMessage.Parse(responseData); return(null); } else { JObject jo = JObject.Parse(responseData); JToken jt; if (jo.TryGetValue("list", out jt) && jt.Type == JTokenType.Array) { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); JArray ja = (JArray)jt; T[] result = new T[ja.Count]; for (int i = 0; i < ja.Count; i++) { T item = new T(); item.Parse((JObject)ja[i]); result[i] = item; } return(result); } else { errorMessage.errmsg = "解析结果失败。"; return(null); } } }
/// <summary> /// 组合url,发送数据,然后返回响应的错误消息。 /// 注:错误消息不一定代表失败或者错误。 /// </summary> /// <param name="urlFormat">url格式字符串,第一个参数为userName获取到的许可令牌,然后依次为parameters中的参数</param> /// <param name="userName">公众号</param> /// <param name="urlParameters">参数</param> /// <param name="httpMethod">执行请求的http方法</param> /// <param name="data">请求的内容</param> /// <returns>返回响应的错误消息</returns> public static ErrorMessage RequestErrorMessage(string urlFormat, string userName, IEnumerable <object> urlParameters = null, string httpMethod = WebRequestMethods.Http.Get, string data = null) { string responseContent = RequestResponseContent(urlFormat, userName, urlParameters, httpMethod, data); if (string.IsNullOrWhiteSpace(responseContent)) { return(new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。")); } else if (ErrorMessage.IsErrorMessage(responseContent)) { return(ErrorMessage.Parse(responseContent)); } else { return(new ErrorMessage(ErrorMessage.ExceptionCode, "解析响应失败。")); } }
/// <summary> /// 下载多媒体文件 /// </summary> /// <param name="userName">公众号</param> /// <param name="mediaId">媒体ID</param> /// <param name="data">返回下载是否成功</param> /// <returns>返回多媒体文件数据;如果下载失败,返回null。</returns> public static byte[] Download(string userName, string mediaId, out ErrorMessage errorMessage) { if (string.IsNullOrWhiteSpace(mediaId)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "媒体id不能为空。"); return(null); } AccessToken token = AccessToken.Get(userName); if (token == null) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "获取许可令牌失败。"); return(null); } string url = GetDownloadUrl(token.access_token, mediaId); byte[] data; bool success = HttpHelper.Request(url, out data, httpMethodForDownloading, (byte[])null); if (!success) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "从微信服务器下载多媒体文件失败。"); return(null); } byte[] error = HttpHelper.ResponseEncoding.GetBytes("{\"errorcode\":"); if (StartsWithBytes(data, error)) { string json = HttpHelper.ResponseEncoding.GetString(data); data = null; if (ErrorMessage.IsErrorMessage(json)) { errorMessage = ErrorMessage.Parse(json); } else { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "从微信服务器下载多媒体文件失败。"); } } else { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "下载多媒体文件成功。"); } return(data); }
/// <summary> /// 查询菜单 /// </summary> /// <param name="userName">公众号</param> /// <param name="errorMessage">返回查询是否成功</param> /// <returns>返回菜单数组;如果获取失败,返回null。</returns> public static BaseMenu[] Get(string userName, out ErrorMessage errorMessage) { BaseMenu[] menus = null; string responseContent = HttpHelper.RequestResponseContent(urlForGetting, userName, null, httpMethodForGetting, null); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "查询菜单成功"); menus = Parse(responseContent); } return(menus); }
/// <summary> /// 创建二维码 /// </summary> /// <param name="userName">公众号</param> /// <param name="json">json数据</param> /// <param name="errorMessage">返回创建是否成功</param> /// <returns>返回二维码;如果创建失败,返回null。</returns> private static QrCode CreateQrCode(string userName, string json, out ErrorMessage errorMessage) { QrCode code = null; string responseContent = HttpHelper.RequestResponseContent(urlForCreating, userName, null, httpMethodForCreating, json); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { var result = JsonConvert.DeserializeAnonymousType(responseContent, new { ticket = "", expire_seconds = 0, url = "" }); code = new QrCode(result.ticket, result.expire_seconds, result.url); errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "创建二维码成功。"); } return(code); }
/// <summary> /// 获取用户分组 /// </summary> /// <param name="userName">公众号</param> /// <param name="errorMessage">返回是否获取成功</param> /// <returns>返回用户分组;如果获取失败,返回null。</returns> public static UserGroup[] GetGroup(string userName, out ErrorMessage errorMessage) { UserGroup[] groups = null; string responseContent = HttpHelper.RequestResponseContent(urlForGettingGroup, userName, null, httpMethodForGettingGroup, null); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); var result = JsonConvert.DeserializeAnonymousType(responseContent, new { groups = new UserGroup[1] }); groups = result.groups; } return(groups); }
/// <summary> /// 获取用户基本信息 /// </summary> /// <param name="userName">公众号</param> /// <param name="openId">用户id</param> /// <param name="language">语言</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回用户基本信息;如果获取失败,返回null。</returns> private static UserInfo GetUserInfo(string userName, string openId, string language, out ErrorMessage errorMessage) { UserInfo info = null; string responseContent = HttpHelper.RequestResponseContent(urlForGettingUserInfo, userName, new object[] { openId, language }, httpMethodForGettingUserInfo, null); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { JObject jo = JObject.Parse(responseContent); JToken jt; if (jo.TryGetValue("subscribe", out jt) && jo.TryGetValue("openid", out jt) && (string)jt == openId) { int subscribe = (int)jo["subscribe"]; string nickname = jo.TryGetValue("nickname", out jt) ? (string)jt : string.Empty; int sex = jo.TryGetValue("sex", out jt) ? (int)jt : (int)SexEnum.Unknown; string lang = jo.TryGetValue("language", out jt) ? (string)jt : string.Empty; string city = jo.TryGetValue("city", out jt) ? (string)jt : string.Empty; string province = jo.TryGetValue("province", out jt) ? (string)jt : string.Empty; string country = jo.TryGetValue("country", out jt) ? (string)jt : string.Empty; string headimgurl = jo.TryGetValue("headimgurl", out jt) ? (string)jt : string.Empty; int subscribe_time = jo.TryGetValue("subscribe_time", out jt) ? (int)jt : 0; string unionid = jo.TryGetValue("unionid", out jt) ? (string)jt : string.Empty; info = new UserInfo(subscribe, openId, nickname, sex, lang, city, province, country, headimgurl, subscribe_time, unionid); errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); } else { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "获取用户基本信息失败。"); } } return(info); }
/// <summary> /// 获取客服的会话列表 /// </summary> /// <param name="userName">公众号</param> /// <param name="kfAccount">客服账号</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回客服的会话列表</returns> public static CustomerServiceSession[] GetSessionList(string userName, string kfAccount, out ErrorMessage errorMessage) { string responseContent = HttpHelper.RequestResponseContent(urlForGettingSessionList, userName, new object[] { kfAccount }, httpMethodForGettingSessionList, null); if (string.IsNullOrWhiteSpace(responseContent)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); return(null); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); return(null); } else { JObject jo = JObject.Parse(responseContent); JToken jt; if (jo.TryGetValue("sessionlist", out jt) && jt.Type == JTokenType.Array) { JArray ja = (JArray)jt; CustomerServiceSession[] sessions = new CustomerServiceSession[ja.Count]; for (int i = 0; i < ja.Count; i++) { sessions[i] = new CustomerServiceSession(); sessions[i].Parse((JObject)ja[i]); } errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); return(sessions); } else { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "解析结果失败。"); return(null); } } }
/// <summary> /// 获取永久图文素材 /// </summary> /// <param name="userName">公众号</param> /// <param name="mediaId">图文素材的id</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回图文消息;如果获取失败,返回null。</returns> public static MultiMediaArticle[] GetNews(string userName, string mediaId, out ErrorMessage errorMessage) { byte[] responseData = Get(userName, mediaId); if (responseData == null || responseData.Length == 0) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "获取永久图文素材失败。"); return(null); } string responseContent = HttpHelper.ResponseEncoding.GetString(responseData); if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); return(null); } else { JObject jo = JObject.Parse(responseContent); JToken jt; if (jo.TryGetValue("news_item", out jt)) { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "获取永久图文素材成功。"); JArray ja = (JArray)jt; MultiMediaArticle[] articles = new MultiMediaArticle[ja.Count]; for (int i = 0; i < articles.Length; i++) { articles[i] = new MultiMediaArticle((JObject)ja[i]); } return(articles); } else { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "获取永久图文素材失败。"); return(null); } } }
/// <summary> /// 组合url,发送数据,然后返回结果。 /// 注:结果为需要解析的类。 /// </summary> /// <typeparam name="T">返回结果的类型</typeparam> /// <param name="urlFormat">url格式字符串,第一个参数为userName获取到的许可令牌,然后依次为parameters中的参数</param> /// <param name="userName">公众号</param> /// <param name="errorMessage">返回请求是否成功</param> /// <param name="urlParameters">参数</param> /// <param name="httpMethod">执行请求的http方法</param> /// <param name="data">请求的内容</param> /// <returns>返回结果;如果请求失败,或者发生错误,返回null。</returns> public static T RequestParsableResult <T>(string urlFormat, string userName, out ErrorMessage errorMessage, IEnumerable <object> urlParameters = null, string httpMethod = WebRequestMethods.Http.Get, string data = null) where T : IParsable, new() { T result = default(T); errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); string responseContent = RequestResponseContent(urlFormat, userName, urlParameters, httpMethod, data); if (string.IsNullOrWhiteSpace(responseContent)) { return(result); } if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { try { result = Utility.Parse <T>(responseContent); if (result != null) { errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); } else { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "解析失败。"); } } catch { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "解析失败。"); } } return(result); }
/// <summary> /// 刷新access token /// </summary> /// <param name="userName">公众号</param> /// <param name="refreshToken">用户刷新token</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回access token;如果获取失败,返回null。</returns> public static OAuthAccessToken Refresh(string userName, string refreshToken, out ErrorMessage errorMessage) { OAuthAccessToken token = null; if (string.IsNullOrWhiteSpace(refreshToken)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "用户刷新token不能为空。"); return(token); } AccountInfo account = AccountInfoCollection.GetAccountInfo(userName); if (account == null) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "获取公众号信息失败。"); return(token); } string url = string.Format(urlForRefreshingAccessToken, account.AppId, refreshToken); string responseContent; if (!HttpHelper.Request(url, out responseContent, httpMethod, (string)null)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "从微信服务器获取响应失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { var result = JsonConvert.DeserializeAnonymousType(responseContent, new { access_token = "", expires_in = 0, refresh_token = "", openid = "", scope = "" }); token = new OAuthAccessToken(result.access_token, result.expires_in, result.refresh_token, result.openid, result.scope); errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "获取access token成功。"); } return(token); }
/// <summary> /// 从微信服务器获取access token /// </summary> /// <param name="userName">公众号</param> /// <param name="msg">从服务器返回的错误信息。</param> /// <returns>返回许可令牌;如果获取失败,返回null。</returns> private static AccessToken GetFromWeixinServer(string userName, out ErrorMessage msg) { AccessToken token = null; msg = new ErrorMessage(ErrorMessage.ExceptionCode, ""); //AccountInfo account = AccountInfoCollection.GetAccountInfo(userName); //if (account == null) //{ // msg.errmsg = "获取公众号参数失败。"; // return token; //} string url = string.Format(urlForGettingAccessToken, "wxdcf5fba0c0a88064", "5a32d0d24faedfa9a6070639f3a59f03"); string result; if (!HttpHelper.Request(url, out result, httpMethodForGettingAccessToken, string.Empty)) { msg.errmsg = "从微信服务器获取响应失败。"; return(token); } if (ErrorMessage.IsErrorMessage(result)) { msg = ErrorMessage.Parse(result); } else { try { token = AccessToken.ParseFromJson(result); } catch (Exception e) { msg = new ErrorMessage(e); } } return(token); }
/// <summary> /// 获取用户基本信息 /// </summary> /// <param name="accessToken">网页access token</param> /// <param name="openId">用户id</param> /// <param name="language">语言</param> /// <param name="errorMessage">返回获取是否成功</param> /// <returns>返回用户基本信息;如果获取失败,返回null。</returns> private static UserInfo GetUserInfo(string accessToken, string openId, string language, out ErrorMessage errorMessage) { UserInfo info = null; if (string.IsNullOrWhiteSpace(accessToken)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "网页access token不能为空。"); return(info); } if (string.IsNullOrWhiteSpace(openId)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "用户id不能为空。"); return(info); } string url = string.Format(urlForGettingUserInfo, accessToken, openId, language); string responseContent; if (!HttpHelper.Request(url, out responseContent, httpMethod, (string)null)) { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "请求失败。"); } else if (ErrorMessage.IsErrorMessage(responseContent)) { errorMessage = ErrorMessage.Parse(responseContent); } else { JObject jo = JObject.Parse(responseContent); JToken jt; if (jo.TryGetValue("openid", out jt) && (string)jt == openId) { string nickname = jo.TryGetValue("nickname", out jt) ? (string)jt : string.Empty; int sex = jo.TryGetValue("sex", out jt) ? (int)jt : (int)SexEnum.Unknown; string lang = jo.TryGetValue("language", out jt) ? (string)jt : string.Empty; string city = jo.TryGetValue("city", out jt) ? (string)jt : string.Empty; string province = jo.TryGetValue("province", out jt) ? (string)jt : string.Empty; string country = jo.TryGetValue("country", out jt) ? (string)jt : string.Empty; string headimgurl = jo.TryGetValue("headimgurl", out jt) ? (string)jt : string.Empty; string[] privilege = null; if (jo.TryGetValue("privilege", out jt)) { if (jt.Type == JTokenType.Array) { JArray ja = (JArray)jt; privilege = new string[ja.Count]; int idx = 0; foreach (JValue jv in ja) { privilege[idx] = (string)jv.Value; idx++; } } else if (jt.Type == JTokenType.String) { privilege = new string[] { (string)jt } } ; } string unionid = jo.TryGetValue("unionid", out jt) ? (string)jt : string.Empty; info = new UserInfo(openId, nickname, sex, lang, city, province, country, headimgurl, privilege, unionid); errorMessage = new ErrorMessage(ErrorMessage.SuccessCode, "请求成功。"); } else { errorMessage = new ErrorMessage(ErrorMessage.ExceptionCode, "获取用户基本信息失败。"); } } return(info); }