コード例 #1
0
        public bool CreateOrderPayOrder(PayOrder payOrder)
        {
            var result = false;

            try
            {
                var       nowDate = DateTime.Now;
                DataTable dt      = new DataTable();
                dt.Columns.Add("PayOrderID");
                dt.Columns.Add("OrderID");
                dt.Columns.Add("CreateDate");
                for (int i = 0; i < payOrder.Orders.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr["PayOrderID"] = payOrder.ID;
                    dr["OrderID"]    = payOrder.Orders[i].OID;
                    dr["CreateDate"] = nowDate;
                    dt.Rows.Add(dr);
                }
                SQLHelper.BulkToDB(dt, "OrderPayOrder");
            }
            catch (Exception ex)
            {
            }
            return(result);
        }
コード例 #2
0
        bool addProductOnServer(PayOrder payData)
        {
            var           persionHMDCache = new PersonalCacheStruct <HappyModeData>();
            HappyModeData hmd             = persionHMDCache.FindKey(payData.the3rdUserId.ToString());

            if (hmd == null)
            {
                hmd = new HappyModeData();
                hmd.the3rdUserId = payData.the3rdUserId;
                persionHMDCache.Add(hmd);
            }
            string hd = GameConfigMgr.Instance().getProductInfo(payData.ProductId, payData.ServerOrderId);

            string[] infos   = hd.Split('*');
            int      itemID  = int.Parse(infos[0]);
            int      itemNum = int.Parse(infos[1]);
            string   infoLog = string.Format("add item:{0}num:{1}", itemID, payData.num * itemNum);

            ConsoleLog.showNotifyInfo(infoLog);
            TraceLog.WriteInfo(infoLog);
            if (payData.ProductId == "5100")
            {
                hmd.HappyPoint += payData.num * itemNum;
                return(true);
            }
            if (payData.ProductId == "5101")
            {
                hmd.HappyReliveNum += payData.num * itemNum;
                return(true);
            }
            return(false);
        }
コード例 #3
0
        void doAdd_finishOrder(string parm)
        {
            string [] theParms = parm.Split(',');
            string    orderId  = theParms[0];
            string    typeUser = theParms[1];
            var       payCache = new ShareCacheStruct <PayOrder>();
            PayOrder  payData  = payCache.Find((o) =>
            {
                if (orderId == o.ServerOrderId)
                {
                    return(true);
                }
                return(false);
            });

            if (null == payData)
            {
                ConsoleLog.showErrorInfo(0, "error doAdd_finishOrder:" + orderId);
            }

            payData.ModifyLocked(() =>
            {
                payData.state           = PayOrder.PayStatus.paySuccess;
                payData.process         = true;
                payData.typeUser        = typeUser;
                payData.hasGetPayReward = true;
            });

            addProductOnServer(payData);
        }
コード例 #4
0
        public PayOrder GetPayOrderByOrder(int orderID)
        {
            PayOrder payOrder = null;

            try
            {
                var sql = new StringBuilder();
                sql.Append("SELECT o2.[ID],o2.[SaleUserID],o2.[BuyUserID],o2.[PayAmount],o2.[PayType],o2.[PayOrderNo],o2.[Describe],o2.[CreateUserID],o2.[CreateDate],o2.[LastUpdateDate],o2.[LastUpdateUserID] FROM OrderPayOrder o ");
                sql.Append("LEFT JOIN PayOrder o2 ON o2.OID =o.PayOrderID ");
                sql.Append(string.Format("WHERE OrderID={0}", orderID));
                var dt = SQLHelper.GetTable(sql.ToString());
                if (dt.Rows.Count > 0)
                {
                    payOrder = new PayOrder
                    {
                        ID        = Convert.IsDBNull(dt.Rows[0]["ID"]) ? 0 : Convert.ToInt32(dt.Rows[0]["ID"]),
                        PayAmount = Convert.IsDBNull(dt.Rows[0]["PayAmount"]) ? 0 : Convert.ToDecimal(dt.Rows[0]["PayAmount"]),
                    };
                }
            }
            catch (Exception ex)
            {
            }
            return(payOrder);
        }
コード例 #5
0
ファイル: OrderController.cs プロジェクト: hello-jim/YunXiu
        public HttpResponseMessage CreatePayOrder()
        {
            HttpResponseMessage response = null;
            PayOrder            payOrder = new PayOrder();

            try
            {
                List <Order> orders = null;
                using (var ms = new MemoryStream())
                {
                    HttpContext.Current.Request.GetBufferlessInputStream().CopyTo(ms);
                    if (ms.Length != 0)
                    {
                        var cText = WebCommom.HttpRequestBodyConvertToStr(ms);//密文
                        var pText = AES.AESDecrypt(cText, AESKey);
                        orders = JsonConvert.DeserializeObject <List <Order> >(pText);
                    }
                }
                if (orders != null)
                {
                    payOrder.Orders = orders;
                    payOrder.ID     = payOrderBll.Value.CreatePayOrder(payOrder);
                }
            }
            catch (Exception ex)
            {
            }
            var responseCText = AES.AESEncrypt(JsonConvert.SerializeObject(payOrder), AESKey);//返回密文

            response = WebCommom.GetResponse(responseCText);
            return(response);
        }
