Beispiel #1
0
        public List <Payment> Parser(int branchOfficeId, PaymentChannel paymentChannel, IFormFile file)
        {
            var listPayments = new List <Payment>();

            using var ms = new MemoryStream();
            file.CopyTo(ms);
            var dbf = new Dbf(Encoding.GetEncoding(866));

            dbf.Read(ms);

            var recordList = paymentChannel.TotalRecord == FileTotalRow.Last
                ? dbf.Records.GetRange(0, dbf.Records.Count - 1)
                : dbf.Records.GetRange(Convert.ToInt16(paymentChannel.TotalRecord), dbf.Records.Count - Convert.ToInt16(paymentChannel.TotalRecord));

            foreach (DbfRecord record in recordList)
            {
                listPayments.Add(
                    new Payment(
                        DateTime.ParseExact(record[paymentChannel.DateFieldName].ToString(), paymentChannel.TextDateFormat, new CultureInfo(CultureInfo.CurrentCulture.ToString())),
                        Convert.ToDecimal(record[paymentChannel.SumFieldName].ToString()),
                        _branchOfficeService.GetOne(branchOfficeId).CurrentPeriodId,
                        paymentChannel.PaymentsType,
                        string.Join(" ", paymentChannel.PersonFieldName.Split("+").Select(x => record[x]).ToList()),
                        _ercContext.AccountingPoints.FirstOrDefault(x => x.Name == record[paymentChannel.RecordpointFieldName.Trim()].ToString())?.Id,
                        record[paymentChannel.RecordpointFieldName].ToString()
                        )
                    );
            }

            return(listPayments);
        }
Beispiel #2
0
        public async Task <PaymentResult> UseBank(User user, decimal amount, DateTime date, BankAccount userAccount, BankAccount platformAccount, string description = "")
        {
            PaymentChannel channel = await DataContext.Store.GetOneAsync <PaymentChannel>(p => p.Type == ChannelType.Bank);

            DepositPaymentRequest request = new DepositPaymentRequest()
            {
                AddedAtUtc            = DateTime.UtcNow,
                TransactionDate       = date,
                User                  = user,
                Amount                = amount,
                PaymentChannel        = channel,
                Status                = RequestStatus.Pending,
                Description           = description,
                TransactionType       = TransactionType.Deposit,
                UserBankAccountId     = userAccount != null ? userAccount.Id : Guid.Empty,
                PlatformBankAccountId = platformAccount.Id
            };

            await user.AddPaymentRequestAsync(request);

            return(new PaymentResult()
            {
                Status = PaymentStatus.Pending
            });
        }
Beispiel #3
0
        public async Task <IActionResult> Add(PaymentChannel paymentChannel)
        {
            _ercContext.PaymentChannels.Add(paymentChannel);
            await _ercContext.SaveChangesAsync();

            return(Ok(paymentChannel));
        }
Beispiel #4
0
        public async Task <bool> ConcludePaystack(PaystackTransactionData data)
        {
            PaymentChannel channel = await DataContext.Store.GetOneAsync <PaymentChannel>(p => p.Type == ChannelType.Paystack);

            if (!decimal.TryParse(data.Amount, out decimal transactionAmount))
            {
                return(false);
            }

            if (!Guid.TryParse((string)data.Metadata["walletId"], out Guid walletId))
            {
                return(false);
            }
            if (!Guid.TryParse(data.Reference, out Guid transactionId))
            {
                return(false);
            }


            User   platformAccount = DataContext.PlatformAccount;
            Wallet wallet          = await DataContext.Store.GetByIdAsync <Wallet>(walletId);

            decimal amount = transactionAmount / channel.ConversionRate;

            await CreateTransaction(wallet, amount, TransactionType.Deposit, ChannelType.Paystack);

            if (data.Authorization.Reusable && string.IsNullOrWhiteSpace(wallet.PaystackAuthorization))
            {
                wallet.PaystackAuthorization = data.Authorization.AuthorizationCode;
                await DataContext.Store.UpdateOneAsync(wallet.User);
            }

            return(true);
        }
Beispiel #5
0
        private static string GetPaymentServerUrl(PaymentEnvironment environment, PaymentChannel channel)
        {
            string host = environment.Equals(PaymentEnvironment.Sandbox) ?
                          "https://payment-sandbox.funplusgame.com" :
                          "https://payment.funplusgame.com";

            string channelName;

            switch (channel)
            {
            case PaymentChannel.PlayStore:
                channelName = "googleplayiap";
                break;

            case PaymentChannel.AppStore:
                channelName = "appleiap";
                break;

            case PaymentChannel.Amazon:
                channelName = "amazoniap";
                break;

            default:
                channelName = "unknown";
                break;
            }

            return(string.Format("{0}/callback/{1}/", host, channelName));
        }
Beispiel #6
0
 public static void SendData(PaymentEnvironment environment,
                             PaymentChannel channel,
                             Dictionary <string, String> data,
                             Action onSuccess,
                             Action <string> onFailure)
 {
     Instance.SendDataToPaymentServer(
         environment,
         channel,
         data,
         onSuccess,
         onFailure
         );
 }
Beispiel #7
0
        public async Task <IActionResult> Update(PaymentChannel paymentChannel)
        {
            var pc = await _ercContext.PaymentChannels.FindAsync(paymentChannel.Id);

            if (pc is null)
            {
                return(NotFound());
            }

            _ercContext.Entry(pc).CurrentValues.SetValues(paymentChannel);
            await _ercContext.SaveChangesAsync();

            return(Ok());
        }
Beispiel #8
0
        /// <summary>
        /// 获取最后车牌号
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="orderType"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public static string QueryLastPaymentPlateNumber(PaymentChannel channel, string openId)
        {
            if (string.IsNullOrWhiteSpace(openId))
            {
                return(string.Empty);
            }

            IOnlineOrder factory     = OnlineOrderFactory.GetFactory();
            string       plateNumber = factory.QueryLastPaymentPlateNumber(channel, openId);

            if (plateNumber.Length > 10)
            {
                return(string.Empty);
            }
            return(plateNumber);
        }
Beispiel #9
0
        private static int GetServicePayWay(PaymentChannel type)
        {
            switch (type)
            {
            case PaymentChannel.WeiXinPay:
            {
                return(2);
            }

            case PaymentChannel.AliPay:
            {
                return(3);
            }

            default: throw new MyException("支付类型错误");
            }
        }
