微信Api

//定义变量
HttpRequest Request;
        HttpResponse Response;
        HttpServerUtility Server;
        HttpContext Context;

        protected string token = string.Empty;
        private string postStr = string.Empty;//接受微信公众平台发送过来的消息
        string sendXML = string.Empty;//要回复给微信公众平台的消息
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        string FromUserName = string.Empty;//接受微信公众用户的微信账号
        string MsgType = string.Empty;//接受微信公众用户发送过来的消息类型
        string Content = string.Empty;//接受微信公众用户发送过来的类容

        private Chain.BLL.WeiXinLog weiXinLogBLL = new Chain.BLL.WeiXinLog();
        private Chain.Model.WeiXinLog weiXinLogModel = new Chain.Model.WeiXinLog();

        private Chain.BLL.Mem memBll = new Chain.BLL.Mem();
        private Chain.Model.Mem memModel = new Chain.Model.Mem();

        private Chain.BLL.WeiXinRule weiXinRuleBLL = new Chain.BLL.WeiXinRule();
        private Chain.Model.WeiXinRule ruleModel = new Chain.Model.WeiXinRule();
View Code
public void ProcessRequest(HttpContext context)
        {
            context.Response.Buffer = true;
            context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";
            context.Response.ContentType = "text/plain";
            Request = context.Request;
            Response = context.Response;
            Server = context.Server;
            Context = context;

            try
            {
                //Log(GetAllParameter());

                //客户端发送过来的消息
                Stream s = System.Web.HttpContext.Current.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                postStr = Encoding.UTF8.GetString(b);
                token = PubFunction.curParameter.strWeiXinToken;

                Log(postStr);
                
                if (Request.HttpMethod.ToLower() == "get")
                {
                    //Get请求
                    if (Request.QueryString["signature"] != null && !string.IsNullOrEmpty(Request.QueryString["signature"].ToString()))
                    {
                        UrlValid();
                    }
                }
                else
                {
                    //Post请求
                    //对消息(事件消息,文本消息)进行分析目前只对 关注(事件)、申请(文本)做处理
                    SendMsg();
                }
            }
            catch (Exception ex)
            {
                Log(ex.ToString());
            }
        }
View Code
/// <summary>
        /// 消息发送(响应请求)
        /// </summary>
        public void SendMsg()
        {
            xmlDoc.LoadXml(postStr);
            MsgType = xmlDoc.GetElementsByTagName("MsgType")[0].InnerText;
            FromUserName = xmlDoc.GetElementsByTagName("FromUserName")[0].InnerText;

            try
            {
                weiXinLogModel = weiXinLogBLL.GetModel(FromUserName);
                if (weiXinLogModel == null)
                {
                    //微信用户不存在“上一次”操作记录
                    weiXinLogModel = new WeiXinLog();
                    NoLastOperating();
                }
                else
                {
                    //微信用户存在“上一次”操作记录
                    YesLastOperating(postStr);
                }
                sendXML = sendXML == "" ? ResponseSendStr.Text(postStr, weiXinRuleBLL.ErrorStr()) : sendXML;

            }
            catch (Exception e)
            {
                Log(e.ToString());
            }
            finally
            {
                Log(sendXML);
            }
            Response.Write(sendXML);
        }
View Code
/// <summary>
        /// 微信用户存在“上一次”操作记录
        /// </summary>
        private void YesLastOperating( string postStr)
        {

            if (MsgType == "event")
            {
                //事件消息
                AttentionNews(postStr);
            }
            else
            {
                //获取微信用户存在“上一次”操作记录
                weiXinLogModel = weiXinLogBLL.GetModel(FromUserName);
                switch (weiXinLogModel.StatusCode)
                {
                    case "0":
                        Do0ForApplicationMember();
                        break;
                    case "1":
                        Do1ForApplicationMemberByReplyTelNumber();
                        break;
                    case "2":
                        Do2MemberTransform();
                        break;
                    case "3":
                        Do3ForMemberTransformByReplyTelNumberOrMemberCard();
                        break;
                }
            }
        }
View Code
/// <summary>
        /// 微信用户不存在“上一次”操作记录
        /// </summary>
        private void NoLastOperating()
        {
            if (MsgType == "event")
            {
                //事件消息
                AttentionNews(postStr);
            }
            else if (MsgType == "text")
            {
                //文本消息
                TextNews();
            }
            else
            {
                //其他消息处理 暂无
            }
        }
