public void TestService() { CreateOrderParameters para = new CreateOrderParameters() { AppOrderAmount = 1, AppOrderDesc = "测试", AppOrderID = sss, AppOrderTime = DateTime.Now.ToJITFormatString(), PayChannelID = 16, MobileNO = "18019438327" }; TradeRequest request = new TradeRequest() { AppID = 1, ClientID = "27", Parameters = para, UserID = "1111" }; string parameter = string.Format("action=CreateOrder&request={1}", Url, request.ToJSON()); //parameter = "action=CreateOrder&request={\"AppID\":1,\"ClientID\":\"e703dbedadd943abacf864531decdac1\",\"UserID\":\"00193aeff94341a1a8f64e224c7c249c\",\"Token\":null,\"Parameters\":{\"PayChannelID\":3,\"AppOrderID\":\"61ebfd4cbb1b4716b40605845cc761cd\",\"AppOrderTime\":\"2014-01-17 09:46:30 562\",\"AppOrderAmount\":1,\"AppOrderDesc\":\"jitmarketing\",\"Currency\":1,\"MobileNO\":\"\",\"ReturnUrl\":\"http://www.o2omarketing.cn:9004/HtmlApp/LJ/html/pay_success.html?orderId=61ebfd4cbb1b4716b40605845cc761cd\",\"DynamicID\":null,\"DynamicIDType\":null}}"; var data = Encoding.GetEncoding("utf-8").GetBytes(parameter); var res = GetResponseStr(Url, data).DeserializeJSONTo <TradeResponse>(); Console.WriteLine(res.ToJSON()); }
/// <summary> /// 设置登录信息(用户Id和会话Id) /// </summary> /// <param name="parameters">订单创建参数</param> public static void SetLoginInfo(this CreateOrderParameters parameters) { var sessionManager = Application.Ioc.Resolve <SessionManager>(); var session = sessionManager.GetSession(); var user = session.GetUser(); parameters.UserId = (user == null) ? null : (long?)user.Id; parameters.SessionId = session.Id; }
/// <summary> /// 创建订单 /// </summary> public virtual CreateOrderResult CreateOrder(CreateOrderParameters parameters) { Parameters = parameters; Result = new CreateOrderResult(); CheckOrderParameters(); CreateOrdersBySellers(); RemoveCartProducts(); SaveShippingAddress(); CreateMergedTransaction(); return(Result); }
/// <summary> /// 创建订单 /// </summary> /// <param name="parameters">创建订单的参数</param> /// <returns></returns> public virtual CreateOrderResult CreateOrder(CreateOrderParameters parameters) { var orderCreator = Application.Ioc.Resolve <IOrderCreator>(); var uow = UnitOfWork; using (uow.Scope()) { uow.Context.BeginTransaction(); var result = orderCreator.CreateOrder(parameters); uow.Context.FinishTransaction(); return(result); } }
/// <summary> /// 复制订单创建参数并使用新的订单商品创建参数 /// 一般用于把一个订单创建参数分割为多个订单创建参数时使用 /// </summary> /// <param name="parameters">订单创建参数</param> /// <param name="productParametersList">订单商品创建参数的列表</param> /// <returns></returns> public static CreateOrderParameters CloneWith( this CreateOrderParameters parameters, IList <CreateOrderProductParameters> productParametersList) { return(new CreateOrderParameters() { UserId = parameters.UserId, SessionId = parameters.SessionId, OrderParameters = parameters.OrderParameters, OrderProductParametersList = productParametersList }); }
/// <summary> /// 创建订单 /// </summary> public virtual CreateOrderResult CreateOrder(IDatabaseContext context, CreateOrderParameters parameters) { Parameters = parameters; Context = context; Result = new CreateOrderResult(); CheckOrderParameters(); CreateOrdersBySellers(); RemoveCartProducts(); SaveShippingAddress(); ReduceProductsStock(); CreateMergedTransaction(); return(Result); }
/// <summary> /// 计算订单使用指定的物流的运费 /// 返回 ((运费, 货币), 错误信息) /// </summary> /// <param name="logisticsId">物流Id</param> /// <param name="sellerId">卖家Id</param> /// <param name="parameters">订单创建参数</param> /// <returns></returns> public virtual Pair <Pair <decimal, string>, string> CalculateLogisticsCost( Guid logisticsId, Guid?sellerId, CreateOrderParameters parameters) { // 判断物流的所属人是否空或卖家 var logisticsManager = Application.Ioc.Resolve <LogisticsManager>(); var logistics = logisticsManager.GetWithCache(logisticsId); if (logistics == null) { throw new BadRequestException(new T("Please select logistics")); } else if (logistics.Owner != null && logistics.Owner.Id != sellerId) { throw new ForbiddenException(new T("Selected logistics is not available for this seller")); } // 获取收货地址中的国家和地区 var shippingAddress = (parameters.OrderParameters .GetOrDefault <IDictionary <string, object> >("ShippingAddress") ?? new Dictionary <string, object>()); var country = shippingAddress.GetOrDefault <string>("Country"); var regionId = shippingAddress.GetOrDefault <long?>("RegionId"); // 获取订单商品的总重量 var productManager = Application.Ioc.Resolve <ProductManager>(); var totalWeight = 0M; foreach (var productParameters in parameters.OrderProductParametersList) { var product = productManager.GetWithCache(productParameters.ProductId); var productSellerId = product.Seller?.Id; if (sellerId != productSellerId) { // 跳过其他卖家的商品 continue; } else if (!(product.GetProductType() is IAmRealProduct)) { // 跳过非实体商品 continue; } var orderCount = productParameters.MatchParameters.GetOrderCount(); var data = product.MatchedDatas .Where(d => d.Weight != null) .WhereMatched(productParameters.MatchParameters).FirstOrDefault(); if (data != null) { totalWeight = checked (totalWeight + data.Weight.Value * orderCount); } } // 使用物流管理器计算运费 return(logisticsManager.CalculateCost(logisticsId, country, regionId, totalWeight)); }
/// <summary> /// 计算订单的价格 /// 返回价格保证大于0 /// </summary> /// <param name="parameters">创建订单的参数</param> /// <returns></returns> public virtual OrderPriceCalcResult CalculateOrderPrice( CreateOrderParameters parameters) { var result = new OrderPriceCalcResult(); var calculators = Application.Ioc.ResolveMany <IOrderPriceCalculator>(); foreach (var calculator in calculators) { calculator.Calculate(parameters, result); } if (result.Parts.Sum() <= 0) { throw new BadRequestException(new T("Order cost must larger than 0")); } return(result); }
/// <summary> /// 重新计算支付手续费 /// 删除原有的手续费并按当前的总价重新计算 /// 手续费不会按各个卖家分别计算 /// - 如果使用合并交易可以在合并交易中设置整体的手续费 /// - 例: (交易A: 手续费0.5, 交易B: 手续费0.3, 合并交易: 手续费0.6) /// </summary> public static void ReCalculatePaymentFee( CreateOrderParameters parameters, OrderPriceCalcResult result) { var oldPartIndex = result.Parts.FindIndex(p => p.Type == "PaymentFee"); if (oldPartIndex >= 0) { result.Parts.RemoveAt(oldPartIndex); } var paymentApiManager = Application.Ioc.Resolve <PaymentApiManager>(); var paymentApiId = parameters.OrderParameters.GetPaymentApiId(); var paymentFee = paymentApiManager.CalculatePaymentFee(paymentApiId, result.Parts.Sum()); if (paymentFee != 0) { result.Parts.Add(new OrderPriceCalcResult.Part("PaymentFee", paymentFee)); } }
/// <summary> /// 创建交易中心支付订单AppOrder /// </summary> /// <param name="pRequest"></param> /// <returns></returns> public static CreateOrderResponse CreateOrder(TradeRequest pRequest) { var userInfo = pRequest.GetUserInfo(); CreateOrderResponse response = new CreateOrderResponse(); response.ResultCode = 0; CreateOrderParameters para = pRequest.GetParameter <CreateOrderParameters>(); Loggers.Debug(new DebugLogInfo() { Message = "业务参数:" + para.ToJSON() }); if (para == null) { throw new Exception("Parameters参数不正确"); } AppOrderBLL bll = new AppOrderBLL(userInfo); AppOrderEntity entity; #region 支付等待5秒后可再次支付 var appOrderEntity = bll.QueryByEntity(new AppOrderEntity() { ClientIP = pRequest.ClientID, AppOrderID = para.AppOrderID }, null).FirstOrDefault(); if (appOrderEntity != null) { DateTime dtNow = DateTime.Now; TimeSpan ts = dtNow - appOrderEntity.CreateTime.Value; if (ts.TotalSeconds < 5) { throw new Exception("支付已启动,请稍后再试"); } } #endregion #region 在支付中心创建订单 var tran = bll.CreateTran(); using (tran.Connection) { try { #region 除已存在的订单 bll.DeleteByAppInfo(pRequest.ClientID, para.AppOrderID, pRequest.AppID.Value, tran); #endregion #region 创建订单 entity = new AppOrderEntity() { Status = 0, MobileNO = para.MobileNO, AppClientID = pRequest.ClientID, AppUserID = pRequest.UserID, AppID = pRequest.AppID, AppOrderAmount = Convert.ToInt32(para.AppOrderAmount), AppOrderDesc = para.AppOrderDesc, AppOrderID = para.AppOrderID, AppOrderTime = para.GetDateTime(), Currency = 1, CreateBy = pRequest.UserID, PayChannelID = para.PayChannelID, LastUpdateBy = pRequest.UserID, OpenId = para.OpenId, ClientIP = para.ClientIP }; bll.Create(entity, tran);//并且生成了一个自动增长的订单标识orderid Loggers.Debug(new DebugLogInfo() { Message = "创建支付中心订单并保存数据库:" + entity.ToJSON() }); #endregion tran.Commit(); } catch { tran.Rollback(); throw; } } #endregion #region 获取Channel PayChannelBLL channelBll = new PayChannelBLL(userInfo); var channel = channelBll.GetByID(para.PayChannelID);//PayChannelID是不同商户的支付方式的标识 if (channel == null) { throw new Exception("无此ChannelID的Channel信息"); } #endregion #region 测试Channel订单价格设置为1分钱*** entity.AppOrderAmount = channel.IsTest.Value ? 1 : entity.AppOrderAmount; #endregion string url = string.Empty; if (para.AppOrderDesc != "ScanWxPayOrder") { if (para.PaymentMode == 0) { channel.PayType = 9; //新版支付宝扫码支付 } url = CreatePayRecord(response, para, bll, entity, channel); } response.PayUrl = url; response.OrderID = entity.OrderID; return(response); }
/// <summary> /// 记录请求支付日志信息 /// </summary> /// <param name="response"></param> /// <param name="para"></param> /// <param name="bll"></param> /// <param name="entity"></param> /// <param name="channel"></param> /// <returns></returns> private static string CreatePayRecord(CreateOrderResponse response, CreateOrderParameters para, AppOrderBLL bll, AppOrderEntity entity, PayChannelEntity channel) { string url = string.Empty; //用于记录支付平台的请求和响应 string requestJson = string.Empty; string responseJson = string.Empty; var recordBll = new PayRequestRecordBLL(new Utility.BasicUserInfo()); var recordEntity = new PayRequestRecordEntity() { ChannelID = channel.ChannelID, ClientID = entity.AppClientID, UserID = entity.AppUserID }; #region 根据Channel类型创建支付订单 try { switch (channel.PayType) { case 1: recordEntity.Platform = 1; #region 银联Wap支付 UnionPayChannel unionWapPaychannel = channel.ChannelParameters.DeserializeJSONTo <UnionPayChannel>(); PreOrderRequest Wapreq = new PreOrderRequest() { BackUrl = ConfigurationManager.AppSettings["UnionPayWapNotifyUrl"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID), FrontUrl = string.IsNullOrEmpty(para.ReturnUrl) ? ConfigurationManager.AppSettings["UnionPayCallBackUrl"] : para.ReturnUrl, MerchantID = unionWapPaychannel.MerchantID, SendTime = DateTime.Now, MerchantOrderCurrency = Currencys.RMB, MerchantOrderDesc = entity.AppOrderDesc, MerchantOrderAmt = entity.AppOrderAmount, MerchantOrderID = entity.OrderID.ToString(), SendSeqID = Guid.NewGuid().ToString("N"), MerchantOrderTime = entity.AppOrderTime }; requestJson = Wapreq.ToJSON(); var unionWapResponse = JIT.Utility.Pay.UnionPay.Interface.Wap.WapGateway.PreOrder(unionWapPaychannel, Wapreq); responseJson = unionWapResponse.ToJSON(); if (unionWapResponse.IsSuccess) { entity.PayUrl = unionWapResponse.RedirectURL; entity.Status = 1; bll.Update(entity); url = unionWapResponse.RedirectURL; Loggers.Debug(new DebugLogInfo() { Message = string.Format("银联Wap创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, Wapreq.ToJSON(), unionWapResponse.ToJSON()) }); } else { Loggers.Debug(new DebugLogInfo() { Message = string.Format("银联Wap创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, Wapreq.ToJSON(), unionWapResponse.ToJSON()) }); response.ResultCode = 100; response.Message = unionWapResponse.Description; } #endregion break; case 2: recordEntity.Platform = 1; #region 银联语音支付 UnionPayChannel unionIVRPaychannel = channel.ChannelParameters.DeserializeJSONTo <UnionPayChannel>(); JIT.Utility.Pay.UnionPay.Interface.IVR.Request.PreOrderRequest IVRreq = new Utility.Pay.UnionPay.Interface.IVR.Request.PreOrderRequest() { SendTime = DateTime.Now, SendSeqID = Guid.NewGuid().ToString("N"), FrontUrl = string.IsNullOrEmpty(para.ReturnUrl) ? ConfigurationManager.AppSettings["UnionPayCallBackUrl"] : para.ReturnUrl, BackUrl = ConfigurationManager.AppSettings["UnionPayIVRNotifyUrl"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID), MerchantOrderDesc = entity.AppOrderDesc, Mode = IVRModes.Callback, TransTimeout = entity.AppOrderTime, MerchantOrderCurrency = Currencys.RMB, MerchantOrderAmt = entity.AppOrderAmount, MerchantID = unionIVRPaychannel.MerchantID, MerchantOrderTime = entity.AppOrderTime, MerchantOrderID = entity.OrderID.ToString(), MobileNum = entity.MobileNO }; requestJson = IVRreq.ToJSON(); var IvrResponse = IVRGateway.PreOrder(unionIVRPaychannel, IVRreq); responseJson = IvrResponse.ToJSON(); if (IvrResponse.IsSuccess) { entity.Status = 1; bll.Update(entity); Loggers.Debug(new DebugLogInfo() { Message = string.Format("银联IVR创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, IVRreq.ToJSON(), IvrResponse.ToJSON()) }); } else { Loggers.Debug(new DebugLogInfo() { Message = string.Format("银联IVR创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, IVRreq.ToJSON(), IvrResponse.ToJSON()) }); response.ResultCode = 200; response.Message = IvrResponse.Description; } #endregion break; case 3: recordEntity.Platform = 2; #region 阿里Wap支付 AliPayChannel aliPayWapChannel = channel.ChannelParameters.DeserializeJSONTo <AliPayChannel>(); AliPayWapTokenRequest tokenRequest = new AliPayWapTokenRequest(aliPayWapChannel) { CallBackUrl = string.IsNullOrEmpty(para.ReturnUrl) ? ConfigurationManager.AppSettings["AliPayCallBackUrl"] : para.ReturnUrl, NotifyUrl = ConfigurationManager.AppSettings["AlipayWapNotify"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID), OutTradeNo = entity.OrderID.ToString(), Partner = aliPayWapChannel.Partner, SellerAccountName = aliPayWapChannel.SellerAccountName, Subject = entity.AppOrderDesc, TotalFee = Math.Round((Convert.ToDecimal(entity.AppOrderAmount) / 100), 2).ToString(), ReqID = Guid.NewGuid().ToString().Replace("-", "") }; requestJson = tokenRequest.ToJSON(); var aliPayWapResponse = AliPayWapGeteway.GetQueryTradeResponse(tokenRequest, aliPayWapChannel); responseJson = aliPayWapResponse.ToJSON(); if (aliPayWapResponse.IsSucess) { entity.PayUrl = aliPayWapResponse.RedirectURL; entity.Status = 1; bll.Update(entity); url = aliPayWapResponse.RedirectURL; Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayWap创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, tokenRequest.ToJSON(), aliPayWapResponse.ToJSON()) }); } else { Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayWap创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, tokenRequest.ToJSON(), aliPayWapResponse.ToJSON()) }); response.ResultCode = 300; response.Message = aliPayWapResponse.Message; } #endregion break; case 4: recordEntity.Platform = 2; #region 阿里OffLine支付 AliPayChannel aliPayChannel = channel.ChannelParameters.DeserializeJSONTo <AliPayChannel>(); //根据DynamicID判断是否预定单支付,DynamicID为空或者Null时调用OffLine预订单接口 if (string.IsNullOrWhiteSpace(para.DynamicID)) { OfflineQRCodePreRequest qrRequest = new OfflineQRCodePreRequest(aliPayChannel) { OutTradeNo = entity.OrderID.ToString(), NotifyUrl = ConfigurationManager.AppSettings["AlipayOfflineNotify"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID), Subject = entity.AppOrderDesc, TotalFee = Math.Round((Convert.ToDecimal(entity.AppOrderAmount) / 100), 2).ToString(), //下面是测试数据,正式须更改 ExtendParams = new { MACHINE_ID = "BJ_001", //? AGENT_ID = aliPayChannel.AgentID, STORE_TYPE = "0", //? STORE_ID = "12314", //? TERMINAL_ID = "111", //? SHOP_ID = "only" //? }.ToJSON() }; requestJson = qrRequest.ToJSON(); var offlineQrResponse = AliPayOffLineGeteway.OfflineQRPay(qrRequest); responseJson = offlineQrResponse.ToJSON(); if (offlineQrResponse.IsSucess) { entity.Status = 1; entity.PayUrl = offlineQrResponse.PicUrl; bll.Update(entity); response.QrCodeUrl = offlineQrResponse.PicUrl; Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayOffline二维码支付创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, qrRequest.ToJSON(), offlineQrResponse.ToJSON()) }); } else { Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayOffline二维码支付创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, qrRequest.ToJSON(), offlineQrResponse.ToJSON()) }); response.ResultCode = 400; response.Message = offlineQrResponse.DetailErrorCode + ":" + offlineQrResponse.DetailErrorDes; } } else { CreateAndPayRequest createAndPayrequest = new CreateAndPayRequest(aliPayChannel) { Subject = entity.AppOrderDesc, TotalFee = Math.Round((Convert.ToDecimal(entity.AppOrderAmount) / 100), 2).ToString(), NotifyUrl = ConfigurationManager.AppSettings["AlipayOfflineNotify"].Trim('?') + string.Format("?ChannelID={0}", channel.ChannelID), OutTradeNo = entity.OrderID.ToString(), DynamicIDType = para.DynamicIDType, DynamicID = para.DynamicID, }; if (!string.IsNullOrEmpty(aliPayChannel.AgentID)) { createAndPayrequest.ExtendParams = (new { AGENT_ID = aliPayChannel.AgentID, MACHINE_ID = "BJ_001", STORE_TYPE = "0", STORE_ID = "BJ_ZZ_001", TERMINAL_ID = "A80001", SHOP_ID = "only" }).ToJSON(); } requestJson = createAndPayrequest.ToJSON(); var offlineCreateAndPayResponse = AliPayOffLineGeteway.OfflineCreateAndPay(createAndPayrequest); responseJson = offlineCreateAndPayResponse.ToJSON(); if (offlineCreateAndPayResponse.IsSuccess) { entity.Status = 2; bll.Update(entity); Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayOffline即支付创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, createAndPayrequest.ToJSON(), offlineCreateAndPayResponse.ToJSON()) }); } else if (offlineCreateAndPayResponse.ResultCode == ResultCodes.ORDER_SUCCESS_PAY_FAIL.ToString()) { entity.Status = 1; bll.Update(entity); Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayOffline即支付创建订单成功{0},支付失败【请求】:{1}{0}【响应】:{2}", Environment.NewLine, createAndPayrequest.ToJSON(), offlineCreateAndPayResponse.ToJSON()) }); } else if (offlineCreateAndPayResponse.ResultCode == ResultCodes.ORDER_SUCCESS_PAY_INPROCESS.ToString()) { entity.Status = 1; bll.Update(entity); Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayOffline即支付创建订单成功{0},支付处理中【请求】:{1}{0}【响应】:{2}", Environment.NewLine, createAndPayrequest.ToJSON(), offlineCreateAndPayResponse.ToJSON()) }); } else { Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayOffline即支付创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, createAndPayrequest.ToJSON(), offlineCreateAndPayResponse.ToJSON()) }); response.ResultCode = 400; response.Message = offlineCreateAndPayResponse.DetailErrorCode + ":" + offlineCreateAndPayResponse.DetailErrorDes; } } #endregion break; case 5: //Native case 6: //微信JS case 7: //微信App recordEntity.Platform = 3; #region 微信Native支付,JS支付 //把channel里的参数传了过去 WeiXinPayHelper helper = new WeiXinPayHelper(channel.ChannelParameters.DeserializeJSONTo <WeiXinPayHelper.Channel>()); entity.PayUrl = ConfigurationManager.AppSettings["WeiXinPrePay"]; entity.NotifyUrl = ConfigurationManager.AppSettings["WeiXinPayNotify"]; WeiXinPayHelper.PrePayResult result = null; if (para.PaymentMode == 1) //PaymentMode=1标示微信扫码支付进入 { helper.channel.trade_type = "NATIVE"; channel.PayType = 5; //走扫码回调返回参数 } Loggers.Debug(new DebugLogInfo() { Message = "isSpPay:" + helper.channel.isSpPay }); if (helper.channel.isSpPay == "1") //isSpPay=1 服务商支付 { result = helper.serPrePay(entity); //统一下单,服务商支付 } else { result = helper.prePay(entity); //统一下单,获取微信网页支付的预支付信息,app支付和js支付是一样的 } Loggers.Debug(new DebugLogInfo() { Message = "微信支付_预支付返回结果:" + result.ToJSON() }); requestJson = helper.prePayRequest; responseJson = helper.prePayResponse; if (result.return_code == "SUCCESS" && result.result_code == "SUCCESS") { if (channel.PayType == 6) { response.WXPackage = helper.getJsParamater(result); } else if (channel.PayType == 7) //后面传的参数和js支付的就不一样了 { response.WXPackage = helper.getAppParamater(result); response.OrderID = entity.OrderID; } else //Native { response.WXPackage = result.ToJSON(); response.QrCodeUrl = result.code_url; } Loggers.Debug(new DebugLogInfo() { Message = "WXPackage:" + response.WXPackage }); } else { response.ResultCode = 101; //支付失败 if (!string.IsNullOrEmpty(result.return_msg)) //不同错误,错误信息位置不同 { response.Message = result.return_msg; } else { response.Message = result.err_code_des; } } #endregion break; case 8: //旺财支付 return(string.Empty); case 9: //新版支付宝扫码支付 #region AliPayChannel aliPayScanChannel = channel.ChannelParameters.DeserializeJSONTo <AliPayChannel>(); RequestScanEntity scRequest = new RequestScanEntity(aliPayScanChannel); scRequest.notify_url = "" + ConfigurationManager.AppSettings["AlipayOfflineNotify"]; RequstScanDetail scanDetail = new RequstScanDetail(); scanDetail.out_trade_no = "" + entity.OrderID; scanDetail.total_amount = "" + Math.Round((Convert.ToDecimal(entity.AppOrderAmount) / 100), 2); scanDetail.seller_id = aliPayScanChannel.Partner; scanDetail.subject = entity.AppOrderDesc; var scResponseJson = AliPayScanGeteway.GetResponseStr(scRequest, scanDetail.ToJSON(), aliPayScanChannel.RSA_PrivateKey); var scResponse = scResponseJson.DeserializeJSONTo <ResponsetScanEntity>(); if (scResponse.alipay_trade_precreate_response.code == "10000") { response.QrCodeUrl = scResponse.alipay_trade_precreate_response.qr_code; Loggers.Debug(new DebugLogInfo() { Message = string.Format("aliPayScanChannel二维码支付创建订单成功{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, requestJson, scResponseJson) }); } else { Loggers.Debug(new DebugLogInfo() { Message = string.Format("AliPayOffline二维码支付创建订单失败{0}【请求】:{1}{0}【响应】:{2}", Environment.NewLine, requestJson, scResponseJson) }); response.ResultCode = 400; response.Message = scResponse.alipay_trade_precreate_response.code + ":" + scResponse.alipay_trade_precreate_response.msg; } #endregion break; default: break; } recordEntity.RequestJson = requestJson; recordEntity.ResponseJson = responseJson; recordBll.Create(recordEntity); } catch (Exception ex) { recordEntity.RequestJson = requestJson; recordEntity.ResponseJson = responseJson; recordBll.Create(recordEntity); throw ex; } #endregion return(url); }
/// <summary> /// 获取购物车商品计算价格的信息 /// 为了保证数据的实时性,这个函数不使用缓存 /// </summary> /// <param name="parameters">订单创建参数</param> /// <returns></returns> public virtual object GetCartCalculatePriceApiInfo(CreateOrderParameters parameters) { // 计算各个商品的单价(数量等改变后有可能会改变单价) var orderProductUnitPrices = new List <object>(); var orderManager = Application.Ioc.Resolve <SellerOrderManager>(); var currencyManager = Application.Ioc.Resolve <CurrencyManager>(); foreach (var productParameters in parameters.OrderProductParametersList) { var productResult = orderManager.CalculateOrderProductUnitPrice( parameters.UserId, productParameters); var currency = currencyManager.GetCurrency(productResult.Currency); var priceString = currency.Format(productResult.Parts.Sum()); var description = productResult.Parts.GetDescription(); orderProductUnitPrices.Add(new { priceString, description, extra = productParameters.Extra }); } // 计算订单总价 var orderResult = orderManager.CalculateOrderPrice(parameters); var orderCurrency = currencyManager.GetCurrency(orderResult.Currency); var orderPriceString = orderCurrency.Format(orderResult.Parts.Sum()); var orderPriceDescription = orderResult.Parts.GetDescription(); // 获取商品总价 var orderProductTotalPricePart = orderResult.Parts .FirstOrDefault(p => p.Type == "ProductTotalPrice"); var orderProductTotalPriceString = orderCurrency.Format( orderProductTotalPricePart == null ? 0 : orderProductTotalPricePart.Delta); // 计算各个物流的运费 // 同时选择可用的物流(部分物流不能送到选择的地区) var availableLogistics = new Dictionary <Guid, IList <object> >(); var sellerIds = parameters.OrderProductParametersList.GetSellerIdsHasRealProducts(); foreach (var sellerId in sellerIds) { var sellerIdOrNull = sellerId == Guid.Empty ? null : (Guid?)sellerId; var logisticsList = orderManager .GetAvailableLogistics(parameters.UserId, sellerIdOrNull) .Select(l => { var result = orderManager.CalculateLogisticsCost(l.Id, sellerIdOrNull, parameters); if (!string.IsNullOrEmpty(result.Second)) { return((object)null); } var currency = currencyManager.GetCurrency(result.First.Second); return(new { logisticsId = l.Id, costString = currency.Format(result.First.First) }); }) .Where(l => l != null).ToList(); availableLogistics[sellerId] = logisticsList; } // 计算各个支付接口的手续费 // 同时选择可用的支付接口 var paymentApiManager = Application.Ioc.Resolve <PaymentApiManager>(); var orderPriceWithoutPaymentFee = orderResult.Parts .Where(p => p.Type != "PaymentFee").ToList().Sum(); var availablePaymentApis = orderManager .GetAvailablePaymentApis(parameters.UserId) .Select(a => { var paymentFee = paymentApiManager.CalculatePaymentFee( parameters.OrderParameters.GetPaymentApiId(), orderPriceWithoutPaymentFee); return(new { apiId = a.Id, feeString = orderCurrency.Format(paymentFee) }); }) .Where(a => a != null).ToList <object>(); return(new { orderPriceString, orderPriceDescription, orderProductTotalPriceString, orderProductUnitPrices, availableLogistics, availablePaymentApis }); }
/// <summary> /// 设置订单价格等于以下的合计 /// - 商品总价 /// - 运费 /// - 支付手续费 /// 注意 /// - 传入的参数中可能会包含多个卖家 /// </summary> public void Calculate(CreateOrderParameters parameters, OrderPriceCalcResult result) { // 计算商品总价 if (!parameters.OrderProductParametersList.Any()) { throw new BadRequestException(new T("Please select the products you want to purchase")); } var orderManager = Application.Ioc.Resolve <OrderManager>(); var orderProductTotalPrice = 0.0M; var currencyIsSet = false; foreach (var productParameters in parameters.OrderProductParametersList) { // 计算商品单价 var productResult = orderManager.CalculateOrderProductUnitPrice( parameters.UserId, productParameters); // 货币按第一个商品设置,后面检查货币是否一致 if (!currencyIsSet) { currencyIsSet = true; result.Currency = productResult.Currency; } else if (result.Currency != productResult.Currency) { throw new BadRequestException(new T("Create order contains multi currency is not supported")); } // 添加到商品总价 var orderCount = productParameters.MatchParameters.GetOrderCount(); if (orderCount <= 0) { throw new BadRequestException(new T("Order count must larger than 0")); } orderProductTotalPrice = checked (orderProductTotalPrice + productResult.Parts.Sum() * orderCount); } result.Parts.Add(new OrderPriceCalcResult.Part("ProductTotalPrice", orderProductTotalPrice)); // 计算运费 // 非实体商品不需要计算运费 var productManager = Application.Ioc.Resolve <ProductManager>(); var sellerToLogistics = parameters.OrderParameters.GetSellerToLogistics(); var sellerIds = parameters.OrderProductParametersList.GetSellerIdsHasRealProducts(); var totalLogisticsCost = 0M; foreach (var sellerId in sellerIds) { var logisticsId = sellerToLogistics.GetOrDefault(sellerId); var logisticsCost = orderManager.CalculateLogisticsCost(logisticsId, sellerId, parameters); if (!string.IsNullOrEmpty(logisticsCost.Second)) { // 计算运费错误 throw new BadRequestException(logisticsCost.Second); } else if (logisticsCost.First.First != 0 && logisticsCost.First.Second != result.Currency) { // 货币不一致 throw new BadRequestException(new T("Create order contains multi currency is not supported")); } totalLogisticsCost = checked (totalLogisticsCost + logisticsCost.First.First); } if (totalLogisticsCost != 0) { result.Parts.Add(new OrderPriceCalcResult.Part("LogisticsCost", totalLogisticsCost)); } // 计算支付手续费 ReCalculatePaymentFee(parameters, result); }
/// <summary> /// 创建订单 /// </summary> /// <param name="parameters">创建订单的参数</param> /// <returns></returns> public virtual CreateOrderResult CreateOrder(CreateOrderParameters parameters) { var orderCreator = Application.Ioc.Resolve <IOrderCreator>(); return(UnitOfWork.Write(context => orderCreator.CreateOrder(context, parameters))); }