Beispiel #10
0
        private void SendDataToPaymentServer(PaymentEnvironment environment,
                                             PaymentChannel channel,
                                             Dictionary <string, String> data,
                                             Action onSuccess,
                                             Action <string> onFailure)
        {
            string url = GetPaymentServerUrl(environment, channel);

            WWWForm wf = new WWWForm();

            foreach (KeyValuePair <string, string> entry in data)
            {
                wf.AddField(entry.Key, entry.Value);
            }

            StartCoroutine(Post(url, wf, onSuccess, onFailure));
        }
Beispiel #11
0
        public async Task BankWithdrawal(User user, decimal amount, BankAccount account)
        {
            PaymentChannel channel = DataContext.Store.GetOne <PaymentChannel>(p => p.Type == ChannelType.Bank);

            PaymentRequest request = new PaymentRequest()
            {
                AddedAtUtc        = DateTime.UtcNow,
                User              = user,
                Amount            = amount,
                PaymentChannel    = channel,
                Status            = RequestStatus.Pending,
                TransactionType   = TransactionType.Withdrawal,
                UserBankAccountId = account.Id
            };

            user.Wallet.AvailableBalance -= amount;

            await user.AddPaymentRequestAsync(request);
        }
Beispiel #12
0
        public async Task <IActionResult> UpdatePaymentChannel([FromBody] ChannelUpdateViewModel model)
        {
            PaymentChannel channel = await DataContext.Store.GetOneAsync <PaymentChannel>(c => c.Type == model.Type);

            if (channel == null)
            {
                return(NotFound());
            }

            if (channel.IsActive == model.IsActive)
            {
                return(Ok());
            }

            channel.IsActive = model.IsActive;
            await DataContext.Store.UpdateOneAsync(channel);

            return(Ok());
        }
Beispiel #13
0
        public async Task <bool> CreateTransaction(Wallet wallet, decimal amount, TransactionType type, ChannelType channelType)
        {
            PaymentChannel channel = await DataContext.Store.GetOneAsync <PaymentChannel>(p => p.Type == channelType);

            User platformAccount = DataContext.PlatformAccount;

            Transaction transaction = new Transaction()
            {
                AddedAtUtc     = DateTime.UtcNow,
                Amount         = amount,
                AuxilaryUser   = wallet.User,
                PaymentChannel = channel,
                Type           = type,
            };

            await wallet.AddTransactionAsync(transaction);

            //await platformAccount.Wallet.AddTransactionAsync(new Transaction(transaction) { AuxilaryUser = wallet.User });

            return(true);
        }
Beispiel #14
0
        public string QueryLastPaymentPlateNumber(PaymentChannel channel, string openId)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.AppendFormat("select top 1 PlateNo FROM onlineorder where OrderType in({0},{1}) and paymentchannel=@PaymentChannel and payAccount=@PayAccount order by OrderID desc", (int)OnlineOrderType.ParkFee, (int)OnlineOrderType.PkBitBooking);

            using (DbOperator dbOperator = ConnectionManager.CreateReadConnection())
            {
                dbOperator.ClearParameters();
                dbOperator.AddParameter("PaymentChannel", (int)channel);
                dbOperator.AddParameter("PayAccount", openId);
                using (DbDataReader reader = dbOperator.ExecuteReader(strSql.ToString()))
                {
                    List <OnlineOrder> models = new List <OnlineOrder>();
                    if (reader.Read())
                    {
                        return(reader.GetStringDefaultEmpty(0));
                    }
                    return(string.Empty);
                }
            }
        }
Beispiel #15
0
        public async Task <bool> ConcludePaystack(PaystackTransactionData data, PaymentType type, UserTransactionMetadata meta = null)
        {
            if (type != PaymentType.Deposit && type != PaymentType.Withdrawal && type != PaymentType.Direct)
            {
                return(false);
            }

            PaymentChannel channel = await DataContext.Store
                                     .GetOneAsync <PaymentChannel, int>(p => p.Type == ChannelType.Paystack);

            if (!decimal.TryParse(data.Amount, out decimal transactionAmount))
            {
                return(false);
            }

            if (!Guid.TryParse((string)data.Metadata["walletId"], out Guid walletId))
            {
                return(false);
            }
            if (!Guid.TryParse(data.Reference, out Guid transactionId))
            {
                return(false);
            }

            Wallet wallet = await DataContext.Store.GetByIdAsync <Wallet>(walletId);

            decimal amount = transactionAmount / channel.ConversionRate;

            await CreateTransaction(wallet, amount, type, ChannelType.Paystack, Status.Approved, meta);

            if (data.Authorization.Reusable && string.IsNullOrWhiteSpace(wallet.PaystackAuthorization))
            {
                wallet.PaystackAuthorization = data.Authorization.AuthorizationCode;
                await DataContext.Store.UpdateOneAsync(wallet.User);
            }

            return(true);
        }
        private List <PaymentChannel> getPaymetChannels(String CountryCode)
        {
            List <PaymentChannel> pcs = new List <PaymentChannel>();
            // PaymentChannel pc = new PaymentChannel { PaymentChannelCode = "ISYSWALLET", CurrencyCode = "KWD",PaymentChannelName="MyAccount" };
            // PaymentChannel pc2 = new PaymentChannel { PaymentChannelCode = "KWKNETDC", CurrencyCode = "KWD", PaymentChannelName = "Knet" };
            //pcs.Add(pc);

            HttpClientHandler handler = new HttpClientHandler();

            handler.Credentials = new NetworkCredential("DelaerWebV1", "dEAlerwEB170409");
            HttpClient client = new HttpClient(handler);

            client.BaseAddress = new Uri("http://192.168.1.11/GlobalPayit/GlobalPayitAPIv5/api/GlobalPayitServices/GetPaymentChannels2");
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));


            HttpResponseMessage response = client.GetAsync("http://192.168.1.11/GlobalPayit/GlobalPayitAPIv5/api/GlobalPayitServices/GetPaymentChannels2?CountryCode=" + CountryCode).Result;
            Task <string>       ss       = response.Content.ReadAsStringAsync();
            var pag = JsonConvert.DeserializeObject <List <PaymentChannelResp> >(ss.Result);

            if (pag != null)
            {
                if (pag.Count > 0)
                {
                    foreach (var item in pag)
                    {
                        PaymentChannel pc = new PaymentChannel {
                            PaymentChannelCode = item.PaymentChannelCode, CurrencyCode = item.PaymentChannelThreeCurrencyCode, PaymentChannelName = item.PaymentChannelName, PaymentChannelID = item.PaymentChannelID, Image = item.Images != null? item.Images.ImageURL1:null
                        };
                        pcs.Add(pc);
                    }
                }
            }
            return(pcs);
        }