View Code
/// <summary>
        /// 绘制微信会员卡
        /// </summary>
        public void DrawImage(Chain.Model.Mem mem, string FromUserName)
        {
            DrawImage(mem, "~/Upload/WeiXin/Images/bg.jpg", "~/Upload/WeiXin/Images/" + mem.MemWeiXinCard + ".jpg");
            DrawImage(mem, "~/Upload/WeiXin/Images/memCard.jpg", "~/Upload/WeiXin/Images/" + mem.MemWeiXinCard + "-MemCard.jpg");

            //Bitmap smallWeiXin = new Bitmap(130, 130);

            //System.Drawing.Image weixinImg = Web.Common.QRCodeImage.CreateQRCode(mem.MemCard);

            //Graphics g = Graphics.FromImage(smallWeiXin);

            //g.DrawImage(weixinImg, new Point(-35, -35));//130 * 130

            //string savePath = Server.MapPath("~/Upload/WeiXin/Images/" + FromUserName + ".jpg");

            //Bitmap bigWeiXin = new Bitmap(200, 200);
            //g = Graphics.FromImage(bigWeiXin);
            //g.DrawImage(smallWeiXin, new Rectangle(0, 0, 200, 200), new Rectangle(0, 0, 130, 130), GraphicsUnit.Pixel);

            //string bg = Server.MapPath("~/Upload/WeiXin/Images/bg.jpg");

            //#region 背景图为非位图的处理
            //System.Drawing.Image bgImg = System.Drawing.Image.FromFile(bg, true);
            //Bitmap bmp = new Bitmap(bgImg.Width, bgImg.Height, PixelFormat.Format32bppArgb);
            //g = Graphics.FromImage(bmp);
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            ////g.DrawImage(bgImg, 0, 0);
            //g.DrawImage(bgImg, new Rectangle(0, 0, bgImg.Width, bgImg.Height), new Rectangle(0, 0, bgImg.Width, bgImg.Height), GraphicsUnit.Pixel);
            //#endregion

            //g.DrawImage(bigWeiXin, new RectangleF(50, 60, 200, 200), new RectangleF(0, 0, 200, 200), GraphicsUnit.Pixel);

            //g.DrawString("NO:" + mem.MemCard + "", new Font("微软雅黑", 34F, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280, 70)); //画会员卡号
            //g.DrawString("积分:" + mem.MemCard + "", new Font("微软雅黑", 30F, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280, 115)); //积分
            //g.DrawString("余额:" + mem.MemMoney.ToString("F2") + "", new Font("微软雅黑", 30F, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280, 160));//余额
            //string pastStr = mem.MemPastTime.ToString("yyyy-MM-dd") == "2900-01-01" ? "有效期:永久有效" : "有效期:" + mem.MemPastTime.ToString("yyyy-MM-dd");//MemIsPast,MemPastTime  False
            //g.DrawString(pastStr, new Font("微软雅黑", 30F, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280, 205));//有效期

            //bmp.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }


        public void DrawImage(Chain.Model.Mem member, string sourceUrl, string targetUrl)
        {
            Bitmap smallWeiXin = new Bitmap(130, 130);

            System.Drawing.Image weixinImg = Web.Common.QRCodeImage.CreateQRCode(member.MemCard);

            Graphics g = Graphics.FromImage(smallWeiXin);

            g.DrawImage(weixinImg, new Point(-35, -35));//130 * 130

            string savePath = System.Web.HttpContext.Current.Server.MapPath(targetUrl);

            Bitmap bigWeiXin = new Bitmap(200, 200);
            g = Graphics.FromImage(bigWeiXin);
            g.DrawImage(smallWeiXin, new Rectangle(0, 0, 200, 200), new Rectangle(0, 0, 130, 130), GraphicsUnit.Pixel);

            string bg = System.Web.HttpContext.Current.Server.MapPath(sourceUrl);

            #region 背景图为非位图的处理
            System.Drawing.Image bgImg = System.Drawing.Image.FromFile(bg, true);
            Bitmap bmp = new Bitmap(bgImg.Width, bgImg.Height, PixelFormat.Format32bppArgb);
            g = Graphics.FromImage(bmp);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.DrawImage(bgImg, new Rectangle(0, 0, bgImg.Width, bgImg.Height), new Rectangle(0, 0, bgImg.Width, bgImg.Height), GraphicsUnit.Pixel);
            #endregion

            g.DrawImage(bigWeiXin, new RectangleF(50, 60, 200, 200), new RectangleF(0, 0, 200, 200), GraphicsUnit.Pixel);

            g.DrawString("NO:" + member.MemCard + "", new Font("微软雅黑", 34F, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280, 70)); //画会员卡号
            g.DrawString("积分:" + member.MemPoint + "", new Font("微软雅黑", 30F, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280, 115)); //积分
            g.DrawString("余额:" + member.MemMoney.ToString("F2") + "", new Font("微软雅黑", 30F, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280, 160));//余额
            string pastStr = member.MemPastTime.ToString("yyyy-MM-dd") == "2900-01-01" ? "有效期:永久有效" : "有效期:" + member.MemPastTime.ToString("yyyy-MM-dd");//MemIsPast,MemPastTime  False
            g.DrawString(pastStr, new Font("微软雅黑", 30F, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.White, new PointF(280, 205));//有效期

            bmp.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
View Code
/// <summary>
        /// 会员注册
        ///  -1:卡号重复    -2:手机号码重复   -6:卡面号重复     1:没有重复项目
        /// </summary>
        public int MemRegister(bool isSMSVcode)
        {
            Mem memModel = new Mem();
            string strTemp = isSMSVcode ? memModel.MemCard = weiXinLogModel.RecordContent : memModel.MemCard = this.Content;
            memModel.MemPassword = DESEncrypt.Encrypt("");
            memModel.MemName = "";
            memModel.MemSex = true;
            memModel.MemIdentityCard = "";
            strTemp = isSMSVcode ? memModel.MemMobile = weiXinLogModel.RecordContent : memModel.MemMobile = this.Content;
            memModel.MemPhoto = "";
            memModel.MemBirthdayType = true;
            memModel.MemBirthday = Convert.ToDateTime("1900-1-1 0:00:00");
            memModel.MemIsPast = false;
            memModel.MemPastTime = Convert.ToDateTime("2900-1-1 0:00:00");
            memModel.MemPoint = 0;
            memModel.MemPointAutomatic = true;
            memModel.MemMoney = 0;
            memModel.MemEmail = "";
            memModel.MemAddress = "";
            memModel.MemState = 0;
            memModel.MemRecommendID = 0;
            memModel.MemLevelID = 0;
            memModel.MemShopID = 1;
            memModel.MemCreateTime = DateTime.Now;
            memModel.MemRemark = "";
            memModel.MemUserID = 1;
            memModel.MemTelePhone = "";
            memModel.MemWeiXinCard = FromUserName;
            memModel.MemQRCode = "";
            memModel.MemProvince = "";
            memModel.MemCity = "";
            memModel.MemCounty = "";
            memModel.MemVillage = "";

            return memBll.Add(memModel);
        }
View Code
/// <summary>
        /// 记录日志
        /// </summary>
        public void Log(string logText)
        {
            try
            {
                string fileName = DateTime.Now.ToShortDateString().Replace("-", "") + "_" + DateTime.Now.Hour + "_" + DateTime.Now.Minute / 10;
                string fullPath = Server.MapPath("~/Upload/Log/" + fileName + ".txt");
                logText = DateTime.Now.ToString() + "\r\n" + logText;
                File.AppendAllText(fullPath, logText + "\r\n\r\n");
            }
            catch (Exception ex)
            {
                PubFunction.SaveSysLog(1, 4, "微信接口错误", ex.ToString() + "  " + ex.StackTrace.ToString(), 1, DateTime.Now, PubFunction.ipAdress);
            }
        }
View Code
/// <summary>
        /// 将单条新闻消息加入到集合
        /// </summary>
        public List<Chain.Model.WeiXinNews> GetModel(string NewsTitle, string NewsDesc, string NewsUrlFirst, string NewsUrlSecond)
        {
            List<Chain.Model.WeiXinNews> list = new List<WeiXinNews>();
            Chain.Model.WeiXinNews model = new WeiXinNews();
            model.NewsTitle = NewsTitle;
            model.NewsDesc = NewsDesc;
            model.NewsUrlFirst = NewsUrlFirst;
            model.NewsUrlSecond = NewsUrlSecond;
            list.Add(model);
            return list;
        }
View Code
 /// <summary>
        /// 响应微信公众平台的验证
        /// </summary>
        protected void UrlValid()
        {
            string signature = Request.QueryString["signature"].ToString();
            string timestamp = Request.QueryString["timestamp"].ToString();
            string nonce = Request.QueryString["nonce"].ToString();
            string echostr = Request.QueryString["echostr"].ToString();
            // 将token、timestamp、nonce三个参数进行字典序排序
            List<string> list = new List<string>();
            list.Add(token);
            list.Add(timestamp);
            list.Add(nonce);
            list.Sort();
            //将三个参数字符串拼接成一个字符串进行sha1加密
            string newSignature = "";
            foreach (var item in list)
            {
                newSignature += item;
            }
            byte[] StrRes = Encoding.UTF8.GetBytes(newSignature);
            System.Security.Cryptography.HashAlgorithm iSHA = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            StrRes = iSHA.ComputeHash(StrRes);
            StringBuilder EnText = new StringBuilder();
            foreach (byte iByte in StrRes)
            {
                EnText.AppendFormat("{0:x2}", iByte);
            }
            //获得加密后的字符串与signature对比,标识该请求来源于微信
            if (signature == EnText.ToString())
                Response.Write(echostr);
            else
                Response.Write("error");

            PubFunction.SaveSysLog(1, 4, "微信接口验证", string.Format("signature={0}&timestamp={1}&nonce={2}&echostr={3}&newSignature={4}&StrRes={5}", signature, timestamp, nonce, echostr, newSignature, EnText.ToString()), 1, DateTime.Now, PubFunction.ipAdress);
        }
View Code
 /// <summary>
        /// 事件消息 回复
        /// </summary>
        private void AttentionNews(string postStr)
        {
            string Event = xmlDoc.GetElementsByTagName("Event")[0].InnerText;
            if (Event == "subscribe") //关注
            {
                StringBuilder tempSb = new StringBuilder();
                tempSb.AppendLine(PubFunction.curParameter.strWeiXinSalutatory).AppendLine().AppendLine(weiXinRuleBLL.AttentionStr());
                sendXML = ResponseSendStr.Text(postStr, tempSb.ToString());
            }
            else if (Event == "CLICK")
            {
                this.MenuClick();
            }
            else
            {
                //其他事件 例如:取消关注
            }
        }
View Code
/// <summary>
        /// 文本消息 回复
        /// </summary>
        private void TextNews()
        {
            Content = xmlDoc.GetElementsByTagName("Content")[0].InnerText.Trim();
            if (Content == "1")
            {
                //回复 申请会员卡
                ApplicationMemberCard();
            }
            else if (Content == "2")
            {
                //doto  回复 已有会员卡转微信会员卡 
                ConvertWeiXinMember(postStr);
            }
            else
            {
                //回复 未知的文本
                UnknownTextNewsHandle(postStr, Content);
            }
        }
View Code
/// <summary>
        /// 申请会员卡
        /// </summary>
        private void ApplicationMemberCard()
        {
            Chain.Model.Mem mem = memBll.GetMemByWeiXinCard(FromUserName);
            if (mem == null)
            {
                //微信会员不存在 提示注册信息
                sendXML = ResponseSendStr.Text(postStr, "您已进入会员申请模式," + weiXinRuleBLL.Reply1());//发送手机号码
                //记录微信日志
                GiveWeiXinLodAssignment("", 0, "0", "", 0);
                weiXinLogBLL.Add(weiXinLogModel);
            }
            else
            {
                //微信会员已存在 发送微信会员卡
                string NewsDesc = string.IsNullOrEmpty(PubFunction.curParameter.strWeiXinShopName) ? "" : PubFunction.curParameter.strWeiXinShopName;
                NewsDesc = NewsDesc == "" ? "您的微信会员卡" : "您的" + NewsDesc + "微信会员卡";//您的【五维月凡】微信会员卡
                Card(mem, "会员卡查询", NewsDesc);
            }
        }
View Code
/// <summary>
        /// 处理未知文本消息
        /// </summary>
        private void UnknownTextNewsHandle(string postStr, string Content)
        {
            ruleModel = weiXinRuleBLL.GetModelByNewsRuleID(Content);
            if (ruleModel != null)
            {
                if (ruleModel.RuleNewsType == "text")
                {
                    //回复的是文本消息
                    sendXML = ResponseSendStr.Text(postStr, ruleModel.RuleContent);
                }
                else if (ruleModel.RuleNewsType == "news")
                {
                    //回复的是图文消息
                    List<Chain.Model.WeiXinNews> newsList = new Chain.BLL.WeiXinNews().GetModelList("NewsRuleID=" + ruleModel.RuleID);
                    sendXML = ResponseSendStr.News(postStr, newsList);
                }
                else
                {
                    //其他消息类型 例如:音乐等
                }
            }
        }
View Code
/// <summary>
        /// 给微信日志模型赋值
        /// </summary>
        private void GiveWeiXinLodAssignment(string RecordContent, int RecordContentType, string StatusCode, string RandomCode, int ErrorTimes)
        {
            weiXinLogModel.MemWeiXinCard = FromUserName;
            weiXinLogModel.RecordContent = RecordContent;
            weiXinLogModel.RecordContentType = RecordContentType;
            weiXinLogModel.StatusCode = StatusCode;
            weiXinLogModel.RandomCode = RandomCode;
            weiXinLogModel.ErrorTimes = ErrorTimes;
            weiXinLogModel.WeiXinLogCreateTime = DateTime.Now;
        }
View Code
/// <summary>
        ///  已有会员转微信会员
        /// </summary>
        private void ConvertWeiXinMember(string postStr)
        {
            Chain.Model.Mem mem = memBll.GetMemByWeiXinCard(FromUserName);
            if (mem != null)
            {
                //微信会员已存在 提示:您已是微信会员
                sendXML = ResponseSendStr.Text(postStr, "您已是微信会员");
            }
            else
            {
                sendXML = ResponseSendStr.Text(postStr, "您已进入转微信会员模式," + weiXinRuleBLL.Reply2());//请发送您的手机号或卡号

                GiveWeiXinLodAssignment("", 0, "2", "", 0);
                weiXinLogBLL.Add(weiXinLogModel);
            }
        }
View Code
/// <summary>
        /// 执行 0 对应的方法:申请会员卡
        /// </summary>
        private void Do0ForApplicationMember()
        {
            Content = xmlDoc.GetElementsByTagName("Content")[0].InnerText.Trim();
            if (System.Text.RegularExpressions.Regex.IsMatch(Content, @"^1[3|4|5|8]\d{9}$"))//用户输入的是手机号码
            {
                Chain.Model.Mem mem = memBll.GetModelByMemMobile(Content);
                if (mem != null)
                {
                    //该手机号已被注册 不可用
                    sendXML = ResponseSendStr.Text(postStr, "该手机号已被注册,请重新输入一个新的手机号");
                }
                else
                {
                    //该手机号未被注册 可以用
                    if (PubFunction.curParameter.bolWeiXinSMSVcode)
                    {
                        //启用短信验证 要发送短信
                        if (PubFunction.curParameter.bolSms)
                        {
                            //系统短信功能已开启
                            if (SMSInfo.GetBalance(false) == "0")
                            {
                                //短信余额不足
                                sendXML = ResponseSendStr.Text(postStr, "商家短信不足,发送短信验证码失败,请与商家联系");
                                weiXinLogBLL.Delete(FromUserName);
                            }
                            else
                            {
                                //短信余额充足
                                string smsVCode = GetRandomCode();
                                string NewsDesc = string.IsNullOrEmpty(PubFunction.curParameter.strWeiXinShopName) ? "" : PubFunction.curParameter.strWeiXinShopName;
                                NewsDesc = "温馨提示,欢迎您注册" + NewsDesc + "微信会员," + "您的" + NewsDesc + "微信会员短信验证码是:" + smsVCode;
                                sendXML = ResponseSendStr.Text(postStr, "请发送短信验证码");
                                SMSInfo.Send_GXSMS(false, Content, NewsDesc, "");
                                #region 发送短信
                                Chain.Model.SmsLog modelSms = new Chain.Model.SmsLog();
                                modelSms.SmsMemID = 0;
                                modelSms.SmsMobile = Content;
                                modelSms.SmsContent = NewsDesc;
                                modelSms.SmsTime = DateTime.Now;
                                modelSms.SmsShopID = 1;
                                modelSms.SmsUserID = 1;
                                modelSms.SmsAmount = PubFunction.GetSmsAmount(NewsDesc);
                                modelSms.SmsAllAmount = modelSms.SmsAmount;
                                Chain.BLL.SmsLog bllSms = new Chain.BLL.SmsLog();
                                bllSms.Add(modelSms);
                                #endregion

                                GiveWeiXinLodAssignment(Content, 2, "1", smsVCode, 0);
                                weiXinLogBLL.Update(weiXinLogModel);
                            }
                        }
                        else
                        {
                            //系统短信功能未开启
                            sendXML = ResponseSendStr.Text(postStr, "系统短信功能暂未开启,发送短信验证码失败,请与商家联系");
                            weiXinLogBLL.Delete(FromUserName);
                        }
                    }
                    else
                    {
                        //未启用短信验证  直接办卡成功 删除微信日志
                        int isOk = MemRegister(false);
                        if (isOk > 0)
                        {
                            DoCard("恭喜您会员卡办理成功");
                        }
                        else
                        {
                            string strErr = "系统错误,会员办卡失败!";
                            switch (isOk)
                            {
                                case -1:
                                    strErr = "会员卡号重复,会员办卡失败!";
                                    break;
                                case -2:
                                    strErr = "手机号码重复,会员办卡失败!";
                                    break;
                                case -6:
                                    strErr = "卡面号重复,会员办卡失败!";
                                    break;
                                default:
                                    break;
                            }
                            sendXML = ResponseSendStr.Text(postStr, strErr);
                        }
                    }
                }
            }
            else
            {
                GiveWeiXinLodAssignment("", 0, "0", "", weiXinLogModel.ErrorTimes + 1);
                ErrorNewsHandle("由于您的误操作次数过多,会员申请模式已退出", "您发送的手机号格式有误,请重新发送");
            }
        }
View Code
/// <summary>
        /// 执行 1 对应的方法:申请会员卡之后回复了“手机号号码“
        /// </summary>
        private void Do1ForApplicationMemberByReplyTelNumber()
        {
            Content = xmlDoc.GetElementsByTagName("Content")[0].InnerText.Trim();
            if (!PubFunction.curParameter.bolWeiXinSMSVcode || weiXinLogModel.RandomCode == Content)
            {
                //短信验证成功
                int isOk = MemRegister(true);
                if (isOk > 0)
                {
                    DoCard("恭喜您会员卡办理成功");
                }
                else
                {
                    string strErr = "系统错误,会员办卡失败!";
                    switch (isOk)
                    {
                        case -1:
                            strErr = "会员卡号重复,会员办卡失败!";
                            break;
                        case -2:
                            strErr = "手机号码重复,会员办卡失败!";
                            break;
                        case -6:
                            strErr = "卡面号重复,会员办卡失败!";
                            break;
                        default:
                            break;
                    }
                    sendXML = ResponseSendStr.Text(postStr, strErr);
                }
            }
            else
            {
                //短信验证失败
                GiveWeiXinLodAssignment(weiXinLogModel.RecordContent, weiXinLogModel.RecordContentType, weiXinLogModel.StatusCode, weiXinLogModel.RandomCode, weiXinLogModel.ErrorTimes + 1);
                ErrorNewsHandle("由于您的误操作次数过多,会员申请模式已退出", "您发送的短信验证码有误,请重新发送");
            }
        }
View Code
/// <summary>
        /// 执行 2 对应的方法:“申请已有会员转微信会员”
        /// </summary>
        private void Do2MemberTransform()
        {
            Content = xmlDoc.GetElementsByTagName("Content")[0].InnerText.Trim();
            memModel = memBll.GetModelByMemCard(Content);
            if (memModel != null)
            {
                //根据会员卡号查找到会员 找到
                sendXML = ResponseSendStr.Text(postStr, "请发送您的会员卡密码,如果密码为空请回复 # 号");
                GiveWeiXinLodAssignment(memModel.MemCard, 1, "3", "", 0);
                weiXinLogBLL.Update(weiXinLogModel);
            }
            else
            {
                //根据会员卡号查找会员 没找到
                Chain.Model.Mem mem = memBll.GetModelByMemMobile(Content);
                if (mem != null)
                {
                    //根据会员电话查找会员 找到
                    //启用短信验证 要发送短信
                    if (PubFunction.curParameter.bolWeiXinSMSVcode)
                    {
                        if (PubFunction.curParameter.bolSms)
                        {
                            //系统短信功能已开启
                            if (SMSInfo.GetBalance(false) == "0")
                            {
                                //短信余额不足
                                string strTemplet = string.Format("由于本系统短信剩余条数不足,无法给您发送短信验证码;\r\n您的会员卡号为:{0}****{1},请发送您的会员卡密码,如果密码为空请回复 # 号", mem.MemCard.Substring(0, 1), mem.MemCard.Substring(mem.MemCard.Length - 1, 1));
                                sendXML = ResponseSendStr.Text(postStr, strTemplet);
                                GiveWeiXinLodAssignment(mem.MemCard, 1, "3", "", 0);
                                weiXinLogBLL.Update(weiXinLogModel);
                            }
                            else
                            {
                                //短信余额充足
                                string smsVCode = GetRandomCode();
                                string NewsDesc = string.IsNullOrEmpty(PubFunction.curParameter.strWeiXinShopName) ? "" : PubFunction.curParameter.strWeiXinShopName;
                                NewsDesc = "温馨提示,欢迎您申请从店铺会员转" + NewsDesc + "微信会员," + "您的" + NewsDesc + "微信会员短信验证码是:" + smsVCode;
                                sendXML = ResponseSendStr.Text(postStr, "请发送短信验证码");
                                SMSInfo.Send_GXSMS(false, Content, NewsDesc, "");
                                #region 发送短信
                                Chain.Model.SmsLog modelSms = new Chain.Model.SmsLog();
                                modelSms.SmsMemID = Convert.ToInt32(mem.MemID);
                                modelSms.SmsMobile = Content;
                                modelSms.SmsContent = NewsDesc;
                                modelSms.SmsTime = DateTime.Now;
                                modelSms.SmsShopID = 1;
                                modelSms.SmsUserID = 1;
                                modelSms.SmsAmount = PubFunction.GetSmsAmount(NewsDesc);
                                modelSms.SmsAllAmount = modelSms.SmsAmount;
                                Chain.BLL.SmsLog bllSms = new Chain.BLL.SmsLog();
                                bllSms.Add(modelSms);
                                #endregion

                                GiveWeiXinLodAssignment(Content, 2, "3", smsVCode, 0);
                                weiXinLogBLL.Update(weiXinLogModel);
                            }
                        }
                        else
                        {
                            //系统短信功能未开启
                            string strTemplet = string.Format("由于本系统短信功能暂未开启,无法给您发送短信验证码;\r\n您的会员卡号为:{0}****{1},请发送您的会员卡密码,如果密码为空请回复 # 号", mem.MemCard.Substring(0, 1), mem.MemCard.Substring(mem.MemCard.Length - 1, 1));
                            sendXML = ResponseSendStr.Text(postStr, strTemplet);
                            GiveWeiXinLodAssignment(mem.MemCard, 1, "3", "", 0);
                            weiXinLogBLL.Update(weiXinLogModel);
                        }
                    }
                    else
                    {
                        //未启用短信验证  直接转微信会员 删除微信日志
                        memModel = memBll.GetMemInfoByMobile(this.Content);
                        memModel.MemWeiXinCard = FromUserName;
                        memBll.Update(memModel);
                        DoCard("恭喜您已转移成微信会员");
                    }
                }
                else
                {
                    //根据会员电话查找会员 没找到
                    GiveWeiXinLodAssignment(weiXinLogModel.RecordContent, weiXinLogModel.RecordContentType, weiXinLogModel.StatusCode, weiXinLogModel.RandomCode, weiXinLogModel.ErrorTimes + 1);
                    ErrorNewsHandle("由于您的错误操作次数过多,转微信会员模式已退出", "您发送的手机号或卡号在系统中没找着,请重新发送");
                }
            }
        }
View Code
/// <summary>
        /// 执行 3 对应的方法:申请已有会员转微信会员之后回复了“手机号或会员卡号”
        /// </summary>
        private void Do3ForMemberTransformByReplyTelNumberOrMemberCard()
        {
            string Content = xmlDoc.GetElementsByTagName("Content")[0].InnerText.Trim();//获取待验证的内容
            if (weiXinLogModel.RecordContentType == 1)//待验证的内容是会员的卡号密码
            {
                //string pwd = Chain.Common.DEncrypt.DESEncrypt.Encrypt(Content == "#" ? "" : Content);
                string pwd = Chain.Common.DEncrypt.DESEncrypt.Encrypt(Content == "#" ? "" : Content == "" ? "" : Content);
                memModel = memBll.GetModelByMemCard(weiXinLogModel.RecordContent);
                if (pwd == memModel.MemPassword)
                {
                    memModel.MemWeiXinCard = weiXinLogModel.MemWeiXinCard;
                    memBll.Update(memModel);
                    DoCard("恭喜您已转移成微信会员");
                }
                else
                {
                    GiveWeiXinLodAssignment(weiXinLogModel.RecordContent, 1, "3", "", weiXinLogModel.ErrorTimes + 1);
                    ErrorNewsHandle("由于您的错误操作次数过多,转微信会员模式已退出", "您发送的会员卡密码不正确,请重新发送");
                }
            }
            else//待验证的内容是短信随机验证码
            {
                if (!PubFunction.curParameter.bolWeiXinSMSVcode || weiXinLogModel.RandomCode == Content)
                {
                    memModel = memBll.GetMemInfoByMobile(weiXinLogModel.RecordContent);
                    memModel.MemWeiXinCard = weiXinLogModel.MemWeiXinCard;
                    memBll.Update(memModel);
                    DoCard("恭喜您已转移成微信会员");
                }
                else
                {
                    GiveWeiXinLodAssignment(weiXinLogModel.RecordContent, 2, weiXinLogModel.StatusCode, weiXinLogModel.RandomCode, weiXinLogModel.ErrorTimes + 1);
                    ErrorNewsHandle("由于您的错误操作次数过多,转微信会员模式已退出", "您发送的短信验证码有误,请重新发送");
                }
            }
        }
View Code
 /// <summary>
        /// 返回短信验证码
        /// </summary>
        private string GetRandomCode()
        {
            Random random = new Random();
            string result = string.Empty;
            for (int i = 0; i < 4; i++)
            {
                result += random.Next(0, 10);
            }
            return result;
        }
View Code
/// <summary>
        /// 发卡
        /// </summary>
        private void Card(Chain.Model.Mem mem, string NewsTitle, string NewsDesc)
        {
            DrawImage(mem, FromUserName);
            #region 会员卡查询 图文模型列表
            string NewsUrlFirst = "http://" + PubFunction.curParameter.strDoMain + "/Upload/WeiXin/Images/" + FromUserName + ".jpg" + "?id=" + Guid.NewGuid();
            //string NewsUrlSecond = "http://" + PubFunction.curParameter.strDoMain + "/WeiXin/MemberManipulate.aspx?MemWeiXinCard=" + FromUserName;
            string NewsUrlSecond = "http://" + PubFunction.curParameter.strDoMain + "/ReceptionPage/index.aspx?MemWeiXinCard=" + FromUserName;
            List<Chain.Model.WeiXinNews> newsList = GetModel(NewsTitle, NewsDesc, NewsUrlFirst, NewsUrlSecond);
            #endregion
            sendXML = ResponseSendStr.News(postStr, newsList);//出示会员卡
        }
View Code
        /// <summary>
        /// 对用户错误次数的处理
        /// </summary>
        private void ErrorNewsHandle(string errorTimesExceed, string errorTimesNoExceed)
        {
            if (weiXinLogModel.ErrorTimes >= 3)
            {
                sendXML = ResponseSendStr.Text(postStr, errorTimesExceed);
                weiXinLogBLL.Delete(FromUserName);
            }
            else
            {
                sendXML = ResponseSendStr.Text(postStr, errorTimesNoExceed);
                weiXinLogBLL.Update(weiXinLogModel);
            }
        }
View Code
        /// <summary>
        /// 办卡
        /// </summary>
        private void DoCard(string NewsTitle)
        {
            Chain.Model.Mem mem = memBll.GetMemByWeiXinCard(FromUserName);
            string NewsDesc = string.IsNullOrEmpty(PubFunction.curParameter.strWeiXinShopName) ? "" : PubFunction.curParameter.strWeiXinShopName;
            NewsDesc = NewsDesc == "" ? "您的微信会员卡" : "您的" + NewsDesc + "微信会员卡";//您的【五维月凡】微信会员卡
            Card(mem, NewsTitle, NewsDesc);
            weiXinLogBLL.Delete(FromUserName);
        }
View Code
        /// <summary>
        /// 微网站
        /// </summary>
        private void WZZ()
        {
            if (this.memBll.GetMemByWeiXinCard(this.FromUserName) == null)
            {
                this.sendXML = ResponseSendStr.Text(this.postStr, "您目前还不是微会员,只有微会员才可以访问微网站");
            }
            else
            {
                string xml = File.ReadAllText(Server.MapPath("WWZ.xml"));
                System.Xml.XmlDocument xmlWZZDoc = new System.Xml.XmlDocument();
                xmlWZZDoc.LoadXml(xml);
                string NewsTitle = xmlWZZDoc.GetElementsByTagName("NewsTitle")[0].InnerText;
                string NewsDesc = xmlWZZDoc.GetElementsByTagName("NewsDesc")[0].InnerText;
                string NewsUrlFirst = string.Concat(new object[] { "http://", PubFunction.curParameter.strDoMain, xmlWZZDoc.GetElementsByTagName("NewsUrlFirst")[0].InnerText, "?id=", Guid.NewGuid() });
                string NewsUrlSecond = "http://" + PubFunction.curParameter.strDoMain + xmlWZZDoc.GetElementsByTagName("NewsUrlSecond")[0].InnerText + "?MemWeiXinCard=" + this.FromUserName;
                List<WeiXinNews> newsList = this.GetModel(NewsTitle, NewsDesc, NewsUrlFirst, NewsUrlSecond);
                this.sendXML = ResponseSendStr.News(this.postStr, newsList);
            }
        }
View Code
        /// <summary>
        /// 微信菜单
        /// </summary>
        private void MenuClick()
        {
            this.weiXinLogBLL.Delete(this.FromUserName);
            string EventKey = this.xmlDoc.GetElementsByTagName("EventKey")[0].InnerText.Trim();
            if (EventKey == "1")
            {
                this.ApplicationMemberCard();
            }
            else if (EventKey == "2")
            {
                this.ConvertWeiXinMember(this.postStr);
            }
            else if (EventKey == "3")
            {
                this.WZZ();
            }
            else
            {
                this.UnknownTextNewsHandle(this.postStr, EventKey);
            }
        }
View Code
        /// <summary>
        /// 获取所有的get和post等参数信息
        /// </summary>
        /// <returns></returns>
        private string GetAllParameter()
        {
            string Para = string.Empty;
            Para += "{QueryString}";
            for (int i = 0; i < Request.QueryString.AllKeys.Length; i++)
            {
                Para += Request.QueryString.Keys[i] + ":" + Request.QueryString[Request.QueryString.Keys[i]].ToString() + ";";
            }
            Para += "{Form}";
            for (int i = 0; i < Request.Form.AllKeys.Length; i++)
            {
                Para += Request.Form.Keys[i] + ":" + Request.Form[Request.Form.Keys[i]].ToString() + ";";
            }
            //Para += "{ServerVariables}";
            //for (int i = 0; i < Request.ServerVariables.Count; i++)
            //{
            //    Para += Request.ServerVariables.Keys[i] + ":" + Request.ServerVariables[i].ToString() + ";";
            //}
            return Para;
        }
View Code

 

posted @ 2016-06-24 11:13  如此低调的男人  阅读(442)  评论(0编辑  收藏  举报