コード例 #6
0
ファイル: getorder.aspx.cs プロジェクト: archangelwin/QY
        /// <summary>
        ///优卡联盟查询接口
        /// </summary>
        /// <param name="orderid">订单号</param>
        /// <param name="callBackurl">返回地址</param>
        private void SendDoQuery()
        {
            if (!String.IsNullOrEmpty(Request["orderid"].ToString()))
            {
                PayOrderController          ent         = new PayOrderController();
                Dictionary <string, object> conditions2 = new Dictionary <string, object>();

                String orderid = Request["orderid"];
                conditions2.Add("OrderID", orderid);
                PayOrder getmodel = ent.PayOrderArr(orderid);
                if (getmodel == null)
                {
                    var fanhui = "{\"status\":\"success\",\"message\":-1}"; //-1 订单不存在 1 充值中 2 充值完成 3 充值失败
                    Response.Write(fanhui);
                }
                else
                {
                    var            geturl = "http://pay.poleneer.com/service/m_get_order?order_no=" + getmodel.ChannelOrderID + "";
                    var            uri    = geturl;
                    var            json   = "";
                    byte[]         b      = Encoding.ASCII.GetBytes(json);
                    HttpWebRequest req    = (HttpWebRequest)HttpWebRequest.Create(uri);
                    req.Method        = "POST";
                    req.ContentType   = "text/html";
                    req.ContentLength = b.Length;
                    req.Headers.Set("Pragma", "no-cache");
                    req.Timeout = 60000;
                    Stream reqstream = req.GetRequestStream();
                    reqstream.Write(b, 0, b.Length);
                    WebResponse  res    = req.GetResponse();
                    Stream       stream = res.GetResponseStream();
                    StreamReader sr     = new StreamReader(stream, Encoding.UTF8);
                    string       result = sr.ReadToEnd();
                    reqstream.Close();
                    reqstream.Dispose();
                    sr.Close();
                    sr.Dispose();
                    stream.Close();
                    stream.Close();

                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    AllGet abc      = jss.Deserialize <AllGet>(result) as AllGet;
                    var    issucc   = abc.success;
                    var    getstate = abc.data[0].state;//0:未支付/支付失败;1:支付成功
                    var    showmsg  = 1;
                    if (getstate == 1)
                    {
                        Dictionary <string, object> conditionsEdit = new Dictionary <string, object>();

                        conditionsEdit.Add("OrderID", orderid);
                        conditionsEdit.Add("ErrorCode", "");
                        conditionsEdit.Add("PayState", "2");//充值成功
                        ent.PayOrderEdit(conditionsEdit);
                        showmsg = 2;
                    }
                    var fanhui = "{\"status\":\"success\",\"message\":" + showmsg + "}"; //-1 订单不存在 1 充值中 2 充值完成 3 充值失败
                    Response.Write(fanhui);
                }
            }
        }
コード例 #7
0
ファイル: Method.cs プロジェクト: nguyenmy494041/MODULE2
        public static void PayOrderByIdOrder()
        {
            Method.ReadOnMember();
            int idorder = Management.CreateInteger("id Order", 1);
            int pos     = Method.Find_IdOrder(idorder, out int index_custumer);

            if (pos != -1 && data.custumers[index_custumer].oders[pos].status == "Waiting")
            {
                string   Path     = @"E:\CODEGYM\Module2\BaitapModule2_lan2\BaitapModule2_lan2\Bai3\PayOrder";
                string   fileName = $"{DateTime.Now.ToString("dd-MM-yyyy")}__{idorder}";
                PayOrder payOrder = new PayOrder();
                payOrder.Id_Custumer   = data.custumers[index_custumer].id_custumer;
                payOrder.Name_Custumer = data.custumers[index_custumer].name_custumer;
                payOrder.Adrres        = data.custumers[index_custumer].adress_custumer;
                payOrder.Phone_number  = data.custumers[index_custumer].number_phone;
                payOrder.status        = "Payed";
                payOrder.products      = data.custumers[index_custumer].oders[pos].products;
                data.custumers[index_custumer].oders[pos].status = "Payed";
                using (StreamWriter sw = File.CreateText($@"{Path}\{fileName}"))
                {
                    var dada = JsonConvert.SerializeObject(payOrder);
                    sw.Write(dada);
                }
                Method.PushInDATA();
                Console.WriteLine("Payment success");
            }
            else
            {
                Console.WriteLine("Not found Order or Order Payed!");
            }
        }
