public void PayPendingModel(BillModel billModel)
        {
            var p = new PayModel();

            p.PhoneNumber = billModel.PhoneNumber;
            p.Amount      = billModel.Amount;
            //Pay(p);

            var user = _userRepository.GetUserByPhoneNumber(p.PhoneNumber);

            if (user.Amount < p.Amount)
            {
                throw new Exception("Not enough money! Top up first.");
            }
            else

            {
                if (p.Amount - (int)p.Amount != 0)
                {
                    double x      = Math.Ceiling(p.Amount);
                    double change = x - p.Amount;
                    _userRepository.AddToUserPocket(p.PhoneNumber, change);
                }
                user.Amount = user.Amount - (int)Math.Ceiling(p.Amount);
                _userRepository.UpdateUser(user);
                _billsRepository.UpdateBill(billModel);
            }
        }
        public void Pay(PayModel payModel)
        {
            var user = _userRepository.GetUserByPhoneNumber(payModel.PhoneNumber);

            if (user.Amount < payModel.Amount)
            {
                throw new Exception("Not enough money! Top up first.");
            }
            else

            {
                if (payModel.Amount - (int)payModel.Amount != 0)
                {
                    double x      = Math.Ceiling(payModel.Amount);
                    double change = x - payModel.Amount;
                    _userRepository.AddToUserPocket(payModel.PhoneNumber, change);
                }

                //user.Amount = user.Amount - (int)Math.Ceiling(payModel.Amount);
                //_userRepository.UpdateUser(user);
                var l = new List <string>();
                l.Add(user.PhoneNumber);
                var b = new Bill(new GroupKey("11", "213"), payModel.Amount);
                _billsRepository.AddBill(b);

                _billsRepository.AddBillMemberAmount(l, b, payModel.Amount);
            }
        }
        public async Task <IActionResult> Pay([FromRoute] PayModel model, [FromForm] PersonalPortalModel bodyModel)
        {
            string mechantId      = "dd5c225c-bbf5-11e9-9621-000c295eb8fc";
            var    personalPortal = await _personalPortalService.GetPersonalPortal(model);

            bodyModel.Price       = !string.IsNullOrEmpty(personalPortal.Price) ? personalPortal.Price : bodyModel.Price;
            bodyModel.Description = !string.IsNullOrEmpty(personalPortal.Description) ? personalPortal.Description : bodyModel.Description;
            var payment = new Zarinpal.Payment(mechantId, int.Parse(bodyModel.Price));

            var retUrl = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, $"PersonalPortal/PayReturn");

            var requestResult = await payment.PaymentRequest(bodyModel.Description, retUrl);

            if (requestResult.Status == 100)
            {
                await _paymentService.CreateRequest(new CreateRequest
                {
                    Status           = requestResult.Status,
                    Authority        = requestResult.Authority,
                    Link             = requestResult.Link,
                    PersonalPortalId = personalPortal.ID,
                    Description      = bodyModel.Description,
                    Price            = bodyModel.Price
                });

                return(Redirect(requestResult.Link));
            }
            return(View(bodyModel));
        }
Exemple #4
0
        /**
         * 调用统一下单,获得下单结果
         * @return 统一下单结果
         * @失败时抛异常WxPayException
         */
        public WxPayData GetUnifiedOrderResult(PayModel payInfo, WxPayConfig payConfig)
        {
            //统一下单 字段最长保存为128
            WxPayData data = new WxPayData();

            data.SetValue("body", payInfo.product_name);
            data.SetValue("attach", payInfo.jsonProduct);
            data.SetValue("out_trade_no", payInfo.trade_no);
            data.SetValue("total_fee", payInfo.total_fee);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", "零售");
            data.SetValue("trade_type", "JSAPI");
            data.SetValue("openid", payInfo.openid);

            WxPayData result = WxPayApi.UnifiedOrder(data, payConfig);

            // Log.Write("GetDataW", result.IsSet("appid").ToString() + "~" + result.IsSet("prepay_id").ToString() + "~" + result.GetValue("prepay_id").ToString());
            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                throw new WxPayException("UnifiedOrder response error!");
            }

            payInfo.unifiedOrderResult = result;
            return(result);
        }
 internal void Pay(PayModel modelPay)
 {
     using (var db = Base.storeDataBaseContext)
     {
         db.Pay(modelPay.packId, this.userId, modelPay.countInBasket, modelPay.payDate, modelPay.transactionNumber, Math.Round(modelPay.totalSumm, 2));
     }
 }