Beispiel #17
0
 /// <summary>
 /// Deposits funds in to this wallet
 /// </summary>
 /// <param name="amount">amount which is being deposited</param>
 /// <param name="refNumber">reference number with the online transaction</param>
 /// <param name="channel">name of the payment service</param>
 /// <param name="timeStamp">date and time of the transaction</param>
 public void Deposit(decimal amount, string refNumber, PaymentChannel channel, DateTime timeStamp)
 {
 }
Beispiel #18
0
        public object BarcodePay(Dictionary <string, object> dicParas)
        {
            try
            {
                string errMsg        = string.Empty;
                string orderId       = dicParas.ContainsKey("orderId") ? dicParas["orderId"].ToString() : string.Empty;
                string strPayChannel = dicParas.ContainsKey("payChannel") ? dicParas["payChannel"].ToString() : string.Empty;
                string subject       = dicParas.ContainsKey("subject") ? dicParas["subject"].ToString() : string.Empty;
                string payType       = dicParas.ContainsKey("payType") ? dicParas["payType"].ToString() : string.Empty;
                string authCode      = dicParas.ContainsKey("authCode") ? dicParas["authCode"].ToString() : string.Empty;

                if (string.IsNullOrWhiteSpace(orderId))
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单号无效"));
                }

                if (string.IsNullOrWhiteSpace(payType))
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付方式为空"));
                }
                //支付方式
                PaymentChannel PayChannel = (PaymentChannel)Convert.ToInt32(payType);

                Flw_Order order = Flw_OrderBusiness.GetOrderModel(orderId);
                if (order == null)
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单号无效"));
                }
                Base_StoreInfo store = XCCloudStoreBusiness.GetStoreModel(order.StoreID);
                if (store == null)
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单所属门店无效"));
                }

                //订单减免金额
                decimal freePay = order.FreePay == null ? 0 : order.FreePay.Value;
                //计算订单实付金额,单位:元
                decimal amount = (decimal)order.PayCount - freePay;

                BarcodePayModel model = new BarcodePayModel();
                model.OrderId = orderId;

                //SelttleType selttleType = (SelttleType)store.SelttleType.Value;
                SelttleType selttleType = (SelttleType)Convert.ToInt32(strPayChannel);
                switch (selttleType)
                {
                case  SelttleType.NotThird:
                    break;

                case SelttleType.AliWxPay:     //微信支付宝官方通道
                {
                    #region 微信支付宝官方通道
                    if (PayChannel == PaymentChannel.ALIPAY)        //支付宝
                    {
                        try
                        {
                            IAlipayTradeService serviceClient = F2FBiz.CreateClientInstance(AliPayConfig.serverUrl, AliPayConfig.appId, AliPayConfig.merchant_private_key, AliPayConfig.version,
                                                                                            AliPayConfig.sign_type, AliPayConfig.alipay_public_key, AliPayConfig.charset);

                            AliPayCommon alipay = new AliPayCommon();
                            AlipayTradePayContentBuilder builder = alipay.BuildPayContent(order, amount, subject, authCode);
                            //string out_trade_no = builder.out_trade_no;

                            AlipayF2FPayResult payResult = serviceClient.tradePay(builder);

                            if (payResult.Status == ResultEnum.SUCCESS)
                            {
                                decimal payAmount = Convert.ToDecimal(payResult.response.TotalAmount);

                                //支付成功后的处理
                                BarcodePayModel callbackModel = Flw_OrderBusiness.OrderPay(payResult.response.OutTradeNo, payAmount, selttleType);

                                model.OrderStatus = callbackModel.OrderStatus;
                                model.PayAmount   = payAmount.ToString("0.00");
                            }
                            else
                            {
                                LogHelper.SaveLog(TxtLogType.AliPay, payResult.response.SubMsg);
                                return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败"));
                            }
                        }
                        catch (Exception e)
                        {
                            LogHelper.SaveLog(TxtLogType.AliPay, e.Message);
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败"));
                        }
                    }
                    else if (PayChannel == PaymentChannel.WXPAY)
                    {
                        try
                        {
                            MicroPay  pay        = new MicroPay();
                            WxPayData resultData = pay.BarcodePay(orderId, subject, amount, authCode);
                            string    resule     = resultData.GetValue("result_code").ToString();
                            if (resule == "SUCCESS")
                            {
                                string  out_trade_no = resultData.GetValue("out_trade_no").ToString();
                                decimal total_fee    = Convert.ToDecimal(resultData.GetValue("total_fee"));
                                decimal payAmount    = total_fee / 100;

                                //支付成功后的处理
                                BarcodePayModel callbackModel = Flw_OrderBusiness.OrderPay(out_trade_no, payAmount, selttleType);

                                model.OrderStatus = callbackModel.OrderStatus;
                                model.PayAmount   = payAmount.ToString("0.00");
                            }
                            else
                            {
                                LogHelper.SaveLog(TxtLogType.WeiXinPay, resultData.GetValue("result_code").ToString());
                                return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败"));
                            }
                        }
                        catch (WxPayException ex)
                        {
                            LogHelper.SaveLog(TxtLogType.WeiXinPay, ex.Message);
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败"));
                        }
                        catch (Exception e)
                        {
                            LogHelper.SaveLog(TxtLogType.WeiXinPay, e.Message);
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败"));
                        }
                    }
                    #endregion
                }
                break;

                case SelttleType.StarPos:     //新大陆
                    #region 新大陆
                    PPosPayData.MicroPay pposOrder = new PPosPayData.MicroPay();
                    //string tradeNo = Guid.NewGuid().ToString().Replace("-", "");
                    string tradeNo = order.OrderID;

                    pposOrder.tradeNo      = tradeNo;
                    pposOrder.amount       = Convert.ToInt32(amount * 100).ToString();
                    pposOrder.total_amount = Convert.ToInt32(amount * 100).ToString();
                    pposOrder.authCode     = authCode;
                    pposOrder.payChannel   = PayChannel.ToString();
                    pposOrder.subject      = subject;
                    pposOrder.selOrderNo   = tradeNo;
                    pposOrder.txnTime      = System.DateTime.Now.ToString("yyyyMMddHHmmss");
                    pposOrder.signValue    = "";

                    string     error = "";
                    PPosPayApi ppos  = new PPosPayApi();
                    PPosPayData.MicroPayACK result = ppos.ScanPay(pposOrder, out error);
                    if (result != null)
                    {
                        //SUCCESS
                        string  out_trade_no = result.tradeNo;
                        decimal total_fee    = Convert.ToDecimal(result.total_amount);
                        decimal payAmount    = total_fee / 100;

                        //支付成功后的处理
                        BarcodePayModel callbackModel = Flw_OrderBusiness.OrderPay(out_trade_no, payAmount, selttleType);

                        model.OrderStatus = callbackModel.OrderStatus;
                        model.PayAmount   = payAmount.ToString("0.00");
                    }
                    else
                    {
                        LogHelper.SaveLog(TxtLogType.PPosPay, error);
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败," + error));
                    }
                    break;

                    #endregion
                case SelttleType.LcswPay:     //扫呗
                    #region 扫呗
                    LcswPayDate.TradePay tradePay = new LcswPayDate.TradePay();
                    tradePay.terminal_trace = order.OrderID;
                    tradePay.pay_type       = PayChannel.ToDescription();
                    tradePay.order_body     = subject;
                    tradePay.total_fee      = Convert.ToInt32(amount * 100).ToString();
                    tradePay.auth_no        = authCode;
                    LcswPayAPI api = new LcswPayAPI();
                    LcswPayDate.OrderPayACK ack = api.BarcodePay(tradePay);
                    if (ack != null)
                    {
                        if (ack.return_code == "01" && ack.result_code == "01")
                        {
                            string  out_trade_no = ack.out_trade_no;
                            decimal total_fee    = Convert.ToDecimal(ack.total_fee);
                            decimal payAmount    = total_fee / 100;

                            //支付成功后的处理
                            BarcodePayModel callbackModel = Flw_OrderBusiness.OrderPay(out_trade_no, payAmount, SelttleType.LcswPay);

                            model.OrderStatus = callbackModel.OrderStatus;
                            model.PayAmount   = payAmount.ToString("0.00");
                        }
                    }
                    else
                    {
                        LogHelper.SaveLog(TxtLogType.LcswPay, "条码支付失败");
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败"));
                    }
                    break;

                    #endregion
                case SelttleType.DinPay:     //智付
                    #region 智付
                    string errmsg = "";

                    DinPayData.MicroPay Pay = new DinPayData.MicroPay();
                    //scanPay.order_no = order.OrderID;
                    Pay.order_no     = Guid.NewGuid().ToString().Replace("-", "");
                    Pay.order_time   = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    Pay.order_amount = amount.ToString("0.01");
                    Pay.service_type = PayChannel == PaymentChannel.WXPAY ? "weixin_micropay" : "alipay_micropay";
                    Pay.product_name = subject;
                    Pay.auth_code    = authCode;
                    //Pay.return_url = "http://106.14.174.131/returnurl.aspx";

                    DinPayApi payApi    = new DinPayApi();
                    string    resultXml = payApi.MicroPay(Pay);

                    //将同步返回的xml中的参数提取出来
                    var el = XElement.Load(new StringReader(resultXml));
                    //处理码
                    string resp_code = el.XPathSelectElement("/response/resp_code").Value;
                    //业务结果
                    string result_code = el.XPathSelectElement("/response/result_code").Value;
                    if (resp_code == "SUCCESS" && result_code == "0")
                    {
                        //支付成功后的处理
                        string  out_trade_no = el.XPathSelectElement("/response/order_no").Value;
                        decimal total_fee    = Convert.ToDecimal(el.XPathSelectElement("/response/order_amount").Value);
                        decimal payAmount    = total_fee / 100;

                        BarcodePayModel callbackModel = Flw_OrderBusiness.OrderPay(out_trade_no, payAmount, SelttleType.DinPay);

                        model.OrderStatus = callbackModel.OrderStatus;
                        model.PayAmount   = payAmount.ToString("0.00");
                    }
                    else
                    {
                        errmsg = el.XPathSelectElement("/response/result_desc").Value;
                        LogHelper.SaveLog(TxtLogType.DinPay, errmsg);
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败," + errmsg));
                    }
                    break;
                    #endregion
                }

                return(ResponseModelFactory <BarcodePayModel> .CreateModel(isSignKeyReturn, model));
            }
            catch (WxPayException ex)
            {
                LogHelper.SaveLog(TxtLogType.WeiXinPay, ex.Message);
                return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败"));
            }
            catch (Exception e)
            {
                LogHelper.SaveLog(TxtLogType.Api, e.Message);
                return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付失败"));
            }
        }