コード例 #8
0
        /// <summary>
        /// 验证商户
        /// </summary>
        /// <param name="model"></param>
        /// <param name="merchant"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private bool OrderVerify(string orderId, out PayOrder payOrder, out PayChannel payChannel, out string msg)
        {
            msg        = "";
            payChannel = null;
            payOrder   = null;

            var order = this._payOrderService.Get(c => c.OrderId == orderId);

            payOrder = order;

            if (order.IsNull())
            {
                msg = "订单不存在";
                return(false);
            }

            var channel = this._payChannelService.Get(c => c.ChannelId == order.ChannelId);

            payChannel = channel;

            if (channel.IsNull())
            {
                msg = "渠道不存在";
                return(false);
            }

            return(true);
        }
コード例 #9
0
        void doCheck_order()
        {
            string   orderId  = requestPack.infoExt;
            var      payCache = new ShareCacheStruct <PayOrder>();
            PayOrder payData  = payCache.Find((o) =>
            {
                if (orderId == o.ServerOrderId)
                {
                    return(true);
                }
                return(false);
            });

            if (payData == null)
            {
                responsePack.errorCode = (byte)Response1004Pack.EnumErrorCode.order_not_find;
                return;
            }

            if (payData.hasGetPayReward)
            {
                responsePack.errorCode = (byte)Response1004Pack.EnumErrorCode.hasGetPayReward;
                return;
            }

            string productId = payData.ProductId;

            responsePack.extInfo   = GameConfigMgr.Instance().getProductInfo(productId, orderId); // add 道具发放信息。
            responsePack.errorCode = (byte)Response1004Pack.EnumErrorCode.ok;
        }
コード例 #10
0
        private PayOrder CreateOrder(Request10001 request, Merchant merchant, PayService payProduct, PayChannel payChannel, MerchantPayService merchantPayService)
        {
            PayOrder order = new PayOrder();

            order.OrderId           = Guid.NewGuid().ToString();
            order.OrderNo           = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 9999);
            order.AgentNo           = merchant.AgentNo;
            order.ChannelId         = payChannel.ChannelId;
            order.ChannelName       = payChannel.ChannelName;
            order.ChannelType       = payChannel.ChannelType;
            order.CreateTime        = DateTime.Now;
            order.DeviceType        = request.DeviceType;
            order.ExtendField       = request.ExtendField;
            order.FeeMode           = payChannel.SettleMode.ToString();
            order.SettleMode        = payChannel.SettleMode.ToStr();
            order.Ip                = request.Ip;
            order.MemberInfo        = "test";
            order.MerchantId        = merchant.MerchantId;
            order.MerchantOrderNo   = request.MerchantOrderNo;
            order.MerchantOrderTime = request.MerchantOrderTime.TryDateTime(DateTime.Now).Value;
            order.NotifyUrl         = request.NotifyUrl;
            order.OrderAmount       = request.OrderAmount.TryDecimal(0).Value;
            order.OrderDescription  = request.OrderDescription;
            order.PayStatus         = (int)Max.Models.Payment.Common.Enums.PayStatus.未支付;
            order.PayTime           = DateTime.Now;
            order.PreorderAmount    = order.OrderAmount;
            order.ServiceFee        = order.OrderAmount * merchantPayService.MerchantFeeRate;
            order.ServiceRate       = merchantPayService.MerchantFeeRate;
            order.TransAmount       = order.OrderAmount - order.ServiceFee;
            order.ServiceId         = payProduct.ServiceId;

            this._payOrderService.Add(order);
            return(order);
        }
コード例 #11
0
        public ActionResult Create([Bind(Include = "Id, Employee, Number, Date, VoucherNumber, VoucherDate, PaymentNumber, PaymentDate, AccountingDocumentNumber, AccountingDocumentDate, PaymentGroup, PaidAmount, IsProfit, IsFixed, Notes")] PayOrder payOrder)
        {
            Db db = new Db(DbServices.ConnectionString);

            if (ModelState.IsValid)
            {
                try
                {
                    PayOrderServices.Insert(CurrentUser.Id, payOrder, db);
                    TempData["Success"] = ResourceServices.GetString(Cf.Data.Resources.ResourceBase.Culture, "UI", "InsertConfirmed");
                    return(RedirectToAction("Index"));
                }
                catch (CfException cfex)
                {
                    TempData["Failure"] = cfex.ErrorDefinition.LocalizedMessage;
                }
                catch (Exception ex)
                {
                    TempData["Failure"] = ex.Message;
                }
            }

            ViewBag.PaymentGroupList = new SelectList(PaymentGroupServices.List(db), "Id", "Name");
            ViewBag.EmployeeList     = new SelectList(EmployeeServices.List(db), "Id", "FirstName");
            return(View(payOrder));
        }
