Пример #1
0
 /// <summary>
 /// 查询余额
 /// 大于等于0 查询成功,并发回剩余条数
 /// -1	账户为空
 /// -2	 密码为空
 /// -3	 企业ID为空
 /// -1	 没有可用的企业ID号
 /// </summary>
 /// <returns></returns>
 public int GetSMSBalance()
 {
     try
     {
         Uri       url    = new Uri(string.Format("http://api.106msg.com/api/get/ua={0}&pwd={1}&gwid={2}", SmsUid, SmsPwd, SmsUnitId));
         WebClient client = new WebClient();
         string    result = client.DownloadString(url);
         if (TmoShare.IsNumeric(result))
         {
             int res = int.Parse(result);
             return(res);
         }
         else
         {
             return(-99);
         }
     }
     catch (Exception ex)
     {
         return(-99);
     }
 }
Пример #2
0
        private void MailScoketAlternation(string[] mailto, string subject, string msg, List <string> attachpathList)
        {
            bool          check  = false;
            NetworkStream stream = sendTcp.GetStream();

            #region 发送Hello握手

            string hostName = Dns.GetHostName();

            check = SendCommand(ref stream, "EHLO " + hostName, "EHLO", "250");

            int round = 0;
            //失败重试
            while (!check && round < 5)
            {
                round++;

                check = SendCommand(ref stream, "EHLO " + hostName, "EHLO", "250");
            }

            #endregion

            #region 请求审核登录

            check = SendCommand(ref stream, "AUTH LOGIN ", "AUTH LOGIN", "334");

            round = 0;
            while (!check && round < 5)
            {
                round++;
                check = SendCommand(ref stream, "AUTH LOGIN ", "AUTH LOGIN", "334");
            }

            #endregion

            #region 身份验证

            check = SendCommand(ref stream, Convert.ToBase64String(Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(SendMailAccount))), "用户名", "334");

            round = 0;
            while (!check && round < 5)
            {
                round++;
                check = SendCommand(ref stream, Convert.ToBase64String(Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(SendMailAccount))), "用户名", "334");
            }

            if (!check)
            {
                //throw new Exception("邮件帐户身份验证失败!");
            }

            check = SendCommand(ref stream, Convert.ToBase64String(Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(SendMailPWD))), "密码", "235");

            round = 0;
            while (!check && round < 5)
            {
                round++;

                check = SendCommand(ref stream, "EHLO " + hostName, "EHLO", "250");
                int round0 = 0;
                while (!check && round0 < 5)
                {
                    round0++;
                    check = SendCommand(ref stream, "EHLO " + hostName, "EHLO", "250");
                }

                check = SendCommand(ref stream, "AUTH LOGIN ", "AUTH LOGIN", "334");

                check = SendCommand(ref stream, Convert.ToBase64String(Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(SendMailAccount))), "用户名", "334");

                check = SendCommand(ref stream, Convert.ToBase64String(Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(SendMailPWD))), "密码", "235");
            }

            if (!check)
            {
                throw new Exception("邮件帐户身份验证失败!");
            }

            #endregion

            #region 发件人

            check = SendCommand(ref stream, "MAIL FROM:<" + SendMailAccount + ">", "MAIL FROM", "250");

            round = 0;
            while (!check && round < 5)
            {
                round++;
                check = SendCommand(ref stream, "MAIL FROM:<" + SendMailAccount + ">", "MAIL FROM", "250");
            }

            #endregion

            #region 收件人

            check = SendCommand(ref stream, "RCPT TO:<" + mailto[0] + ">", "RCPT TO", "250");

            round = 0;
            while (!check && round < 5)
            {
                round++;
                check = SendCommand(ref stream, "RCPT TO:<" + mailto[0] + ">", "RCPT TO", "250");
            }

            #endregion

            #region 抄送人

            if (mailto.Length > 1)
            {
                for (int i = 1; i < mailto.Length; i++)
                {
                    check = SendCommand(ref stream, "RCPT TO:<" + mailto[i] + ">", "RCPT TO", "250");

                    round = 0;
                    while (!check && round < 5)
                    {
                        round++;
                        check = SendCommand(ref stream, "RCPT TO:<" + mailto[i] + ">", "RCPT TO", "250");
                    }
                }
            }

            #endregion

            #region 密送人

            //这里看是否需要了,可以偷偷给自己发一份,呵呵

            #endregion

            #region 请求发送邮件体

            check = SendCommand(ref stream, "DATA", "DATA", "354");

            round = 0;
            while (!check && round < 5)
            {
                round++;
                check = SendCommand(ref stream, "DATA", "DATA", "354");
            }

            #endregion

            #region 发送邮件头

            StringBuilder mailhead = new StringBuilder();
            mailhead.Append("Subject: " + subject)
            .Append("\nDate: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"))
            .Append("\nFrom: " + "<" + SendMailAccount + ">")
            .Append("\nTo: " + mailto[0] + CRLF)
            .Append("MIME-Version:1.0" + CRLF);
            if (mailto.Length > 1)
            {
                mailhead.Append("\nCc: ");

                for (int i = 1; i < mailto.Length; i++)
                {
                    mailhead.Append(mailto[i] + ";");
                }
            }
            #endregion

            #region 发送邮件内容
            if (attachpathList == null || attachpathList.Count <= 0)
            {
                mailhead.Append("Content-Type:multipart/alertnative;" + CRLF + " ".PadRight(8, ' ') + "boundary"
                                + "=\"=====003_Dragon310083331177_=====\"" + CRLF + CRLF + CRLF);
                mailhead.Append("This is a multi-part message in MIME format" + CRLF + CRLF);
                mailhead.Append("--=====003_Dragon310083331177_=====" + CRLF);
                mailhead.Append("Content-Type:text/html;" + CRLF + " ".PadRight(8, ' ') + "charset=\"utf-8\"" + CRLF);
                mailhead.Append("Content-Transfer-Encoding:base64" + CRLF + CRLF);
                if (msg.Length > 0)
                {
                    mailhead.Append(Convert.ToBase64String(Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8("单位").ToCharArray()), 0, Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8("单位").ToCharArray()).Length) + CRLF + CRLF + CRLF + "." + CRLF);
                }
                //mailhead.Append(Convert.ToBase64String(Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(msg).ToCharArray()), 0, Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(msg).ToCharArray()).Length) + CRLF + CRLF + CRLF + "." + CRLF);
                mailhead.Append("--=====003_Dragon310083331177_=====--" + CRLF + CRLF + CRLF + "." + CRLF);
                check = SendCommand(ref stream, mailhead
                                    + "\n\r\n.\r\n", "信已发出,服务器", "250", false);
                string s = TmoShare.GB2312ToUTF8(msg);
                round = 0;
                while (!check && round < 5)
                {
                    round++;

                    check = SendCommand(ref stream, mailhead
                                        + "\n\r\n.\r\n", "信已发出,服务器", "250", false);
                }
            }
            else
            {
                //处理要在邮件中显示的每个附件的数据
                StringCollection attatchmentDatas = new StringCollection();
                foreach (string path in attachpathList)
                {
                    if (!File.Exists(path))
                    {
                        UserMessageBox.MessageError("指定的附件没有找到" + path);
                    }
                    else
                    {
                        //得到附件的字节流
                        FileInfo   file = new FileInfo(path);
                        FileStream fs   = new FileStream(path, FileMode.Open, FileAccess.Read);
                        if (fs.Length > (long)int.MaxValue)
                        {
                            UserMessageBox.MessageError("附件的大小超出了最大限制");
                        }
                        byte[] file_b = new byte[(int)fs.Length];
                        fs.Read(file_b, 0, file_b.Length);
                        fs.Close();
                        string attatchmentMailStr = "Content-Type:application/octet-stream;" + CRLF + " ".PadRight(8, ' ') + "name=" +
                                                    "\"" + file.Name + "\"" + CRLF;
                        attatchmentMailStr += "Content-Transfer-Encoding:base64" + CRLF;
                        attatchmentMailStr += "Content-Disposition:attachment;" + CRLF + " ".PadRight(8, ' ') + "filename=" +
                                              "\"" + file.Name + "\"" + CRLF + CRLF;
                        attatchmentMailStr += Convert.ToBase64String(file_b, 0, file_b.Length) + CRLF + CRLF;
                        attatchmentDatas.Add(attatchmentMailStr);
                    }
                }
                #region 设置邮件信息

                mailhead.Append("Content-Type:multipart/mixed;" + CRLF + " ".PadRight(8, ' ') + "boundary=\"=====001_Dragon255511664284_=====\""
                                + CRLF + CRLF);
                mailhead.Append("This is a multi-part message in MIME format." + CRLF + CRLF);
                mailhead.Append("--=====001_Dragon255511664284_=====" + CRLF);
                mailhead.Append("Content-Type:text/html;" + CRLF + " ".PadRight(8, ' ') + "charset=\"utf-8\"" + CRLF);
                mailhead.Append("Content-Transfer-Encoding:base64" + CRLF + CRLF);
                if (msg.Length > 0)
                {
                    mailhead.Append(Convert.ToBase64String(Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(msg).ToCharArray()), 0, Encoding.UTF8.GetBytes(TmoShare.GB2312ToUTF8(msg).ToCharArray()).Length) + CRLF + CRLF);
                }
                for (int i = 0; i < attatchmentDatas.Count; i++)
                {
                    mailhead.Append("--=====001_Dragon255511664284_=====" + CRLF + attatchmentDatas[i] + CRLF + CRLF);
                }
                mailhead.Append("--=====001_Dragon255511664284_=====--" + CRLF + CRLF + CRLF + "." + CRLF);
                #endregion

                check = SendCommand(ref stream, mailhead.ToString(), "信已发出,服务器", "250", false);

                round = 0;
                while (!check && round < 5)
                {
                    round++;

                    check = SendCommand(ref stream, mailhead.ToString(), "信已发出,服务器", "250", false);
                }
            }

            #endregion

            #region 退出系统
            SendCommand(ref stream, "QUIT", "QUIT", "250");
            #endregion
        }