Beispiel #19
0
        private void CheckMonthCardOrder(ParkUserCarInfo card, int month, double paymoney, PaymentChannel paytype, DateTime afterdate)
        {
            TxtLogServices.WriteTxtLog("31");
            if (card == null)
            {
                throw new MyException("获月卡信息失败");
            }

            if (!card.IsAllowOnlIne)
            {
                throw new MyException("该车场不支持手机续期");
            }

            if (month < 1)
            {
                throw new MyException("请选择续期月数");
            }

            if (card.MaxMonth != 0 && card.MaxMonth < month)
            {
                throw new MyException(string.Format("续期月数必须小于等于{0}个月", card.MaxMonth));
            }
            if (card.Amount * month != (decimal)paymoney)
            {
                throw new MyException("支付金额不正确");
            }

            TxtLogServices.WriteTxtLog("32");
            DateTime start = DateTime.Now;

            if (card.BeginDate != DateTime.MinValue)
            {
                start = card.BeginDate;
            }

            TxtLogServices.WriteTxtLog("M:" + Convert.ToString(month));
            TxtLogServices.WriteTxtLog(Convert.ToString(start));
            TxtLogServices.WriteTxtLog(Convert.ToString(card.EndDate));

            DateTime dtCal = BaseCardServices.CalculateNewEndDate(start, card.EndDate, month);

            TxtLogServices.WriteTxtLog(Convert.ToString(dtCal));
            TxtLogServices.WriteTxtLog(Convert.ToString(afterdate));

            if (BaseCardServices.CalculateNewEndDate(start, card.EndDate, month) != afterdate.Date)
            {
                throw new MyException("计算月卡结束时间错误");
            }
            TxtLogServices.WriteTxtLog("34");
        }
