public ActionResult ApplyWithDraw()
        {
            var siteSetting = SiteSettingApplication.SiteSettings;

            if (string.IsNullOrWhiteSpace(siteSetting.WeixinAppId) || string.IsNullOrWhiteSpace(siteSetting.WeixinAppSecret))
            {
                throw new MallException("未配置公众号参数");
            }

            var token = AccessTokenContainer.TryGetAccessToken(siteSetting.WeixinAppId, siteSetting.WeixinAppSecret);

            SceneModel scene = new SceneModel(QR_SCENE_Type.WithDraw)
            {
                Object = CurrentUser.Id.ToString()
            };
            SceneHelper helper  = new SceneHelper();
            var         sceneid = helper.SetModel(scene);
            var         ticket  = QrCodeApi.Create(token, 300, sceneid, Senparc.Weixin.MP.QrCode_ActionName.QR_LIMIT_SCENE, null);

            ViewBag.ticket  = ticket.ticket;
            ViewBag.Sceneid = sceneid;
            var balance = MemberCapitalApplication.GetBalanceByUserId(CurrentUser.Id);

            ViewBag.ApplyWithMoney = balance;
            var member = _iMemberService.GetMember(CurrentUser.Id);//CurrentUser对象有缓存,取不到最新数据

            ViewBag.IsSetPwd        = string.IsNullOrWhiteSpace(member.PayPwd) ? false : true;
            ViewBag.WithDrawMinimum = siteSetting.WithDrawMinimum;
            ViewBag.WithDrawMaximum = siteSetting.WithDrawMaximum;
            ViewBag.Keyword         = string.IsNullOrWhiteSpace(SiteSettings.SearchKeyword) ? SiteSettings.Keyword : SiteSettings.SearchKeyword;
            ViewBag.Keywords        = SiteSettings.HotKeyWords;
            return(View());
        }
Beispiel #2
0
        /// <summary>
        /// 获取用于换取二维码(临时二维码和长久二维码)的Ticket
        /// </summary>
        /// <param name="senceId">场景值ID</param>
        /// <param name="type">值为:long 时:代表长久性二维码  值为short时:代表临时二维码</param>
        /// <returns></returns>
        public string GeterweimaTicket(int senceId, string type = "short")
        {
            string             Ticket = "";
            CreateQrCodeResult re     = new CreateQrCodeResult();

            try
            {
                if (type == "short")//临时二维码
                {
                    re = QrCodeApi.Create(IsExistAccess_Token2(), 604800, senceId);
                }
                else
                {
                    re = QrCodeApi.Create(IsExistAccess_Token2(), 0, senceId);
                }
                Ticket = re.ticket;
            }
            catch
            {
                if (type == "short")//临时二维码
                {
                    Ticket = CreateTicket(IsExistAccess_Token2());
                }
                else
                {
                    Ticket = CreateLongTicket(IsExistAccess_Token2());
                }
            }

            return(Ticket);
        }
        public ActionResult AddQrCode(QrCodeView model)
        {
            var config  = WeChatCommonService.GetWeChatConfigByID(model.AppId);
            var sceneId = ((IQrCodeService)_BaseService).GenerateSceneId();
            var result  = QrCodeApi.Create(config.WeixinAppId, config.WeixinCorpSecret, 0, sceneId);

            if (result.errcode == Weixin.ReturnCode.请求成功)
            {
                var    url      = QrCodeApi.GetShowQrCodeUrl(result.ticket);
                string ourPath  = "/content/OrCodeMP" + result.url.Substring(result.url.IndexOf("/q/")) + ".jpg";
                string savePath = Server.MapPath(ourPath);
                if (!System.IO.File.Exists(savePath))//判断文件是否存在
                {
                    string saveFolderPath = savePath.Replace(savePath.Split('\\').Last(), "");

                    if (!Directory.Exists(saveFolderPath))         //判断文件夹是否存在
                    {
                        Directory.CreateDirectory(saveFolderPath); //不存在则创建文件夹
                    }
                    var mClient = new WebClient();
                    mClient.DownloadFile(url, savePath);
                }
                model.Url     = ourPath;
                model.SceneId = sceneId;
                ((IQrCodeService)_BaseService).AddOrCode(model, User.Identity.Name);
            }

            return(Json(new { result = 200 }));
        }
