/// <summary>
        /// 微信开放平台拉取用户信息(需scope为 snsapi_userinfo)
        /// </summary>
        /// <param name="access_token">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>
        /// <param name="openid">用户的唯一标识</param>
        /// <returns></returns>
        public static WeChatUserInfo GetWeChatUserInfo(string access_token, string openid)
        {
            WeChatUserInfo uinfo      = new WeChatUserInfo();
            string         url        = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);
            string         jsonResult = HttpUtils.Ins.GET(url);

            ClassLoger.Info("WeChatAPIHelper.GetWeChatUserInfo", url, jsonResult);
            if (!jsonResult.IsNull())
            {
                if (jsonResult.Contains("errcode"))
                {
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatUserInfo", url);
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatUserInfo", jsonResult);
                }
                else
                {
                    Dictionary <string, object> resultDic = JsonHelper.DeserializeObject(jsonResult);
                    uinfo.city       = resultDic["city"].TryToString();
                    uinfo.country    = resultDic["country"].TryToString();
                    uinfo.headimgurl = resultDic["headimgurl"].TryToString();
                    uinfo.nickname   = resultDic["nickname"].TryToString();
                    uinfo.openid     = resultDic["openid"].TryToString();
                    uinfo.privilege  = resultDic["privilege"].TryToString();
                    uinfo.province   = resultDic["province"].TryToString();
                    uinfo.sex        = resultDic["sex"].TryToInt(0);
                    if (resultDic.ContainsKey("unionid"))
                    {
                        uinfo.unionid = resultDic["unionid"].TryToString();
                    }
                }
            }
            return(uinfo);
        }
        void ClearQC()
        {
            ClassLoger.Info("ClearQCPicJob.ClearQC", "定时清理图片文件任务启动");

            string key = CacheKey.GetQrCodeKey(DateTime.Now.AddDays(-1));

            if (RedisBase.ContainsKey(key))
            {
                int i = 0;
                while (IsWork)
                {
                    List <string> qcimageList = RedisBase.List_GetList <string>(key, i, 1000);
                    foreach (string pathStr in qcimageList)
                    {
                        try
                        {
                            if (File.Exists(pathStr))
                            {
                                File.Delete(pathStr);
                            }
                        }
                        catch (Exception ex) { }
                    }
                    i++;
                    if (qcimageList == null || qcimageList.Count == 0)
                    {
                        break;
                    }
                }

                RedisBase.List_RemoveAll <string>(key);
            }

            ClassLoger.Info("ClearQCPicJob.ClearQC", "图片文件清理完毕");
        }