Пример #3
0
        /// <summary>
        /// 功能说明:
        /// 开发人员:高新刚
        /// 创建日期:2011-4-13 9:19
        /// 修改日期:
        /// 备注信息:
        /// </summary>
        /// <param name="subject">邮件名称</param>
        /// <param name="msg">邮件文本内容</param>
        /// <param name="attachpath">The attachpath.</param>
        /// <param name="ProxyType">Type of the proxy.</param>
        /// <returns></returns>
        public bool SendMail(string subject, string msg, List <string> attachpathList, ProxyType ProxyType)
        {
            bool retbool = false;

            try
            {
                switch (ProxyType)
                {
                case ProxyType.http:

                    #region HTTP方式处理
                    string[] mails = Mails;
                    if (sendTcp == null)
                    {
                        string authstr = ProxyUID + ":" + ProxyPWD;

                        string authproxy = "CONNECT " + SendMailSmtpAdd + ":" + SendMailSmtpPort
                                           + " HTTP/1.0\r\nProxy-Authorization: Basic "
                                           + Convert.ToBase64String(Encoding.UTF8.GetBytes(authstr)) + "\r\n\r\n"; //代理服务器审核

                        bool testproxyflag = true;                                                                 //测试时候使用,设置成false可以不使用代理的Socket方式发邮件

                        if (testproxyflag)
                        {
                            sendTcp = new TcpClient(ProxyIP, ProxyPort);
                        }
                        else
                        {
                            sendTcp = new TcpClient(SendMailSmtpAdd, SendMailSmtpPort);    //注释1
                        }

                        NetworkStream stream = sendTcp.GetStream();

                        //发送代理验证
                        if (testproxyflag)
                        {
                            WriteToNetStream(ref stream, authproxy, false);
                        }

                        //获取验证反馈
                        string response = ReadFromNetStream(ref stream);

                        bool check = false;

                        if (testproxyflag)
                        {
                            check = CheckForError(response, "HTTP/1.0 200") ||
                                    CheckForError(response, "HTTP/1.1 200");

                            if (!check)
                            {
                                TmoShare.WriteLog("邮件发送失败 失败原因:邮件代理连接失败");
                                throw new Exception("邮件代理连接失败\r\n");
                            }

                            string receive = ReadFromNetStream(ref stream);

                            check = CheckForError(receive, "220");

                            if (!check)
                            {
                                TmoShare.WriteLog("邮件发送失败 失败原因:远端服务器连接失败");
                                throw new Exception("远端服务器连接失败\r\n");
                            }
                        }
                        else
                        {
                            check = CheckForError(response, "220");    //注释3

                            if (!check)
                            {
                                TmoShare.WriteLog("邮件发送失败 失败原因:远端服务器连接失败");
                                throw new Exception("远端服务器连接失败\r\n");
                            }
                        }
                    }

                    try
                    {
                        //发送邮件
                        MailScoketAlternation(mails, subject, msg, attachpathList);
                    }
                    catch (Exception ex)
                    {
                        sendTcp.Close();
                        sendTcp = null;
                        throw ex;
                    }
                    finally
                    {
                        if (sendTcp != null)
                        {
                            try
                            {
                                NetworkStream stream = sendTcp.GetStream();
                                WriteToNetStream(ref stream, "QUIT");
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                sendTcp.Close();
                                sendTcp = null;
                            }
                        }
                    }

                    #endregion

                    break;

                case ProxyType.SOCKS4:
                    //此种方式我软件没让他支持,如果大家想用可以使用CDO的方法试一下,我也没有试是否可行,但是Socket的方式肯定是可以的,只是要有一些变化,如果有人感兴趣可以给我留言。使用CDO需要在项目里引用Microsoft CDO for Windows 2000 Library和Microsoft ActiveX Data Objects 2.8 Library两个COM

                    #region SOCKS4方式处理--暂时不予支持

                    //CDO.Message oMsg = new CDO.Message();

                    //oMsg.From = clsParam.Param.SendMailAccount;
                    //oMsg.To = mails[0];
                    //oMsg.Subject = subject;

                    //oMsg.HTMLBody = msg;

                    //if (File.Exists(attachpath))
                    //{
                    //    oMsg.AddAttachment(attachpath, "", "");
                    //}

                    //CDO.IConfiguration iConfg = oMsg.Configuration;
                    //ADODB.Fields oFields = iConfg.Fields;

                    //oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2;
                    //oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 1;
                    ////value=0   代表Anonymous验证方式(不需要验证)
                    ////value=1   代表Basic验证方式(使用basic   (clear-text)   authentication.
                    ////The   configuration   sendusername/sendpassword   or   postusername/postpassword   fields   are   used   to   specify   credentials.)
                    ////Value=2   代表NTLM验证方式(Secure   Password   Authentication   in   Microsoft   Outlook   Express)
                    //oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = clsParam.Param.SendMailSmtpAdd;
                    //oFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = clsParam.Param.SendMailAccount;   //sender   mail
                    //oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = clsParam.Param.SendMailAccount;
                    //oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = clsParam.Param.SendMailPWD;

                    //oFields["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"].Value = 5;
                    //oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value = 0x0804;

                    ////代理设置
                    ////oFields["http://schemas.microsoft.com/cdo/configuration/urlproxyserver"].Value = "182.1.1.200";
                    ////oFields["http://schemas.microsoft.com/cdo/configuration/proxyserverport"].Value = 8080;

                    //oFields.Update();
                    //oMsg.BodyPart.Charset = "gb2312";
                    //oMsg.HTMLBodyPart.Charset = "gb2312";

                    //oMsg.Send();
                    //oMsg = null;

                    #endregion

                    break;

                case ProxyType.Socks5:     //同Socket4的注释

                    #region SOCKS5方式处理--暂时不予支持

                    #endregion

                    break;
                }


                retbool = true;
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("发送邮件异常:" + ex.Message);

                retbool = false;
            }
            finally
            {
            }

            return(retbool);
        }