コード例 #12
0
        /**
         * 调用统一下单,获得下单结果
         * @return 统一下单结果
         * @失败时抛异常WxPayException
         */
        public WxPayData GetUnifiedOrderResult(PayOrder payOrder)
        {
            //统一下单
            openid                = payOrder.WeixinName;
            total_fee             = (int)(payOrder.Amount * 100);
            payOrder.Out_trade_no = WxPayApi.GenerateOutTradeNo();
            WxPayData data = new WxPayData();

            data.SetValue("body", body);
            data.SetValue("attach", payOrder.WeixinName);
            data.SetValue("out_trade_no", payOrder.Out_trade_no);
            data.SetValue("total_fee", total_fee);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", "recharge");
            data.SetValue("trade_type", "JSAPI");
            data.SetValue("openid", openid);
            data.SetValue("notify_url", WxPayConfig.NOTIFY_URL);
            WxPayData result = WxPayApi.UnifiedOrder(data);

            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                throw new WxPayException("UnifiedOrder response error!");
            }
            unifiedOrderResult = result;
            return(result);
        }
コード例 #13
0
ファイル: PaymentController.cs プロジェクト: losol/sjop
        public async Task <ActionResult> Pay([FromBody] PayOrder payOrder)
        {
            _logger.LogInformation($"*** Paying order: {payOrder.OrderId}.");

            var order = await _context.Orders
                        .Where(p => p.Id == payOrder.OrderId)
                        .Include(order => order.OrderLines)
                        .FirstOrDefaultAsync();

            if (order == null)
            {
                return(BadRequest("No order found"));
            }

            switch (order.PaymentProvider)
            {
            case PaymentProviderType.StripeCheckout:
                _logger.LogInformation($"* Pay with StripeCheckout");
                return(await PayWithStripeCheckout(order));

            case PaymentProviderType.StripeElements:
                _logger.LogInformation($"* Pay with StripeElements");
                return(await PayWithStripeElements(order));

            case PaymentProviderType.Vipps:
                _logger.LogInformation($"* Pay order #{order.Id} with Vipps ");
                var initiate = await _vippsApiClient.InitiatePayment(order, _vippsSettings);

                return(Ok(initiate));

            default:
                return(BadRequest());
            }
        }
コード例 #14
0
        public async Task AddPayment(PayOrder model, int corpClientId, long userId)
        {
            if (model.Amount <= 0)
            {
                throw new BusinessException("O valor do pagamento deve ser maior que zero");
            }

            var currentOrder = await GetByNumber(model.OrderNumber, corpClientId);

            var payments = await transactionApp.GetTransactions(currentOrder.OrderId, corpClientId);

            var totalPaid = payments.Where(p => (p.IsOrderPrincipalAmount ?? false)).Sum(s => s.Amount);

            if (totalPaid + model.Amount > currentOrder.ItemsTotalAfterDiscounts)
            {
                throw new BusinessException("O valor total pago não pode ser maior que o total da venda");
            }

            var nextPaymentStatus = (totalPaid + model.Amount == currentOrder.ItemsTotalAfterDiscounts) ?
                                    PaymentStatusEnum.Pago : PaymentStatusEnum.ParcialmentePago;

            using var trans = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            await orderApp.Update(new UpdateOrder
            {
                CompleteBy      = currentOrder.CompleteBy,
                FreightPrice    = currentOrder.FreightPrice,
                OrderNumber     = currentOrder.OrderNumber,
                PaymentStatusId = nextPaymentStatus
            }, corpClientId);

            await transactionApp.AddTransaction(new NewTransaction
            {
                Amount                 = model.Amount,
                CorpClientId           = corpClientId,
                Date                   = DateTimeOffset.UtcNow,
                Description            = $"Recebimento referente ao Pedido #{currentOrder.OrderNumber}",
                MerchantName           = currentOrder.Customer.Name,
                OrderId                = currentOrder.OrderId,
                TransactionTypeId      = model.OrderPaymentMethod,
                TransactionStatusId    = 1,
                IsOrderPrincipalAmount = true
            }, userId);

            if (model.Tip > 0)
            {
                await transactionApp.AddTransaction(new NewTransaction
                {
                    Amount                 = model.Tip,
                    CorpClientId           = corpClientId,
                    Date                   = DateTimeOffset.UtcNow,
                    Description            = $"Recebimento de Tips referente ao Pedido #{currentOrder.OrderNumber}",
                    MerchantName           = currentOrder.Customer.Name,
                    OrderId                = currentOrder.OrderId,
                    TransactionTypeId      = model.TipPaymentMethod,
                    TransactionStatusId    = 1,
                    IsOrderPrincipalAmount = false
                }, userId);
            }
            trans.Complete();
        }