Exemple #6
0
        public async Task <ActionResult <PayModel> > Put(int employeeId, int Id, PayModel updatedModel)
        {
            try
            {
                var currentPay = await _repository.GetPayAsync(employeeId, Id);

                if (currentPay == null)
                {
                    return(NotFound($"Could not find Pay with Id of {Id}"));
                }

                _mapper.Map(updatedModel, currentPay);

                if (await _repository.UpdatePayAsync(employeeId, currentPay))
                {
                    return(_mapper.Map <PayModel>(currentPay));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure"));
            }

            return(BadRequest());
        }
Exemple #7
0
        public ActionResult Pay(PayModel model)
        {
            if (model == null || String.IsNullOrEmpty(model.Email) || String.IsNullOrEmpty(model.Name) ||
                String.IsNullOrEmpty(model.Phone) || model.Sum < 0)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var robokassa = new RobokassaService(model.Name, model.Email, model.Phone, model.Sum);

            robokassa.CalcOutSum(); //calculate out sum for bank card way of payment


            var redirectModel = new RedirectPaymetModel()
            {
                Sum             = robokassa.Sum,
                Signature       = robokassa.Signature,
                MerchantLogin   = robokassa.MerchantLogin,
                Email           = robokassa.Email,
                EmailUrlEncoded = robokassa.EmailUrlEncoded,
                Name            = robokassa.Name,
                NameUrlEncoded  = robokassa.NameUrlEncoded,
                Phone           = robokassa.Phone,
                PhoneUrlEncoded = robokassa.PhoneUrlEncoded,
                IncCurrLabel    = robokassa.IncCurrLabel
            };

            return(View("PayPlatformRedirect", redirectModel));
        }
Exemple #8
0
        private PayModel EntityToModel(DataRow dr)
        {
            if (dr != null)
            {
                PayModel model = new PayModel();
                model.ID = dr["id"].ToInt();
                model.AuthorizerAppID = dr["authorizer_appid"].ToString();
                model.OpenID          = dr["openid"].ToString();
                model.OutTradeNo      = dr["out_trade_no"].ToString();
                model.TotalFee        = dr["total_fee"].ToInt();
                model.Body            = dr["body"].ToString();
                model.PayType         = dr["pay_type"].ToInt();
                model.TradeNo         = dr["trade_no"].ToString();
                model.RealFee         = dr["real_fee"].ToInt();
                model.TradeState      = dr["trade_state"].ToString();
                model.PayState        = dr["pay_state"].ToInt();
                model.PayTime         = dr["pay_time"].ToDateTime();

                model.RefundFee  = dr["refund_fee"].ToInt();
                model.RefundTime = dr["refund_time"].ToDateTime();

                model.CreateTime = dr["create_time"].ToDateTime();
                model.UpdateTime = dr["update_time"].ToDateTime();
                return(model);
            }
            return(null);
        }
        /// <summary>
        /// 初始化
        /// </summary>
        public override async void InitViewModel()
        {
            base.InitViewModel();
            Store        = "999.00";
            PayModelList = new ObservableCollection <PayModel>();

            List <string> listPayList = new List <string> {
                "今日充值", "今日耗卡", "今日赠送", "储值金额"
            };

            listPayList.ForEach((ary) =>
            {
                PayModel model = new PayModel()
                {
                    Type  = ary,
                    Money = Convert.ToDecimal(Common.GetRandomSeed())
                };
                PayModelList.Add(model);
            });

            //Get Zcgllist
            var assstEntity = await RequestConver.DataRequest <UcZcglEntity> .GetModelList();

            if (assstEntity != null && assstEntity.Count != 0)
            {
                assstEntity.ForEach((ary) => GridModelList.Add(ary));
            }
        }
Exemple #10
0
        public ApiMessage <OutPayModel> CkeckData(PayModel pm, CurrentUser user)
        {
            var res = new ApiMessage <OutPayModel>();

            res.Success = false;
            res.Msg     = "数据有误";
            var oData = new OutPayModel();

            if (pm.Type == "order")
            {
                var oModel  = odal.Get(pm.OrderNo);
                var oModeld = odal.GetOrder(pm.OrderNo).rows;
                if (oModel.Money != pm.Money)
                {
                    return(res);
                }

                oData.Subject = "购买商品";
                foreach (var item in oModeld)
                {
                    oData.Body = oData.Body + item.ProductName + "/" + item.UnitName + " ";
                }
                oData.TotalAmount = pm.Money;
                Random rd = new Random();
                oModel.PayOrderNo = oModel.OrderNo + rd.Next(1000, 10000);
                oModel.Update();
                oData.OutTradeNo = oModel.PayOrderNo;
            }
            else
            {
                var sModel = sdal.GetOptByType("member").FirstOrDefault(n => n.ID == pm.OrderNo);
                if (sModel.OptionValue2 != pm.Money.ToString())
                {
                    return(res);
                }
                oData.Subject     = "购买会员";
                oData.Body        = sModel.OptionValue1;
                oData.TotalAmount = Convert.ToDecimal(sModel.OptionValue2);
                var payNo = CodeNo.Get(CodeType.VIP);
                oData.OutTradeNo = payNo;
                var mb = new member();
                mb.Money   = oData.TotalAmount;
                mb.ID      = Guid.NewGuid().ToString();
                mb.State   = "待支付";
                mb.UserID  = user.Id;
                mb.ProName = sModel.OptionValue1;

                mb.ProID      = sModel.ID;
                mb.CreateDate = DateTime.Now;
                mb.PMoney     = 0;
                mb.OrderNo    = payNo;
                mb.PayOrderNo = payNo;
                mb.Insert();
            }
            res.Data    = oData;
            res.Msg     = "";
            res.Success = true;
            LogHelper.WriteLog("支付请求:" + JsonConvert.SerializeObject(res.Data), LogHelper.LogType.Info);
            return(res);
        }
Exemple #11
0
        /**
         * pay接口:       星云地址之间的转账
         * @param goods   商品详情
         * @param to      转账目标地址
         * @param value   转账value,单位为wei (1NAS =10^18 wei)
         */
        public static void Pay(GoodsModel goods, String to, String value, String serialNumber)
        {
            OpenAppMode openAppMode = new OpenAppMode();

            openAppMode.category = Constants.CATEGORY;
            openAppMode.des      = Constants.DESCRIPTION;

            PageParamsModel pageParamsModel = new PageParamsModel();

            pageParamsModel.serialNumber = serialNumber;
            pageParamsModel.callback     = isMainnet ? mainnetUrl : testnetUrl;
            pageParamsModel.goods        = goods;

            PayloadModel payloadModel = new PayloadModel();

            payloadModel.type = Constants.PAY_PAYLOAD_TYPE;

            PayModel payModel = new PayModel();

            payModel.currency = Constants.PAY_CURRENCY;
            payModel.payload  = payloadModel;
            payModel.value    = value;
            payModel.to       = to;

            pageParamsModel.pay = payModel;

            openAppMode.pageParams = pageParamsModel;

            String _params = OpenAppMode.getOpenAppModel(openAppMode);

            String url = OpenAppSchema.getSchemaUrl(_params);

            ContractAction.start(url);
        }
Exemple #12
0
/// <summary>
/// 更新信息
/// </summary>
        public int UpdateInfo(SqlTransaction trans, PayModel payModel, int PayId)
        {
            string key = "Cache_Pay_Model_" + PayId;

            CacheHelper.RemoveCache(key);
            return(payDAL.UpdateInfo(trans, payModel, PayId));
        }
Exemple #13
0
        //public PayModel payInfo = new PayModel();

        /**
         *
         * 网页授权获取用户基本信息的全部过程
         * 详情请参看网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
         * 第一步:利用url跳转获取code
         * 第二步:利用code去获取openid和access_token
         *
         */
        public void GetOpenidAndAccessToken(string code, WxPayConfig payConfig, PayModel payInfo, string urlParam, string scopeTyp)
        {
            if (code != "-1")
            {
                //获取code码,以获取openid和access_token
                GetOpenidAndAccessTokenFromCode(code, payConfig, payInfo);
            }
            else
            {
                //构造网页授权获取code的URL
                string    redirect_uri = HttpUtility.UrlEncode(payConfig.FRONT_URL + urlParam);
                WxPayData data         = new WxPayData();
                data.SetValue("appid", payConfig.APPID);
                data.SetValue("redirect_uri", redirect_uri);
                data.SetValue("response_type", "code");
                data.SetValue("scope", string.IsNullOrEmpty(scopeTyp) ? "snsapi_base": scopeTyp); // snsapi_userinfo
                data.SetValue("state", "STATE" + "#wechat_redirect");
                string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
                try
                {
                    //触发微信返回code码
                    // page.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常

                    payInfo.redirect_url = url;
                }
                catch (System.Threading.ThreadAbortException ex)
                {
                }
            }
        }
Exemple #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                webinfo = new TravelAgent.BLL.WebInfo().loadConfig(Server.MapPath(ConfigurationManager.AppSettings["WebInfoConfig"].ToString()));
                if (webinfo == null)
                {
                    Response.Write("配置信息获取错误!");
                    Response.End();
                }
                //获取当前用户的OpenId,如果可以通过系统获取用户Openid就不用调用该函数
                this.GetUserOpenId();
                LogUtil.WriteLog("数据0" + Request["o"]);
                LogUtil.WriteLog("数据total_fee" + Request["total_fee"]);
                LogUtil.WriteLog("数据subject" + Request["subject"]);
                //设置支付数据
                PayModel model = new PayModel();
                model.OrderSN = Request.QueryString["o"];
                model.TotalFee = int.Parse(Request.QueryString["total_fee"]);
                model.Body = Request.QueryString["subject"];
                model.Attach = ""; //不能有中午
                model.OpenId = this.UserOpenId;

                //跳转到 WeiPay.aspx 页面,请设置函数中WeiPay.aspx的页面地址
                this.Response.Redirect(model.ToString());
            }
        }
        public async Task <IActionResult> Pay([FromRoute] PayModel model)
        {
            model.PersonalPortalId += "pay";
            var result = await _personalPortalService.GetPersonalPortal(model);

            return(View(result));
        }