Beispiel #4
0
        /// <summary>
        /// 获取带有参数的场景关注的二维码的URL;
        /// http://www.cnblogs.com/txw1958/p/weixin-qrcode-with-parameters.html
        /// 说明: 本地不下载图片,因为此图片为临时链接,
        /// 所以,在 APP端下载图片并叠加图片;
        /// </summary>
        /// <param name="sceneId">场景Id</param>
        /// <returns></returns>
        public string GetErcodeWithEntryParameter(int sceneId)
        {
            var result = QrCodeApi.Create(Config.AppId, 300, sceneId, QrCode_ActionName.QR_SCENE);
            var ticket = result.ticket;

            return("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + HttpUtility.UrlEncode(ticket));
        }
        /// <summary>
        /// 根据用户openId 创建或者更新新的二维码
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="appid"></param>
        /// <param name="activityName"></param>
        /// <param name="activityid"></param>
        /// <returns></returns>
        public ActionResult CreateOrUpdateQrCodeByOpenId(string openId, string wechatappid, string activityName, string activityid, string isUpdate)
        {
            if (!VerifyParam("openId,wechatappid,activityName,activityid,isUpdate"))
            {
                return(ErrMsg());
            }
            int newAppid      = System.Convert.ToInt32(wechatappid);
            int newactivityId = System.Convert.ToInt32(activityid);

            try
            {
                var          config = WeChatCommonService.GetWeChatConfigByID(newAppid);
                var          user   = _WechatMPUserService.Repository.Entities.Where(u => u.OpenId.Equals(openId, StringComparison.CurrentCultureIgnoreCase) && u.AccountManageId == config.AccountManageId && u.IsCanceled == false).FirstOrDefault();
                var          qrcode = _QrCodeService.Repository.Entities.Where(q => q.RelatedUserId == user.Id);
                QrCodeMPItem newqr  = new QrCodeMPItem();
                if (qrcode.Any())
                {
                    newqr = qrcode.FirstOrDefault();
                    UpdateQRCode(newqr, newAppid, isUpdate);
                }
                else
                {
                    newqr.AppId         = newAppid;
                    newqr.Description   = activityName;
                    newqr.CreatedDate   = DateTime.Now;
                    newqr.Deleted       = false;
                    newqr.CreatedUserID = User.Identity.Name;
                    newqr.UpdatedDate   = DateTime.Now;
                    newqr.UpdatedUserID = User.Identity.Name;
                    newqr.RelatedUserId = user.Id;
                    _QrCodeService.Repository.Insert(newqr);
                    ///添加临时二维码时 先插入数据获取当前记录id
                    ///目前商定 所有活动用二维码 由10位数字组成 前三位代表活动id,后7位代表活动用二维码id。
                    ///
                    newqr.SceneId = newactivityId * 10000000 + newqr.Id;
                    //var config = WeChatCommonService.GetWeChatConfigByID(newAppid);
                    ///临时用二维码 过期时间为2592000秒 30天

                    ///x向腾讯申请二维码 并获取二维码url
                    var result = QrCodeApi.Create(config.WeixinAppId, config.WeixinCorpSecret, 2592000, (int)newqr.SceneId);
                    if (result.errcode == Weixin.ReturnCode.请求成功)
                    {
                        var    qrurl       = QrCodeApi.GetShowQrCodeUrl(result.ticket);
                        var    userinfo    = Innocellence.Weixin.MP.AdvancedAPIs.UserApi.Info(config.WeixinCorpId, config.WeixinCorpSecret, openId);
                        string userHeadUrl = userinfo.headimgurl;
                        newqr.Url = CombineQrCodeAndHeadImg(userHeadUrl, qrurl);
                    }
                    ///重新更新当前model
                    _QrCodeService.Repository.Update(newqr);
                }
                return(Json(new { QrcodeUrl = newqr.Url, SceneId = newqr.SceneId, Status = 200, UpdatedDate = newqr.UpdatedDate }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                _Logger.Error(e);
            }
            return(Json(new { Status = 400 }, JsonRequestBehavior.AllowGet));
        }
Beispiel #6
0
        /// <summary>
        /// 微信二维码
        /// </summary>
        public ActionResult WxQRCode()
        {
            if (WorkContext.UserLevel <= 0)
            {
                return(PromptView("请先提升您的等级"));
            }

            string pth1 = "~/mobile/Qcode/" + WorkContext.Openid.ToString() + ".jpeg";
            string pth2 = "~/mobile/Qcode/" + WorkContext.Openid.ToString() + ".jpg";
            //LogHelper.WriteLog("二维码:" + pth1); LogHelper.WriteLog("二维码:" + pth2);
            //if (File.Exists(pth1)||File.Exists(pth2))
            //{
            //    File.Delete(pth1); File.Delete(pth2);
            //    LogHelper.WriteLog("二维码222222");
            //}
            CreateQrCodeResult re = new CreateQrCodeResult();

            re = QrCodeApi.Create(WeiXinHelp.IsExistAccess_Token2(), 604000, Convert.ToInt32(WorkContext.Uid));
            string tickets = re.ticket;

            //string quserno = WorkContext.Userno.ToString();
            WeiXinHelp.GetTicketImage(tickets, WorkContext.Openid.ToString(), @"\mobile\Qcode");
            string        picPth = @"~/mobile/Qcode/" + WorkContext.Openid.ToString() + ".jpeg";
            WxQRCodeModel model  = new WxQRCodeModel();

            model.picPth = "";
            if (!System.IO.File.Exists(picPth))
            {
                // LogHelper.WriteLog("二维码JPG");
                {
                    model.picPth = @"/mobile/Qcode/" + WorkContext.Openid.ToString() + ".jpg";
                }
            }
            WebClient mywebclient = new WebClient();
            // @"
            string savepath = Server.MapPath("~/mobile/Aavatar/") + WorkContext.Openid + ".jpg";

            // //LogHelper.WriteLog(savepath);

            //try
            //{
            if (!System.IO.File.Exists(savepath))
            {
                mywebclient.DownloadFile(WorkContext.Avatar, savepath);
            }

            //下载生成的二维码图片
            //}
            //catch (Exception ex)
            //{
            //    // ex.ToString();
            //    // BrnMall.Core.Common.LogHelper.WriteLog("错误了" + savepath);
            //}
            Core.ImageHelp.DrawImage("", "", (float)1.0, "", "", "", WorkContext.NickName, WorkContext.Openid);
            model.picPth = @"/mobile/Qcode/new/" + WorkContext.Openid.ToString() + ".jpg";
            return(View(model));
        }
Beispiel #7
0
        /// <summary>
        /// 传入场景Id后,获取场景Id的二维码图片地址的Url;
        /// 用户扫描后将关注公众号,且将传递场景Id参数;
        /// </summary>
        /// <param name="sceneStr">场景字符串</param>
        /// <param name="expireSeconds">二维码过期时间,默认5分钟;</param>
        public string GetQrCodeUrl(string sceneStr, int expireSeconds = 300)
        {
            var result = QrCodeApi.Create(AccessToken, expireSeconds, 0, QrCode_ActionName.QR_STR_SCENE, sceneStr);

            if (result.errcode == Senparc.Weixin.ReturnCode.请求成功)
            {
                return(QrCodeApi.GetShowQrCodeUrl(result.ticket));
            }
            return(null);
        }
Beispiel #8
0
        public ActionResult NotAttention(long id)
        {
            BonusModel  bonusModel  = new BonusModel(_bonusService.Get(id));
            string      str         = AccessTokenContainer.TryGetToken(_siteSetting.WeixinAppId, _siteSetting.WeixinAppSecret, false);
            SceneHelper sceneHelper = new SceneHelper();
            int         num         = sceneHelper.SetModel(new SceneModel(QR_SCENE_Type.Bonus, bonusModel), 600);
            string      str1        = QrCodeApi.Create(str, 86400, num, 10000).ticket;

            ViewBag.ticket = str1;
            return(View("~/Areas/Mobile/Templates/Default/Views/Bonus/NotAttention.cshtml", bonusModel));
        }
Beispiel #9
0
        public ActionResult BindQRCodeSence()
        {
            var memberId = GetMemberId();
            var member   = wechatCoreDb.QueryMemberWechat()
                           .Where(m => !m.IsDel)
                           .Where(m => m.MemberId == memberId)
                           .FirstOrDefault();

            if (member != null)
            {
                throw new Exception("已经绑定微信");
            }
            var code = Common.CommonUtil.CreateNoncestr(15);

            WechatQRScene model = new WechatQRScene()
            {
                Category     = "BindMember",
                Status       = WechatQRSceneStatus.未处理,
                QrCodeTicket = ""
            };

            wechatCoreDb.AddToWechatQRScene(model);
            wechatCoreDb.SaveChanges();


            var b = model.Id / 4294967295;

            model.SceneId = (int)(model.Id - 4294967295 * b);

            var accessToken = GetAccessToken();
            var qrResult    = QrCodeApi.Create(accessToken, 60 * 5, model.SceneId, QrCode_ActionName.QR_SCENE);

            model.QrCodeTicket = qrResult.ticket;
            wechatCoreDb.AddToMemberWeChatBindTask(new MemberWeChatBindTask()
            {
                AddIp    = GetIp(),
                AddTime  = DateTime.Now,
                Code     = model.SceneId.ToString(),
                MemberId = GetMemberId(),
                OpenId   = "",
                Status   = MemberWeChatBindTaskStatus.未使用
            });
            wechatCoreDb.SaveChanges();

            using (var stream = new MemoryStream())
            {
                QrCodeApi.ShowQrCode(model.QrCodeTicket, stream);
                byte[] data = stream.ToArray();

                return(File(data, "image/jpeg"));
            }
        }
Beispiel #10
0
        public static string WXCreateQrCode(string url)
        {
            var qr = QrCodeApi.Create(MPBasicSetting.AppID, 0, (int)CustomerAgent.LIN, QrCode_ActionName.QR_LIMIT_SCENE);

            if (qr.errcode == ReturnCode.请求成功)
            {
                return(QrCodeApi.GetShowQrCodeUrl(qr.ticket));
            }
            else
            {
                return(null);
            }
        }
Beispiel #11
0
        /// <summary>
        /// 创建分享二维码
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public string CreateShareQrCode(string openId)
        {
            var accessToken = AccessToken();

            if (string.IsNullOrEmpty(accessToken))
            {
                return(null);
            }
            var qrResult  = QrCodeApi.Create(accessToken, 10000, 111, QrCode_ActionName.QR_LIMIT_STR_SCENE, openId);
            var qrCodeUrl = QrCodeApi.GetShowQrCodeUrl(qrResult.ticket);

            return(qrCodeUrl);
        }
Beispiel #12
0
        public ActionResult CreateQrCode(int isRefresh = 0)
        {
            try
            {
                string   userMsg   = Common.UserHelper.Instance.getCookie();
                string[] userArray = userMsg.Split('|');
                string   userStr   = userArray[0] + "P|" + userArray[4];
                //string userStr = "5P|oCbECv1pwMNyAodYQtRJVvJf_Zsg";
                string   fullPath = Server.MapPath("\\images\\full\\") + string.Format("full-{0}.jpg", userArray[4]);
                FileInfo fileInfo = new FileInfo(fullPath);
                if ((!fileInfo.Exists) || (isRefresh == 1))
                {
                    //var result = QrCodeApi.Create(Common.CommonConst.AppID, 100, 999999, QrCode_ActionName.QR_SCENE, "邀请");
                    var result       = QrCodeApi.Create(Common.CommonConst.AppID, 100, 1000, QrCode_ActionName.QR_LIMIT_STR_SCENE, userStr);
                    var headFileName = Server.MapPath("\\images\\header\\") + string.Format("head-{0}.jpg", DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));
                    using (FileStream fsHeader = new FileStream(headFileName, FileMode.OpenOrCreate))
                    {
                        var user = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(Common.CommonConst.AppID, userArray[4]);
                        Senparc.Weixin.HttpUtility.Get.Download(user.headimgurl, fsHeader);
                    }

                    var dirPath  = Server.MapPath("\\images");
                    var fileName = Server.MapPath("\\images\\qrcode\\") + string.Format("qrcode-{0}.jpg", DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));
                    using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
                    {
                        QrCodeApi.ShowQrCode(result.ticket, fs);//下载二维码
                    }

                    // 模板路径
                    string sourcePath = dirPath + "\\template\\haibao.jpg";
                    // 二维码路径
                    string twoDimensionCode = fileName;
                    string headPath         = headFileName;
                    fileInfo.Delete();

                    int seq = 0;
                    int.TryParse(userArray[0], out seq);

                    string reqNum = (seq + 2000).ToString();
                    Logger.Warn("seq:" + reqNum);
                    // 生成个人海报
                    //ImageHelper.GeneratePoster(sourcePath, twoDimensionCode, fullPath, headPath);
                    ImageHelper.GeneratePoster(sourcePath, twoDimensionCode, fullPath, headPath, reqNum);
                }
                return(Content(fullPath));
            }
            catch (Exception e)
            {
                return(Content(e.Message));
            }
        }
Beispiel #13
0
 public void CreateQrCode(Wx_App app, string activityIds)
 {
     activityIds.Split <long>().Each(activityId =>
     {
         var activity = Get(activityId);
         if (activity != null)
         {
             var result       = QrCodeApi.Create(app.AppId, 2592000, 1, QrCode_ActionName.QR_LIMIT_STR_SCENE, $"{activityId}");
             activity.QrCode  = result.url;
             activity.DUpdate = DateTime.Now;
             UpdateQrCode(activity);
         }
     });
 }
        public ActionResult ApplyWithDraw()
        {
            SiteSettingsInfo siteSettings = ServiceHelper.Create <ISiteSettingService>().GetSiteSettings();

            if (string.IsNullOrWhiteSpace(siteSettings.WeixinAppId) || string.IsNullOrWhiteSpace(siteSettings.WeixinAppSecret))
            {
                throw new HimallException("Can not Set WeiXin AppId");
            }
            string     str        = AccessTokenContainer.TryGetToken(siteSettings.WeixinAppId, siteSettings.WeixinAppSecret, true);
            SceneModel sceneModel = new SceneModel(QR_SCENE_Type.WithDraw)
            {
                Object = base.CurrentUser.Id.ToString()
            };
            int num = (new SceneHelper()).SetModel(sceneModel, 600);
            CreateQrCodeResult createQrCodeResult = QrCodeApi.Create(str, 300, num, 10000);

            ViewBag.ticket  = createQrCodeResult.ticket;
            ViewBag.Sceneid = num;
            IMemberCapitalService memberCapitalService = ServiceHelper.Create <IMemberCapitalService>();
            CapitalInfo           capitalInfo          = memberCapitalService.GetCapitalInfo(base.CurrentUser.Id);

            if (capitalInfo == null)
            {
                ViewBag.ApplyWithMoney = 0;
            }
            else
            {
                dynamic viewBag = base.ViewBag;
                decimal?balance = capitalInfo.Balance;
                ViewBag.ApplyWithMoney = balance.Value;
            }
            string membersId = this.CurrentUser.UserName;
            IEnumerable <WithDrawInfo> WithDraws = ServiceHelper.Create <IWithDrawService>().GetWithDrawByMembersId(membersId);//因为UserName值唯一,所以没有登录账号ID去获取信息

            String[] Array = new String[WithDraws.Count()];
            int      i     = 0;

            foreach (var item in WithDraws)
            {
                Array[i] = item.WithdrawType + "【" + item.AccountNumber + "," + item.Name + "】";
                i++;
            }
            ViewBag.List = Array;
            ViewBag.Num  = Array.Length;


            base.ViewBag.IsSetPwd = (string.IsNullOrWhiteSpace(base.CurrentUser.PayPwd) ? false : true);
            return(View());
        }
Beispiel #15
0
        //未关注
        public ActionResult NotAttention(long id)
        {
            BonusModel model    = new BonusModel(this._iBonusService.Get(id));
            var        settings = SiteSettingApplication.SiteSettings;
            //TODO:改成统一的方式取 Token
            var token = AccessTokenContainer.TryGetAccessToken(settings.WeixinAppId, settings.WeixinAppSecret);

            SceneHelper helper  = new SceneHelper();
            SceneModel  scene   = new SceneModel(QR_SCENE_Type.Bonus, model);
            int         sceneId = helper.SetModel(scene);
            var         ticket  = QrCodeApi.Create(token, 86400, sceneId, QrCode_ActionName.QR_LIMIT_SCENE, null, 10000).ticket;

            ViewBag.ticket = ticket;
            return(View("~/Areas/Mobile/Templates/Default/Views/Bonus/NotAttention.cshtml", model));
        }
Beispiel #16
0
        public ActionResult Add(long id = 0)
        {
            int    sceneid   = 0;
            string ticketstr = "";
            var    settings  = SiteSettingApplication.SiteSettings;

            try
            {
                if (!string.IsNullOrWhiteSpace(settings.WeixinAppId) && !string.IsNullOrWhiteSpace(settings.WeixinAppSecret))
                {
                    string token = AccessTokenContainer.TryGetAccessToken(settings.WeixinAppId, settings.WeixinAppSecret);
                    if (string.IsNullOrWhiteSpace(token))
                    {
                        token = AccessTokenContainer.TryGetAccessToken(settings.WeixinAppId, settings.WeixinAppSecret, true);
                    }

                    SceneModel scene = new SceneModel(QR_SCENE_Type.ShopShipper)
                    {
                        //Object = CurrentUser.Id.ToString()
                    };
                    SceneHelper helper = new SceneHelper();
                    sceneid = helper.SetModel(scene);
                    var ticket = QrCodeApi.Create(token, 300, sceneid, QrCode_ActionName.QR_LIMIT_SCENE, null, 10000);
                    ticketstr = ticket.ticket;
                }
            }
            catch {
                Log.Error("设置退货地址出错:微信配置错误,无法获取到微信凭证");
            }
            ViewBag.ticket  = ticketstr;
            ViewBag.Sceneid = sceneid;
            ShopShipper data = new ShopShipper
            {
                ShopId = CurShopId
            };

            if (id > 0)
            {
                data = ShopShippersApplication.GetShopShipper(CurShopId, id);
                if (data == null)
                {
                    throw new MallException("错误的参数");
                }
            }
            return(View(data));
        }
Beispiel #17
0
        public ActionResult CanReceiveNotAttention(long id, string openId = "", decimal price = 0)
        {
            ViewBag.Price = price;
            BonusModel model = new BonusModel(this._iBonusService.Get(id));
            //TODO:改成统一的方式取 Token
            var settings = SiteSettingApplication.SiteSettings;
            var token    = AccessTokenContainer.TryGetAccessToken(settings.WeixinAppId, settings.WeixinAppSecret);

            SceneHelper helper   = new SceneHelper();
            var         qrTicket = QrCodeApi.Create(token, 86400, 123456789, QrCode_ActionName.QR_LIMIT_SCENE, null).ticket;

            ViewBag.ticket   = WXApiApplication.GetTicket(settings.WeixinAppId, settings.WeixinAppSecret);
            model.ImagePath  = MallIO.GetFilePath(model.ImagePath);
            ViewBag.OpenId   = openId;
            ViewBag.QRTicket = qrTicket;
            return(View(model));
        }
Beispiel #18
0
        private string GetRegQrCode(Guid guid)
        {
            var sceneId             = int.Parse(DateTime.Now.ToString("MMddHHmmss"));
            var senparcWeixinConfig = SenparcDI.GetService <IOptions <SenparcWeixinSetting> >().Value;
            var qrCodeRegCache      = SenparcDI.GetService <QrCodeRegCache>();

            while (qrCodeRegCache.MessageCollection.ContainsKey(sceneId.ToString()))
            {
                sceneId++;
            }
            CreateQrCodeResult qrCodeResult = QrCodeApi.Create(senparcWeixinConfig.WeixinAppId, 600, sceneId,
                                                               QrCode_ActionName.QR_SCENE, "reg_code");
            var qrCodeRegData = new QrCodeRegData(sceneId, qrCodeResult.expire_seconds, qrCodeResult.ticket, guid, QrCodeRegDataType.Reg);

            qrCodeRegCache.Insert(qrCodeRegData, qrCodeRegData.Key);
            return(qrCodeResult.url);
        }
Beispiel #19
0
        public async Task <Qrcode> CreateQrcodeAsync(UserIdentifier userIdentifier)
        {
            string appId = await SettingManager.GetSettingValueForTenantAsync(WechatSettings.General.AppId, userIdentifier.TenantId.Value);

            string appSecret = await SettingManager.GetSettingValueForTenantAsync(WechatSettings.General.Secret, userIdentifier.TenantId.Value);

            Qrcode maxSceneIdQrcode = qrcodeRepository.GetAll().OrderByDescending(model => model.SceneId).FirstOrDefault();
            int    sceneId          = maxSceneIdQrcode == null?1: maxSceneIdQrcode.SceneId + 1;

            Qrcode qrcode = new Qrcode()
            {
                ExpireSeconds = 604800,
                UserId        = userIdentifier.UserId
            };

            //大于10万,生成临时二维码
            if (sceneId > 100000)
            {
                qrcode.Type = QrCode_ActionName.QR_LIMIT_SCENE;
            }
            else
            {
                qrcode.SceneId = sceneId;
                qrcode.Type    = QrCode_ActionName.QR_SCENE;
            }
            string accessToken = AccessTokenContainer.TryGetAccessToken(appId, appSecret);

            CreateQrCodeResult createQrCodeResult = QrCodeApi.Create(
                accessToken,
                qrcode.ExpireSeconds,
                qrcode.SceneId,
                qrcode.Type);

            qrcode.Ticket        = createQrCodeResult.ticket;
            qrcode.ExpireSeconds = createQrCodeResult.expire_seconds;
            qrcode.Url           = createQrCodeResult.url;

            string qrcodePreUrl = String.Format(qrcodePreUrlBaseFormat, qrcode.Ticket);

            qrcode.Path = GetQrcodeFolderPathOfUser(userIdentifier.UserId) + "/" + qrcode.SceneId + ".png";
            Image.GetAndSaveImage(qrcodePreUrl, HttpContext.Current.Server.MapPath(qrcode.Path));

            qrcodeRepository.Insert(qrcode);
            return(qrcode);
        }
        public ActionResult Index(long id)
        {
            WeiActivityModel activityModelByBigWheel = WeiActivityApplication.GetActivityModelByBigWheel(id);

            activityModelByBigWheel.userId = this.curUserId;
            int availableIntegrals = this._iMemberIntegralService.GetMemberIntegral(this.curUserId).AvailableIntegrals;

            activityModelByBigWheel.participationCount = this.GetParticipationCount(activityModelByBigWheel);
            this.consumePoint = activityModelByBigWheel.consumePoint;
            ((dynamic)base.ViewBag).Integrals = availableIntegrals;
            try
            {
                string ticket = QrCodeApi.Create(AccessTokenContainer.TryGetToken(this._siteSetting.WeixinAppId, this._siteSetting.WeixinAppSecret, false), 0x15180, 0x7661b3, 0x2710).ticket;
                ((dynamic)base.ViewBag).QRTicket = ticket;
            }
            catch
            {
            }
            return(base.View(activityModelByBigWheel));
        }
Beispiel #21
0
        public APIResult <string> GetLoginQRCodeUrl([FromBody] GetLoginQRCodeUrlArgsModel args)
        {
            if (string.IsNullOrEmpty(args.ClientId))
            {
                throw new ArgumentNullException("clientId");
            }
            WechatQRScene model = new WechatQRScene()
            {
                Category     = "Login",
                Status       = WechatQRSceneStatus.未处理,
                QrCodeTicket = ""
            };

            wechatCoreDb.AddToWechatQRScene(model);
            wechatCoreDb.SaveChanges();


            var b = model.Id / 4294967295;

            model.SceneId = (int)(model.Id - 4294967295 * b);

            var accessToken = GetAccessToken();
            var qrResult    = QrCodeApi.Create(accessToken, 60 * 5, model.SceneId, QrCode_ActionName.QR_SCENE);

            model.QrCodeTicket = qrResult.ticket;
            wechatCoreDb.AddToMemberWeChatLoginTask(new MemberWeChatLoginTask()
            {
                AddIp    = GetIp(),
                AddTime  = DateTime.Now,
                Code     = model.SceneId.ToString(),
                OpenId   = "",
                ClientId = args.ClientId,
                Status   = MemberWeChatLoginTaskStatus.扫二维码进行中
            });
            wechatCoreDb.SaveChanges();

            var url = QrCodeApi.GetShowQrCodeUrl(model.QrCodeTicket);

            return(Success <string>(url));
        }
 public void UpdateQRCode(QrCodeMPItem thisqr, int newappid, string isUpdate)
 {
     if (thisqr.UpdatedDate.Value.AddMonths(1) < DateTime.Now || isUpdate.Equals("true"))
     {
         var config = WeChatCommonService.GetWeChatConfigByID(newappid);
         var result = QrCodeApi.Create(config.WeixinAppId, config.WeixinCorpSecret, 2592000, (int)thisqr.SceneId);
         if (result.errcode == Weixin.ReturnCode.请求成功)
         {
             var user = _WechatMPUserService.Repository.Entities.Where(u => u.Id == thisqr.RelatedUserId);
             if (user.Any())
             {
                 var    userinfo    = Innocellence.Weixin.MP.AdvancedAPIs.UserApi.Info(config.WeixinCorpId, config.WeixinCorpSecret, user.FirstOrDefault().OpenId);
                 string userHeadUrl = userinfo.headimgurl;
                 var    qrurl       = QrCodeApi.GetShowQrCodeUrl(result.ticket);
                 thisqr.Url         = CombineQrCodeAndHeadImg(userHeadUrl, qrurl);
                 thisqr.UpdatedDate = DateTime.Now;
             }
         }
         ///重新更新当前model
         _QrCodeService.Repository.Update(thisqr);
     }
 }
Beispiel #23
0
        public JsonResult getWinxin(string pluginId, string destination)
        {
            long uid         = ShopApplication.GetShopManagers(CurrentSellerManager.ShopId);
            var  siteSetting = SiteSettingApplication.SiteSettings;

            //微信二维码
            if (string.IsNullOrWhiteSpace(siteSetting.WeixinAppId) || string.IsNullOrWhiteSpace(siteSetting.WeixinAppSecret))
            {
                throw new MallException("未配置公众号参数");
            }
            var token = AccessTokenContainer.TryGetAccessToken(siteSetting.WeixinAppId, siteSetting.WeixinAppSecret);

            SceneModel scene = new SceneModel(QR_SCENE_Type.Binding)
            {
                Object = uid.ToString()
            };
            SceneHelper helper  = new SceneHelper();
            var         sceneid = helper.SetModel(scene);
            var         ticket  = QrCodeApi.Create(token, 300, sceneid, Senparc.Weixin.MP.QrCode_ActionName.QR_LIMIT_SCENE, null);

            return(Json(new { success = true, msg = "成功", ticket = ticket.ticket, Sceneid = sceneid }));
        }
Beispiel #24
0
        public ActionResult Index(long id)
        {
            WeiActivityModel activityModel = WeiActivityApplication.GetActivityModelByBigWheel(id);

            activityModel.userId             = curUserId;
            activityModel.participationCount = GetParticipationCount(activityModel);
            consumePoint = activityModel.consumePoint;

            ViewBag.Integrals = MemberIntegralApplication.GetAvailableIntegral(curUserId);

            //TODO:改成统一的方式取 Token
            try
            {
                var settings = SiteSettingApplication.SiteSettings;
                var token    = AccessTokenContainer.TryGetAccessToken(settings.WeixinAppId, settings.WeixinAppSecret);
                //  var qrTicket = QrCodeApi.Create(token, 86400, 7758259).ticket;

                string qrTicket = QrCodeApi.Create(token, 86400, 7758259, QrCode_ActionName.QR_LIMIT_SCENE, null, 10000).ticket;

                ViewBag.QRTicket = qrTicket;
            }
            catch { }
            return(View(activityModel));
        }
Beispiel #25
0
        public ActionResult Index(long id)
        {
            //TODO:改成统一的方式取 Token
            var settings = SiteSettingApplication.SiteSettings;

            if (settings.IsOpenH5)
            {
                var token = AccessTokenContainer.TryGetAccessToken(settings.WeixinAppId, settings.WeixinAppSecret);

                SceneHelper helper   = new SceneHelper();
                var         qrTicket = QrCodeApi.Create(token, 86400, 7758258, Senparc.Weixin.MP.QrCode_ActionName.QR_LIMIT_SCENE, null).ticket;

                ViewBag.QRTicket = qrTicket;
            }

            WeiActivityModel activityModel = WeiActivityApplication.GetActivityModel(id);

            activityModel.userId             = curUserId;
            activityModel.winModel           = AddWinInfo(activityModel);
            activityModel.winModel.integrals = MemberIntegralApplication.GetAvailableIntegral(curUserId);
            activityModel.participationCount = GetParticipationCount(activityModel);
            consumePoint = activityModel.consumePoint;
            return(View(activityModel));
        }
        public ActionResult Detail(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(RedirectToAction("Error404", "Error", new { area = "Web" }));
            }
            string price = "";

            #region 定义Model和变量

            LimitTimeProductDetailModel model = new LimitTimeProductDetailModel
            {
                MainId = long.Parse(id),
                HotAttentionProducts = new List <HotProductInfo>(),
                HotSaleProducts      = new List <HotProductInfo>(),
                Product      = new Entities.ProductInfo(),
                Shop         = new ShopInfoModel(),
                ShopCategory = new List <CategoryJsonModel>(),
                Color        = new CollectionSKU(),
                Size         = new CollectionSKU(),
                Version      = new CollectionSKU()
            };

            FlashSaleModel    market = null;
            Entities.ShopInfo shop   = null;

            long gid = 0, mid = 0;

            #endregion


            #region 商品Id不合法
            if (long.TryParse(id, out mid))
            {
            }
            if (mid == 0)
            {
                //跳转到出错页面
                return(RedirectToAction("Error404", "Error", new { area = "Web" }));
            }
            #endregion


            #region 初始化商品和店铺

            market = _iLimitTimeBuyService.Get(mid);

            switch (market.Status)
            {
            case Entities.FlashSaleInfo.FlashSaleStatus.Ended:
                return(RedirectToAction("Detail", "Product", new { id = market.ProductId }));

            case Entities.FlashSaleInfo.FlashSaleStatus.Cancelled:
                return(RedirectToAction("Detail", "Product", new { id = market.ProductId }));
            }
            if (market.Status != Entities.FlashSaleInfo.FlashSaleStatus.Ongoing)
            {
                return(RedirectToAction("Home"));
            }
            model.FlashSale = market;
            if (market == null || market.Id == 0 || market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
            {
                //可能参数是商品ID
                market = market == null?_iLimitTimeBuyService.GetFlaseSaleByProductId(mid) : market;

                if (market == null)
                {
                    //跳转到404页面
                    return(RedirectToAction("Error404", "Error", new { area = "Mobile" }));
                }
                if (market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
                {
                    return(RedirectToAction("Detail", "Product", new { id = market.ProductId }));
                }
            }

            model.MaxSaleCount = market.LimitCountOfThePeople;
            model.Title        = market.Title;

            shop            = _iShopService.GetShop(market.ShopId);
            model.Shop.Name = shop.ShopName;
            #endregion

            #region 商品描述
            var product = _iProductService.GetProduct(market.ProductId);
            gid = market.ProductId;


            var brandModel = ServiceApplication.Create <IBrandService>().GetBrand(product.BrandId);
            product.BrandName = brandModel == null ? "" : brandModel.Name;
            if (CurrentUser != null && CurrentUser.Id > 0)
            {
                product.IsFavorite = ProductManagerApplication.IsFavorite(product.Id, CurrentUser.Id);
            }
            model.Product = product;
            model.Skus    = ProductManagerApplication.GetSKUsByProduct(new List <long> {
                product.Id
            });
            var description = ProductManagerApplication.GetProductDescription(product.Id);
            model.ProductDescription = description.Description;
            if (description.DescriptionPrefixId != 0)
            {
                var desc = _iProductDescriptionTemplateService
                           .GetTemplate(description.DescriptionPrefixId, product.ShopId);
                model.DescriptionPrefix = desc == null ? "" : desc.Content;
            }

            if (description.DescriptiondSuffixId != 0)
            {
                var desc = _iProductDescriptionTemplateService
                           .GetTemplate(description.DescriptiondSuffixId, product.ShopId);
                model.DescriptiondSuffix = desc == null ? "" : desc.Content;
            }

            #endregion

            #region 店铺

            var categories = _iShopCategoryService.GetShopCategory(product.ShopId);
            List <Entities.ShopCategoryInfo> allcate = categories.ToList();
            foreach (var main in allcate.Where(s => s.ParentCategoryId == 0))
            {
                var topC = new CategoryJsonModel()
                {
                    Name        = main.Name,
                    Id          = main.Id.ToString(),
                    SubCategory = new List <SecondLevelCategory>()
                };
                foreach (var secondItem in allcate.Where(s => s.ParentCategoryId == main.Id))
                {
                    var secondC = new SecondLevelCategory()
                    {
                        Name = secondItem.Name,
                        Id   = secondItem.Id.ToString(),
                    };

                    topC.SubCategory.Add(secondC);
                }
                model.ShopCategory.Add(topC);
            }
            model.CashDeposits = _iCashDepositsService.GetCashDepositsObligation(product.Id);

            #endregion

            #region 热门销售

            //会员折扣
            decimal discount   = 1M;
            long    SelfShopId = 0;
            if (CurrentUser != null)
            {
                discount = CurrentUser.MemberDiscount;
                var shopInfo = ShopApplication.GetSelfShop();
                SelfShopId = shopInfo.Id;
            }
            var sale = _iProductService.GetHotSaleProduct(shop.Id, 5);
            if (sale != null)
            {
                foreach (var item in sale.ToArray())
                {
                    var salePrice = item.MinSalePrice;
                    if (item.ShopId == SelfShopId)
                    {
                        salePrice = item.MinSalePrice * discount;
                    }
                    var limitBuy = LimitTimeApplication.GetLimitTimeMarketItemByProductId(item.Id);
                    if (limitBuy != null)
                    {
                        salePrice = limitBuy.MinPrice;
                    }
                    model.HotSaleProducts.Add(new HotProductInfo
                    {
                        ImgPath   = item.ImagePath,
                        Name      = item.ProductName,
                        Price     = Math.Round(salePrice, 2),
                        Id        = item.Id,
                        SaleCount = (int)item.SaleCounts + Mall.Core.Helper.TypeHelper.ObjectToInt(item.VirtualSaleCounts)
                    });
                }
            }

            #endregion

            #region 热门关注

            var hot = _iProductService.GetHotConcernedProduct(shop.Id, 5);
            if (hot != null)
            {
                foreach (var item in hot.ToArray())
                {
                    model.HotAttentionProducts.Add(new HotProductInfo
                    {
                        ImgPath   = item.ImagePath,
                        Name      = item.ProductName,
                        Price     = item.MinSalePrice,
                        Id        = item.Id,
                        SaleCount = (int)item.ConcernedCount
                    });
                }
            }
            #endregion

            #region 商品规格

            Entities.TypeInfo typeInfo     = _iTypeService.GetType(product.TypeId);
            string            colorAlias   = (typeInfo == null || string.IsNullOrEmpty(typeInfo.ColorAlias)) ? SpecificationType.Color.ToDescription() : typeInfo.ColorAlias;
            string            sizeAlias    = (typeInfo == null || string.IsNullOrEmpty(typeInfo.SizeAlias)) ? SpecificationType.Size.ToDescription() : typeInfo.SizeAlias;
            string            versionAlias = (typeInfo == null || string.IsNullOrEmpty(typeInfo.VersionAlias)) ? SpecificationType.Version.ToDescription() : typeInfo.VersionAlias;
            if (product != null)
            {
                colorAlias   = !string.IsNullOrWhiteSpace(product.ColorAlias) ? product.ColorAlias : colorAlias;
                sizeAlias    = !string.IsNullOrWhiteSpace(product.SizeAlias) ? product.SizeAlias : sizeAlias;
                versionAlias = !string.IsNullOrWhiteSpace(product.VersionAlias) ? product.VersionAlias : versionAlias;
            }
            model.ColorAlias   = colorAlias;
            model.SizeAlias    = sizeAlias;
            model.VersionAlias = versionAlias;
            var skus = _iProductService.GetSKUs(product.Id);
            if (skus.Count > 0)
            {
                long colorId = 0, sizeId = 0, versionId = 0;
                foreach (var sku in skus)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 0 && !string.IsNullOrEmpty(sku.Color))
                    {
                        if (long.TryParse(specs[1], out colorId))
                        {
                        }
                        if (colorId != 0)
                        {
                            if (!model.Color.Any(v => v.Value.Equals(sku.Color)))
                            {
                                var c = skus.Where(s => s.Color.Equals(sku.Color)).Sum(s => s.Stock);
                                model.Color.Add(new ProductSKU
                                {
                                    //Name = "选择颜色",
                                    Name         = "选择" + colorAlias,
                                    EnabledClass = c != 0 ? "enabled" : "disabled",
                                    //SelectedClass = !model.Color.Any(c1 => c1.SelectedClass.Equals("selected")) && c != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = colorId,
                                    Value         = sku.Color,
                                    Img           = Mall.Core.MallIO.GetImagePath(sku.ShowPic)
                                });
                            }
                        }
                    }
                    if (specs.Count() > 1 && !string.IsNullOrEmpty(sku.Size))
                    {
                        if (long.TryParse(specs[2], out sizeId))
                        {
                        }
                        if (sizeId != 0)
                        {
                            if (!model.Size.Any(v => v.Value.Equals(sku.Size)))
                            {
                                var ss = skus.Where(s => s.Size.Equals(sku.Size)).Sum(s1 => s1.Stock);
                                model.Size.Add(new ProductSKU
                                {
                                    //Name = "选择尺码",
                                    Name         = "选择" + sizeAlias,
                                    EnabledClass = ss != 0 ? "enabled" : "disabled",
                                    //SelectedClass = !model.Size.Any(s1 => s1.SelectedClass.Equals("selected")) && ss != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = sizeId,
                                    Value         = sku.Size
                                });
                            }
                        }
                    }

                    if (specs.Count() > 2 && !string.IsNullOrEmpty(sku.Version))
                    {
                        if (long.TryParse(specs[3], out versionId))
                        {
                        }
                        if (versionId != 0)
                        {
                            if (!model.Version.Any(v => v.Value.Equals(sku.Version)))
                            {
                                var v = skus.Where(s => s.Version.Equals(sku.Version)).Sum(s => s.Stock);
                                model.Version.Add(new ProductSKU
                                {
                                    //Name = "选择版本",
                                    Name         = "选择" + versionAlias,
                                    EnabledClass = v != 0 ? "enabled" : "disabled",
                                    //SelectedClass = !model.Version.Any(v1 => v1.SelectedClass.Equals("selected")) && v != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = versionId,
                                    Value         = sku.Version
                                });
                            }
                        }
                    }
                }

                price = ProductWebApplication.GetProductPriceStr(product, skus, discount);//最小价或区间价文本
            }
            model.Price = string.IsNullOrWhiteSpace(price) ? product.MinSalePrice.ToString("f2") : price;
            #endregion

            #region 商品属性
            List <TypeAttributesModel> ProductAttrs = new List <TypeAttributesModel>();
            var prodAttrs = ProductManagerApplication.GetProductAttributes(product.Id);
            foreach (var attr in prodAttrs)
            {
                if (!ProductAttrs.Any(p => p.AttrId == attr.AttributeId))
                {
                    var attribute = _iTypeService.GetAttribute(attr.AttributeId);
                    var values    = _iTypeService.GetAttributeValues(attr.AttributeId);
                    var attrModel = new TypeAttributesModel()
                    {
                        AttrId     = attr.AttributeId,
                        AttrValues = new List <TypeAttrValue>(),
                        Name       = attribute.Name
                    };
                    foreach (var attrV in values)
                    {
                        if (prodAttrs.Any(p => p.ValueId == attrV.Id))
                        {
                            attrModel.AttrValues.Add(new TypeAttrValue
                            {
                                Id   = attrV.Id.ToString(),
                                Name = attrV.Value
                            });
                        }
                    }
                    ProductAttrs.Add(attrModel);
                }
                else
                {
                    var attrTemp = ProductAttrs.FirstOrDefault(p => p.AttrId == attr.AttributeId);
                    var values   = _iTypeService.GetAttributeValues(attr.AttributeId);
                    if (!attrTemp.AttrValues.Any(p => p.Id == attr.ValueId.ToString()))
                    {
                        attrTemp.AttrValues.Add(new TypeAttrValue
                        {
                            Id   = attr.ValueId.ToString(),
                            Name = values.FirstOrDefault(a => a.Id == attr.ValueId).Value
                        });
                    }
                }
            }
            model.ProductAttrs = ProductAttrs;
            #endregion

            #region 获取评论、咨询数量

            model.CommentCount = CommentApplication.GetCommentCountByProduct(product.Id);

            var consultations = _iConsultationService.GetConsultations(gid);
            model.Consultations = consultations.Count();

            #endregion

            #region 累加浏览次数、 加入历史记录
            if (CurrentUser != null)
            {
                BrowseHistrory.AddBrowsingProduct(product.Id, CurrentUser.Id);
            }
            else
            {
                BrowseHistrory.AddBrowsingProduct(product.Id);
            }

            //_iProductService.LogProductVisti(gid);
            //统计商品浏览量、店铺浏览人数
            StatisticApplication.StatisticVisitCount(product.Id, product.ShopId);
            #endregion

            #region 红包
            var bonus = ServiceApplication.Create <IShopBonusService>().GetByShopId(product.ShopId);
            if (bonus != null)
            {
                model.GrantPrice = bonus.GrantPrice;
            }
            else
            {
                model.GrantPrice = 0;
            }
            #endregion

            #region 获取店铺的评价统计

            var shopStatisticOrderComments = _iShopService.GetShopStatisticOrderComments(shop.Id);

            var productAndDescription = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescription).FirstOrDefault();
            var sellerServiceAttitude = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitude).FirstOrDefault();
            var sellerDeliverySpeed   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                         Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeed).FirstOrDefault();

            var productAndDescriptionPeer = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionPeer).FirstOrDefault();
            var sellerServiceAttitudePeer = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudePeer).FirstOrDefault();
            var sellerDeliverySpeedPeer   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                             Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedPeer).FirstOrDefault();

            var productAndDescriptionMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionMax).FirstOrDefault();
            var productAndDescriptionMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionMin).FirstOrDefault();

            var sellerServiceAttitudeMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudeMax).FirstOrDefault();
            var sellerServiceAttitudeMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudeMin).FirstOrDefault();

            var sellerDeliverySpeedMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedMax).FirstOrDefault();
            var sellerDeliverySpeedMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedMin).FirstOrDefault();

            decimal defaultValue = 5;
            //宝贝与描述
            if (productAndDescription != null && productAndDescriptionPeer != null)
            {
                ViewBag.ProductAndDescription     = productAndDescription.CommentValue;
                ViewBag.ProductAndDescriptionPeer = productAndDescriptionPeer.CommentValue;
                ViewBag.ProductAndDescriptionMin  = productAndDescriptionMin.CommentValue;
                ViewBag.ProductAndDescriptionMax  = productAndDescriptionMax.CommentValue;
            }
            else
            {
                ViewBag.ProductAndDescription     = defaultValue;
                ViewBag.ProductAndDescriptionPeer = defaultValue;
                ViewBag.ProductAndDescriptionMin  = defaultValue;
                ViewBag.ProductAndDescriptionMax  = defaultValue;
            }
            //卖家服务态度
            if (sellerServiceAttitude != null && sellerServiceAttitudePeer != null)
            {
                ViewBag.SellerServiceAttitude     = sellerServiceAttitude.CommentValue;
                ViewBag.SellerServiceAttitudePeer = sellerServiceAttitudePeer.CommentValue;
                ViewBag.SellerServiceAttitudeMax  = sellerServiceAttitudeMax.CommentValue;
                ViewBag.SellerServiceAttitudeMin  = sellerServiceAttitudeMin.CommentValue;
            }
            else
            {
                ViewBag.SellerServiceAttitude     = defaultValue;
                ViewBag.SellerServiceAttitudePeer = defaultValue;
                ViewBag.SellerServiceAttitudeMax  = defaultValue;
                ViewBag.SellerServiceAttitudeMin  = defaultValue;
            }
            //卖家发货速度
            if (sellerDeliverySpeedPeer != null && sellerDeliverySpeed != null)
            {
                ViewBag.SellerDeliverySpeed     = sellerDeliverySpeed.CommentValue;
                ViewBag.SellerDeliverySpeedPeer = sellerDeliverySpeedPeer.CommentValue;
                ViewBag.SellerDeliverySpeedMax  = sellerDeliverySpeedMax.CommentValue;
                ViewBag.sellerDeliverySpeedMin  = sellerDeliverySpeedMin.CommentValue;
            }
            else
            {
                ViewBag.SellerDeliverySpeed     = defaultValue;
                ViewBag.SellerDeliverySpeedPeer = defaultValue;
                ViewBag.SellerDeliverySpeedMax  = defaultValue;
                ViewBag.sellerDeliverySpeedMin  = defaultValue;
            }
            #endregion

            #region 客服
            model.Service = ServiceApplication.Create <ICustomerService>().GetCustomerService(shop.Id).Where(c => c.Type == Entities.CustomerServiceInfo.ServiceType.PreSale && c.TerminalType == Entities.CustomerServiceInfo.ServiceTerminalType.PC).OrderBy(m => m.Tool);
            #endregion

            #region 开团提醒场景二维码
            var siteSetting = SiteSettingApplication.SiteSettings;
            if (DateTime.Parse(model.FlashSale.BeginDate) > DateTime.Now && WXIsConfig(siteSetting.WeixinAppId, siteSetting.WeixinAppSecret))
            {
                try
                {
                    var         token   = AccessTokenContainer.TryGetAccessToken(siteSetting.WeixinAppId, siteSetting.WeixinAppSecret);
                    SceneHelper helper  = new SceneHelper();
                    SceneModel  scene   = new SceneModel(QR_SCENE_Type.FlashSaleRemind, model.FlashSale.Id);
                    int         sceneId = helper.SetModel(scene);
                    var         ticket  = QrCodeApi.Create(token, 86400, sceneId, Senparc.Weixin.MP.QrCode_ActionName.QR_LIMIT_SCENE, null).ticket;
                    ViewBag.ticket = ticket;
                }
                catch { }
            }
            #endregion

            model.Logined    = (null != CurrentUser) ? 1 : 0;
            model.EnabledBuy = product.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited && DateTime.Parse(market.BeginDate) <= DateTime.Now && DateTime.Parse(market.EndDate) > DateTime.Now && product.SaleStatus == Entities.ProductInfo.ProductSaleStatus.OnSale;
            if (market.Status == FlashSaleInfo.FlashSaleStatus.Ongoing && DateTime.Parse(market.BeginDate) < DateTime.Now && DateTime.Parse(market.EndDate) > DateTime.Now)
            {
                TimeSpan end   = new TimeSpan(DateTime.Parse(market.EndDate).Ticks);
                TimeSpan start = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts    = end.Subtract(start);
                model.Second = ts.TotalSeconds < 0 ? 0 : ts.TotalSeconds;
            }
            else if (market.Status == FlashSaleInfo.FlashSaleStatus.Ongoing && DateTime.Parse(market.BeginDate) > DateTime.Now)
            {
                TimeSpan end   = new TimeSpan(DateTime.Parse(market.BeginDate).Ticks);
                TimeSpan start = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts    = end.Subtract(start);
                model.Second = ts.TotalSeconds < 0 ? 0 : ts.TotalSeconds;
            }

            //补充当前店铺红包功能
            ViewBag.isShopPage     = true;
            ViewBag.CurShopId      = product.ShopId;
            TempData["isShopPage"] = true;
            TempData["CurShopId"]  = product.ShopId;

            ViewBag.Keyword          = SiteSettings.Keyword;
            ViewBag.Quantity         = market.Quantity;//总活动库存
            model.VirtualProductInfo = ProductManagerApplication.GetVirtualProductInfoByProductId(product.Id);
            model.FreightTemplate    = FreightTemplateApplication.GetFreightTemplate(product.FreightTemplateId);
            return(View(model));
        }
        public void CreateHaiBao(string fromUser, string toUser, string temppath)
        {
            OfficialAccount_BLL obll = new OfficialAccount_BLL();
            //OfficialAccount model = obll.Get(a => a.OriginalID == toUser);
            OfficialAccount model = obll.Get(a => a.OriginalID == "gh_9229f06559cd");



            if (!AccessTokenContainer.CheckRegistered(model.AppID))          //检查是否已经注册
            {
                AccessTokenContainer.Register(model.AppID, model.AppSecret); //如果没有注册则进行注册
            }
            try
            {
                Account_QRCode_Template aqt =
                    new Account_QRCode_Template_BLL().GetList(a => a.AccountID == model.AccountID)
                    .OrderByDescending(a => a.CreateTime)
                    .FirstOrDefault();

                QRCode_Template temp = new QRCode_Template_BLL().Get(a => a.TemplateID == aqt.TemplateID);



                DateTime now = DateTime.Now.AddMinutes(-2);
                WS.Utility.FileHelper.DeleteFilesBeforeTime(temppath, now);



                WebClient    wc = new WebClient();
                ICredentials cred;
                cred = new NetworkCredential("user-22", "user-22");

                WebProxy wp = new WebProxy("http://172.18.226.109:808/", true, null, cred);
                wc.Proxy = wp;
                //下载原图
                //string yuanfilename = Guid.NewGuid().ToString() + ".png";
                string yuanlocalfilename =
                    temppath + Guid.NewGuid().ToString() + ".jpg";
                //wc.DownloadFile(ConfigurationManager.AppSettings["QiNiuDomain"] + model.QRCodeBgImg, yuanlocalfilename);
                wc.DownloadFile("http://qiniu.weixin.hairuiit.com/" + aqt.QRCodeBgImg, yuanlocalfilename);


                Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson uij =
                    Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(model.AppID, fromUser);
                //加入昵称
                string savename1 = temppath + Guid.NewGuid().ToString() + ".jpg";
                ImageHelper.Add_FontMark(yuanlocalfilename, savename1, uij.nickname, temp.NickName_FontFamily, (int)temp.NickName_FontSize, Color.Black, (int)temp.NickName_FontX, (int)temp.NickName_FontY);

                //下载头像
                string touxiang = temppath + Guid.NewGuid().ToString() + ".png";
                wc.DownloadFile(uij.headimgurl, touxiang);
                //下载二维码
                // Senparc.Weixin.MP.AdvancedAPIs.QrCode.CreateQrCodeResult createQrCodeResult =QrCodeApi.CreateByStr(model.AppID, fromUser);
                Senparc.Weixin.MP.AdvancedAPIs.QrCode.CreateQrCodeResult createQrCodeResult = QrCodeApi.Create(model.AppID, 0, 0, Senparc.Weixin.MP.QrCode_ActionName.QR_LIMIT_STR_SCENE, fromUser);
                string localcodefile =
                    temppath + Guid.NewGuid().ToString() + ".png";
                wc.DownloadFile(QrCodeApi.GetShowQrCodeUrl(createQrCodeResult.ticket), localcodefile);
                wc.Dispose();

                ///加头像

                string savename2 = temppath + Guid.NewGuid().ToString() + ".jpg";

                ImageHelper.Add_ImageMark(savename1, touxiang, savename2, (int)temp.HeadImg_X, (int)temp.HeadImg_Y, (int)temp.HeadImg_Width, (int)temp.HeadImg_Height);



                string savename3 = temppath + Guid.NewGuid().ToString() + ".jpg";

                ImageHelper.Add_ImageMark(savename2, localcodefile, savename3, (int)temp.QRCode_X, (int)temp.QRCode_Y, (int)temp.QRCode_Width, (int)temp.QRCode_Height);

                Senparc.Weixin.MP.AdvancedAPIs.Media.UploadTemporaryMediaResult media =
                    Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(model.AppID,
                                                                                 Senparc.Weixin.MP.UploadMediaFileType.image, savename3);

                Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(model.AppID, fromUser,
                                                                  "专属海报已经接收成功,请保存到手机相册,分享海报兑换奖品哦!");
                Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendImage(model.AppID, fromUser,
                                                                   media.media_id);


                Thread.Sleep(6000);
                WS.Utility.FileHelper.Delete(yuanlocalfilename);
                WS.Utility.FileHelper.Delete(savename1);
                WS.Utility.FileHelper.Delete(savename2);
                WS.Utility.FileHelper.Delete(savename3);
                WS.Utility.FileHelper.Delete(touxiang);
                WS.Utility.FileHelper.Delete(localcodefile);


                //var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
                //responseMessage.Content = "生成成功";
                //return responseMessage;

                //return null;
            }
            catch (Exception ex)
            {
                //LogHelper.ErrorInfo(ex);
                //Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(model.AppID, requestMessage.FromUserName,
                //    ex.Message.ToString());
                Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(model.AppID, fromUser,
                                                                  ex.ToString());
            }
        }