Beispiel #20
0
        public ActionResult SubmitMonthRenewals(string cardId, int month, double paymoney, PaymentChannel paytype, DateTime afterdate, string plateno, int source)
        {
            try
            {
                TxtLogServices.WriteTxtLog("1");

                TxtLogServices.WriteTxtLog(plateno);
                TxtLogServices.WriteTxtLog(cardId);
                TxtLogServices.WriteTxtLog(source.ToString());
                //TxtLogServices.WriteTxtLog(carInfos.Count().ToString());

                List <ParkUserCarInfo> carInfos = source == 1
                    ?RechargeService.GetMonthCarInfoByPlateNumber(plateno)
                    : RechargeService.GetMonthCarInfoByAccountID(WeiXinUser.AccountID);

                ParkUserCarInfo card = carInfos.FirstOrDefault(p => p.CardID == cardId);

                if (card == null)
                {
                    TxtLogServices.WriteTxtLog(carInfos.Count().ToString());
                    TxtLogServices.WriteTxtLog("2");
                }
                TxtLogServices.WriteTxtLog("3");

                CheckMonthCardOrder(card, month, paymoney, paytype, afterdate);
                TxtLogServices.WriteTxtLog("4");
                BaseCompany company = CompanyServices.QueryByParkingId(card.PKID);
                if (company == null)
                {
                    throw new MyException("获取单位信息失败");
                }

                WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(company.CPID);
                if (config == null)
                {
                    ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "获取微信配置信息失败", "单位编号:" + company.CPID, LogFrom.WeiXin);
                    return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取微信配置信息失败!" }));
                }
                if (!config.Status)
                {
                    ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "该车场暂停使用微信支付", "单位编号:" + company.CPID, LogFrom.WeiXin);
                    return(RedirectToAction("Index", "ErrorPrompt", new { message = "该车场暂停使用微信支付!" }));
                }
                if (config.CompanyID != WeiXinUser.CompanyID)
                {
                    ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "微信用户所属公众号和当前公众号不匹配,不能支付", string.Format("支付单位:{0},微信用户单位:{1}", config.CompanyID, WeiXinUser.CompanyID), LogFrom.WeiXin);
                    return(RedirectToAction("Index", "ErrorPrompt", new { message = "微信用户所属公众号和当前公众号不匹配,不能支付!" }));
                }
                if (CurrLoginWeiXinApiConfig == null || config.CompanyID != CurrLoginWeiXinApiConfig.CompanyID)
                {
                    string loginCompanyId = CurrLoginWeiXinApiConfig != null ? CurrLoginWeiXinApiConfig.CompanyID : string.Empty;
                    ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "车场所属公众号和当前公众号不匹配,不能支付", string.Format("支付单位:{0},微信用户单位:{1}", config.CompanyID, loginCompanyId), LogFrom.WeiXin);
                    return(RedirectToAction("Index", "ErrorPrompt", new { message = "车场所属公众号和当前公众号不匹配,不能支付!" }));
                }

                OnlineOrder model = new OnlineOrder();
                model.OrderID        = IdGenerator.Instance.GetId();
                model.CardId         = card.CardID;
                model.PKID           = card.PKID;
                model.PKName         = card.PKName;
                model.EntranceTime   = card.EndDate;
                model.ExitTime       = afterdate;
                model.MonthNum       = month;
                model.Amount         = (decimal)paymoney;
                model.Status         = OnlineOrderStatus.WaitPay;
                model.PaymentChannel = PaymentChannel.WeiXinPay;
                model.Payer          = WeiXinUser.OpenID;
                model.PayAccount     = WeiXinUser.OpenID;
                model.OrderTime      = DateTime.Now;
                model.PayeeChannel   = paytype;
                model.AccountID      = WeiXinUser.AccountID;
                model.OrderType      = OnlineOrderType.MonthCardRecharge;
                model.PlateNo        = card.PlateNumber;
                model.PayeeUser      = config.SystemName;
                model.PayeeAccount   = config.PartnerId;
                model.CompanyID      = config.CompanyID;
                bool result = OnlineOrderServices.Create(model);
                if (!result)
                {
                    throw new MyException("续期失败[保存订单失败]");
                }

                Response.Cookies.Add(new HttpCookie("SmartSystem_MonthCardPayment_Month", string.Format("{0},{1}", month, (int)paytype)));

                switch (model.PaymentChannel)
                {
                case PaymentChannel.WeiXinPay:
                {
                    return(RedirectToAction("MonthCardPayment", "WeiXinPayment", new { orderId = model.OrderID }));
                }

                default: throw new MyException("支付方式错误");
                }
            }
            catch (MyException ex)
            {
                return(PageAlert("MonthCardRenewal", "CardRenewal", new { cardId = cardId, RemindUserContent = ex.Message }));
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptionToDbAndTxt("WeiXinWeb", string.Format("获取续费信息失败,编号:" + cardId), ex, LogFrom.WeiXin);
                return(PageAlert("MonthCardRenewal", "CardRenewal", new { cardId = cardId, RemindUserContent = "提交支付失败" }));
            }
        }