Exemple #16
0
        public ApiMessage <string> Alipay(PayModel pm)
        {
            var                    api    = new ApiMessage <string>();
            IAopClient             client = new DefaultAopClient(URL, APPID, APP_PRIVATE_KEY, "json", "1.0", RSA2, ALIPAY_PUBLIC_KEY, CHARSET, false);
            AlipayTradeAppPayModel model  = new AlipayTradeAppPayModel();
            var                    res    = bll.CkeckData(pm, UserInfo);

            if (!res.Success)
            {
                api.Success = false;
                api.Msg     = res.Msg;
                return(api);
            }
            var oData = res.Data;

            model.Body        = oData.Body;
            model.Subject     = oData.Subject;
            model.TotalAmount = oData.TotalAmount.ToString();
            model.ProductCode = "QUICK_MSECURITY_PAY";
            model.OutTradeNo  = oData.OutTradeNo;


            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();

            request.SetBizModel(model);
            request.SetNotifyUrl(ConfigHelper.WebSiteUrl + "/api/payment/updateorder/alipay");
            AlipayTradeAppPayResponse response = client.SdkExecute(request);

            api.Data = response.Body;
            return(api);
        }
Exemple #17
0
        public async Task <ActionResult> Payment(Payment payment)
        {
            //var userIp = HttpContext.Request.Host;
            var _IP = "RemoteIp:" + Request.HttpContext.Connection.RemoteIpAddress.ToString() + " - LocalIpAddress:" +
                      Request.HttpContext.Connection.LocalIpAddress;

            String payendpoint  = configuration.GetValue <string>("SecurePay:Endpoint") + configuration.GetValue <string>("SecurePay:PayAPI");
            String merchantcode = configuration.GetValue <string>("SecurePay:MerchantCode");

            var authValue = new AuthenticationHeaderValue("Bearer", payment.AccessToken);

            var authValueString = authValue.ToString();

            var IdempotencyKey = Guid.NewGuid();

            client.DefaultRequestHeaders.Authorization = authValue;
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Idempotency-Key", IdempotencyKey.ToString());

            var payModel = new PayModel
            {
                merchantCode = merchantcode,
                amount       = payment.Amount,
                token        = payment.Token,
                ip           = Request.HttpContext.Connection.RemoteIpAddress.ToString()
            };
            string json          = JsonConvert.SerializeObject(payModel);
            var    stringContent = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PostAsync(payendpoint, stringContent);

            var responseString = await response.Content.ReadAsStringAsync();

            return(Ok(responseString));
        }