コード例 #15
0
 public int CreatePayOrder(PayOrder pay)
 {
     for (int i = 0; i < pay.Orders.Count; i++)
     {
         pay.PayAmount += pay.Orders[i].BuyUnitPrice * pay.Orders[i].BuyNumber;
     }
     return(dal.CreatePayOrder(pay));
 }
コード例 #16
0
ファイル: PayOrderService.cs プロジェクト: orf53975/Max.Pay
        public ServiceResult Add(PayOrder model)
        {
            var result = new ServiceResult();

            this._PayOrderReps.Add(model);

            return(result.IsSucceed("新增支付订单成功"));
        }
コード例 #17
0
 public ActionResult EditForAjax(PayOrder model)
 {
     return(Json(this._payOrderService.Update(c => c.ServiceId == model.ServiceId, c => new PayOrder()
     {
         PayStatus = model.PayStatus,
         NotifyStatus = model.NotifyStatus
     })));
 }
コード例 #18
0
ファイル: PayOrderService.cs プロジェクト: orf53975/Max.Pay
        public ServiceResult Update(PayOrder model)
        {
            var result = new ServiceResult();

            this._PayOrderReps.Update(model);

            return(result.IsSucceed("编辑支付订单成功"));
        }
コード例 #19
0
        /// <summary>
        /// 创建支付订单
        /// </summary>
        /// <param name="player">玩家</param>
        /// <param name="amount">金额</param>
        /// <returns></returns>
        public virtual PayOrder CreatPayOrder(Player player, decimal amount)
        {
            PayOrder payOrder = new PayOrder(player.WeixinName, amount);

            _storeHouse.AddEntity <PayOrder>(payOrder);
            _storeHouse.SaveChanges();
            return(payOrder);
        }
コード例 #20
0
ファイル: PayOrder.cs プロジェクト: JerryPig/mynetcore
        protected override CommandResult <PayOrderResult> OnExecute(object commandParameter)
        {
            var           param     = commandParameter as PayOrderParamter;
            var           result    = new CommandResult <PayOrderResult>();
            PaymentConfig payConfig = null;

            using (CoreContext db = new CoreContext())
            {
                PayOrder payOrder = param.Order;

                if (payOrder == null)
                {
                    Serilog.Log.Logger.Error($"#{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType}#order payment not fount {payOrder.OrderNo}");
                    result.ErrorCode    = -1;
                    result.ErrorMessage = "order payment not fount";
                    return(result);
                }
                if (payOrder.PayFee != param.PaymentPrice)
                {
                    Serilog.Log.Logger.Error($"#{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType}#Weixinpaynotify#支付失败,paymentNo ={payOrder.OrderNo}," +
                                             $" tradeNo ={param.TradeNo},totalprice={param.PaymentPrice}");
                    result.ErrorCode    = -1;
                    result.ErrorMessage = $"requestfee-{param.PaymentPrice} and checkfee-{payOrder.PayFee} not match ";
                    return(result);
                }
                payConfig = db.PaymentConfig.Where(p => p.Id == payOrder.PaymentId && p.Status == "1").FirstOrDefault();

                int updateRes = db.Database.ExecuteSqlCommand($@"update pay_order set status=1 where order_no={payOrder.OrderNo} and status !=1 ");
                if (updateRes == 1 && payConfig != null)
                {
                    // payOrder.Status = 1;

                    db.PaymentLog.Add(new PaymentLog()
                    {
                        PayStatus      = "1",
                        CreateDate     = DateTime.Now,
                        PaymentAccount = payOrder.MemberAccount,
                        PaymentFee     = payOrder.PayFee,
                        PaymentId      = payConfig.Id,
                        PaymentNo      = payOrder.OrderNo,
                        PayTime        = DateTime.Now,
                        TradeNo        = param.TradeNo
                    });
                    db.SaveChanges();
                    Serilog.Log.Logger.Error($"#{System.Reflection.MethodBase.GetCurrentMethod().DeclaringType}#Weixinpaynotify#支付成功,paymentNo ={payOrder.OrderNo}," +
                                             $" tradeNo ={param.TradeNo},totalprice={param.PaymentPrice}");

                    result.Data = new PayOrderResult
                    {
                        PayOrder = payOrder
                    };
                    result.Data.PayOrder.Status = 1;
                }
            }
            return(result);
        }
コード例 #21
0
        private void UpdatePayOrder(String service, PayOrder order)
        {
            _payOrderRepository.Update(order);
            var saveResult = _payOrderRepository.SaveChanges();

            if (!saveResult.Success)
            {
                _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, $"{nameof(_payOrderRepository)}.SaveChanges()", "更新协议支付结果失败", saveResult.FirstException, order);
            }
        }
コード例 #22
0
        public async Task <ApiResult <string> > SendNotify(PayOrder parm)
        {
            var res = new ApiResult <string>()
            {
                statusCode = (int)ApiEnum.Status
            };

            res.message = SettleOrderBll._.SendNotify(parm.Order_id.SqlFilters(), false, false).Result;
            return(await Task.Run(() => res));
        }