Пример #4
0
        ///<summary>
        /// 将JSON解析成DataSet只限特定格式的JSON数据
        /// JAFly 2015-11-26
        /// </summary>
        public static DataSet JsonToDataSet(object Json, string DataTableName)
        {
            try
            {
                Json = Json.ToString().Replace("}", "}").Replace("{", "{").Replace(":", ":");
                DataSet       ds  = new DataSet("well_data");
                List <object> lst = new List <object>();
                lst.Add(Json.ToString());
                foreach (object js in lst)
                {
                    object obj = null;
                    if (js is System.String)
                    {
                        obj = JsonConvert.DeserializeObject(js.ToString().Replace("“", "\"").Replace("”", "\"").Replace(":", ":").Replace(",", ",")); //去除中文标点影响
                    }

                    #region 多价值对
                    Newtonsoft.Json.Linq.JArray objs = null;
                    objs = (Newtonsoft.Json.Linq.JArray)obj;
                    DataTable dt = new DataTable(DataTableName);
                    if (!dt.Columns.Contains("objIndex"))
                    {
                        dt.Columns.Add("objIndex", typeof(System.Int32));
                    }
                    int objIndex = 1;



                    foreach (object obc in objs)
                    {
                        if (obc is System.String)
                        {
                            if (!dt.Columns.Contains("objName"))
                            {
                                dt.Columns.Add("objName");
                            }
                            DataRow dr = dt.NewRow();
                            dr["objIndex"] = objIndex;
                            dr["objName"]  = obc.ToString().Trim();
                            dt.Rows.Add(dr);
                        }
                        else
                        {
                            Newtonsoft.Json.Linq.JObject datajson = (Newtonsoft.Json.Linq.JObject)obc;
                            DataRow dr = dt.NewRow();
                            foreach (KeyValuePair <string, Newtonsoft.Json.Linq.JToken> sss in datajson)
                            {
                                if (!dt.Columns.Contains(sss.Key))
                                {
                                    dt.Columns.Add(sss.Key.ToString());
                                }

                                dr[sss.Key] = sss.Value;
                            }
                            dr["objIndex"] = objIndex;
                            dt.Rows.Add(dr);
                        }
                        objIndex++;
                    }

                    DataView dv = dt.DefaultView;
                    dv.Sort = "objIndex desc ";
                    DataTable dtTemp = dv.ToTable();
                    ds.Tables.Add(dtTemp);


                    #endregion
                }
                if (TmoShare.DataSetVerify(ds) != null)
                {
                    DataSet dsTemp = TmoShare.getDataSetFromXML(TmoShare.getXMLFromDataSet(ds));
                    return(TmoShare.DataSetVerify(dsTemp));
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }
        }
Пример #5
0
        public static string WXTemplateMsgSend(object[] infoValue)
        {
            string strRecode = "微信模板消息发送失败!-原因:{0}-当前医生:{1}";

            try
            {
                if (string.IsNullOrEmpty(infoValue[0].ToString()))  //参数缺少医生编号
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_002(参数中未找到医生编号)", "null"));
                    return("err_wx_002");
                }

                string doc_code    = infoValue[0].ToString();       //取得参数中的值
                string openid      = infoValue[1].ToString();
                string template_id = infoValue[2].ToString();
                string url         = infoValue[3].ToString();
                string topcolor    = infoValue[4].ToString();
                string data        = infoValue[5].ToString();
                data = TmoCommon.JsonHelper.XMLToJSON(data);
                data = data.TrimStart('{').Remove(data.Length - 2);
                #region 发送命令
send:
                string AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, true);
                if (string.IsNullOrEmpty(AccessToken) || AccessToken.StartsWith("err"))
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_accessToken(获取accessToken失败:(" + AccessToken + "))", doc_code));
                    return("err_wx_accessToken");
                }
                string     uri      = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + AccessToken;
                string     postdata = "{\"touser\":\"" + openid + "\",\"template_id\":\"" + template_id + "\",\"url\":\"" + url + "\",\"topcolor\":\"" + topcolor + "\"," + data + "}";
                WebRequest request  = WebRequest.Create(uri);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                Stream writer = request.GetRequestStream();
                byte[] pdarry = Encoding.UTF8.GetBytes(postdata);
                writer.Write(pdarry, 0, pdarry.Length);
                writer.Close();
                #endregion
                #region 取得命令返回值
                WebResponse  response = request.GetResponse();
                Stream       rpReader = response.GetResponseStream();
                StreamReader reader   = new StreamReader(rpReader, Encoding.UTF8);
                string       rtStr    = reader.ReadToEnd();
                reader.Close();
                rpReader.Close();
                response.Close();
                rtStr = rtStr.Replace("&lt;", "<").Replace("&gt;", ">");
                #endregion

                #region 结果处理
                if (string.IsNullOrEmpty(rtStr))
                {
                    return("err_wx_003");
                }

                var jsNodes = TmoCommon.JsonHelper.GetJsonValues(rtStr);
                if (jsNodes == null || jsNodes.Count == 0)
                {
                    return("err_json_converter");
                }
                if (jsNodes.ContainsKey("errcode"))
                {
                    string errcode = jsNodes["errcode"].Value.Trim();
                    if (errcode == "0")
                    {
                        //if (!AddWeiXinPushHistory(openid, data))
                        //{
                        //   TmoShare.WriteLog("WeiXin", "创建微信模板消息历史记录失败");
                        //    return "err_success_创建微信模板消息历史记录失败";
                        //}
                        if (jsNodes.ContainsKey("msgid"))
                        {
                            return("success_" + jsNodes["msgid"].Value.Trim()); //成功
                        }
                        else
                        {
                            return("err_success");
                        }
                    }
                    else if (errcode == "40001" || errcode == "40002") //access_token问题
                    {
                        AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, false);
                        goto send;
                    }
                    else
                    {
                        return("err_" + errcode + "_" + jsNodes["errmsg"].Value);
                    }
                }
                else
                {
                    return("err_errcode_null");
                }
                #endregion
            }
            catch (Exception e)
            {
                TmoShare.WriteLog(string.Format(strRecode, "err_wx_001(未知异常失败)", infoValue[0]) + e.Message);
                return("err_wx_001");
            }
        }