Beispiel #21
0
        public ActionResult SubmitMonthRenewals(string cardId, int month, double paymoney, PaymentChannel paytype, DateTime afterdate, string plateno, int source)
        {
            try
            {
                List <ParkUserCarInfo> carInfos = new List <ParkUserCarInfo>();
                if (source == 1)
                {
                    carInfos = RechargeService.GetMonthCarInfoByPlateNumber(plateno);
                }
                else
                {
                    if (UserAccount != null)
                    {
                        carInfos = RechargeService.GetMonthCarInfoByAccountID(UserAccount.AccountID);
                    }
                }
                ParkUserCarInfo card = carInfos.FirstOrDefault(p => p.CardID == cardId);
                if (card == null)
                {
                    throw new MyException("获月卡信息失败");
                }
                CheckMonthCardOrder(card, month, paymoney, paytype, afterdate);

                BaseCompany company = CompanyServices.QueryByParkingId(card.PKID);
                if (company == null)
                {
                    throw new MyException("获取单位信息失败");
                }

                OnlineOrder model = new OnlineOrder();
                if (paytype == PaymentChannel.AliPay)
                {
                    AliPayApiConfig config = AliPayApiConfigServices.QueryAliPayConfig(company.CPID);
                    if (config == null)
                    {
                        ExceptionsServices.AddExceptionToDbAndTxt("H5CardRenewalError", "获取支付宝配置信息失败[0001]", "单位编号:" + company.CPID, LogFrom.WeiXin);
                        return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取支付宝配置信息失败!" }));
                    }
                    if (!config.Status)
                    {
                        ExceptionsServices.AddExceptionToDbAndTxt("H5CardRenewalError", "该支付宝暂停使用", "单位编号:" + config.CompanyID, LogFrom.WeiXin);
                        return(RedirectToAction("Index", "ErrorPrompt", new { message = "该车场暂停使用支付宝支付!" }));
                    }
                    AliPayApiConfig requestConfig = AliPayApiConfigServices.QueryAliPayConfig(GetRequestCompanyId);
                    if (requestConfig == null)
                    {
                        throw new MyException("获取请求单位微信配置失败");
                    }

                    if (config.CompanyID != requestConfig.CompanyID)
                    {
                        ExceptionsServices.AddExceptionToDbAndTxt("H5CardRenewalError", "支付的支付宝配置和请求的支付配置不匹配,不能支付", string.Format("支付单位:{0},请求单位:{1}", config.CompanyID, requestConfig.CompanyID), LogFrom.WeiXin);
                        return(RedirectToAction("Index", "ErrorPrompt", new { message = "支付的支付宝配置和请求的支付配置不匹配,不能支付!" }));
                    }
                    model.PayeeUser      = config.SystemName;
                    model.PayeeAccount   = config.PayeeAccount;
                    model.PayeeChannel   = PaymentChannel.AliPay;
                    model.PaymentChannel = PaymentChannel.AliPay;
                    model.CompanyID      = config.CompanyID;
                }
                else
                {
                    WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(company.CPID);
                    if (config == null)
                    {
                        ExceptionsServices.AddExceptionToDbAndTxt("H5CardRenewalError", "获取微信配置信息失败", "单位编号:" + company.CPID, LogFrom.WeiXin);
                        return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取微信配置信息失败!" }));
                    }
                    if (!config.Status)
                    {
                        ExceptionsServices.AddExceptionToDbAndTxt("H5CardRenewalError", "该车场暂停使用微信支付", "单位编号:" + company.CPID, LogFrom.WeiXin);
                        return(RedirectToAction("Index", "ErrorPrompt", new { message = "该车场暂停使用微信支付!" }));
                    }
                    WX_ApiConfig requestConfig = WXApiConfigServices.QueryWXApiConfig(GetRequestCompanyId);
                    if (requestConfig == null)
                    {
                        throw new MyException("获取请求单位微信配置失败");
                    }

                    if (config.CompanyID != requestConfig.CompanyID)
                    {
                        ExceptionsServices.AddExceptionToDbAndTxt("H5CardRenewalError", "微信支付配置和当前请求微信支付配置不匹配,不能支付", string.Format("支付单位:{0},请求单位:{1}", config.CompanyID, requestConfig.CompanyID), LogFrom.WeiXin);
                        return(RedirectToAction("Index", "ErrorPrompt", new { message = "微信支付配置和当前请求微信支付配置不匹配,不能支付!" }));
                    }
                    model.PayeeUser      = config.SystemName;
                    model.PayeeAccount   = config.PartnerId;
                    model.PayeeChannel   = PaymentChannel.WeiXinPay;
                    model.PaymentChannel = PaymentChannel.WeiXinPay;
                    model.CompanyID      = config.CompanyID;
                }

                model.OrderID      = IdGenerator.Instance.GetId();
                model.CardId       = card.CardID;
                model.PKID         = card.PKID;
                model.PKName       = card.PKName;
                model.EntranceTime = card.EndDate;
                model.ExitTime     = afterdate;
                model.MonthNum     = month;
                model.Amount       = (decimal)paymoney;
                model.Status       = OnlineOrderStatus.WaitPay;

                model.OrderTime = DateTime.Now;
                model.AccountID = LoginAccountID;
                model.OrderType = OnlineOrderType.MonthCardRecharge;
                model.PlateNo   = card.PlateNumber;

                bool result = OnlineOrderServices.Create(model);
                if (!result)
                {
                    throw new MyException("续期失败[保存订单失败]");
                }

                Response.Cookies.Add(new HttpCookie("SmartSystem_MonthCardPayment_Month", string.Format("{0},{1}", month, (int)paytype)));

                switch (model.PaymentChannel)
                {
                case PaymentChannel.WeiXinPay:
                {
                    return(RedirectToAction("MonthCardPayment", "H5WeiXinPayment", new { orderId = model.OrderID }));
                }

                case PaymentChannel.AliPay:
                {
                    return(RedirectToAction("AliPayRequest", "H5Order", new { orderId = model.OrderID, requestSource = 2 }));
                }

                default: throw new MyException("支付方式错误");
                }
            }
            catch (MyException ex)
            {
                return(PageAlert("MonthCardRenewal", "H5CardRenewal", new { cardId = cardId, RemindUserContent = ex.Message }));
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptionToDbAndTxt("H5CardRenewalError", string.Format("获取续费信息失败,编号:" + cardId), ex, LogFrom.WeiXin);
                return(PageAlert("MonthCardRenewal", "CardRenewal", new { cardId = cardId, RemindUserContent = "提交支付失败" }));
            }
        }
