Esempio n. 1
0
        /// <summary>
        /// 请求向微信服务器通讯发送可客服消息,验证是否成功
        /// </summary>
        /// <param name="url">请求微信服务器的URL</param>
        /// <param name="data">请求的json数据</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns>0:发送成功,-1:发送失败,-2:媒体文件过期</returns>
        private static int RequestAndValidOpenID(string url, string data, ref string errorDescription)
        {
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers["Content-Type"] = "application/json";
                client.Encoding = System.Text.Encoding.UTF8;

                int errorId = 0;

                try
                {
                    string strResult = client.UploadString(url, "post", data);
                    string errorCode = Utility.AnalysisJson(strResult, "errcode");

                    if (errorCode.Equals("40007"))
                    {
                        return(errorId = -2);
                    }

                    if (!errorCode.Equals("0"))
                    {
                        errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");
                        return(errorId = -1);
                    }
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;
                    errorId          = -1;
                }

                errorDescription = "发送成功";
                return(errorId);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// 带Json参数的请求
        /// </summary>
        /// <param name="url">请求服务器路径</param>
        /// <param name="data">json数据</param>
        /// <param name="errorDescription">错误描述</param>
        /// <param name="JsonResult">json结果</param>
        /// <returns></returns>
        private static bool UploadString(string url, string data, ref string errorDescription, ref string JsonResult)
        {
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers["Content-Type"] = "application/json";
                client.Encoding = System.Text.Encoding.UTF8;
                string by = "";

                try
                {
                    by = client.UploadString(url, "post", data);
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;

                    return(false);
                }

                if (by.IndexOf("errcode") >= 0)
                {
                    if (!Utility.AnalysisJson(by, "errcode").Equals("0"))
                    {
                        errorDescription = ErrorInformation.GetErrorCode(by, "errcode");

                        return(false);
                    }
                }

                JsonResult = by;//json结果

                return(true);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 获取用户的基本信息
        /// </summary>
        /// <param name="OpenId">用户账号的唯一标识ID</param>
        /// <param name="lang">返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 为空默认中文简体</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns>返回用户基本信息实体UserInformation</returns>
        public static UserInformation GetUserInformation(string OpenId, string lang, ref string errorDescription)
        {
            Shove._IO.Log log = new _IO.Log("WeixinGongzhong");

            errorDescription = "";
            lang             = string.IsNullOrEmpty(lang) ? "zh_CN" : lang.Trim();

            if (string.IsNullOrEmpty(OpenId))
            {
                errorDescription = "OpenId不正确,null";
                return(null);
            }

            if (string.IsNullOrEmpty(Utility.Access_token))
            {
                errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法";
                return(null);
            }

            string errorCode = "";

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                try
                {
                    byte[] by = client.DownloadData(string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang={2}", Utility.Access_token, OpenId, lang));

                    errorCode = System.Text.Encoding.UTF8.GetString(by);
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;
                    return(null);
                }
            }

            if (errorCode.IndexOf("errcode") >= 0)
            {
                errorDescription = ErrorInformation.GetErrorCode(errorCode, "errcode");
                log.Write(errorDescription + "\t" + Utility.Access_token + "\t" + Utility.AppID + "\t" + Utility.AppSecret);
                return(null);
            }

            return(JsonToObject(errorCode, ref errorDescription));
        }
Esempio n. 4
0
        /// <summary>
        /// 删除群发消息(删除消息只是将消息的图文详情页失效,已经收到的用户,还是能在其本地看到消息卡片)
        /// </summary>
        /// <param name="msg_id">群发的消息ID</param>
        /// <param name="errorDescription">描述</param>
        /// <returns>返回成功:true 失败:false</returns>
        public static bool DeleteMassSendMessage(string msg_id, ref string errorDescription)
        {
            errorDescription = "";

            if (string.IsNullOrEmpty(msg_id))
            {
                errorDescription = "-10007,消息ID能为空";
                return(false);
            }

            if (Shove._Convert.StrToLong(msg_id, -1) < 0)
            {
                errorDescription = "-10008,不合法的msg_id";
                return(false);
            }

            string json = "{\"msgid\":" + msg_id + "}";

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers["Content-Type"] = "application/json";
                client.Encoding = System.Text.Encoding.UTF8;

                try
                {
                    string strResult = client.UploadString
                                           (string.Format("https://api.weixin.qq.com//cgi-bin/message/mass/delete?access_token={0}", Utility.Access_token), "post", json);
                    string errorCode = Utility.AnalysisJson(strResult, "errcode");

                    if (!errorCode.Equals("0"))
                    {
                        errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;
                    return(false);
                }

                return(true);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 请求向微信服务器通讯,并取得结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="errorDescription"></param>
        /// <returns></returns>
        private static bool PostToWeixinServer(string url, string data, ref string errorDescription)
        {
            // 通过 AppID,AppSecret 得到菜单token
            //access_token = GetAccessToken(AppID, AppSecret);

            if (string.IsNullOrEmpty(Utility.Access_token))
            {
                errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法";
                return(false);
            }

            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers["Content-Type"] = "application/json";
            client.Encoding = System.Text.Encoding.UTF8;

            try
            {
                string strResult = "";

                if (string.IsNullOrEmpty(data))
                {
                    strResult = client.UploadString(string.Format("{0}?access_token={1}", url, Utility.Access_token), (string.IsNullOrEmpty(data) ? "get" : "post"));
                }
                else
                {
                    strResult = client.UploadString(string.Format("{0}?access_token={1}", url, Utility.Access_token), (string.IsNullOrEmpty(data) ? "get" : "post"), data);
                }

                if (strResult.IndexOf("ok") <= 0)
                {
                    errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");

                    return(false);
                }
            }
            catch (Exception e)
            {
                errorDescription = e.Message;

                return(false);
            }

            return(true);
        }
Esempio n. 6
0
        /// <summary>
        /// 获取请求返回的Json结果
        /// </summary>
        /// <param name="url">请求微信服务器路径</param>
        /// <param name="errorDescription">错误描述</param>
        /// <param name="JsonResult">json结果</param>
        /// <returns></returns>
        private static bool GetRepuestResult(string url, ref string errorDescription, ref string JsonResult)
        {
            errorDescription = "";

            if (string.IsNullOrEmpty(url))
            {
                errorDescription = "发生错误!请求路径为空";
                return(false);
            }

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                string result = "";

                try
                {
                    byte[] by = client.DownloadData(url);
                    result = System.Text.Encoding.UTF8.GetString(by);
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;

                    return(false);
                }

                if (result.IndexOf("errcode") >= 0)
                {
                    if (!Utility.AnalysisJson(result, "errcode").Equals("0"))
                    {
                        errorDescription = ErrorInformation.GetErrorCode(result, "errcode");

                        return(false);
                    }
                }

                JsonResult = result;

                return(true);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// 根据Openid进行群发
        /// </summary>
        /// <param name="OpenidList">用户openid集合(用 "," 隔开)</param>
        /// <param name="messagetype">群发的消息类型(目前只支持 1、mpnews(图文) 2、voice(语音) 3、image(图片)  4、text(文本)</param>
        /// <param name="content">群发的消息的内容(如果发送信息是媒体类型,此参数填写媒体media_id,如果消息类型为文本类型,直接填写文本内容就可)</param>
        /// <param name="msg_id">发送成功返回本次的群发的消息ID(可以通过消息ID删除群发信息)</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns>成功返回:true,否则返回true</returns>
        public static bool SendFansListMessage(string OpenidList, string messagetype, string content, ref string msg_id, ref string errorDescription)
        {
            errorDescription = "";
            msg_id           = "";

            if (string.IsNullOrEmpty(content))
            {
                errorDescription = "-10005,media_id不能为空";
                return(false);
            }

            if (string.IsNullOrEmpty(OpenidList))
            {
                errorDescription = "-10004,OpenidList不能为空";
                return(false);
            }

            StringBuilder dr = new StringBuilder();

            string media_id = "media_id";//类型名称

            if (string.IsNullOrEmpty(content))
            {
                errorDescription = "-10004,media_id不能为空";
                return(false);
            }

            if (messagetype == "text")
            {
                media_id = "content";
            }

            try
            {
                string[] openid = OpenidList.Split(',');

                dr.Append("{");
                dr.Append("\"touser\":[");

                string str = "";
                for (int i = 0; i < openid.Length; i++)
                {
                    if (i < 10000 && !string.IsNullOrEmpty(openid[i]))
                    {
                        str += "\"" + openid[i] + "\",";
                    }
                }

                dr.Append(str.Substring(0, str.Length - 1));
                dr.Append("],");
                dr.Append("\"" + messagetype + "\":{");
                dr.Append("\"" + media_id + "\":\"" + content + "\"");
                dr.Append("},");
                dr.Append("\"msgtype\":\"" + messagetype + "\"");
                dr.Append("}");
            }
            catch (Exception ex)
            {
                errorDescription = "发送失败:" + ex.Message;
                return(false);
            }

            string result = RequestSend(string.Format("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={0}", Utility.Access_token), dr.ToString(), ref errorDescription);

            if (string.IsNullOrEmpty(result))
            {
                return(false);
            }

            long errcode = Shove._Convert.StrToLong(Utility.AnalysisJson(result, "errcode"), -1);

            if (errcode == 0)
            {
                msg_id = Utility.AnalysisJson(result, "msg_id");
                return(true);
            }

            errorDescription = ErrorInformation.GetErrorCode(result, "errcode");

            return(false);
        }
Esempio n. 8
0
        /// <summary>
        /// 群发视频信息(根据分组和Openid进行发送)
        /// </summary>
        /// <param name="to_user"></param>
        /// <param name="Video_media_id"></param>
        /// <param name="type"></param>
        /// <param name="VideoTitle"></param>
        /// <param name="description"></param>
        /// <param name="msg_id"></param>
        /// <param name="errorDescription"></param>
        /// <returns></returns>
        public static bool SendGroupVideoMessage(string to_user, string Video_media_id, int type, string VideoTitle, string description, ref string msg_id, ref string errorDescription)
        {
            #region 参数验证
            if (type <= 0 && type > 2)
            {
                errorDescription = "-1,参数\"type\":类型不合法";
                return(false);
            }

            errorDescription = "";
            msg_id           = "";

            if (string.IsNullOrEmpty(Video_media_id))
            {
                errorDescription = "-10004,Video_media_id不能为空";
                return(false);
            }

            if (string.IsNullOrEmpty(to_user))
            {
                errorDescription = "-10003,group_id不能为空";
                return(false);
            }

            if (type == 1)
            {
                if (Shove._Convert.StrToLong(to_user, -1) < 0)
                {
                    errorDescription = "-10002,不合法的groupId";
                    return(false);
                }
            }
            else
            {
            }

            #endregion

            #region 微信重新处理视频文件id,返回新的视频文件ID
            string json = "{\"media_id\": \"" + Video_media_id + "\", \"title\": \"" + VideoTitle + "\",\"description\": \"" + description + "\"}";


            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                client.Headers["Content-Type"] = "application/json";
                client.Encoding    = System.Text.Encoding.UTF8;
                client.Credentials = CredentialCache.DefaultCredentials;
                try
                {
                    string strResult = "";
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                    strResult = client.UploadString(string.Format("https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token={0}", Utility.Access_token), "post", json);

                    if (strResult.IndexOf("errcode") >= 0)
                    {
                        errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");
                        Video_media_id   = "";
                        return(false);
                    }

                    string media_type = Utility.AnalysisJson(strResult, "type");
                    Video_media_id = Utility.AnalysisJson(strResult, "media_id");
                }
                catch (Exception e)
                {
                    errorDescription = e.Message;

                    return(false);
                }
            }
            #endregion

            #region 群发处理后的视频文件
            StringBuilder dr = new StringBuilder();

            if (type == 1)
            {
                dr.Append("{");
                dr.Append("\"filter\":{");
                dr.Append("\"group_id\":\"" + to_user + "\"");
                dr.Append("},");
                dr.Append("\"mpvideo\":{");
                dr.Append("\"media_id\":\"" + Video_media_id + "\"");
                dr.Append("},");
                dr.Append("\"msgtype\":\"mpvideo\"");
                dr.Append("}");
            }
            else
            {
                string[] openid = to_user.Split(',');

                dr.Append("{");
                dr.Append("\"touser\":[");

                string str = "";
                for (int i = 0; i < openid.Length; i++)
                {
                    if (i < 10000 && !string.IsNullOrEmpty(openid[i]))
                    {
                        str += "\"" + openid[i] + "\",";
                    }
                }

                dr.Append(str.Substring(0, str.Length - 1));
                dr.Append("],");

                dr.Append("\"mpnews\":{");
                dr.Append("\"media_id\":\"" + Video_media_id + "\"");
                dr.Append("},");
                dr.Append("\"msgtype\":\"mpnews\"");
                dr.Append("}");
            }

            string result = RequestSend(string.Format("https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}", Utility.Access_token), dr.ToString(), ref errorDescription);

            if (string.IsNullOrEmpty(result))
            {
                return(false);
            }

            long errcode = Shove._Convert.StrToLong(Utility.AnalysisJson(result, "errcode"), -1);

            if (errcode == 0)
            {
                msg_id = Utility.AnalysisJson(result, "msg_id");
                return(true);
            }

            errorDescription = ErrorInformation.GetErrorCode(result, "errcode");

            return(false);

            #endregion
        }
Esempio n. 9
0
        /// <summary>
        /// 根据分组进行群发
        /// </summary>
        /// <param name="group_id">用户分组ID</param>
        /// <param name="messagetype">群发的消息类型(目前只支持 1、mpnews(图文) 2、voice(语音) 3、image(图片)  4、text(文本))</param>
        /// <param name="content">群发的消息的内容(如果发送消息是媒体类型,此参数填写媒体media_id,如果消息为文本类型,直接填写文本消息内容就可)</param>
        /// <param name="msg_id">发送成功返回本次的群发的消息ID(可以通过消息ID删除群发信息)</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns>成功返回:true,否则返回true</returns>
        public static bool SendGroupMessage(string group_id, string messagetype, string content, ref string msg_id, ref string errorDescription)
        {
            List <string> typeList = new List <string>();

            typeList.Add("mpnews");
            typeList.Add("voice");
            typeList.Add("image");
            typeList.Add("text");

            if (!typeList.Contains(messagetype))
            {
                errorDescription = "-1,参数\"messagetype\":类型不合法";
                return(false);
            }

            errorDescription = "";
            msg_id           = "";
            string media_id = "media_id";//类型名称

            if (string.IsNullOrEmpty(content))
            {
                errorDescription = "-10004,media_id不能为空";
                return(false);
            }

            if (string.IsNullOrEmpty(group_id))
            {
                errorDescription = "-10003,group_id不能为空";
                return(false);
            }

            if (Shove._Convert.StrToLong(group_id, -1) < 0)
            {
                errorDescription = "-10002,不合法的groupId";
                return(false);
            }

            if (messagetype == "text")
            {
                media_id = "content";
            }

            StringBuilder dr = new StringBuilder();

            dr.Append("{");
            dr.Append("\"filter\":{");
            dr.Append("\"group_id\":\"" + group_id + "\"");
            dr.Append("},");
            dr.Append("\"" + messagetype + "\":{");
            dr.Append("\"" + media_id + "\":\"" + content + "\"");
            dr.Append("},");
            dr.Append("\"msgtype\":\"" + messagetype + "\"");
            dr.Append("}");

            string result = RequestSend(string.Format("https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}", Utility.Access_token), dr.ToString(), ref errorDescription);

            if (string.IsNullOrEmpty(result))
            {
                return(false);
            }

            long errcode = Shove._Convert.StrToLong(Utility.AnalysisJson(result, "errcode"), -1);

            if (errcode == 0)
            {
                msg_id = Utility.AnalysisJson(result, "msg_id");
                return(true);
            }

            errorDescription = ErrorInformation.GetErrorCode(result, "errcode");

            return(false);
        }
Esempio n. 10
0
        /// <summary>删除永久素材
        /// </summary>
        /// <param name="media_id">素材标识id</param>
        /// <param name="errorDescription">返回错误信息</param>
        /// <returns></returns>
        public static bool DeletePermanenceMaterial(string media_id, ref string errorDescription)
        {
            if (string.IsNullOrEmpty(Access_token))
            {
                errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法";

                return(false);
            }

            string param = "{\"media_id\":\"" + media_id + "\"}";

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(string.Format("https://api.weixin.qq.com/cgi-bin/material/del_material?access_token={0}", Access_token));
            request.Method      = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            byte[] payload = System.Text.Encoding.UTF8.GetBytes(param);
            request.ContentLength = payload.Length;
            string strResult = string.Empty;

            Stream          requestStream  = null;
            HttpWebResponse response       = null;
            Stream          responseStream = null;
            StreamReader    myStreamReader = null;

            try
            {
                requestStream = request.GetRequestStream();
                requestStream.Write(payload, 0, payload.Length);

                response       = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
            }
            catch (Exception ex)
            {
                errorDescription = ex.Message;

                return(false);
            }
            finally
            {
                if (responseStream != null)
                {
                    myStreamReader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
                    strResult      = myStreamReader.ReadToEnd();

                    if (myStreamReader != null)
                    {
                        myStreamReader.Close();
                        myStreamReader.Dispose();
                    }

                    responseStream.Close();
                    responseStream.Dispose();
                }

                if (requestStream != null)
                {
                    requestStream.Close();
                }

                if (response != null)
                {
                    response.Close();
                }
            }

            if (String.IsNullOrEmpty(strResult))
            {
                errorDescription = "接口调用异常";

                return(false);
            }

            if (strResult.IndexOf("errcode") >= 0)
            {
                //根据错误代码获取错误代码对应的解释
                errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");

                if (Utility.AnalysisJson(strResult, "errcode") == "0")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 11
0
        /// <summary>修改永久图文素材
        /// </summary>
        /// <param name="massImageTextMessage">图文信息集合</param>
        /// <param name="media_id">上传素材后获取的唯一标识(用于群发接口中使用)</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns>成功: true | 失败:false</returns>
        public static bool UpdatePermanenceImageTextMaterial(List <MassImageTextMessage> massImageTextMessage, string media_id, ref string errorDescription)
        {
            errorDescription = string.Empty;

            if (massImageTextMessage == null || massImageTextMessage.Count <= 0)
            {
                errorDescription = "-10000,消息集合不能为空";

                return(false);
            }

            if (string.IsNullOrEmpty(Access_token))
            {
                errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法";

                return(false);
            }

            StringBuilder json = new StringBuilder();

            json.Append("{ \"media_id\":\"" + media_id + "\",\"index\":\"0\",\"articles\": ");

            for (int i = 0; i < massImageTextMessage.Count; i++)
            {
                json.Append(massImageTextMessage[i].Tojson());
            }

            json.Remove(json.Length - 1, 1);
            json.Append("}");

            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers["Content-Type"] = "application/json";
            client.Encoding = System.Text.Encoding.UTF8;
            string strResult = string.Empty;

            try
            {
                strResult = client.UploadString(string.Format("https://api.weixin.qq.com/cgi-bin/material/update_news?access_token={0}", Access_token), "post", json.ToString());
            }
            catch (Exception e)
            {
                errorDescription = e.Message;

                return(false);
            }
            finally
            {
                client.Dispose();
            }

            if (String.IsNullOrEmpty(strResult))
            {
                errorDescription = "接口调用异常";

                return(false);
            }

            if (strResult.IndexOf("errcode") >= 0)
            {
                //根据错误代码获取错误代码对应的解释
                errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");

                if (Utility.AnalysisJson(strResult, "errcode") == "0")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 12
0
        /// <summary>上传永久文件类型素材
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="type">文件类型</param>
        /// <param name="videoTitle">视频标题(不是视频填空即可)</param>
        /// <param name="videoIntroduction">视频简介(不是视频填空即可)</param>
        /// <param name="media_id">返回媒体文件ID</param>
        /// <param name="url">媒体文件路径(仅新增图片素材时会返回该字段)</param>
        /// <param name="errorDescription">返回消息</param>
        /// <returns></returns>
        public static bool UploadPermanenceFileMaterial(string filePath, string type, string videoTitle, string videoIntroduction, ref string media_id, ref string url, ref string errorDescription)
        {
            errorDescription = string.Empty;
            string types = "image,voice,video,thumb";

            if (types.IndexOf(type) < 0)
            {
                errorDescription = "媒体文件类型错误";

                return(false);
            }

            if (string.IsNullOrEmpty(filePath))
            {
                errorDescription = "错误:媒体文件为空";

                return(false);
            }

            if (string.IsNullOrEmpty(Access_token))
            {
                errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法";

                return(false);
            }

            HttpWebRequest request = null;

            if (type == "video")
            {
                if (string.IsNullOrEmpty(videoTitle))
                {
                    errorDescription = "上传视频的标题不能为空";

                    return(false);
                }

                string videoStr = "{ \"title\":\"" + videoTitle + "\", \"introduction\":\"" + videoIntroduction + "\"}";
                request = (HttpWebRequest)WebRequest.Create(string.Format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}&description={2}", Access_token, type, videoStr));
            }
            else
            {
                request = (HttpWebRequest)WebRequest.Create(string.Format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}", Access_token, type));
            }

            MemoryStream postStream = new MemoryStream();
            string       boundary   = "----" + DateTime.Now.Ticks.ToString("x");
            FileInfo     files      = new FileInfo(filePath);

            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
            string formdata         = string.Format(formdataTemplate, "media", files.Name);

            byte[] footer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            request.Method      = "POST";
            request.Timeout     = 300000;
            request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            request.Accept      = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.KeepAlive   = true;
            request.ServicePoint.ConnectionLimit = 1000;
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";

            byte[] buffer    = new byte[1024];
            int    bytesRead = 0;
            string strResult = string.Empty;

            FileStream fileStream = null;

            byte[] formdataBytes = null;

            try
            {
                fileStream    = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                formdataBytes = System.Text.Encoding.UTF8.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行
                postStream.Write(formdataBytes, 0, formdataBytes.Length);

                //写入文件
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    postStream.Write(buffer, 0, bytesRead);
                }
                //结尾
                postStream.Write(footer, 0, footer.Length);
            }
            catch (Exception ex)
            {
                errorDescription = ex.Message;

                return(false);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }

            if (postStream == null)
            {
                errorDescription = "读写流异常";

                return(false);
            }

            bytesRead             = 0;
            request.ContentLength = postStream.Length;
            postStream.Position   = 0;
            Stream          requestStream  = null;
            HttpWebResponse response       = null;
            Stream          responseStream = null;
            StreamReader    myStreamReader = null;

            try
            {
                requestStream = request.GetRequestStream();
                while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                response       = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
            }
            catch (Exception ex)
            {
                errorDescription = ex.Message;

                return(false);
            }
            finally
            {
                if (responseStream != null)
                {
                    myStreamReader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
                    strResult      = myStreamReader.ReadToEnd();

                    if (myStreamReader != null)
                    {
                        myStreamReader.Close();
                        myStreamReader.Dispose();
                    }

                    responseStream.Close();
                    responseStream.Dispose();
                }

                if (postStream != null)
                {
                    postStream.Close();   //关闭文件访问
                    postStream.Dispose(); //释放资源
                }

                if (requestStream != null)
                {
                    requestStream.Close();
                    requestStream.Dispose();
                }

                if (response != null)
                {
                    response.Close();
                }
            }

            if (String.IsNullOrEmpty(strResult))
            {
                errorDescription = "接口调用异常";

                return(false);
            }

            if (strResult.IndexOf("errcode") < 0)
            {
                //媒体文件ID;
                media_id = Utility.AnalysisJson(strResult, "media_id");

                //媒体文件路径
                if (strResult.Contains("url"))
                {
                    url = Utility.AnalysisJson(strResult, "url");
                }
                else
                {
                    url = string.Empty;
                }

                return(true);
            }
            else
            {
                //根据错误代码获取错误代码对应的解释
                errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");

                return(false);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// 上传群图文素材(此方法上传素材只能用作于群发)
        /// </summary>
        /// <param name="massImageTextMessage">上传素材的集合(支持1到10条图文信息)</param>
        /// <param name="media_id">上传素材后获取的唯一标识(用于群发接口中使用)</param>
        /// <param name="errorDescription"></param>
        /// <returns>成功: true | 失败:false</returns>
        public static bool UploadMassImageTextMessage(List <MassImageTextMessage> massImageTextMessage, ref string media_id, ref string errorDescription)
        {
            errorDescription = string.Empty;
            media_id         = string.Empty;

            if (massImageTextMessage == null || massImageTextMessage.Count <= 0)
            {
                errorDescription = "-10000,消息集合不能为空";

                return(false);
            }

            StringBuilder json = new StringBuilder();

            json.Append("{\"articles\": [");

            for (int i = 0; i < massImageTextMessage.Count; i++)
            {
                json.Append(massImageTextMessage[i].Tojson());
            }

            json.Remove(json.Length - 1, 1);
            json.Append("]}");


            System.Net.WebClient client = new System.Net.WebClient();
            client.Headers["Content-Type"] = "application/json";
            client.Encoding = System.Text.Encoding.UTF8;

            string strResult = string.Empty;

            try
            {
                strResult = client.UploadString(string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", Access_token), "post", json.ToString());
            }
            catch (Exception e)
            {
                errorDescription = e.Message;

                return(false);
            }
            finally
            {
                client.Dispose();
            }

            if (String.IsNullOrEmpty(strResult))
            {
                errorDescription = "接口调用异常";

                return(false);
            }

            if (strResult.IndexOf("errcode") >= 0)
            {
                errorDescription = ErrorInformation.GetErrorCode(strResult, "errcode");
                media_id         = "";

                return(false);
            }

            string type = Utility.AnalysisJson(strResult, "type");

            media_id = Utility.AnalysisJson(strResult, "media_id");

            return(true);
        }
Esempio n. 14
0
        /// <summary>
        /// 下载媒体文件
        /// </summary>
        /// <param name="media_id">文件的ID</param>
        /// <param name="saveFilePath">保存文件的地址 下载成功返回文件的地址</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns></returns>
        public static bool DownloadFile(string media_id, ref string saveFilePath, ref string errorDescription)
        {
            errorDescription = string.Empty;
            //得到文件名称,byte
            string pathName = string.Empty;

            if (string.IsNullOrEmpty(media_id))
            {
                errorDescription = "发生错误,media_id为空";

                return(false);
            }

            if (string.IsNullOrEmpty(Access_token))
            {
                errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法";

                return(false);
            }

            Uri downUri = new Uri(
                string.Format("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}",
                              Access_token, media_id));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(downUri);

            //设置接收对象大小为0-2097152字节(2MB)。
            request.AddRange(0, 2097152);

            if (string.IsNullOrEmpty(saveFilePath))
            {
                saveFilePath = "~/Downloads/Weixin/";
            }

            byte[] bytes = new byte[102400];
            int    n     = 1;

            try
            {
                #region 如果返回的信息小于0,获取微信服务器返回的错误编码

                if (request.GetResponse().ContentLength <= 0)
                {
                    using (System.Net.WebClient client = new System.Net.WebClient())
                    {
                        byte[] by = client.DownloadData(string.Format("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", Access_token, media_id));

                        string errorCode = System.Text.Encoding.UTF8.GetString(by);

                        //获取返回错误代码
                        errorDescription = ErrorInformation.GetErrorCode(errorCode, "errcode");
                    }

                    return(false);
                }
                #endregion


                pathName = request.GetResponse().Headers.GetValues(1)[0].Split('\"')[1];

                //媒体文件类型
                // string type = request.GetResponse().ContentType;
                using (Stream stream = request.GetResponse().GetResponseStream())
                {
                    if (!Directory.Exists(HttpContext.Current.Server.MapPath(saveFilePath)))
                    {
                        Directory.CreateDirectory(HttpContext.Current.Server.MapPath(saveFilePath));
                    }

                    using (FileStream fs = File.Create(HttpContext.Current.Server.MapPath(saveFilePath) + pathName))
                    {
                        while (n > 0)
                        {
                            //一次从流中读多少字节,
                            n = stream.Read(bytes, 0, 10240);

                            //将指定字节的流信息写入文件流中
                            fs.Write(bytes, 0, n);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorDescription = ex.Message;

                return(false);
            }

            saveFilePath = saveFilePath + pathName;

            return(true);
        }
Esempio n. 15
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="filePath">要上传的本地文件路径</param>
        /// <param name="type">媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)</param>
        /// <param name="media_id">上传成功后,返回媒体文件ID</param>
        /// <param name="created_at">媒体文件上传的时间 文件上传三天系统会自动删除</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns></returns>
        public static bool UploadFile(string filePath, string type, ref string media_id, ref string created_at, ref string errorDescription)
        {
            errorDescription = string.Empty;
            created_at       = string.Empty;
            string types = "image,voice,video,thumb";

            if (types.IndexOf(type) < 0)
            {
                errorDescription = "媒体文件类型错误";
                return(false);
            }

            if (string.IsNullOrEmpty(filePath))
            {
                errorDescription = "错误:媒体文件为空";
                return(false);
            }

            if (string.IsNullOrEmpty(Access_token))
            {
                errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法";
                return(false);
            }

            string errorCode = string.Empty;

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                try
                {
                    byte[] by = client.UploadFile(string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", Access_token, type), filePath);
                    errorCode = System.Text.Encoding.UTF8.GetString(by);
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;

                    return(false);
                }
                finally
                {
                    client.Dispose();
                }

                if (String.IsNullOrEmpty(errorCode))
                {
                    errorDescription = "接口调用异常";

                    return(false);
                }

                if (errorCode.IndexOf("errcode") < 0)
                {
                    //媒体文件ID;
                    media_id = Utility.AnalysisJson(errorCode, type == "thumb" ? "thumb_media_id" : "media_id");// errorCode.Split('\"')[7];

                    //媒体文件上传时间
                    created_at = Utility.FromUnixTime(Utility.AnalysisJson(errorCode, "created_at")).ToString();

                    return(true);
                }

                //根据错误代码获取错误代码对应的解释
                errorDescription = ErrorInformation.GetErrorCode(errorCode, "errcode");
            }

            return(false);
        }
Esempio n. 16
0
        /// <summary>
        /// 获取粉丝列表
        /// </summary>
        /// <param name="next_openid">第一个拉取的openID,如果不填默认从头开始拉取</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns>返回FansListInformation实体对象</returns>
        public static FansListInformation GetFansList(string next_openid, ref string errorDescription)
        {
            errorDescription = "";

            if (string.IsNullOrEmpty(Utility.Access_token))
            {
                errorDescription = "发生错误:access_token为null,请查看页面的Load事件是否调用了Utility.GetAccessToken()方法";
                return(null);
            }

            bool IsBool = true;

            FansListInformation FansList = new FansListInformation();

            FansList.Next_openid = next_openid;

            //循环读取粉丝列表,每次只拉取1000个, 通过每次返回粉丝列表最后一个Next_openid作为下一次Next_openid参数,
            //直到把粉丝列表取完Next_openid=""
            while (IsBool)
            {
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    byte[] by;

                    try
                    {
                        by = client.DownloadData(
                            string.Format("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}",
                                          Utility.Access_token, FansList.Next_openid));
                    }
                    catch (Exception ex)
                    {
                        errorDescription = ex.Message;
                        return(null);
                    }

                    if (by.Length <= 0)
                    {
                        errorDescription = "拉取用户列表发生错误!";
                        return(null);
                    }

                    string values = System.Text.Encoding.UTF8.GetString(by).Replace("count", "usercount");

                    if (values.IndexOf("errcode") >= 0)
                    {
                        errorDescription = ErrorInformation.GetErrorCode(values, "errcode");
                        return(null);
                    }

                    FansList.Next_openid = Utility.AnalysisJson(values, "next_openid"); //每次获取用户列表最后一个openid
                    FansList.Total       = Utility.AnalysisJson(values, "total");       //总用户数
                    FansList.Count       = Utility.AnalysisJson(values, "usercount");   //每次获取的用户数
                    if (string.IsNullOrEmpty(FansList.Next_openid))
                    {
                        IsBool = false;

                        break;
                    }
                    //分解列表数据
                    string[] _openid = values.Replace("[", "]").Split(']')[1].Split(',');

                    for (int i = 0; i < _openid.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(_openid[i]))
                        {
                            //将拉取到的_openid存入 FansList.Data集合中
                            FansList.Data.Add(_openid[i].Trim('\"'));
                        }
                    }
                }
            }

            if (FansList.Data.Count <= 0)
            {
                errorDescription = "该公众账号没有粉丝关注。";
                return(null);
            }

            return(FansList);
        }