微信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();

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());
            }
        }

/// <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);
        }

/// <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;
                }
            }
        }

/// <summary>
        /// 微信用户不存在“上一次”操作记录
        /// </summary>
        private void NoLastOperating()
        {
            if (MsgType == "event")
            {
                //事件消息
                AttentionNews(postStr);
            }
            else if (MsgType == "text")
            {
                //文本消息
                TextNews();
            }
            else
            {
                //其他消息处理 暂无
            }
        }

/// <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);
        }

/// <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);
        }

/// <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);
            }
        }

/// <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;
        }

 /// <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);
        }

 /// <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
            {
                //其他事件 例如:取消关注
            }
        }

/// <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);
            }
        }

/// <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);
            }
        }

/// <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
                {
                    //其他消息类型 例如:音乐等
                }
            }
        }

/// <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;
        }

/// <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);
            }
        }

/// <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("由于您的误操作次数过多,会员申请模式已退出", "您发送的手机号格式有误,请重新发送");
            }
        }

/// <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("由于您的误操作次数过多,会员申请模式已退出", "您发送的短信验证码有误,请重新发送");
            }
        }

/// <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("由于您的错误操作次数过多,转微信会员模式已退出", "您发送的手机号或卡号在系统中没找着,请重新发送");
                }
            }
        }

/// <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("由于您的错误操作次数过多,转微信会员模式已退出", "您发送的短信验证码有误,请重新发送");
                }
            }
        }

 /// <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;
        }

/// <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);//出示会员卡
        }

        /// <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);
            }
        }

        /// <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);
        }

        /// <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);
            }
        }

        /// <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);
            }
        }

        /// <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;
        }

时间: 2024-10-08 12:01:26

微信Api的相关文章

总结的一些微信API接口

本文给大家介绍的是个人总结的一些微信API接口,包括微信支付.微信红包.微信卡券.微信小店等,十分的全面,有需要的小伙伴可以参考下. 1. [代码]index.php <?php include_once 'lib.inc.php';   $wcObj = new WeChat("YOUKUIYUAN"); $wcObj->wcValid(); 2. [代码]微信入口类 <?php /**  * Description of wechat  *  * @author

python利用企业微信api来进行发送自定义报警的类实现

python利用企业微信api来进行发送自定义报警的类实现 企业微信注册 打开http://work.weixin.qq.com/企业微信主页: 点击企业注册: 填写相关信息,营业执照和注册号可以不用填,直接下一步,按照提示操作即可: 注册完成后,登陆,就显示如下界面: 点击我的企业标签: 看到如上界面,复制CorpID对应的值: 点击企业应用: 点击 创建应用: 填写对应内容,点击创建应用即可: 然后再点击企业应用,就可以在自建应用里看到自己创建的应用: 点击应用图标,看到如下图 复制Agen

(微信API接口开发) 使用HttpWebRequest进行请求时发生错误:基础连接已关闭,发送时发生错误处理

最近调试原来的微信模拟登陆时发生了"基础连接已关闭,发送时发生错误"的错误提示,原来都是好好的,只是很久没用了. 出错代码如下: ? 1 2 3 4 5 6 7 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN");///cgi-bin/loginpage?

BPM实例分享:DMZ内部网络转发https请求访问微信API

应用场景:H3 BPM部署在企业内部网络需要访问微信API但不能直接访问互联网 解决方案:通过DMZ服务器部署Nginx转发来自H3 BPM的https请求至微信服务器 1. 在H3 BPM服务器配置hosts文件添加一条记录,将访问微信API服务器重定向至内部的DMZ服务器 [DMZ IP] qyapi.weixin.qq.com 2.参考链接创建SSL服务器的无密码证书和key用于解密https加密内容 http://www.voidcn.com/blog/huplion/article/p

面向对象的全套“企业微信”api接口的代码实现,网上太多“面向过程”微信api接口的代码,这个开源给需要的人用

有段时间没有写文章了. 一直以来,微信的热门是看得到的,很多人都需要与微信的api对接. 今天我这里就分享全套的企业微信api接口的代码. 关于微信api,网上已经有很多实现的了. 但是我今天之所以还写这个,是因为网上基本上找不到面向对象的api接口实现的编程,几乎都是“面向过程”的. 本文章的代码,也许能带给你极大的方便,以及非常方便的扩展和应用. 1.如下图,在你的业务逻辑层中,将本文章附件的Weixin代码文件夹整套放进去 2.在你的页面中,类似于下图,插入下面的代码即可实现调用. 下图例

写微信API所遇到的问题

1.接口还没出来之前. 根据微信网页版的页面,自己做了页面,分成了两个页面,一个是登录之后的,一个是登录之前的.后来接口出来之后我师兄说要做成只有一个页面时,我就有点吓到了,想想都觉得难,后来用了JQ的hide():函数,觉得只要有方法,什么都变得很简单. 2.关于接口如何调用的问题. 在这个项目中大多都是用$.post();方法请求的,这样的话一般都发送的参数在我们地址栏里面就不会那么直接的看到,不过在Network那里还是可以看到的,在这里也可以知道请求都没有成功.并且可以知道请求后的返回值

java 微信api开发

最近使用了一个很好的微信api框架,比较好使. 源码地址:https://github.com/chanjarster/weixin-java-tools/wiki 微信公众平台:微信公众平台开发文档 nrgok内网穿刺:https://ngrok.com/

使用delphi+intraweb进行微信开发5—准备实现微信API,先从获取AccessToken开始

在前4讲中我们已经使iw开发的应用成功和微信进行了对接,再接下来的章节中我们开始逐一尝试和实现微信的各个API,开始前先来点准备工作. 首先需要明确的是,微信的API都是通过https调用实现的,分为post方法调用和get方法调用.不需要上传数据的采用get方法(例如获取AccessToken),而需要向微信服务器提交数据的采用post方法(例如创建菜单). 微信方法调用均需传递AccessToken(URL参数方式),这个AccessToken不是我们微信接入时使用的Token,这个Acce

微信api退款操作

状况:证书加载进去,本地调试退款成功,然而发不到iis上却是不成功. 分析:定然是iis配置问题. 问题一:证书加载不进去,出现“内部错误” 解决:在iis中找到对应的应用连接池,右键高级设置,找到“加载用户配置文件”改为true. 解决问题一之后,会出来问题二 问题二:出现基础连接被意外关闭. 解决: 1.开始-运行  mmc 2.文件-添加/删除管理单元 在可用的管理单元中选择 证书 添加到右侧 弹框选择计算机帐户 3.展开个人-证书 选择你导入的证书或从这里右键导入(微信api证书在选择的

【 微信API接口(全) - 微信支付/微信红包/微信卡券/微信小店/JSAPI】

微信入口绑定,微信事件处理,微信API全部操作包含在这些文件中. 微信支付.微信红包.微信卡券.微信小店. 源码地址 点击阅读 更多java,java学习,java面试题  http://techfoxbbs.com