コード例 #23
0
        public async Task <object> PayAsync(OrderPayRequestDto input)
        {
            var productOrder = await Repository.Include(x => x.OrderItems).FirstOrDefaultAsync(x => x.Id == input.OrderId);

            if (productOrder == null)
            {
                throw new UserFriendlyException("NotFind");
            }

            var appName = _httpContextAccessor?.GetAppName();
            var app     = await _appProvider.GetOrNullAsync(appName);

            var appid = app["appid"] ?? throw new AbpException($"App:{appName} appid未设置");

            var mchId = await _setting.GetOrNullAsync(MallManagementSetting.PayMchId);

            var mchKey = await _setting.GetOrNullAsync(MallManagementSetting.PayKey);

            var notifyUrl = await _setting.GetOrNullAsync(MallManagementSetting.PayNotify);


            var payorder = new PayOrder();

            payorder.CreatWxPayFromProductOrder(id: GuidGenerator.Create(),
                                                productOrder: productOrder,
                                                mchId: mchId,
                                                openid: input.openid,
                                                appName: appName,
                                                shareFromUserId: null,
                                                partnerId: null
                                                );

            var insertPayOrder = await _payOrderRepository.InsertAsync(payorder, autoSave : true);

            productOrder.SetBillNo(insertPayOrder.Id, insertPayOrder.BillNo);

            var unifiedResult = await _payApi.UnifiedOrderAsync(
                appid,
                mchId,
                mchKey,
                body : productOrder.OrderItems.First().SpuName,
                outTradeNo : insertPayOrder.BillNo,
                totalFee : Convert.ToInt32(productOrder.PriceOriginal * 100),
                notifyUrl : notifyUrl.EnsureEndsWith('/') + appName,
                tradeType : Consts.TradeType.JsApi,
                openId : input.openid,
                billCreateIp : _httpContext.HttpContext.Connection.RemoteIpAddress.ToString()
                );

            _rabbit.PushDelyMessage(new PayOrderLisenerData {
                Type = "PayOrder", Data = insertPayOrder
            }, MallConsts.PayAutoCancelTime, "SoMall_DelayQueue");                                                                                          // 半小时内未支付删除

            return(unifiedResult);
        }
コード例 #24
0
        public string CreateWxJsApiParam(PayOrder payOrder)
        {
            JsApiPay  jsApiPay           = new JsApiPay();
            WxPayData unifiedOrderResult = jsApiPay.GetUnifiedOrderResult(payOrder);

            payOrder.Prepay_id = (string)unifiedOrderResult.GetValue("prepay_id");
            _storeHouse.SaveChanges();
            string wxJsApiParam = jsApiPay.GetJsApiParameters();

            return(wxJsApiParam);
        }
コード例 #25
0
        public IActionResult WeiXinPayCallBack()
        {
            Hashtable requestHash = WxPayUtil.ParseXML(Request.Body);
            string    payno       = requestHash["out_trade_no"] as string;

            LogUtil.Log("wxpay", payno, JsonConvert.SerializeObject(requestHash));

            PaymentConfig payConfig = null;
            PayOrder      payOrder  = (from o in _context.PayOrder where o.OrderNo == payno select o).FirstOrDefault();

            payConfig = (from p in _context.PaymentConfig where p.Status == "1" && p.Id == payOrder.PaymentId select p).FirstOrDefault();
            if (payOrder == null || payConfig == null)
            {
                return(Content("fail"));
            }

            if (!WxPayUtil.CheckSign(requestHash, payConfig.PrivateKey))
            {
                logger.Error("Weixinpay:验证签名失败" + payno);
                return(Content("fail"));
            }

            //获取交易状态
            string returnCode = requestHash["return_code"] as string;
            string resultCode = requestHash["result_code"] as string;

            //状态正常的时候才能调用PayOrder接口
            if (returnCode == "SUCCESS" && resultCode == "SUCCESS")
            {
                string  tradeNo    = requestHash["transaction_id"] as string;
                decimal paymentFee = Convert.ToDecimal(requestHash["total_fee"]) / 100;

                var payRes = new PayOrderCommand().Execute(new PayOrderParamter()
                {
                    PaymentPrice = paymentFee,
                    Order        = payOrder,
                    TradeNo      = tradeNo
                });

                if (payRes.ErrorCode != 0)
                {
                    logger.Error(payRes.ErrorMessage);
                    return(Content("fail"));
                }
                else
                {
                    return(Content("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"));
                }
            }
            else
            {
                return(Content("fail"));
            }
        }
コード例 #26
0
        public async Task <IActionResult> Pay(string id, [FromBody] PayOrder model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var command = new PayOrderCommand(id, model.Amount.Value);

            return(await QueueCommandAsync(command));
        }