Пример #6
0
        /// <summary>
        ///获得模板ID
        /// </summary>
        /// <param name="infoValue">0-医生编号 1-模板库中的短ID</param>
        /// <returns></returns>
        public static string WXGetTemplateSetID(object[] infoValue)
        {
            string strRecode = "获得微信模板ID失败!-原因:{0}-当前医生:{1}";

            try
            {
                if (string.IsNullOrEmpty(infoValue[0].ToString()))  //参数缺少医生编号
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_002(参数中未找到医生编号)", "null"));
                    return("err_wx_002");
                }
                string doc_code          = infoValue[0].ToString(); //取得参数中的值
                string template_id_short = infoValue[1].ToString();

                #region 发送命令
send:
                string AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, true);
                if (string.IsNullOrEmpty(AccessToken) || AccessToken.StartsWith("err"))
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_accessToken(获取accessToken失败:(" + AccessToken + "))", doc_code));
                    return("err_wx_accessToken");
                }
                string     url      = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + AccessToken;
                string     postdata = "{\"template_id_short\":\"" + template_id_short + "\"}";
                WebRequest request  = WebRequest.Create(url);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                Stream writer = request.GetRequestStream();
                byte[] pdarry = Encoding.UTF8.GetBytes(postdata);
                writer.Write(pdarry, 0, pdarry.Length);
                writer.Close();
                #endregion
                #region 取得命令返回值
                WebResponse  response = request.GetResponse();
                Stream       rpReader = response.GetResponseStream();
                StreamReader reader   = new StreamReader(rpReader, Encoding.UTF8);
                string       rtStr    = reader.ReadToEnd();
                reader.Close();
                rpReader.Close();
                response.Close();
                rtStr = rtStr.Replace("&lt;", "<").Replace("&gt;", ">");
                #endregion

                #region 结果处理
                if (string.IsNullOrEmpty(rtStr))
                {
                    return("err_wx_003");
                }
                var nodes = TmoCommon.JsonHelper.JSONToObject <Dictionary <string, string> >(rtStr);
                if (nodes == null || nodes.Count == 0)
                {
                    return("err_json_converter");
                }
                if (nodes.ContainsKey("errcode"))
                {
                    string errcode = nodes["errcode"].Trim();
                    if (errcode == "0")
                    {
                        if (nodes.ContainsKey("template_id"))
                        {
                            string          template_id = nodes["template_id"].Trim();
                            WxTemplateID    template    = null;
                            BinaryFormatter bf          = new BinaryFormatter();
                            string          configValue = ConfigHelper.GetConfigString("wx_templateid");
                            if (!string.IsNullOrEmpty(configValue))
                            {
                                MemoryStream msr = new MemoryStream(Encoding.UTF8.GetBytes(configValue));
                                template = (WxTemplateID)bf.Deserialize(msr);
                                msr.Close();
                            }
                            if (template == null)
                            {
                                template = new WxTemplateID(TmoShare.WX_APP_ID);
                            }
                            template.AddTemplate(template_id_short, template_id);
                            byte[]       tmp = new byte[1024];
                            MemoryStream msw = new MemoryStream(tmp);
                            bf.Serialize(msw, template);
                            msw.Close();
                            configValue = Encoding.UTF8.GetString(tmp);
                            if (!ConfigHelper.UpdateConfig("wx_templateid", configValue, true))
                            {
                                ConfigHelper.GetConfigString("wx_templateid", configValue, true);
                            }
                            return(template_id); //成功
                        }
                        else
                        {
                            return("err_success");
                        }
                    }
                    else if (errcode == "40001" || errcode == "40002") //access_token问题
                    {
                        AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, false);
                        goto send;
                    }
                    else
                    {
                        return("err_" + errcode + "_" + nodes["errmsg"]);
                    }
                }
                else
                {
                    return("err_errcode_null");
                }
                #endregion
            }
            catch (Exception e)
            {
                TmoShare.WriteLog(string.Format(strRecode, "err_wx_001(未知异常失败)", infoValue[0]) + e.Message);
                return("err_wx_001");
            }
        }