Example #3
0
        /// <summary>
        /// 微信公共号授权登录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static Access_tokenResult GetWeChatServiceAccess_token(string code)
        {
            string             url        = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", SystemSet.Serviceappid, SystemSet.Serviceappsecret, code);
            Access_tokenResult result     = new Access_tokenResult();
            string             resultJson = HttpUtils.Ins.GET(url);

            ClassLoger.Info("WeChatAccessTokenAPI.GetWeChatServiceAccess_token", url, resultJson);
            if (!resultJson.IsNull())
            {
                if (resultJson.Contains("errcode"))
                {
                    //WeChatErrorResult errorResult = JsonHelper.DeserializeObject<WeChatErrorResult>(resultJson);
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token(" + code + ")", url);
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token(" + code + ")", resultJson);
                }
                else
                {
                    Dictionary <string, object> resDic = JsonHelper.DeserializeObject(resultJson);
                    result.access_token  = resDic["access_token"].TryToString();
                    result.expires_in    = resDic["expires_in"].TryToInt(100);
                    result.openid        = resDic["openid"].TryToString();
                    result.refresh_token = resDic["refresh_token"].TryToString();
                    result.scope         = resDic["scope"].TryToString();
                }
            }
            return(result);
        }
        /// <summary>
        /// 创建管理员微信公共号菜单
        /// </summary>
        /// <returns></returns>
        public static bool CreateAdminMenu()
        {
            string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token();
            string url          = string.Format("https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token={0}", access_token);
            string json         = SystemSet.AdminMenu;
            string resultJson   = HttpUtils.Ins.POST(url, json);
            Dictionary <string, object> reslut = JsonHelper.DeserializeObject(resultJson);

            ClassLoger.Info("WeChatMenuAPI.CreateAdminMenu", resultJson);
            if (resultJson.Contains("errcode"))
            {
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// 删除自定义菜单
        /// </summary>
        /// <returns></returns>
        public static bool DeleteAllMenu()
        {
            string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token();
            string url          = string.Format("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={0}", access_token);

            string resultJson = HttpUtils.Ins.GET(url);

            ClassLoger.Info("WeChatMenuAPI.DeleteAllMenu", resultJson);
            Dictionary <string, object> reslut = JsonHelper.DeserializeObject(resultJson);

            if (reslut["errcode"].TryToInt(0) != 0)
            {
                return(false);
            }
            return(true);
        }
        public async Task <IHttpActionResult> VerCodePic()
        {
            JsonResult <VerCodePicViewModel> result = new JsonResult <VerCodePicViewModel>();

            result.code = 1;
            result.msg  = "OK";
            await Task.Run(() => {
                try
                {
                    ClassLoger.Info("VerCodePic", "开始获取成语");
                    cy_dictBll cybll       = new cy_dictBll();
                    IList <cy_dict> cylist = cybll.GetAllcy_dict();
                    ClassLoger.Info("VerCodePic", cylist.Count.ToString());
                    int i = Utils.GetRandom(0, cylist.Count - 1);
                    ClassLoger.Info("VerCodePic", i.ToString());
                    cy_dict cy = cylist[i];
                    ClassLoger.Info("VerCodePic成语:", cy.chengyu);
                    VerCodePicViewModel vcvm = new VerCodePicViewModel();

                    string sourcePic = FileHelper.GetVerCodePicResource();
                    if (sourcePic.IsNull() || !File.Exists(sourcePic))
                    {
                        sourcePic = @"E:\WebResources\images\VerCodePicSource\1.jpg";
                    }
                    ClassLoger.Info("VerCodePic图片", sourcePic);
                    VerCodePic codepic = FileHelper.GetVerCodePic(cy.chengyu, sourcePic);
                    vcvm.content       = cy.chengyu;
                    vcvm.MainPic       = codepic.PicURL;
                    result.Result      = vcvm;

                    string key = cookieKey();
                    RedisBase.Item_Set(key, codepic);
                    RedisBase.ExpireEntryAt(key, DateTime.Now.AddMinutes(10));
                    result.ResultMsg = key;
                }
                catch (Exception ex)
                {
                    ClassLoger.Error("AccountController.VerCodePic", ex);
                    result.code = -1;
                    result.msg  = "AccountController.VerCodePic发生异常:" + ex.Message;
                }
            });

            return(Ok(result));
        }
Example #7
0
        /**
         *
         * 测速上报接口实现
         * @param WxPayData inputObj 提交给测速上报接口的参数
         * @param int timeOut 测速上报接口超时时间
         * @throws WxPayException
         * @return 成功时返回测速上报接口返回的结果,其他抛异常
         */
        public static WxPayData Report(WxPayData inputObj, int timeOut = 1)
        {
            string url = "https://api.mch.weixin.qq.com/payitil/report";

            //检测必填参数
            if (!inputObj.IsSet("interface_url"))
            {
                throw new WxPayException("接口URL,缺少必填参数interface_url!");
            }
            if (!inputObj.IsSet("return_code"))
            {
                throw new WxPayException("返回状态码,缺少必填参数return_code!");
            }
            if (!inputObj.IsSet("result_code"))
            {
                throw new WxPayException("业务结果,缺少必填参数result_code!");
            }
            if (!inputObj.IsSet("user_ip"))
            {
                throw new WxPayException("访问接口IP,缺少必填参数user_ip!");
            }
            if (!inputObj.IsSet("execute_time_"))
            {
                throw new WxPayException("接口耗时,缺少必填参数execute_time_!");
            }

            inputObj.SetValue("appid", SystemSet.Serviceappid);                 //公众账号ID
            inputObj.SetValue("mch_id", SystemSet.Mch_id);                      //商户号
            inputObj.SetValue("user_ip", WxPayConfig.IP);                       //终端ip
            inputObj.SetValue("time", DateTime.Now.ToString("yyyyMMddHHmmss")); //商户上报时间
            inputObj.SetValue("nonce_str", GenerateNonceStr());                 //随机字符串
            inputObj.SetValue("sign", inputObj.MakeSign());                     //签名
            string xml = inputObj.ToXml();

            ClassLoger.Info("WxPayApi", "Report request : " + xml);

            string response = HttpService.Post(xml, url, false, timeOut);

            ClassLoger.Info("WxPayApi", "Report response : " + response);

            WxPayData result = new WxPayData();

            result.FromXml(response);
            return(result);
        }
Example #8
0
 public string GET(string signature, string token, string timestamp, string nonce, string echostr)
 {
     ClassLoger.Info("checkWeChatSignatureController,signature:", signature, "token:" + token, "timestamp:" + timestamp, "nonce:" + nonce, "echostr:" + echostr);
     try
     {
         List <string> paraList = new List <string>()
         {
             token, timestamp, nonce
         };
         var para    = paraList.OrderBy(x => x);
         var paraStr = string.Join("", para);
         var sig     = Utils.SHA1(paraStr);
         if (sig.Equals(signature))
         {
             return(echostr);
         }
     } catch (Exception ex)
     {
         ClassLoger.Error("WeChatSigController.GET", ex);
     }
     return(echostr);
 }
Example #9
0
        public ActionResult jssignature()
        {
            string   url = Request["url"].TryToString();
            TimeSpan ts  = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);

            string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
            //随机数
            var noncestr = url.MD5() + Utils.GetRandom(10000, 99999);

            var jsapi_ticket = WeChatAccessTokenAPI.Getjsapi_ticket();

            ClassLoger.Info("jsapi_ticket", jsapi_ticket);
            ClassLoger.Info("url", url);
            if (url.IsNull())
            {
                url = Request.Url.ToString();
            }
            string data      = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsapi_ticket, noncestr, timestamp, url);
            string signature = Utils.SHA1(data);

            return(Json(new { timestamp = timestamp, noncestr = noncestr, appid = SystemSet.Serviceappid, signature = signature }, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// 根据文字和图片获取验证码图片
        /// </summary>
        /// <param name="content"></param>
        /// <param name="picFileName"></param>
        /// <returns></returns>
        public static VerCodePic GetVerCodePic(string content, string picFileName, int fontSize = 20)
        {
            ClassLoger.Info("FileHelper.GetVerCodePic", "开始生成二维码");
            Bitmap     bmp     = new Bitmap(picFileName);
            List <int> hlist   = new List <int>();
            VerCodePic codepic = new VerCodePic();
            int        i       = Utils.GetRandom(0, SystemSet.FontPoint.Count - 1);

            codepic.Font1 = SystemSet.FontPoint[i] as FontPoint;
            hlist.Add(i);

            A : int i2 = Utils.GetRandom(0, SystemSet.FontPoint.Count - 1);
            if (hlist.Contains(i2))
            {
                goto A;
            }
            codepic.Font2 = SystemSet.FontPoint[i2] as FontPoint;
            hlist.Add(i2);

            B : int i3 = Utils.GetRandom(0, SystemSet.FontPoint.Count - 1);
            if (hlist.Contains(i3))
            {
                goto B;
            }
            hlist.Add(i3);
            codepic.Font3 = SystemSet.FontPoint[i3] as FontPoint;

            C : int i4 = Utils.GetRandom(0, SystemSet.FontPoint.Count - 1);
            if (hlist.Contains(i4))
            {
                goto C;
            }
            hlist.Add(i4);
            codepic.Font4 = SystemSet.FontPoint[i4] as FontPoint;

            ClassLoger.Info("FileHelper.GetVerCodePic", "xxxxxxxxxxxxxxxxxxxxx");
            string fileName = (content + "-" + picFileName + "-" + i + "|" + i2 + "|" + i3 + "|" + i4).MD5() + Path.GetExtension(picFileName);
            string dir      = Path.Combine(SystemSet.ResourcesPath, SystemSet.VerCodePicPath);
            string filePath = Path.Combine(dir, fileName);

            if (File.Exists(filePath))
            {
                codepic.PicURL = string.Format("{0}/{1}/{2}", SystemSet.WebResourcesSite, SystemSet.VerCodePicPath, fileName);
                return(codepic);
            }
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            Graphics    g        = Graphics.FromImage(bmp);
            Font        font     = new Font("微软雅黑", fontSize, GraphicsUnit.Pixel);
            SolidBrush  sbrush   = new SolidBrush(Color.Black);
            SolidBrush  sbrush1  = new SolidBrush(Color.Peru);
            SolidBrush  sbrush2  = new SolidBrush(Color.YellowGreen);
            SolidBrush  sbrush3  = new SolidBrush(Color.SkyBlue);
            List <char> fontlist = content.ToList();

            ClassLoger.Info("FileHelper.GetVerCodePic", fontlist.Count.ToString());
            g.DrawString(fontlist[0].TryToString(), font, sbrush, new PointF(codepic.Font1.X, codepic.Font1.Y));
            g.DrawString(fontlist[1].TryToString(), font, sbrush1, new PointF(codepic.Font2.X, codepic.Font2.Y));
            g.DrawString(fontlist[2].TryToString(), font, sbrush2, new PointF(codepic.Font3.X, codepic.Font3.Y));
            g.DrawString(fontlist[3].TryToString(), font, sbrush3, new PointF(codepic.Font4.X, codepic.Font4.Y));

            bmp.Save(filePath, ImageFormat.Jpeg);
            codepic.PicURL = string.Format("{0}/{1}/{2}", SystemSet.WebResourcesSite, SystemSet.VerCodePicPath, fileName);
            return(codepic);
        }
Example #11
0
        /// <summary>
        /// 开始发送
        /// </summary>
        public static void StartSendEmail(int sendEmailTaskId)
        {
            if (sendEmailTaskId <= 0)
            {
                ClassLoger.Fail("SendEmailHelper.StartSendEmail", "邮件发送任务Id小于0不能发送任务");
                return;
            }
            Task.Run(() =>
            {
                ClassLoger.Info("SendEmailHelper.StartSendEmail", "开始发送邮件");
                SendEmailLogBll sendEmailLogBll   = new SendEmailLogBll();
                EmailTemplateBll emailTemplateBll = new EmailTemplateBll();

                try
                {
                    EmailResourcesBll emailResourcesBll    = new EmailResourcesBll();
                    List <EmailResources> emailResourceses = emailResourcesBll.GetLists();
                    if (emailResourceses == null || emailResourceses.Count == 0)
                    {
                        ClassLoger.Fail("SendEmailHelper.StartSendEmail", "邮件资源为空不能发邮件");
                    }
                    int pageIndex = 0;
                    int pageSize  = 60;
                    A:
                    pageIndex++;
                    var tup = sendEmailLogBll.GetNoSendByTaskId(sendEmailTaskId, pageIndex, pageSize);
                    if (tup.Item1 != null && tup.Item1.Count > 0)
                    {
                        foreach (var sendEmailLog in tup.Item1)
                        {
                            Random r            = new Random();
                            int i               = r.Next(0, emailResourceses.Count - 1);
                            var emailResourcese = emailResourceses[i];
                            var template        = emailTemplateBll.GetByIds(sendEmailLog.EmailTempId);
                            string url          =
                                $"http://open.lsc.com:8080/Account/OpenEmailCallBack?logid=" + sendEmailLog.Id;
                            string imag =
                                $"<img src=\"{url}\" style=\"width: 1px; height: 1px;\" />";

                            string emailCount = template.EmailContent + "<br/>" + imag;//邮箱内容

                            EmailHelper emailHelper = new EmailHelper(emailResourcese.SenderServerIp,
                                                                      sendEmailLog.Email, emailResourcese.Email, template.Title,
                                                                      emailCount, emailResourcese.UserName, emailResourcese.Password,
                                                                      emailResourcese.Port, false, false);
                            try
                            {
                                emailHelper.Send();
                                sendEmailLog.IsSendOk = true;
                            }
                            catch (Exception e)
                            {
                                sendEmailLog.IsSendOk = false;
                            }
                            sendEmailLog.IsSend = true;
                            sendEmailLogBll.Update(sendEmailLog);
                            Thread.Sleep(1000 * 60 * 3);
                        }
                        goto A;
                    }
                }
                catch (Exception e)
                {
                    ClassLoger.Error("SendEmailHelper.SendEmail", e);
                }
            });
        }
Example #12
0
        public string POST(string signature, string token, string timestamp, string nonce, string echostr)
        {
            try
            {
                Stream requestStream = System.Web.HttpContext.Current.Request.InputStream;
                byte[] requestByte   = new byte[requestStream.Length];
                requestStream.Read(requestByte, 0, (int)requestStream.Length);
                string requestStr = Encoding.UTF8.GetString(requestByte);

                ClassLoger.Info("checkWeChatSignatureController接收到的信息:", requestStr);
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(requestStr);

                var msg = WeChatXMLMessageHelper.GetWeChatMsg(xd);
                if (msg != null)
                {
                    WxTextMsg msgs = new WxTextMsg();
                    msgs.ToUserName   = msg.FromUserName;
                    msgs.FromUserName = msg.ToUserName;
                    msgs.CreateTime   = DateTime.Now.Ticks;
                    msgs.MsgType      = "text";
                    //订阅服务号
                    if (msg.Event.Equals(MsgTypeEvent.subscribe))
                    {
                        WeChatUserInfo uinfo  = WeChatUserInfoAPI.GetWeChatUserInfo(msg.FromUserName);
                        WeChatUser     weuser = userbll.GetWeChatUserByUnionID(uinfo.unionid);
                        if (weuser == null)
                        {
                            weuser = new WeChatUser();
                        }
                        weuser.ServiceOpenID = uinfo.openid;
                        weuser.UnionID       = uinfo.unionid;
                        userbll.UpdateWeChatUser(weuser);

                        UserInfo      user       = ubll.GetUserInfoByOpenID(uinfo.unionid);
                        List <string> openIDList = new List <string>(1)
                        {
                            weuser.ServiceOpenID
                        };
                        if (user == null)
                        {
                            user            = new UserInfo();
                            user.Openid     = uinfo.unionid;
                            user.CreateTime = DateTime.Now;
                            user.Headimgurl = uinfo.headimgurl;
                            user.Nickname   = uinfo.nickname;
                            user.Sex        = (SexEnum)uinfo.sex;
                            user.Name       = uinfo.nickname;
                            user.city       = uinfo.city;
                            user.province   = uinfo.province;
                            ubll.UpdateUserinfo(user);
                        }
                        else
                        {
                            if (user.IsAdmin)
                            {
                                WeChatTagsAPI.batchtagging(openIDList, SystemSet.AdminUserTagID);
                            }
                        }
                        msgs.Content = "感谢您关注【....】";
                    }
                    return(XmlEntityExchange <WxTextMsg> .ConvertEntity2Xml(msgs));
                }
            } catch (Exception ex)
            {
                ClassLoger.Error("WeChatSig.POST", ex);
            }
            return(string.Empty);
        }
Example #13
0
        private void SpiderList(string url, string price, string city)
        {
            EnterCustomerBll bll = new EnterCustomerBll();
            int       totalPage  = 1;
            HttpUtils httpUtils  = new HttpUtils();

            for (int j = 1; j < 6; j++)
            {
                for (int i = 1; i <= totalPage; i++)
                {
                    Thread.Sleep(2000);
                    string     lurl       = $"{url}&t={j}&p={i}";
                    string     html       = httpUtils.Get(lurl);
                    HtmlParser htmlParser = new HtmlParser();
                    var        dom        = htmlParser.ParseDocument(html);
                    if (dom != null)
                    {
                        var slist = dom.QuerySelectorAll("div.sk");
                        if (slist != null)
                        {
                            foreach (var s in slist)
                            {
                                EnterCustomer enterCustomer = new EnterCustomer();
                                var           h4            = s.QuerySelector("h4");
                                if (h4 != null)
                                {
                                    enterCustomer.Abbreviation = h4.TextContent;
                                    enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.MiddleSchool;
                                    enterCustomer.EnterName    = h4.TextContent;

                                    s.RemoveChild(h4);
                                }
                                var div = s.QuerySelector("div.kw");
                                if (div != null)
                                {
                                    s.RemoveChild(div);
                                }
                                string context = s.TextContent;
                                var    param   = context.Split("地址");
                                if (context.Contains("地址") && context.Contains("电话") && param != null && param.Length >= 2)
                                {
                                    string p1 = param[0];
                                    string p2 = param[1];//地址
                                    if (p1.Contains("邮编"))
                                    {
                                        var pr = p1.Split("邮编");
                                        if (pr != null && pr.Length >= 2)
                                        {
                                            enterCustomer.Landline = pr[0].Replace("电话:", "");
                                        }
                                    }
                                    else
                                    {
                                        enterCustomer.Landline = p1.Replace("电话:", "");
                                    }
                                }
                                enterCustomer.Province = price;
                                enterCustomer.City     = city;
                                enterCustomer.Source   = Model.Enume.CustSource.Other;
                                enterCustomer.State    = Model.Enume.StateEnum.Invalid;
                                switch (j)
                                {
                                case 1:
                                    enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.PrimarySchool;
                                    break;

                                case 2:
                                    enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.PrimarySchool;
                                    break;

                                case 3:
                                    enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.MiddleSchool;
                                    break;

                                case 4:
                                    enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.Colleges;
                                    break;

                                case 5:
                                    enterCustomer.CustomerType = Model.Enume.CustomerTypeEnum.Colleges;
                                    break;
                                }
                                if (!bll.ExistsEnterNameAsync(0, enterCustomer.EnterName).Result)
                                {
                                    bll.AddEnterCustomer(enterCustomer);
                                }
                                ClassLoger.Info("成功抓取学校:", enterCustomer.EnterName);
                                Console.WriteLine(enterCustomer.EnterName);
                            }
                        }
                        var fenyeDiv = dom.QuerySelector("div.fy");
                        if (fenyeDiv != null)
                        {
                            var zysspan = fenyeDiv.QuerySelector("span.zys");
                            if (zysspan != null)
                            {
                                totalPage = zysspan.TextContent.TryToInt(1);
                            }
                        }
                    }
                }
            }
        }
Example #14
0
        public JsonResult <PayOrder> Post(UnifiedOrder obj)
        {
            ClassLoger.Info("PayController.Post", obj.PayTyp.ToString(), obj.product_id, obj.productType.TryToString());
            JsonResult <PayOrder> result = new JsonResult <PayOrder>();

            result.code = 1;
            result.msg  = "OK";
            PayOrderBll porderbll = new PayOrderBll();

            try
            {
                if (obj.PayTyp == 1)
                {
                    JsApiPay jsApiPay = new JsApiPay();
                    jsApiPay.openid = "";
                    if (!obj.openid.IsNull())
                    {
                        WeChatUserBll wuserbll = new WeChatUserBll();
                        WeChatUser    wuser    = wuserbll.GetWeChatUserByUnionID(obj.openid);
                        jsApiPay.openid = wuser.ServiceOpenID;
                    }
                    else if (!obj.userid.IsNull())
                    {
                        UserInfoBll ubll = new UserInfoBll();
                        var         user = ubll.GetUserinfoByID(obj.userid);
                        if (!user.Openid.IsNull())
                        {
                            WeChatUserBll wuserbll = new WeChatUserBll();
                            WeChatUser    wuser    = wuserbll.GetWeChatUserByUnionID(user.Openid);
                            jsApiPay.openid = wuser.ServiceOpenID;
                        }
                    }
                    jsApiPay.total_fee  = 1;
                    jsApiPay.trade_type = obj.trade_type;
                    if (obj.productType == 1)
                    {
                        //查询商品信息,获取商品价格
                        double Price = 0.1;
                        jsApiPay.total_fee = (Price * 100).TryToInt();
                        jsApiPay.body      = "商品名称";
                    }
                    jsApiPay.attach = "北京xx";
                    string out_trade_no = porderbll.GetOnlineOrder(PayTypeEnum.WeChart);
                    jsApiPay.out_trade_no = out_trade_no;
                    jsApiPay.product_id   = obj.product_id;

                    ClassLoger.Info("api/Pay/UnifiedOrder", "total_fee", jsApiPay.total_fee.ToString());
                    WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult();
                    PayOrder  porder             = new PayOrder();

                    if (unifiedOrderResult.GetValue("return_code").TryToString() == "SUCCESS" && unifiedOrderResult.GetValue("result_code").TryToString() == "SUCCESS")
                    {
                        if (unifiedOrderResult.IsSet("code_url"))
                        {
                            string code_url = unifiedOrderResult.GetValue("code_url").TryToString();
                            string filename = string.Format("WXPY{0}.png", code_url.MD5());
                            string filepath = Path.Combine(SystemSet.ResourcesPath, SystemSet.QrCodePic, filename);
                            if (!File.Exists(filepath))
                            {
                                QrCodeHelper.CreateImgCode(code_url, filepath);
                            }
                            porder.code_url = Path.Combine(SystemSet.WebResourcesSite, SystemSet.QrCodePic, filename);
                        }
                        porder.OnlineOrder = out_trade_no;
                        porder.openid      = obj.openid;
                        porder.PayState    = PayStateEnum.Unpaid;
                        porder.PayType     = PayTypeEnum.WeChart;
                        porder.prepay_id   = unifiedOrderResult.GetValue("prepay_id").TryToString();
                        porder.product_id  = obj.product_id;
                        porder.total_fee   = jsApiPay.total_fee;
                        porder.trade_type  = obj.trade_type;
                        porder.CreateTime  = DateTime.Now;
                        porder.UserID      = obj.userid;
                        porder.ID          = porderbll.AddPayOrder(porder);
                        result.Result      = porder;
                        return(result);
                    }
                    else
                    {
                        result.code      = 0;
                        result.msg       = unifiedOrderResult.GetValue("return_code").TryToString();
                        result.ResultMsg = unifiedOrderResult.GetValue("result_code").TryToString();
                    }
                }
            } catch (Exception ex)
            {
                result.code = -1;
                result.msg  = "PayController.unifiedorder:" + ex.Message;
            }
            return(result);
        }
Example #15
0
        public ActionResult CallBackRedirect()
        {
            //网络授权有有效期,最好用redis缓存
            //获取用户网络授权
            string code  = Request["code"].TryToString();
            string state = Request["state"].TryToString();

            ClassLoger.Info("WeixinRedirectController.CallBackRedirect", state, code);
            string access_token = string.Empty;
            string openid       = string.Empty;

            if (RedisBase.ContainsKey(code))
            {
                Access_tokenResult accResult = RedisBase.Item_Get <Access_tokenResult>(code);
                access_token = accResult.access_token;
                openid       = accResult.openid;
            }
            else
            {
                Access_tokenResult accResult = WeChatAccessTokenAPI.GetWeChatServiceAccess_token(code);
                RedisBase.Item_Set(code, accResult);
                RedisBase.ExpireEntryAt(code, DateTime.Now.AddSeconds(accResult.expires_in));
                access_token = accResult.access_token;
                openid       = accResult.openid;
            }

            //获取用户信息
            WeChatUserInfo userinfo = null;
            string         userkey  = getWeChatUserKey(access_token, openid);

            if (RedisBase.ContainsKey(userkey))
            {
                userinfo = RedisBase.Item_Get <WeChatUserInfo>(userkey);
            }
            else
            {
                userinfo = WeChatUserInfoAPI.GetWeChatUserInfo(access_token, openid);
                if (userinfo != null)
                {
                    RedisBase.Item_Set(userkey, userinfo);
                    RedisBase.ExpireEntryAt(userkey, DateTime.Now.AddDays(2));
                }
            }
            UserInfo _user = userbll.GetUserInfoByOpenID(userinfo.unionid);

            if (_user == null)
            {
                _user            = new UserInfo();
                _user.Openid     = userinfo.unionid;
                _user.CreateTime = DateTime.Now;
                _user.Headimgurl = userinfo.headimgurl;
                _user.Nickname   = userinfo.nickname;
                _user.Sex        = (SexEnum)userinfo.sex;
                _user.Name       = userinfo.nickname;
                _user.city       = userinfo.city;
                _user.province   = userinfo.province;
                userbll.UpdateUserinfo(_user);
            }
            ClassLoger.Info("CallBackRedirect", userkey);
            RedisSession <UserInfo> redissession = new Models.RedisSession <UserInfo>(HttpContext, true, 120);

            redissession["UserCode"] = _user;
            switch (state)
            {
            //普通用户个人中心
            case "UserCore":
                return(RedirectToAction("Index", "UserCore"));

            case "AdminCore":
            //return RedirectToAction("Index", "AdminCore");
            default:
                string url = HttpUtils.Ins.UrlDecode(state);
                if (RedisBase.ContainsKey(state))
                {
                    url = RedisBase.Item_Get <string>(state);
                }
                return(Redirect(url));
            }
        }
        public void Index()
        {
            try
            {
                WxPayData notifyData = GetNotifyData(Request, Response);
                ClassLoger.Info("WeChartPayCallBack.Index", notifyData.ToJson());
                //检查支付结果中transaction_id是否存在
                if (!notifyData.IsSet("transaction_id"))
                {
                    //若transaction_id不存在,则立即返回结果给微信支付后台
                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", "支付结果中微信订单号不存在");
                    ClassLoger.Fail("WeChartPayCallBackController.Index:支付结果中微信订单号不存在", notifyData.ToXml());
                    Response.Write(res.ToXml());
                    Response.End();
                }
                string transaction_id = notifyData.GetValue("transaction_id").ToString();
                //查询订单,判断订单真实性
                if (!QueryOrder(transaction_id))
                {
                    //若订单查询失败,则立即返回结果给微信支付后台
                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", "订单查询失败");
                    ClassLoger.Fail(this.GetType().ToString(), "Order query failure : " + res.ToXml());
                    Response.Write(res.ToXml());
                    Response.End();
                }//查询订单成功
                else
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(p => {
                        string out_trade_no   = notifyData.GetValue("out_trade_no").ToString();
                        PayOrderBll porderBll = new PayOrderBll();
                        PayOrder porder       = porderBll.GetByOnlineOrder(out_trade_no);
                        string mqttmsg        = string.Empty;
                        if (notifyData.GetValue("result_code").ToString() == "SUCCESS")
                        {
                            porder.PayState = Model.EnumModel.PayStateEnum.Paid;
                            mqttmsg         = MqttAgreement.GetPsychtestWeChartPayState(out_trade_no, true);
                        }
                        else
                        {
                            porder.PayState = Model.EnumModel.PayStateEnum.Fail;
                            if (notifyData.IsSet("err_code_des"))
                            {
                                porder.PayStateMsg = notifyData.GetValue("err_code_des").TryToString();
                            }
                            mqttmsg = MqttAgreement.GetPsychtestWeChartPayState(out_trade_no, false);
                        }
                        porderBll.UpdatePayOrder(porder);
                        MqttPublishClient.Ins.PublishOneUser(porder.ID, mqttmsg);
                    }), null);

                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "SUCCESS");
                    res.SetValue("return_msg", "OK");
                    ClassLoger.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
                    Response.Write(res.ToXml());
                    Response.End();
                }
            } catch (Exception ex)
            {
                ClassLoger.Error("WeChartPayCallBackController.Index", ex);
            }
        }