Beispiel #22
0
        public int CreatePayment(int orderId)
        {
            var order = _orderService.GetOrderById(orderId);

            if (order == null)
            {
                throw new ArgumentNullException("Order");
            }

            var nopBillingAddress = _addressService.GetAddressById(order.BillingAddressId);

            var amount            = Math.Round(order.OrderTotal, 2);
            var shopTransactionId = order.OrderGuid.ToString();
            var buyerName         = String.Format(
                "{0} {1}",
                nopBillingAddress?.FirstName,
                nopBillingAddress?.LastName
                );

            var endpoint = _gestpayPayByLinkPaymentSettings.UseSandbox ? "https://sandbox.gestpay.net/api/v1/payment/create/" : "https://ecomms2s.sella.it/api/v1/payment/create/";

            OrderDetails orderDetails = new OrderDetails();

            CustomInfo customInfo = new CustomInfo();
            Dictionary <string, string> myDict = new Dictionary <string, string>();

            myDict.Add("OrderNumber", order.CustomOrderNumber);
            customInfo.customInfo = myDict;

            PaymentCreateRequestModel model = new PaymentCreateRequestModel();

            model.shopLogin         = _gestpayPayByLinkPaymentSettings.ShopOperatorCode;
            model.currency          = "EUR";
            model.amount            = amount.ToString("0.00", CultureInfo.InvariantCulture);
            model.shopTransactionID = shopTransactionId;
            model.buyerName         = buyerName;
            model.buyerEmail        = nopBillingAddress?.Email;
            model.languageId        = _gestpayPayByLinkPaymentSettings.LanguageCode.ToString();

            model.customInfo   = customInfo;
            model.orderDetails = orderDetails;

            PaymentChannel paymentChannel = new PaymentChannel();

            paymentChannel.channelType = new List <string> {
                "EMAIL"
            };
            model.paymentChannel = paymentChannel;

            var            responseStr = string.Empty;
            HttpWebRequest request     = (HttpWebRequest)WebRequest.Create(endpoint);

            request.ContentType = "application/json";
            request.Headers.Add("Authorization", "apikey " + _gestpayPayByLinkPaymentSettings.ApiKey);
            request.Method = "POST";

            var json = JsonConvert.SerializeObject(model);

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream       dataStream = response.GetResponseStream();
                    StreamReader reader     = new StreamReader(dataStream);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                    dataStream.Close();

                    PaymentCreateResponseModel paymentResponse = JsonConvert.DeserializeObject <PaymentCreateResponseModel>(responseStr);
                    return(Convert.ToInt32(paymentResponse.error.code));
                }
            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        responseStr = reader.ReadToEnd();
                    }
                PaymentCreateResponseModel paymentResponse = JsonConvert.DeserializeObject <PaymentCreateResponseModel>(responseStr);
                _logger.Error("Gestpay Pay Link Error = " + paymentResponse.error.code + " " + paymentResponse.error.description, ex);
                return(-1);
            }
        }