コード例 #27
0
ファイル: Action1006.cs プロジェクト: dannisliang/scutlogic
        public override bool TakeAction()
        {
            // 存入数据库
            var      hmdCache      = new PersonalCacheStruct <HappyModeData>();
            var      cache         = new ShareCacheStruct <PayOrder>();
            int      index         = (int)cache.GetNextNo();
            PayOrder PayData       = new PayOrder();
            string   ServerOrderId = System.Guid.NewGuid().ToString("N");
            int      keyid         = utils.KeyUInt2Int(requestPack.the3rdUserId);

            PayData.Index            = index;
            PayData.UserId           = requestPack.UserID;
            PayData.Identify         = requestPack.identify;
            PayData.typeUser         = requestPack.typeUser; // 360Pay..maybe
            PayData.ProductId        = requestPack.productId;
            PayData.num              = requestPack.num;
            PayData.the3rdUserId     = keyid;// utils.KeyUInt2Int(requestPack.the3rdUserId);
            PayData.strThe3rdOrderId = requestPack.strThe3rdUserId;
            PayData.ServerOrderId    = ServerOrderId;
            PayData.the3rdOrderId    = "";
            cache.Add(PayData);

            // hmd persion
            HappyModeData hmd = hmdCache.FindKey(keyid.ToString());
            int           happyPointMaxEnterNum = GameConfigMgr.Instance().getInt("happyPointMaxEnterNum", 3);

            if (null == hmd)
            {
                responsePack.errorCode = 1;
                return(true);
            }
            PayOrderPersion pop = new PayOrderPersion();

            pop.Index            = index;
            pop.UserId           = requestPack.UserID;
            pop.Identify         = requestPack.identify;
            pop.typeUser         = requestPack.typeUser; // 360Pay..maybe
            pop.ProductId        = requestPack.productId;
            pop.num              = requestPack.num;
            pop.the3rdUsrID      = (int)requestPack.the3rdUserId;// utils.KeyUInt2Int(requestPack.the3rdUserId);
            pop.strThe3rdOrderId = requestPack.strThe3rdUserId;
            pop.ServerOrderId    = ServerOrderId;
            pop.the3rdOrderId    = "";
            hmd.PayInfoDic.Add(ServerOrderId, pop);

            // end return
            responsePack.errorCode = 0;
            responsePack.typeUser  = requestPack.typeUser;
            responsePack.result    = PayData.ServerOrderId; // 服务器订单号

            ConsoleLog.showErrorInfo(0, "create order success" + requestPack.the3rdUserId + ":" + ServerOrderId);
            return(true);
        }
コード例 #28
0
        public IActionResult GetPayResult([FromServices] IPayServiceWeixin payServiceWeixin)
        {
            PayOrder payOrder = payServiceWeixin.CompletePayOrderAndReback(httpContextAccessor.HttpContext, out string successStr);

            if (payOrder.Success == true)
            {
                return(Content(successStr));
            }
            else
            {
                return(null);
            }
        }
コード例 #29
0
ファイル: payto.aspx.cs プロジェクト: llqing0852/payapi
    private void AddNewOrder(PayOrder order)
    {
        try
        {
            var sqlParms = new List <SqlParameter>();
            sqlParms.Add(new SqlParameter("@OrderNo", SqlDbType.NVarChar, 50)
            {
                Direction = ParameterDirection.Input, Value = order.OrderNo
            });
            sqlParms.Add(new SqlParameter("@Account", SqlDbType.NVarChar, 50)
            {
                Direction = ParameterDirection.Input, Value = order.Account
            });
            sqlParms.Add(new SqlParameter("@RealName", SqlDbType.NVarChar, 50)
            {
                Direction = ParameterDirection.Input, Value = order.RealName
            });
            sqlParms.Add(new SqlParameter("@Amount", SqlDbType.Float)
            {
                Direction = ParameterDirection.Input, Value = order.Amount
            });
            sqlParms.Add(new SqlParameter("@ShowName", SqlDbType.NVarChar, 50)
            {
                Direction = ParameterDirection.Input, Value = order.ShowName
            });
            sqlParms.Add(new SqlParameter("@Remark", SqlDbType.NVarChar, 50)
            {
                Direction = ParameterDirection.Input, Value = order.Remark
            });
            sqlParms.Add(new SqlParameter("@CaseStatus", SqlDbType.NVarChar, 50)
            {
                Direction = ParameterDirection.Input, Value = order.CaseStatus
            });
            sqlParms.Add(new SqlParameter("@Response", SqlDbType.NVarChar, 500)
            {
                Direction = ParameterDirection.Input, Value = order.Response
            });
            sqlParms.Add(new SqlParameter("@Key", SqlDbType.NVarChar, 50)
            {
                Direction = ParameterDirection.Input, Value = order.Key
            });

            DataAccess.ExecuteStoredProcedureNonQuery("AddPayOrder", sqlParms);
        }
        catch (Exception e)
        {
            Logger.Log("AddPayOrder Exception:" + e.ToString());
            throw e;
        }
    }