Пример #7
0
        /// <summary>
        ///设置模板消息所属行业(每月仅可修改1次)
        /// </summary>
        /// <param name="infoValue">0-医生编号 1-主行业 2-副行业</param>
        /// <returns></returns>
        public static string WXTemplateSetIndustry(object[] infoValue)
        {
            string strRecode = "设置微信模板消息所属行业失败!-原因:{0}-当前医生:{1}";

            try
            {
                if (string.IsNullOrEmpty(infoValue[0].ToString()))  //参数缺少医生编号
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_002(参数中未找到医生编号)", "null"));
                    return("err_wx_002");
                }
                string doc_code     = infoValue[0].ToString();      //取得参数中的值
                string industry_id1 = infoValue[1].ToString();
                string industry_id2 = infoValue[2].ToString();
                #region 行业代码查询

                /*
                 *  主行业	        副行业	            代码
                 *  IT科技	        互联网/电子商务	    1
                 *  IT科技	        IT软件与服务	        2
                 *  IT科技	        IT硬件与设备	        3
                 *  IT科技	        电子技术	            4
                 *  IT科技	        通信与运营商	        5
                 *  IT科技	        网络游戏	            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
                 */

                #endregion
                #region 发送命令
send:
                string AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, true);
                if (string.IsNullOrEmpty(AccessToken) || AccessToken.StartsWith("err"))
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_accessToken(获取accessToken失败:(" + AccessToken + "))", doc_code));
                    return("err_wx_accessToken");
                }
                string     url      = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=" + AccessToken;
                string     postdata = "{\"industry_id1\":\"" + industry_id1 + "\",\"industry_id2\":\"" + industry_id2 + "\"}";
                WebRequest request  = WebRequest.Create(url);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                Stream writer = request.GetRequestStream();
                byte[] pdarry = Encoding.UTF8.GetBytes(postdata);
                writer.Write(pdarry, 0, pdarry.Length);
                writer.Close();
                #endregion
                #region 取得命令返回值
                WebResponse  response = request.GetResponse();
                Stream       rpReader = response.GetResponseStream();
                StreamReader reader   = new StreamReader(rpReader, Encoding.UTF8);
                string       rtStr    = reader.ReadToEnd();
                reader.Close();
                rpReader.Close();
                response.Close();
                rtStr = rtStr.Replace("&lt;", "<").Replace("&gt;", ">");
                #endregion

                #region 结果处理
                if (string.IsNullOrEmpty(rtStr))
                {
                    return("err_wx_003");
                }

                var jsNodes = TmoCommon.JsonHelper.GetJsonValues(rtStr);
                if (jsNodes == null || jsNodes.Count == 0)
                {
                    return("err_json_converter");
                }
                if (jsNodes.ContainsKey("errcode"))
                {
                    string errcode = jsNodes["errcode"].Value.Trim();
                    if (errcode == "0")
                    {
                        return("success");                             //成功
                    }
                    else if (errcode == "40001" || errcode == "40002") //access_token问题
                    {
                        AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, false);
                        goto send;
                    }
                    else
                    {
                        return("err_" + errcode + "_" + jsNodes["errmsg"].Value);
                    }
                }
                else
                {
                    return("err_errcode_null");
                }
                #endregion
            }
            catch (Exception e)
            {
                TmoShare.WriteLog(string.Format(strRecode, "err_wx_001(未知异常失败)", infoValue[0]) + e.Message);
                return("err_wx_001");
            }
        }