Beispiel #23
0
        public object getPayQRcode(Dictionary <string, object> dicParas)
        {
            try
            {
                string errMsg        = string.Empty;
                string orderId       = dicParas.ContainsKey("orderId") ? dicParas["orderId"].ToString() : string.Empty;
                string strPayChannel = dicParas.ContainsKey("payChannel") ? dicParas["payChannel"].ToString() : string.Empty;
                string payType       = dicParas.ContainsKey("payType") ? dicParas["payType"].ToString() : string.Empty;
                string subject       = dicParas.ContainsKey("subject") ? dicParas["subject"].ToString() : string.Empty;

                if (string.IsNullOrWhiteSpace(orderId))
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单号无效"));
                }

                if (string.IsNullOrWhiteSpace(payType))
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "支付方式为空"));
                }
                //支付方式
                PaymentChannel PayChannel = (PaymentChannel)Convert.ToInt32(payType);

                Flw_Order order = Flw_OrderBusiness.GetOrderModel(orderId);
                if (order == null)
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单号无效"));
                }

                Base_StoreInfo store = XCCloudStoreBusiness.GetStoreModel(order.StoreID);
                if (store == null)
                {
                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "订单所属门店无效"));
                }

                //订单减免金额
                decimal freePay = order.FreePay == null ? 0 : order.FreePay.Value;
                //计算订单实付金额,单位:元
                decimal amount = (decimal)order.PayCount - freePay;

                PayQRcodeModel model = new PayQRcodeModel();
                model.OrderId = orderId;

                //SelttleType selttleType = (SelttleType)store.SelttleType.Value;
                SelttleType selttleType = (SelttleType)Convert.ToInt32(strPayChannel);
                switch (selttleType)
                {
                case SelttleType.NotThird:
                    break;

                case SelttleType.AliWxPay:     //微信支付宝官方通道
                {
                    #region 支付宝、微信
                    if (PayChannel == PaymentChannel.ALIPAY)        //支付宝
                    {
                        try
                        {
                            IAlipayTradeService serviceClient = F2FBiz.CreateClientInstance(AliPayConfig.serverUrl, AliPayConfig.appId, AliPayConfig.merchant_private_key, AliPayConfig.version,
                                                                                            AliPayConfig.sign_type, AliPayConfig.alipay_public_key, AliPayConfig.charset);

                            AliPayCommon alipay = new AliPayCommon();
                            AlipayTradePrecreateContentBuilder builder = alipay.BuildPrecreateContent(order, amount, subject);
                            //如果需要接收扫码支付异步通知,那么请把下面两行注释代替本行。
                            //推荐使用轮询撤销机制,不推荐使用异步通知,避免单边账问题发生。
                            //AlipayF2FPrecreateResult precreateResult = serviceClient.tradePrecreate(builder);
                            //AliPayConfig.notify_url  //商户接收异步通知的地址
                            AlipayF2FPrecreateResult precreateResult = serviceClient.tradePrecreate(builder, AliPayConfig.notify_url);

                            switch (precreateResult.Status)
                            {
                            case ResultEnum.SUCCESS:
                                model.QRcode = precreateResult.response.QrCode;
                                break;

                            case ResultEnum.FAILED:
                                LogHelper.SaveLog(TxtLogType.AliPay, precreateResult.response.Body);
                                return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, precreateResult.response.Body));

                            case ResultEnum.UNKNOWN:
                                if (precreateResult.response == null)
                                {
                                    LogHelper.SaveLog(TxtLogType.AliPay, "配置或网络异常,请检查后重试");
                                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败"));
                                }
                                else
                                {
                                    LogHelper.SaveLog(TxtLogType.AliPay, "系统异常,请更新外部订单后重新发起请求");
                                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败"));
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            LogHelper.SaveLog(TxtLogType.AliPay, e.Message);
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败"));
                        }
                    }
                    else if (PayChannel == PaymentChannel.WXPAY)        //微信
                    {
                        NativePay native = new NativePay();
                        try
                        {
                            WxPayData resultData = native.GetPayUrl(order, amount, subject);
                            if (resultData.GetValue("result_code") != null)
                            {
                                string resule = resultData.GetValue("result_code").ToString();
                                if (resule == "SUCCESS")
                                {
                                    model.QRcode = resultData.GetValue("code_url").ToString();        //获得统一下单接口返回的二维码链接
                                }
                                else
                                {
                                    LogHelper.SaveLog(TxtLogType.WeiXinPay, resultData.GetValue("err_code_des").ToString());
                                    return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败," + resultData.GetValue("err_code_des").ToString()));
                                }
                            }
                            else
                            {
                                LogHelper.SaveLog(TxtLogType.WeiXinPay, resultData.GetValue("return_msg").ToString());
                                return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败," + resultData.GetValue("return_msg").ToString()));
                            }
                        }
                        catch (WxPayException ex)
                        {
                            LogHelper.SaveLog(TxtLogType.WeiXinPay, ex.Message);
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败"));
                        }
                        catch (Exception e)
                        {
                            LogHelper.SaveLog(TxtLogType.WeiXinPay, e.Message);
                            return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败"));
                        }
                    }
                    #endregion
                }
                break;

                case SelttleType.StarPos:     //新大陆
                    #region 新大陆
                {
                    string error = "";
                    PPosPayData.OrderPay pposOrder = new PPosPayData.OrderPay();
                    pposOrder.txnTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
                    pposOrder.tradeNo = order.OrderID;
                    //pposOrder.tradeNo = Guid.NewGuid().ToString().Replace("-", "");
                    pposOrder.amount       = Convert.ToInt32(amount * 100).ToString();  //实际付款
                    pposOrder.total_amount = Convert.ToInt32(amount * 100).ToString();  //订单总金额
                    pposOrder.subject      = subject;
                    pposOrder.payChannel   = PayChannel.ToString();

                    PPosPayApi ppos = new PPosPayApi();
                    PPosPayData.OrderPayACK result = ppos.OrderPay(pposOrder, out error);
                    if (result == null)
                    {
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败," + error));
                    }
                    model.QRcode = result.payCode;
                }
                break;

                    #endregion
                case SelttleType.LcswPay:     //扫呗
                    #region 扫呗
                {
                    string qrcode = "";
                    LcswPayDate.OrderPay payInfo = new LcswPayDate.OrderPay();
                    //payInfo.terminal_trace = Guid.NewGuid().ToString().Replace("-", "");
                    payInfo.terminal_trace = order.OrderID;
                    payInfo.pay_type       = PayChannel.ToDescription();
                    payInfo.order_body     = subject;
                    payInfo.total_fee      = Convert.ToInt32(amount * 100).ToString();
                    LcswPayAPI api = new LcswPayAPI();
                    if (api.OrderPay(payInfo, out qrcode))
                    {
                        model.QRcode = qrcode;
                    }
                    else
                    {
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败"));
                    }
                }
                break;

                    #endregion
                case SelttleType.DinPay:     //智付
                    #region 智付
                    string             errmsg  = "";
                    DinPayData.ScanPay scanPay = new DinPayData.ScanPay();
                    //scanPay.order_no = order.OrderID;
                    scanPay.order_no     = Guid.NewGuid().ToString().Replace("-", "");
                    scanPay.order_time   = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    scanPay.order_amount = amount.ToString("0.01");
                    scanPay.service_type = PayChannel == PaymentChannel.WXPAY ? "weixin_scan" : "alipay_scan";
                    scanPay.product_name = subject;
                    scanPay.product_desc = subject;

                    DinPayApi payApi  = new DinPayApi();
                    string    payCode = payApi.GetQRcode(scanPay, out errmsg);
                    if (payCode == "")
                    {
                        return(ResponseModelFactory.CreateModel(isSignKeyReturn, Return_Code.T, "", Result_Code.F, "获取支付二维码失败," + errmsg));
                    }
                    model.QRcode = payCode;
                    break;
                    #endregion
                }

                return(ResponseModelFactory <PayQRcodeModel> .CreateModel(isSignKeyReturn, model));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #24
0
        public async Task <PaymentResult> UsePaystack(User user, decimal amount)
        {
            bool customerExists = false;

            try
            {
                customerExists = Paystack.Customers.Fetch(user.Email).Status;
            }
            catch { }

            if (!customerExists)
            {
                Paystack.Customers.Create(new CustomerCreateRequest()
                {
                    Email     = user.Email,
                    FirstName = user.FirstName,
                    LastName  = user.LastName,
                    Phone     = user.PhoneNumber
                });
            }

            PaymentResult result = new PaymentResult();

            bool isRecurring = !string.IsNullOrWhiteSpace(user.Wallet.PaystackAuthorization);

            PaymentChannel channel = await DataContext.Store.GetOneAsync <PaymentChannel>(p => p.Type == ChannelType.Paystack);

            // Convert to kobo
            int total = (int)Math.Round(amount * channel.ConversionRate);
            int fee   = (int)Math.Round((total * channel.FeePercentage) + channel.FixedFee);

            // Handle Recurring payments
            if (isRecurring)
            {
                var success = Paystack.Transactions
                              .ChargeAuthorization(user.Wallet.PaystackAuthorization, user.Email, total, user.WalletId.ToString(), false);

                if (success.Status)
                {
                    result.Status = PaymentStatus.Success;
                    return(result);
                }
            }

            var request = new TransactionInitializeRequest()
            {
                Email          = user.Email,
                AmountInKobo   = total,
                Reference      = Guid.NewGuid().ToString(),
                MetadataObject = new Dictionary <string, object>()
                {
                    { "walletId", user.WalletId.ToString() }
                }
            };



            var response = Paystack.Transactions.Initialize(request);

            result.Status  = response.Status ? PaymentStatus.Redirected : PaymentStatus.Failed;
            result.Message = response.Data.AuthorizationUrl;

            if (result.Status == PaymentStatus.Failed)
            {
                Logger.LogError("A Paystack Transaction appears to have failed. \n{0}", response.Message);
                result.Message = response.Message;
            }

            return(result);
        }