コード例 #30
0
        public async Task <ApiResult <string> > Query(PayOrder parm)
        {
            var res = new ApiResult <string>()
            {
                statusCode = (int)ApiEnum.Status
            };

            res.message = SettleOrderBll._.Query(WebConfig.MchId, parm.Order_id).Result.ReturnMsg;
            if (res.message == "ok")
            {
                SettleOrderBll._.SendNotify(parm.Order_id.SqlFilters());
            }
            return(await Task.Run(() => res));
        }
コード例 #31
0
ファイル: wxpay.cs プロジェクト: szoliver/wxpay
        /// <summary>
        /// 获取微信支付签名信息
        /// 调用前请先配置wxPayV3Info属性,否则会支付失败,如果paySign = "ERROR",请查看package内容信息
        /// 目前提供最基本的签名字段,有时间的话可以增加基础以外字段的动态增加,一般情况下,基础的字段也能满足支付需求了
        /// 微信支付步骤:</summary>
        /// 1.$.post调用GetWXPayInfo()获取WXPayModel数据,其中包含签名数据
        /// 2.wxpay.js调用 WeixinJSBridge.invoke('getBrandWCPayRequest')发起微信支付
        /// 3.处理回调,成功后返回success
        /// <param name="payorder"></param>
        /// <param name="openid"></param>
        /// <param name="tfee">支付的金额</param>
        /// <param name="body">备注</param>
        /// <param name="pid">产品信息</param>
        /// <param name="sp_billno">订单号码</param>
        /// <returns>返回签名数据,Response给JS呼出微信支付控件,返回WXPayModel.paySign=ERROR时报错</returns>
        public static WXPayModel GetWXPayInfo(PayOrder payorder, string openid, string tfee, string body, string pid, string sp_billno)
        {
            try
            {
                string timeStamp = "";
                string nonceStr = "";
                string package = "";
                string paySign = "";

                //创建支付应答对象
                RequestHandler packageReqHandler = new RequestHandler(null);
                //初始化
                packageReqHandler.Init();

                //调起微信支付签名
                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr = TenPayV3Util.GetNoncestr();

                //设置package订单参数
                packageReqHandler.SetParameter("appid", wxPayV3Info.AppId);		  //公众账号ID
                packageReqHandler.SetParameter("mch_id", wxPayV3Info.MchId);		  //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
                packageReqHandler.SetParameter("body", body);
                packageReqHandler.SetParameter("out_trade_no", sp_billno);		//商家订单号
                packageReqHandler.SetParameter("spbill_create_ip", HttpContext.Current.Request.UserHostAddress);
                packageReqHandler.SetParameter("total_fee", tfee);
                packageReqHandler.SetParameter("notify_url", wxPayV3Info.TenPayV3Notify);		    //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());	 //交易类型
                packageReqHandler.SetParameter("openid", openid);//OPENID

                //获取package包
                string sign = packageReqHandler.CreateMd5Sign("key", wxPayV3Info.Key);
                packageReqHandler.SetParameter("sign", sign);
                string data = packageReqHandler.ParseXML();
                var result = TenPayV3.Unifiedorder(data);
                var res = XDocument.Parse(result);
                if (res.Element("xml").Element("prepay_id") == null)
                {
                    string err_code = res.Element("xml").Element("return_msg").Value;
                    return new WXPayModel() { paySign = "ERROR", package = err_code };
                }
                string prepayId = res.Element("xml").Element("prepay_id").Value;
                package = string.Format("prepay_id={0}", prepayId);
                //设置支付参数
                RequestHandler paySignReqHandler = new RequestHandler(null);
                paySignReqHandler.SetParameter("appId", wxPayV3Info.AppId);
                paySignReqHandler.SetParameter("timeStamp", timeStamp);
                paySignReqHandler.SetParameter("nonceStr", nonceStr);
                paySignReqHandler.SetParameter("package", package);
                paySignReqHandler.SetParameter("signType", "MD5");
                paySign = paySignReqHandler.CreateMd5Sign("key", wxPayV3Info.Key);
                WXPayModel wm = new WXPayModel()
                {
                    appId = wxPayV3Info.AppId,
                    nonceStr = nonceStr,
                    package = package,
                    payNo = sp_billno,
                    paySign = paySign,
                    timeStamp = timeStamp
                };
                //payorder(wm, openid, tfee, body, pid, param, sp_billno);
                payorder(wm);
                return wm;

            }
            catch (Exception ex)
            {
                return new WXPayModel() { paySign = "ERROR", package = "抛出异常:" + ex.ToString() };
            }
        }