Пример #8
0
        /// <summary>
        /// 微信消息保存入库
        /// </summary>
        /// <param name="infoValue"></param>
        /// <returns></returns>
        //public static string WXMsgToDB(object[] infoValue)
        //{
        //    string resStr = "";
        //    try
        //    {
        //        if (infoValue[0] != null && infoValue[0].ToString() != "")
        //        {
        //            if (WellDBBLL.well_weixin_contentManager.Instance.AddWeixinMsg(infoValue[0].ToString()))
        //            {
        //                #region 医生Tcp消息推送
        //                DataSet dsXml = TmoShare.getDataSetfromXML(infoValue[0].ToString());
        //                string token_open_id = dsXml.Tables[0].Rows[0]["token_open_id"].ToString();

        //                bool blDN = AddDocNotifycation(dsXml);
        //                #endregion
        //                DataSet ds = WMFEntityManager.Instance.GetEntityInfoByPKLiteWhere("well_weixin_content", "token_open_id", token_open_id, "create_time,-*",
        //                    "(is_answer=1 and create_time >'" + DateTime.Now.AddMinutes(-3).ToString("yyyy-MM-dd HH:mm:ss") + "' and create_time <'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        //                    + "') or "
        //                    + "(is_answer=2 and create_time >'" + DateTime.Now.AddMinutes(-1).ToString("yyyy-MM-dd HH:mm:ss") + "' and create_time <'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')");

        //                if (TmoShare.DataSetEmpty(ds))
        //                {
        //                    resStr = "msg_sucess";
        //                }
        //                else
        //                {
        //                    resStr = "msg_sucess_rep";//如果3分钟内医生回复过本人消息,则不重复提醒。
        //                }

        //            }
        //            else
        //            {
        //                resStr = "error";
        //            }
        //        }
        //        else
        //        {
        //            resStr = "error";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        TmoShare.WriteWXLog("微信消息相应", ex.Message);
        //        resStr = "error";
        //    }

        //    return resStr;
        //}

        //public static bool AddDocNotifycation(DataSet dsXml)
        //{
        //    #region 数据格式
        //    //            string WeiMsgStr = TmoShare.XML_TITLE +
        //    //  @"<wellweixincontent>
        //    //<well_weixin_content>
        //    //<doc_code></doc_code>
        //    //<token_open_id></token_open_id>
        //    //<message_content></message_content>
        //    //<create_time></create_time>
        //    //<input_time></input_time>
        //    //<is_look></is_look>
        //    //<is_answer></is_answer>
        //    //<is_fousc></is_fousc>
        //    //<wm_id></wm_id>
        //    //<is_del></is_del>
        //    //<r_mark></r_mark>
        //    //<wx_type></wx_type>
        //    //<media_id></media_id>
        //    //<MsgId></MsgId>
        //    //<format></format>
        //    //</well_weixin_content>
        //    //</wellweixincontent>";
        //    #endregion
        //    //提问者编号
        //    string push_id = TmoShare.GetGuidString();
        //    string token_open_id = dsXml.Tables[0].Rows[0]["token_open_id"].ToString();
        //    string user_code = "";
        //    DataSet dsToken = WMFEntityManager.Instance.GetEntityInfoByPKLite("well_reg_userinfo_token", "reg_login_token", token_open_id, "");
        //    if (TmoShare.DataSetIsNotEmpty(dsToken))
        //    {
        //        user_code = dsToken.Tables[0].Rows[0]["user_code"].ToString();
        //    }

        //    #region 寻找医生
        //    string doc_code = "admin";
        //    if (dsXml.Tables[0].Columns.Contains("doc_code") && dsXml.Tables[0].Rows[0]["doc_code"].ToString().Trim() != "")
        //    {
        //        doc_code = dsXml.Tables[0].Rows[0]["doc_code"].ToString();
        //    }
        //    else
        //    {
        //        DataSet ds = WMFEntityManager.Instance.GetEntityInfoByPKLite("well_reg_userinfo",
        //            "user_code", user_code, "doc_code,-*");
        //        if (TmoShare.DataSetIsNotEmpty(ds))
        //        {
        //            doc_code = ds.Tables[0].Rows[0]["doc_code"].ToString();
        //        }
        //        else
        //        {
        //            doc_code = "admin";
        //        }
        //    }
        //    #endregion

        //    string push_type = "1";//推送类型 1 用户对医生 2 医生对医生
        //    string to_doc_id = doc_code;
        //    string from_user_id = user_code;
        //    string content_type = "1";
        //    string content_title = "";
        //    string content_value = dsXml.Tables[0].Rows[0]["message_content"].ToString();
        //    string content_url = "";
        //    string content_key = "";
        //    string push_status = "1"; //推送状态 1 未推送  2 已推送 3 推送中
        //    string push_source = "6";
        //    string timestamp = dsXml.Tables[0].Rows[0]["timestamp"].ToString();


        //    string remark = string.Format("msg_r|token_open_id:{0}|to_doc_id:{1}|from_user_id:{2}|timestamp:{3}",
        //        token_open_id, to_doc_id, user_code, timestamp);
        //    bool blNotify = WMFEntityManager.Instance.SubmitEntityInfoByDictionaryLite("well_noitfycation_doc",
        //           new Dictionary<string, string>() {
        //                        { "push_id",  push_id },
        //                        { "push_type", push_type },
        //                        { "push_source", push_source },
        //                        { "to_doc_id", to_doc_id },
        //                        { "from_user_id", from_user_id },
        //                        { "content_type", content_type },
        //                        { "content_title", content_title },
        //                        { "content_value",content_value },
        //                        { "content_url",content_url },
        //                        { "content_key",content_key },
        //                        { "push_status",push_status },
        //                        { "push_count","0" },
        //                        { "push_time",TmoShare.DateTimeNow() },
        //                        { "doc_code",doc_code },
        //                        { "remark",remark }
        //                    },
        //                    "push_id", push_id);
        //    return blNotify;
        //}

        /// <summary>
        /// 删除消息
        /// </summary>
        /// <param name="infoValue"></param>
        /// <returns></returns>
        //public static string DeleWXMsg(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        string aw_id = "";
        //        if (infoValue[1] != null && !string.IsNullOrEmpty(infoValue[1].ToString()))
        //        {
        //            aw_id = infoValue[1].ToString();
        //        }

        //        if (WellDBBLL.well_weixin_contentManager.Instance.DeleWXMsg(infoValue[0].ToString(), aw_id))
        //        {
        //            return "success";
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        /// <summary>
        /// 更新消息
        /// </summary>
        /// <param name="infoValue"></param>
        /// <returns></returns>
        //public static string UpdateWXMsg(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = TmoShare.getDataSetfromXML(infoValue[0].ToString());
        //        if (WellDBBLL.well_weixin_contentManager.Instance.UpdateWXMsg(ds))
        //        {
        //            return "success";
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        //public static string GetWxms(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWxms(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        //public static string GetWxmsByWhere(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWxmsByWhere(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        /// <summary>
        /// 获取分页数据信息
        /// </summary>
        /// <param name="infoValue"></param>
        /// <returns></returns>
        //public static string GetWxmBypage(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWxmBypage(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        //public static string DownloadImg(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "" && infoValue[1] != null)
        //    {

        //        return WellDBBLL.well_weixin_contentManager.Instance.DownloadImg(infoValue[0].ToString(), infoValue[1].ToString());

        //    }
        //    return "error";
        //}
        //public static string GetWx(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWx(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        //public static string GetWAsBypage(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWAsBypage(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        /// <summary>
        /// 发送微信消息
        /// </summary>
        /// <param name="infoValue">
        /// doc_code
        /// openID
        /// msgType
        /// msgContent
        /// </param>
        /// <returns></returns>
        public static string WXMsgSend(object[] infoValue)
        {
            string strRecode = "";

            try
            {
                if (infoValue[0].ToString() != "")
                {
                    string doc_code = infoValue[0].ToString();
                    string openID   = infoValue[1].ToString();
                    string msgType  = infoValue[2].ToString();

                    string msgContent = infoValue[3].ToString();

                    string AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, true);

                    string url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + AccessToken;

                    string postDataStr = "{\"touser\":\"" + openID + "\",\"msgtype\":\"text\",\"" + msgType + "\":{\"content\":\"" + msgContent + "\"}}";


                    System.Net.HttpWebRequest request;

                    request = (System.Net.HttpWebRequest)WebRequest.Create(url);
                    //Post请求方式
                    request.Method = "POST";
                    // 内容类型
                    request.ContentType = "application/x-www-form-urlencoded";
                    // 参数经过URL编码
                    //string paraUrlCoded = "";// System.Web.HttpUtility.UrlEncode("keyword");
                    //paraUrlCoded = System.Web.HttpUtility.UrlEncode(postDataStr);
                    byte[] payload;
                    //将URL编码后的字符串转化为字节
                    payload = System.Text.Encoding.UTF8.GetBytes(postDataStr);
                    //设置请求的 ContentLength
                    request.ContentLength = payload.Length;
                    //获得请 求流
                    Stream writer = request.GetRequestStream();
                    //将请求参数写入流
                    writer.Write(payload, 0, payload.Length);
                    // 关闭请求流
                    writer.Close();
                    System.Net.HttpWebResponse response;
                    // 获得响应流
                    response = (System.Net.HttpWebResponse)request.GetResponse();
                    System.IO.Stream data;
                    data = response.GetResponseStream();
                    string strValue = "";
                    using (StreamReader reader = new StreamReader(data, Encoding.Default))
                    {
                        strValue = reader.ReadToEnd().Trim();
                        data.Close();
                        reader.Close();
                    }


                    strValue = strValue.Replace("&lt;", "<");
                    strValue = strValue.Replace("&gt;", ">");


                    string retString = strValue;

                    #region 结果处理
                    if (string.IsNullOrEmpty(retString))
                    {
                        return("err_wx_003");
                    }

                    Dictionary <string, TmoCommon.JsonHelper.JsonNode> jsNodes = TmoCommon.JsonHelper.GetJsonValues(retString);
                    if (jsNodes != null || jsNodes.Count > 0)
                    {
                        if (jsNodes.ContainsKey("errcode"))
                        {
                            #region 返回参数解析格式
                            //                                            全局返回码说明如下:

                            //返回码  说明
                            //-1  系统繁忙
                            //0  请求成功
                            //40001  获取access_token时AppSecret错误,或者access_token无效
                            //40002  不合法的凭证类型
                            //40003  不合法的OpenID
                            //40004  不合法的媒体文件类型
                            //40005  不合法的文件类型
                            //40006  不合法的文件大小
                            //40007  不合法的媒体文件id
                            //40008  不合法的消息类型
                            //40009  不合法的图片文件大小
                            //40010  不合法的语音文件大小
                            //40011  不合法的视频文件大小
                            //40012  不合法的缩略图文件大小
                            //40013  不合法的APPID
                            //40014  不合法的access_token
                            //40015  不合法的菜单类型
                            //40016  不合法的按钮个数
                            //40017  不合法的按钮个数
                            //40018  不合法的按钮名字长度
                            //40019  不合法的按钮KEY长度
                            //40020  不合法的按钮URL长度
                            //40021  不合法的菜单版本号
                            //40022  不合法的子菜单级数
                            //40023  不合法的子菜单按钮个数
                            //40024  不合法的子菜单按钮类型
                            //40025  不合法的子菜单按钮名字长度
                            //40026  不合法的子菜单按钮KEY长度
                            //40027  不合法的子菜单按钮URL长度
                            //40028  不合法的自定义菜单使用用户
                            //40029  不合法的oauth_code
                            //40030  不合法的refresh_token
                            //40031  不合法的openid列表
                            //40032  不合法的openid列表长度
                            //40033  不合法的请求字符,不能包含\uxxxx格式的字符
                            //40035  不合法的参数
                            //40038  不合法的请求格式
                            //40039  不合法的URL长度
                            //40050  不合法的分组id
                            //40051  分组名字不合法
                            //41001  缺少access_token参数
                            //41002  缺少appid参数
                            //41003  缺少refresh_token参数
                            //41004  缺少secret参数
                            //41005  缺少多媒体文件数据
                            //41006  缺少media_id参数
                            //41007  缺少子菜单数据
                            //41008  缺少oauth code
                            //41009  缺少openid
                            //42001  access_token超时
                            //42002  refresh_token超时
                            //42003  oauth_code超时
                            //43001  需要GET请求
                            //43002  需要POST请求
                            //43003  需要HTTPS请求
                            //43004  需要接收者关注
                            //43005  需要好友关系
                            //44001  多媒体文件为空
                            //44002  POST的数据包为空
                            //44003  图文消息内容为空
                            //44004  文本消息内容为空
                            //45001  多媒体文件大小超过限制
                            //45002  消息内容超过限制
                            //45003  标题字段超过限制
                            //45004  描述字段超过限制
                            //45005  链接字段超过限制
                            //45006  图片链接字段超过限制
                            //45007  语音播放时间超过限制
                            //45008  图文消息超过限制
                            //45009  接口调用超过限制
                            //45010  创建菜单个数超过限制
                            //45015  回复时间超过限制
                            //45016  系统分组,不允许修改
                            //45017  分组名字过长
                            //45018  分组数量超过上限
                            //46001  不存在媒体数据
                            //46002  不存在的菜单版本
                            //46003  不存在的菜单数据
                            //46004  不存在的用户
                            //47001  解析JSON/XML内容错误
                            //48001  api功能未授权
                            //50001  用户未授权该api

                            #endregion

                            if (jsNodes["errcode"].Value.Trim() == "0")
                            {
                                return("success");
                            }
                            else if (jsNodes["errcode"].Value.Trim() == "40001" || jsNodes["errcode"].Value.Trim() == "40002")
                            {
                                AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, false);
                                if (AccessToken.StartsWith("err") || AccessToken == "")
                                {
                                    return("err_access_token_creat");
                                }
                            }
                            else if (jsNodes["errcode"].Value == "45015") //用户一定时间内没有和公众号沟通 回复受限
                            {
                                return("err_wx_time_limit");
                            }
                            else
                            {
                                strRecode = "err_" + jsNodes["errcode"].Value + "_" + jsNodes["errmsg"].Value;
                            }
                        }
                        else
                        {
                            strRecode = "err_errcode_null";
                        }
                    }
                    else
                    {
                        strRecode = "err_json_converter";
                    }

                    #endregion
                }
                else
                {
                    strRecode = "未传入医生编码!";
                    TmoShare.WriteLog(strRecode);
                    return("err_wx_002");
                }
            }
            catch (Exception e)
            {
                strRecode = "当前医生" + infoValue[0].ToString() + "获取列表失败! 原因:err_wx_001(未知异常失败)";
                TmoShare.WriteLog(strRecode + e.Message.ToString());
                return("err_wx_001");
            }
            return("");
        }