Exemple #18
0
        public async Task <ActionResult <PayModel> > Post(int employeeId, PayModel model)
        {
            try
            {
                //Make sure PayId is not already taken
                var existing = await _repository.GetPayAsync(employeeId, model.Id);

                if (existing != null)
                {
                    return(BadRequest("Pay Id in Use"));
                }

                //map
                var Pay = _mapper.Map <Pay>(model);

                //save and return
                if (!await _repository.StoreNewPayAsync(employeeId, Pay))
                {
                    return(BadRequest("Bad request, could not create record!"));
                }
                else
                {
                    var location = _linkGenerator.GetPathByAction("Get",
                                                                  "Pay",
                                                                  new { employeeId = Pay.EmployeeId, Pay.Id });

                    return(Created(location, _mapper.Map <PayModel>(Pay)));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure"));
            }
        }
Exemple #19
0
        public void SurePay(PayModel model)
        {
            ////////////////////////////////////////////////////////////////////////////////////////////////

            //把请求参数打包成数组
            SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>();

            sParaTemp.Add("service", Config.service);
            sParaTemp.Add("partner", Config.partner);
            sParaTemp.Add("seller_id", Config.seller_id);
            sParaTemp.Add("_input_charset", Config.input_charset.ToLower());
            sParaTemp.Add("payment_type", Config.payment_type);
            sParaTemp.Add("notify_url", Config.notify_url);
            sParaTemp.Add("return_url", Config.return_url);
            sParaTemp.Add("anti_phishing_key", Config.anti_phishing_key);
            sParaTemp.Add("exter_invoke_ip", Config.exter_invoke_ip);
            sParaTemp.Add("out_trade_no", model.WIDout_trade_no);
            sParaTemp.Add("subject", model.WIDsubject);
            sParaTemp.Add("total_fee", model.WIDtotal_fee);
            sParaTemp.Add("body", model.WIDbody);
            //其他业务参数根据在线开发文档,添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1
            //如sParaTemp.Add("参数名","参数值");

            //建立请求
            string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认");

            Response.Write(sHtmlText);

            // return View();
        }
Exemple #20
0
        public ActionResult Payment(PayModel model)
        {
            UserTrans us     = new UserTrans();
            Payments  paym   = new Payments();
            CaseTrans ct     = new CaseTrans();
            var       user   = userManager.FindByName(User.Identity.Name);
            decimal   totalb = repoUser.TotalBalance(user.Id);

            us.UserId    = user.Id;
            us.Prize     = 0;
            us.Loose     = 0;
            us.PaymentId = true;
            us.Balance   = totalb + model.Bill;
            repoUser.Add(us);
            paym.UserId      = user.Id;
            paym.UserTransId = us.Id;
            paym.Price       = ((model.Bill) * Convert.ToDecimal(7.42) / 1000);
            paym.OrderType   = "Ödeme";
            repoPayments.Add(paym);
            ct.UserTransId = us.Id;
            ct.Income      = paym.Price;
            ct.Expense     = 0;
            ct.TransType   = "Bill Satış";
            repoCaseTrans.Add(ct);
            return(RedirectToAction("AccountInfo", "Account"));
        }
Exemple #21
0
        public async Task <IActionResult> CreateCustomer()
        {
            PayModel paymodel = getPayModel();
            var      client   = CreateStripeClient(paymodel.Email, paymodel.Name, paymodel.CardNumder, paymodel.ExpMonth, paymodel.ExpYear, paymodel.CVC);
            var      response = await Task.FromResult(client);

            return(Ok(response));
        }
Exemple #22
0
        /// <summary>
        /// 缴费
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private bool DoTuition(HttpContext context)
        {
            PayModel model       = new PayModel();
            int      id          = Convert.ToInt32(context.Request.Params["pay_id"]);
            decimal  realpay_pay = Decimal.Parse(context.Request.Params["ui_registration_realpay_pay"] ?? "0");
            string   remark_pay  = context.Request.Params["ui_registration_remark_pay"] ?? "";
            bool     isPayAll    = context.Request.Params["ui_registration_status_pay"] == "true" ? true : false;

            bool isLocal = context.Request.Params["islocal_pay"] == "0" ? false : true;

            decimal?shoudPay    = 0;
            string  strShoudPay = new DriveMgr.BLL.RegistrationBLL().GetShoudPayByIsLocal(isLocal);

            if (strShoudPay != "")
            {
                shoudPay = Decimal.Parse(strShoudPay);
            }
            else
            {
                shoudPay = 0;
            }

            model.ShoudPay = shoudPay;

            if ((shoudPay - realpay_pay) > 0)
            {
                if (isPayAll)
                {
                    model.Status  = 2;                      //完全交费
                    model.SalePay = shoudPay - realpay_pay; //优惠金额
                }
                else
                {
                    model.Status = 1; //未完全交费
                }
            }
            else
            {
                model.Status = 2; //完全交费
            }

            model.StudentsID = id;
            model.RealPay    = realpay_pay;
            FormsIdentity             iid     = (FormsIdentity)context.User.Identity;
            FormsAuthenticationTicket tickets = iid.Ticket;

            //获取票证里序列化的用户对象(反序列化)
            DriveMgr.Model.User userCheck = new JavaScriptSerializer().Deserialize <DriveMgr.Model.User>(tickets.UserData);

            model.Operater = userCheck.UserName;

            model.Remark = remark_pay;

            bool result = new DriveMgr.BLL.RegistrationBLL().DoTuition(model);

            return(result);
        }
Exemple #23
0
        public RESTfulModel OrderQuery(string outTradeNo)
        {
            PayModel payModel = payDAL.GetByOutTradeNo(outTradeNo);

            return(new RESTfulModel()
            {
                Code = (int)CodeEnum.成功, Msg = codeMsgDAL.GetByCode((int)CodeEnum.成功)
            });
        }
Exemple #24
0
        public ActionResult Payment()
        {
            PayModel pm   = new PayModel();
            var      list = userManager.FindByName(User.Identity.Name);

            pm.Name    = list.Name;
            pm.Surname = list.Surname;
            return(View(pm));
        }
Exemple #25
0
        public ActionResult PayBasket(string idcount, bool?isFast)
        {
            var customer = new CustomerAction(Session.GetUserId());

            Session.UpdateBasket();
            var basket = Session.GetUser().basket;

            if (isFast != true && !string.IsNullOrWhiteSpace(idcount))
            {
                var splitBasket = idcount.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (basket.Count != splitBasket.Count())
                {
                    var message = "Количество товара в корзине не соответствует ожидаемому";
                    return(RedirectToAction("Info", "Home", new InfoModel {
                        message = message, header = "Ошибка!", status = StatusMessage.Error
                    }));
                }
                foreach (var item in splitBasket)
                {
                    var bask     = item.Trim().Split(':');
                    var basketId = Int64.Parse(bask[0]);
                    var count    = decimal.Parse(bask[1]);
                    if (!basket.Any(s => s.id == basketId))
                    {
                        var message = "Идентификатор корзины был испорчен!!";
                        return(RedirectToAction("Info", "Home", new InfoModel {
                            message = message, header = "Ошибка!", status = StatusMessage.Error
                        }));
                    }
                    var basketElement = basket.Single(s => s.id == basketId);
                    if (basketElement.count != count && count > 0)
                    {
                        customer.UpdateCount(basketElement.id, count);
                    }
                }
                Session.UpdateBasket();
                basket = Session.GetUser().basket;
            }
            var payModel = new PayModel
            {
                countInBasket     = basket.Count(),
                payDate           = DateTime.Now,
                totalSumm         = basket.Sum(s => s.summTotal) ?? 0.00M,
                transactionNumber = Guid.NewGuid().ToString(),
                packId            = basket.Select(s => s.packId).Distinct().Single() ?? 1
            };

            customer.Pay(payModel);
            Session.UpdateBasket();
            var mess = $"Заказ на сумму {payModel.totalSumm} руб. успешно создан. Идентификатор заказа: {payModel.transactionNumber}";

            return(RedirectToAction("Info", "Home", new InfoModel {
                message = mess, header = "Оплачено!", status = StatusMessage.Accept
            }));
        }
Exemple #26
0
        //
        // GET: /V3Jsapi/


        /// <summary>
        ///
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult Pay()
        {
            string code        = "";                               //网页授权获得的code
            string orderNo     = "";                               //文档中的out_trade_no
            string description = "";                               //商品描述
            string totalFee    = "1";                              //订单金额(单位:分)
            string createIp    = "127.0.0.1";
            string notifyUrl   = "";                               //通知url
            string openId      = WeiXinHelper.GetUserOpenId(code); //通过网页授权code获取用户openid(或者之前有存储用户的openid 也可以直接拿来用)

            //prepayid 只有第一次支付时生成,如果需要再次支付,必须拿之前生成的prepayid。
            //也就是说一个orderNo 只能对应一个prepayid
            string prepayid = string.Empty;

            #region 之前生成过 prepayid,此处可略过

            //创建Model
            UnifiedWxPayModel model = UnifiedWxPayModel.CreateUnifiedModel(WeiXinConst.AppId, WeiXinConst.PartnerId, WeiXinConst.PartnerKey);

            //预支付
            UnifiedPrePayMessage result = WeiXinHelper.UnifiedPrePay(model.CreatePrePayPackage(description, orderNo, totalFee, createIp, notifyUrl, openId));

            if (result == null ||
                !result.ReturnSuccess ||
                !result.ResultSuccess ||
                string.IsNullOrEmpty(result.Prepay_Id))
            {
                throw new Exception("获取PrepayId 失败");
            }

            //预支付订单
            prepayid = result.Prepay_Id;

            #endregion

            //JSAPI 支付参数的Model
            PayModel payModel = new PayModel()
            {
                AppId     = model.AppId,
                Package   = string.Format("prepay_id={0}", prepayid),
                Timestamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(),
                Noncestr  = CommonUtil.CreateNoncestr(),
            };

            Dictionary <string, string> nativeObj = new Dictionary <string, string>();
            nativeObj.Add("appId", payModel.AppId);
            nativeObj.Add("package", payModel.Package);
            nativeObj.Add("timeStamp", payModel.Timestamp);
            nativeObj.Add("nonceStr", payModel.Noncestr);
            nativeObj.Add("signType", payModel.SignType);
            payModel.PaySign = model.GetCftPackage(nativeObj); //生成JSAPI 支付签名


            return(View(payModel));
        }
 public ActionResult Index(PayModel p)
 {
     if ((string)Session["u_type"] == "Gen" && (int)Session["LoggedIn"] == 1)
     {
         if (ModelState.IsValid)
         {
             return(RedirectToAction("Index", "GenUser"));
         }
         return(View(p));
     }
     return(RedirectToAction("LogIn", "User"));
 }
Exemple #28
0
        public JsonResult GetOrdPaymentMethod(String fields)
        {
            string retJSON = "";

            if (Session["ctx"] != null)
            {
                Ctx      ctx      = Session["ctx"] as Ctx;
                PayModel paymodel = new PayModel();
                retJSON = JsonConvert.SerializeObject(paymodel.GetOrdPaymentMethod(ctx, fields));
            }
            return(Json(retJSON, JsonRequestBehavior.AllowGet));
        }
Exemple #29
0
        void SendPay()
        {
            //if (orderid <= 0)
            //{
            //    Response.Write("<script>alert('参数orderid=" + orderid + "错误');history.go(-1);</script>");
            //    return;
            //}
            //orderinfo = BLL.g_orderBLL.GetModel(orderid);
            //if (orderinfo == null || orderinfo.orderid != orderid)
            //{
            //    Response.Write("<script>alert('参数orderid错误');history.go(-1);</script>");
            //    return;
            //}
            //if (orderinfo.orderstatus != 0)
            //{
            //    Response.Write("<script>alert('当前订单已处理,不能重复支付');history.go(-1);</script>");
            //    return;
            //}


            string[] sta = State_Str.Split(new string[] { "*" }, StringSplitOptions.RemoveEmptyEntries);
            //LogUtil.WriteLog("Send 页面  State_Str:" + State_Str + ",coupon_id:" + sta[2]);
            if (sta.Length > 1)
            {
                //string _uid = sta[2];
                string _model = sta[2];//所属订单模块
                //if (_uid == null || !_uid.Equals(base.uid))
                //{
                //    Response.Write("<script>alert('参数uid错误');history.go(-1);</script>");
                //    return;
                //}
                if (_model == null || _model.Trim().Length == 0)
                {
                    Response.Write("<script>alert('参数model错误');history.go(-1);</script>");
                    return;
                }
                string Body = "手机充值支付";
                if (_model.Trim().ToLower().Equals("recharge_order"))
                {
                    Body = "手机充值支付";
                }
                //设置支付数据
                PayModel model = new PayModel();
                model.OrderSN  = sta[0];
                model.TotalFee = Convert.ToInt32(Convert.ToDecimal(sta[1]) * 100);
                model.Body     = Body;
                model.Attach   = _model; //uid|model 不能有中文
                model.OpenId   = this.UserOpenId;

                //跳转到 WeiPay.aspx 页面,请设置函数中WeiPay.aspx的页面地址
                this.Response.Redirect(model.ToString());
            }
        }
Exemple #30
0
        public JsonResult GetPaymentRule(string fields)
        {
            string retJSON = "";

            if (Session["ctx"] != null)
            {
                VAdvantage.Utility.Ctx ctx = Session["ctx"] as Ctx;
                PayModel payModel          = new PayModel();
                retJSON = JsonConvert.SerializeObject(payModel.GetPaymentRule(ctx, fields));
            }
            return(Json(retJSON, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// 提交支付信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            //设置支付数据
            PayModel model = new PayModel();
            model.OrderSN = this.txtOrderSN.Text;
            model.TotalFee = int.Parse(this.txtPrice.Text);
            model.Body = this.txtBody.Text;
            model.Attach = this.txtOther.Text; //不能有中午
            model.OpenId = this.lblOpenId.Text;

            //跳转到 WeiPay.aspx 页面,请设置函数中WeiPay.aspx的页面地址
            this.Response.Redirect(model.ToString());
        }