Пример #9
0
        //appID wx80b8ea65e4f18e65
        //appsecret b3c748800db56e4019814109a79dc06b

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        public static string WXGetAccessToken(object[] infoValue, bool useCache)
        {
            if (useCache)
            {
                TimeSpan ts = DateTime.Now - TmoShare.WX_ACCESS_TOKEN_TIME;
                if (ts.TotalSeconds <= 3600)
                {
                    return(TmoShare.WX_ACCESS_TOKEN);
                }
            }

            string strRecode = "";

            try
            {
                string appID     = TmoShare.WX_APP_ID;     // "wx80b8ea65e4f18e65";
                string appSecret = TmoShare.WX_APP_SECRET; //"b3c748800db56e4019814109a79dc06b";
                string url       = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret + "";

                #region 特别注意
                //{"errcode":45009,"errmsg":"api freq out of limit"}
                //接口调用频率限制如下:
                //接口  每日限额
                //获取access_token  2000
                #endregion
                if (infoValue[0].ToString() != "")
                {
                    using (WebClient client = new WebClient())
                    {
                        try
                        {
                            Stream data = client.OpenRead(url);
                            using (StreamReader reader = new StreamReader(data, Encoding.Default))
                            {
                                string resultData = reader.ReadToEnd();
                                resultData = resultData.Trim();
                                data.Close();
                                reader.Close();
                                switch (resultData)
                                {
                                case "":
                                    strRecode = "err_null";
                                    break;

                                case "45009":
                                    TmoShare.WriteLog("调用WXGetAccessToken当天过于频繁! 详细信息:err_wx_45009");
                                    strRecode = "err_wx_45009";
                                    break;

                                case "40013":
                                    TmoShare.WriteLog("调用WXGetAccessToken当天过于频繁! 详细信息:err_wx_45009");
                                    strRecode = "err_wx_45009";
                                    break;

                                //{"errcode":40013,"errmsg":"invalid appid"}
                                default:
                                    Dictionary <string, TmoCommon.JsonHelper.JsonNode> jsNodes =
                                        TmoCommon.JsonHelper.GetJsonValues(resultData);
                                    if (jsNodes != null || jsNodes.Count > 0)
                                    {
                                        if (jsNodes.ContainsKey("access_token"))
                                        {
                                            TmoShare.WX_ACCESS_TOKEN = jsNodes["access_token"].Value;
                                            //string expires_in = jsNodes["expires_in"].Value;
                                            TmoShare.WX_ACCESS_TOKEN_TIME = DateTime.Now;
                                        }
                                        else if (jsNodes.ContainsKey("errcode"))
                                        {
                                            //{"errcode":40013,"errmsg":"invalid appid"}
                                            strRecode = "err_" + jsNodes["errcode"].Value + "_" + jsNodes["errmsg"].Value;
                                        }
                                        else
                                        {
                                            TmoShare.WX_ACCESS_TOKEN = "";
                                            //string expires_in = jsNodes["expires_in"].Value;
                                            TmoShare.WX_ACCESS_TOKEN_TIME = DateTime.Now;
                                        }
                                    }
                                    else
                                    {
                                        strRecode = "err_json_converter";
                                    }
                                    break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            TmoShare.WriteLog("调用WXGetAccessToken接口发生未知错误! 详细信息:" + ex.Message);
                            strRecode = "err_002";
                        }
                    }
                }
                else
                {
                    strRecode = "err_wx_003";
                    TmoShare.WriteLog("调用WXGetAccessToken未传入医生编码!");
                }
            }
            catch (Exception e)
            {
                strRecode = "err_wx_001";
                TmoShare.WriteLog("当前医生" + infoValue[0].ToString() + "获取列表失败! 原因:err_cdp_001(未知异常失败)" + e.Message.ToString());
            }
            strRecode = TmoShare.WX_ACCESS_TOKEN;
            return(strRecode);
        }