Пример #1
0
        public void GetAllShouldReturnTransactionsFromExpectedMerchant()
        {
            var tasks          = new List <Task>();
            var transactionsNr = 10;

            var sut = new Services.PaymentRepository();

            for (var i = 0; i < transactionsNr; i++)
            {
                var expectedTransaction = new TransactionPayment()
                {
                    TransactionId = i,
                    Payment       = new TransactionPaymentDetails()
                };

                tasks.Add(sut.Insert(expectedTransaction, (i % 2) + 1));
            }

            Task.WaitAll(tasks.ToArray());

            var transactions = sut.GetAllByMerchantId(1).Result;

            Assert.NotNull(transactions);
            Assert.Equal(transactionsNr / 2, transactions.Count());
            foreach (var transaction in transactions)
            {
                Assert.NotNull(transaction.Payment);
            }
        }
Пример #2
0
        public void GetShouldReturnElement()
        {
            var merchantId          = 1;
            var supplierId          = "1";
            var transactionId       = 1;
            var expectedTransaction = new TransactionPayment()
            {
                TransactionId = transactionId,
                Payment       = new TransactionPaymentDetails()
                {
                    SupplierId = supplierId
                },
            };

            var sut = new Services.PaymentRepository();

            sut.Insert(expectedTransaction, merchantId).Wait();

            var actual = sut.Get(merchantId, transactionId).Result;

            Assert.NotNull(actual);
            Assert.Equal(expectedTransaction.TransactionId, actual.TransactionId);
            var payment = actual.Payment;

            Assert.NotNull(payment);
            Assert.Equal(supplierId, payment.SupplierId);
        }
Пример #3
0
        protected override void GetFormSourceData(object[] parameters)
        {
            _loan   = (Loan)parameters[1];
            _entity = (Payment)parameters[2];
            _loans  = LoanList.NewList(_loan);

            PaymentList pagos = PaymentList.GetListByPrestamo(_loans[0], false);

            TransactionPayment pf = _entity.Operations.GetItemByFactura(_loans[0].Oid);

            if (pf != null)
            {
                _loans[0].Asignado    = pf.Cantidad;
                _loans[0].TotalPagado = 0;

                foreach (PaymentInfo pago in pagos)
                {
                    if (pago.EEstado == moleQule.Base.EEstado.Anulado)
                    {
                        continue;
                    }

                    _loans[0].TotalPagado += pago.Importe;
                }
            }

            _loans[0].Pendiente        = _loans[0].Importe - _loans[0].TotalPagado + _loans[0].Asignado;
            _loans[0].PendienteAsignar = _loans[0].Pendiente - _loans[0].Asignado;
        }
Пример #4
0
        public ActionResult About(FormCollection collection, byte id)
        {
            string             message = string.Empty;
            long               transactionPaymentId = 0;
            TransactionPayment transactionPayment   = new TransactionPayment();

            if (id != 1)
            {
                transactionPayment = IoC.Resolve <ITransactionPaymentService>().GetTransactionPaymentByUserId(1);
                transactionPayment.TransactionPaymentType = id;
                transactionPayment.MemberIP             = Request.UserHostAddress;
                transactionPayment.RecurringTotalCycles = 1;
                transactionPayment.RecurringCycleLength = 7;
            }
            else
            {
                transactionPayment.TransactionPaymentType = id;
                transactionPayment.MemberId                   = 1;
                transactionPayment.MemberIP                   = Request.UserHostAddress;
                transactionPayment.MemberEmail                = transactionPayment.Customer.Email1;
                transactionPayment.TransactionPaymentTotal    = collection["Amount"].ToDecimal();
                transactionPayment.TransactionPaymentStatusId = (int)PaymentStatusEnum.Authorized;
                transactionPayment.PaymentMethodId            = 1;
            }

            message = IoC.Resolve <ITransactionPaymentService>().PlaceTransactionPayment(transactionPayment, out transactionPaymentId);

            ViewBag.Message = message;
            return(View());
        }
        /// <summary>
        /// Post process payment (payment gateways that require redirecting)
        /// </summary>
        /// <param name="betting">betting</param>
        /// <returns>The error status, or String.Empty if no errors</returns>
        public string PostProcessPayment(TransactionPayment transactionPayment)
        {
            RemotePost remotePostHelper = new RemotePost();

            remotePostHelper.FormName = "MoneybookersForm";
            remotePostHelper.Url      = GetMoneybookersUrl();

            remotePostHelper.Add("pay_to_email", payToEmail);
            remotePostHelper.Add("recipient_description", Constant.Payment.STORENAME);
            remotePostHelper.Add("transaction_id", transactionPayment.TransactionPaymentId.ToString());
            remotePostHelper.Add("cancel_url", CommonHelper.GetStoreLocation(false));
            remotePostHelper.Add("status_url", CommonHelper.GetStoreLocation(false) + "MoneybookersReturn.aspx");
            //supported moneybookers languages (EN, DE, ES, FR, IT, PL, GR, RO, RU, TR, CN, CZ or NL)
            remotePostHelper.Add("language", "EN");
            remotePostHelper.Add("amount", transactionPayment.TransactionPaymentTotal.ToString(new CultureInfo("en-US", false).NumberFormat));
            remotePostHelper.Add("currency", Constant.Payment.CURRENCYCODE);
            remotePostHelper.Add("detail1_description", "TransactionPayment ID:");
            remotePostHelper.Add("detail1_text", transactionPayment.TransactionPaymentId.ToString());

            remotePostHelper.Add("firstname", transactionPayment.Customer.FirstName);
            remotePostHelper.Add("lastname", transactionPayment.Customer.Language);
            remotePostHelper.Add("address", transactionPayment.Customer.Address);
            remotePostHelper.Add("phone_number", transactionPayment.Customer.Telephone);
            remotePostHelper.Add("postal_code", transactionPayment.Customer.PostalCode);
            remotePostHelper.Add("city", transactionPayment.Customer.City);
            //review later
            //Country billingCountry = IoC.Resolve<ICountryService>().GetCountryById(order.BillingCountryId);
            //if (billingCountry != null)
            //    remotePostHelper.Add("country", billingCountry.ThreeLetterIsoCode);
            //else
            remotePostHelper.Add("country", transactionPayment.Customer.Country.ToString());
            remotePostHelper.Post();
            return(string.Empty);
        }
Пример #6
0
        public void GetAllShouldObtainSeveralTransactions()
        {
            var tasks          = new List <Task>();
            var merchantId     = 1;
            var supplierId     = "1";
            var transactionsNr = 10;

            var sut = new Services.PaymentRepository();

            for (var i = 0; i < transactionsNr; i++)
            {
                var expectedTransaction = new TransactionPayment()
                {
                    TransactionId = i,
                    Payment       = new TransactionPaymentDetails()
                    {
                        SupplierId = supplierId
                    }
                };

                tasks.Add(sut.Insert(expectedTransaction, merchantId));
            }

            Task.WaitAll(tasks.ToArray());

            var transactions = sut.GetAllByMerchantId(merchantId).Result;

            Assert.NotNull(transactions);
            Assert.Equal(transactionsNr, transactions.Count());
        }
Пример #7
0
        protected override void GetFormSourceData(long oid, object[] parameters)
        {
            try
            {
                ETipoPago tipo = ETipoPago.Prestamo;

                if (parameters[1] != null)
                {
                    _loan = (Loan)parameters[1];
                }

                if (parameters.Length >= 3)
                {
                    _entity = (Payment)parameters[2];
                }
                else
                {
                    _entity = Payment.Get(oid, tipo, true);
                    _entity.BeginEdit();
                }

                _loans = _loan != null?
                         LoanList.NewList(_loan)
                             : LoanList.GetByPagoAndPendientesList(_entity.GetInfo(false));

                if (_loans.Count > 0)
                {
                    PaymentList pagos = PaymentList.GetListByPrestamo(_loans[0], false);

                    TransactionPayment pf = _entity.Operations.GetItemByFactura(_loans[0].Oid);

                    if (pf != null)
                    {
                        _loans[0].Asignado    = pf.Cantidad;
                        _loans[0].TotalPagado = 0;

                        foreach (PaymentInfo pago in pagos)
                        {
                            if (pago.EEstado == moleQule.Base.EEstado.Anulado)
                            {
                                continue;
                            }

                            _loans[0].TotalPagado += pago.Importe;
                        }
                    }

                    _loans[0].Pendiente        = _loans[0].Importe - _loans[0].TotalPagado + _loans[0].Asignado;
                    _loans[0].PendienteAsignar = _loans[0].Pendiente - _loans[0].Asignado;
                }
            }
            catch (Exception ex)
            {
                if (_entity != null)
                {
                    _entity.CloseSession();
                }
                throw ex;
            }
        }
Пример #8
0
        protected override void AddAllPaymentsAction()
        {
            DateTime payment_date = _entity.InicioPago;
            LoanInfo entity_info  = _entity.GetInfo();

            for (int i = 1; i <= _entity.NCuotas; i++)
            {
                Payment payment = _entity.Payments.GetItemByDueDate(payment_date);

                if (payment == null)
                {
                    payment = _entity.Payments.NewItem(entity_info, payment_date);
                    TransactionPayment transaction = payment.Operations.NewItem(payment, _entity, ETipoPago.Prestamo);
                    transaction.Cantidad = payment.Importe;
                }
                else if (payment.Vencimiento >= DateTime.Today)
                {
                    payment.SetCuota(entity_info);
                }

                payment.Observaciones = "PLAZO " + i + "/" + _entity.NCuotas;

                payment_date = payment_date.AddMonths(1);
            }

            UpdatePayments();
        }
Пример #9
0
        public void UpdateStatusShouldThrowExceptionIfMerchantDoesNotExist()
        {
            var updateTransaction = new TransactionPayment()
            {
                TransactionId = 1,
                Payment       = new TransactionPaymentDetails()
            };

            var sut = new Services.PaymentRepository();

            Assert.Throws <ArgumentException>(() => sut.UpdateTransactionStatus(updateTransaction, 1).Result);
        }
Пример #10
0
        public void ProcessPaymentShouldCallApiAndStoreResult()
        {
            var requestPayment = new MerchantPaymentDetails()
            {
                Amount     = 1,
                CardNumber = 1,
                CCV        = 1,
                MerchantId = 1,
                Timestamp  = DateTime.MaxValue
            };

            var expectedTransaction = new TransactionPayment()
            {
                Status        = PaymentStatus.Success,
                TransactionId = 1,
                Payment       = new TransactionPaymentDetails()
                {
                    Amount     = requestPayment.Amount,
                    CardNumber = requestPayment.CardNumber,
                    CCV        = requestPayment.CCV,
                    Timestamp  = requestPayment.Timestamp
                }
            };

            var mockApi = new Mock <IPaymentApi>();

            mockApi.Setup(a => a.ProcessPayment(It.IsAny <MerchantPaymentDetails>()))
            .Returns(Task.FromResult(expectedTransaction));

            var mockRepo = new Mock <IPaymentRepository>();

            mockRepo.Setup(a => a.Insert(
                               It.IsAny <TransactionPayment>(),
                               It.IsAny <int>()))
            .Returns(Task.CompletedTask);

            var sut = new Services.PaymentService(mockApi.Object, mockRepo.Object);

            var transaction = sut.ProcessPayment(requestPayment).Result;

            mockApi.Verify(a => a.ProcessPayment(
                               It.Is <MerchantPaymentDetails>(p =>
                                                              requestPayment.Equals(p)
                                                              )), Times.Once);

            mockRepo.Verify(a => a.Insert(
                                It.Is <TransactionPayment>(t =>
                                                           expectedTransaction.Equals(t)),
                                It.Is <int>(i => i == requestPayment.MerchantId)
                                ), Times.Once);
        }
Пример #11
0
        public void GetShouldCallRepositoryAndReturnTransaction()
        {
            var merchandId    = 1;
            var transactionId = 1;

            var expectedPayment = new TransactionPaymentDetails()
            {
                Amount     = 1,
                CardNumber = 1,
                CCV        = 1,
                SupplierId = "1",
                Timestamp  = DateTime.MaxValue
            };

            var expectedTransaction = new TransactionPayment()
            {
                Status        = PaymentStatus.Success,
                TransactionId = transactionId,
                Payment       = expectedPayment
            };

            var mockApi  = new Mock <IPaymentApi>();
            var mockRepo = new Mock <IPaymentRepository>();

            mockRepo.Setup(a => a.Get(It.IsAny <int>(), It.IsAny <int>()))
            .Returns(Task.FromResult(expectedTransaction));

            var sut = new Services.PaymentService(mockApi.Object, mockRepo.Object);

            var transaction = sut.Get(merchandId, transactionId).Result;

            Assert.NotNull(transaction);

            Assert.Equal(expectedTransaction.Status, transaction.Status);
            Assert.Equal(expectedTransaction.TransactionId, transaction.TransactionId);

            var payment = transaction.Payment;

            Assert.NotNull(payment);
            Assert.Equal(expectedPayment.Amount, payment.Amount);
            Assert.Equal(expectedPayment.CardNumber, payment.CardNumber);
            Assert.Equal(expectedPayment.CCV, payment.CCV);
            Assert.Equal(merchandId, payment.MerchantId);
            Assert.Equal(expectedPayment.Timestamp, payment.Timestamp);

            mockRepo.Verify(a => a.Get(
                                It.Is <int>(m => m == merchandId),
                                It.Is <int>(t => t == transactionId)
                                ), Times.Once);
        }
        public static TransactionPayment AddTransactionPayment(this Transaction currentTransaction,
                                                               EnumPaymentType paymentType, decimal amount, DateTime timeStamp, DateTime datePaid, string notes)
        {
            TransactionPayment newTransactionPayment = new TransactionPayment();

            newTransactionPayment.GUID          = Guid.NewGuid().ToString();
            newTransactionPayment.TransactionID = currentTransaction.TransactionID;
            newTransactionPayment.PaymentType   = paymentType.ToString();
            newTransactionPayment.Amount        = amount;
            newTransactionPayment.TimeStamp     = timeStamp;
            newTransactionPayment.DatePaid      = datePaid;
            newTransactionPayment.Notes         = notes;

            newTransactionPayment.Transaction = currentTransaction;

            return(newTransactionPayment);
        }
Пример #13
0
        public Task Insert(TransactionPayment elem, int merchantId)
        {
            if (!transactions.ContainsKey(merchantId))
            {
                transactions.Add(merchantId, new ConcurrentBag <TransactionPayment>()
                {
                    elem
                });
                return(Task.CompletedTask);
            }

            var transaction = transactions[merchantId];

            transactions[merchantId] = Enumerable.Append(transaction, elem);

            return(Task.CompletedTask);
        }
Пример #14
0
 public SqliteFinanceiro(string db_path = "db.db")
 {
     if (!db_path.Contains(@"\"))
     {
         db_path = AppDomain.CurrentDomain.BaseDirectory + @"\" + db_path;
     }
     Handler = new SqliteHandler(db_path);
     if (!File.Exists(db_path))
     {
         Handler.NonQuery(Properties.Resources.DatabaseCreation);
         Handler.NonQuery(Properties.Resources.InitialData);
     }
     Transaction        = new Transaction(Handler);
     TransactionPayment = new TransactionPayment(Handler);
     SimpleTableManager = new SimpleTableManager(Handler);
     ToUpload           = new ToUpload(Handler);
     TransactionV       = new TransactionV(Handler);
 }
        /// <summary>
        /// Cancels recurring payment
        /// </summary>
        /// <param name="transactionPayment">transactionPayment</param>
        /// <param name="cancelPaymentResult">Cancel payment result</param>
        public void CancelRecurringPayment(TransactionPayment transactionPayment, ref CancelPaymentResult cancelPaymentResult)
        {
            InitSettings();
            MerchantAuthenticationType authentication = PopulateMerchantAuthentication();
            long subscriptionID = 0;

            long.TryParse(cancelPaymentResult.SubscriptionTransactionId, out subscriptionID);
            ARBCancelSubscriptionResponseType response = webService.ARBCancelSubscription(authentication, subscriptionID);

            if (response.resultCode == MessageTypeEnum.Ok)
            {
                //ok
            }
            else
            {
                cancelPaymentResult.Error     = "Error cancelling subscription, please contact customer support. " + GetErrors(response);
                cancelPaymentResult.FullError = "Error cancelling subscription, please contact customer support. " + GetErrors(response);
            }
        }
Пример #16
0
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="transactionPayment">transactionPayment required for an betting processing</param>
        /// <param name="bettingGuid">Unique betting identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessRecurringPayment(TransactionPayment transactionPayment, Guid bettingGuid, ref ProcessPaymentResult processPaymentResult)
        {
            int    transactionMode = (int)TransactMode.OriginalCredit;
            string reply           = webService.DoTransaction(loginID, loginPass, transactionMode.ToString(),
                                                              transactionPayment.PaymentMenthod.CreditCardNumber, transactionPayment.PaymentMenthod.CardCvv2, "", transactionPayment.PaymentMenthod.CardExpirationMonth, transactionPayment.PaymentMenthod.CardExpirationYear,
                                                              transactionPayment.PaymentMenthod.NameOnCard, transactionPayment.TransactionPaymentTotal.ToString("0.00", CultureInfo.InvariantCulture),
                                                              Constant.Payment.CURRENCYCODENUMBER, transactionPayment.Customer.Address, transactionPayment.Customer.PostalCode, transactionPayment.TransactionIDRespone.ToString(), //transactionPayment.TransactionPaymentId.ToString(),
                                                              CommonHelper.GetRequestIP(), "Authorization 1", "Authorization 2", "Authorization 3");

            if (!String.IsNullOrEmpty(reply))
            {
                reply = reply.Replace("||", "|");
                string[] responseFields = reply.Split('|');
                switch (responseFields[0])
                {
                case "CAPTURED":
                    processPaymentResult.AuthorizationTransactionCode   = string.Format("{0}", responseFields[1]);
                    processPaymentResult.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", responseFields[2], responseFields[11]);
                    processPaymentResult.AVSResult = responseFields[0];
                    //responseFields[38];
                    if (transactionMode == (int)TransactMode.Authorization)
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                    }
                    else
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                    }
                    break;

                default:
                    processPaymentResult.Error     = string.Format("Declined {0}", responseFields[0]);
                    processPaymentResult.FullError = string.Format("Declined {0}", responseFields[0]);
                    break;
                }
            }
            else
            {
                processPaymentResult.Error     = "Unknown error";
                processPaymentResult.FullError = "Unknown error";
            }
        }
Пример #17
0
        public void UpdateStatusShouldOnlyChangeStatus()
        {
            var merchantId          = 1;
            var supplierId          = "1";
            var transactionId       = 1;
            var expectedTransaction = new TransactionPayment()
            {
                TransactionId = transactionId,
                Status        = PaymentStatus.Failed,
                Payment       = new TransactionPaymentDetails()
                {
                    SupplierId = supplierId,
                    Amount     = 1,
                    CardNumber = 1,
                    CCV        = 1,
                    Timestamp  = DateTime.MaxValue
                }
            };

            var sut = new Services.PaymentRepository();

            sut.Insert(expectedTransaction, merchantId).Wait();

            var updateTransaction = new TransactionPayment()
            {
                TransactionId = transactionId,
                Status        = PaymentStatus.Success,
                Payment       = new TransactionPaymentDetails()
                {
                    SupplierId = supplierId,
                    Amount     = 2,
                    CardNumber = 2,
                    CCV        = 2,
                    Timestamp  = DateTime.MaxValue
                }
            };

            var actual = sut.UpdateTransactionStatus(updateTransaction, merchantId).Result;

            Assert.NotNull(actual);
            Assert.Equal(expectedTransaction, actual);
        }
Пример #18
0
        protected override void NewPaymentAction()
        {
            Payment            payment     = _entity.Payments.NewItem(_entity.GetInfo());
            TransactionPayment transaction = payment.Operations.NewItem(payment, _entity, ETipoPago.Prestamo);

            transaction.Cantidad = payment.Importe;

            LoanPaymentEditForm form = new LoanPaymentEditForm(payment, ETipoPago.Prestamo, _entity, this);

            form.ShowDialog();

            if (form.ActionResult != DialogResult.OK)
            {
                _entity.Payments.Remove(payment);
            }

            UpdatePayments();

            UpdateImportes();
        }
Пример #19
0
        public Task <TransactionPayment> UpdateTransactionStatus(TransactionPayment elem, int merchantId)
        {
            if (!transactions.ContainsKey(merchantId))
            {
                throw new ArgumentException($"Merchant id {merchantId} does not exist");
            }

            var transaction = transactions[merchantId];
            var payment     = transaction.FirstOrDefault(t =>
                                                         t.TransactionId == elem.TransactionId);

            if (payment == null)
            {
                throw new ArgumentException($"Merchant id {merchantId} does not have a transaction {elem.TransactionId}");
            }

            payment.Status = elem.Status;

            return(Task.FromResult(payment));
        }
Пример #20
0
        public ActionResult Deposit(FormCollection collection)
        {
            string message = string.Empty;
            long   transactionPaymentId = 0;
            long   memberId             = SessionManager.USER_ID;

            TransactionPayment transactionPayment = new TransactionPayment();

            transactionPayment.TransactionPaymentType = (int)Constant.TransactionType.DEPOSIT;
            transactionPayment.MemberId                   = memberId;
            transactionPayment.MemberIP                   = Request.UserHostAddress;
            transactionPayment.MemberEmail                = transactionPayment.Customer.Email1;
            transactionPayment.TransactionPaymentTotal    = collection["Amount"].ToDecimal();
            transactionPayment.TransactionPaymentStatusId = (int)PaymentStatusEnum.Authorized;
            transactionPayment.PaymentMethodId            = 1;

            message = IoC.Resolve <ITransactionPaymentService>().PlaceTransactionPayment(transactionPayment, out transactionPaymentId);

            ViewBag.Message = message;
            return(View());
        }
Пример #21
0
        public void GetAllByMerchantShouldCallRepositoryAndReturnAllMerchantsTransactions()
        {
            var merchandId           = 1;
            var transactionNr        = 10;
            var expectedTransactions = new List <TransactionPayment>();

            for (var i = 0; i < transactionNr; i++)
            {
                var expectedTransaction = new TransactionPayment()
                {
                    Status        = PaymentStatus.Success,
                    TransactionId = i,
                    Payment       = new TransactionPaymentDetails()
                    {
                        Amount     = 1,
                        CardNumber = 1,
                        CCV        = 1,
                        SupplierId = "1",
                        Timestamp  = DateTime.MaxValue
                    }
                };
                expectedTransactions.Add(expectedTransaction);
            }

            var mockApi  = new Mock <IPaymentApi>();
            var mockRepo = new Mock <IPaymentRepository>();

            mockRepo.Setup(a => a.GetAllByMerchantId(It.IsAny <int>()))
            .Returns(Task.FromResult <IEnumerable <TransactionPayment> >(expectedTransactions));

            var sut = new Services.PaymentService(mockApi.Object, mockRepo.Object);

            var transactions = sut.GetAllByMerchantId(merchandId).Result;

            Assert.NotNull(transactions);

            Assert.Equal(transactionNr, transactions.Count());

            mockRepo.Verify(a => a.GetAllByMerchantId(It.Is <int>(m => m == merchandId)), Times.Once);
        }
Пример #22
0
        public void UpdateStatusShouldThrowExceptionIfTransactionDoesNotExist()
        {
            var merchantId          = 1;
            var transactionId       = 1;
            var expectedTransaction = new TransactionPayment()
            {
                TransactionId = transactionId,
                Payment       = new TransactionPaymentDetails()
            };

            var updateTransaction = new TransactionPayment()
            {
                TransactionId = 2,
                Payment       = new TransactionPaymentDetails()
            };

            var sut = new Services.PaymentRepository();

            sut.Insert(expectedTransaction, merchantId).Wait();

            Assert.Throws <ArgumentException>(() => sut.UpdateTransactionStatus(updateTransaction, merchantId).Result);
        }
Пример #23
0
        public ActionResult Withdraw(FormCollection collection)
        {
            string message              = string.Empty;
            long   memberId             = SessionManager.USER_ID;
            long   transactionPaymentId = 0;

            if (IoC.Resolve <ITransactionPaymentService>().GetTransactionByUserId(memberId) != null)
            {
                message = Constant.Messagage.NOTRANSACTION;
            }
            else
            {
                TransactionPayment transactionPayment = new TransactionPayment();
                transactionPayment = IoC.Resolve <ITransactionPaymentService>().GetTransactionPaymentByUserId(memberId);
                transactionPayment.TransactionPaymentType = (int)Constant.TransactionType.WITHDRAW;
                transactionPayment.MemberIP             = Request.UserHostAddress;
                transactionPayment.RecurringTotalCycles = 1;
                transactionPayment.RecurringCycleLength = 7;

                message = IoC.Resolve <ITransactionPaymentService>().PlaceTransactionPayment(transactionPayment, out transactionPaymentId);
            }
            ViewBag.Message = message;
            return(View());
        }
        public static void CreateApuntesBancarios(PaymentList pagos)
        {
            List <PaymentInfo> list = new List <PaymentInfo>();

            CreditCardList tarjetas      = CreditCardList.GetList();
            Payments       pagos_tarjeta = Payments.NewList();

            foreach (PaymentInfo item in pagos)
            {
                if (!Common.EnumFunctions.NeedsCuentaBancaria(item.EMedioPago))
                {
                    continue;
                }
                if (item.Vencimiento > DateTime.Today)
                {
                    continue;
                }

                if (item.EMedioPago != EMedioPago.Tarjeta)
                {
                    //Apunte bancario del pagaré, talón, etc..
                    BankLine.InsertItem(item, true);

                    list.Add(item);
                }
                else
                {
                    Payment pago_tarjeta = pagos_tarjeta.GetItemByTarjetaCredito(item.OidTarjetaCredito, item.Vencimiento);

                    if (pago_tarjeta == null)
                    {
                        pago_tarjeta = pagos_tarjeta.NewItem(item, ETipoPago.ExtractoTarjeta);
                        TransactionPayment pf = pago_tarjeta.Operations.NewItem(pago_tarjeta, item, item.ETipoPago);
                        pf.Cantidad = item.Total;
                        pago_tarjeta.EEstadoPago = EEstado.Pagado;
                    }
                    else
                    {
                        pago_tarjeta.Importe         += item.Importe;
                        pago_tarjeta.GastosBancarios += item.GastosBancarios;
                        TransactionPayment pf = pago_tarjeta.Operations.NewItem(pago_tarjeta, item, item.ETipoPago);
                        pf.Cantidad = item.Total;
                    }

                    list.Add(item);
                }
            }

            Payments pagos_fraccionados = Payments.NewList();

            pagos_fraccionados.OpenNewSession();

            //Apunte bancario de la tarjeta
            foreach (Payment item in pagos_tarjeta)
            {
                Payment root = pagos_fraccionados.NewItem(item.GetInfo(false), ETipoPago.FraccionadoTarjeta);
                root.Pagos.AddItem(item);

                //if (item.Importe != 0)
                //    MovimientoBanco.InsertItemTarjeta(item, tarjetas.GetItem(item.OidTarjetaCredito));
            }

            pagos_fraccionados.BeginTransaction();
            pagos_fraccionados.Save();

            Payment.UpdatePagadoFromList(list, true);
        }
Пример #25
0
        // Bắt sự kiện trước khi user click button OK trong màn hình thanh toán (sau khi đã chọn phương thức thanh toán)
        public override void OnBeforeAddPayment(object sender, EventArgs <Transaction, TransactionPayment> args)
        {
            Transaction        tran        = args.Item;
            var                a           = tran.TransactionSaleAttributes;
            TransactionPayment tranPayment = args.ChildItem;

            // TransactionkeyVNPAY: Tên của SaleAttribute do user tạo ra để lưu thêm key khi tạo transaction gửi sang VNPAY
            TransactionSaleAttribute transactionkeyVNPAY = tran.TransactionSaleAttributes.FirstOrDefault(p => p.SaleAttribute.Name == "TransactionkeyVNPAY");

            string            popMappingFile = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\Models\\POSMapping.json";
            string            popMappingText = File.ReadAllText(popMappingFile);
            List <POSMapping> lstPOSMapping  = JsonConvert.DeserializeObject <List <POSMapping> >(popMappingText);

            // Lấy thông tin máy mPOS tương ứng với từng điểm bán hàng đã được setup
            POSMapping objMapping = lstPOSMapping.FirstOrDefault(x => x.StoreKey == tran.StoreKey && x.POSKey == tran.POSKey);

            if (objMapping == null)
            {
                XtraMessageBox.Show("Không tìm thấy máy mPOS.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                args.Cancel = true;
                return;
            }
            string terminalCode = objMapping.TerminalCode;

            TenderType paytype = tranPayment.PaymentType.Type;
            string     id      = tranPayment.PaymentType.Id;

            if (paytype == TenderType.Custom && id == "VNPAYCard")
            {
                // Tạo metadata
                MetaData data = new MetaData();
                data.payerName = tran.TransactionCustomerName;
                data.language  = "vi";
                string metadata = JsonConvert.SerializeObject(data);

                // Tạo parameter call API
                ParameterTransactionAPI para = new ParameterTransactionAPI();
                para.amount                = Money.ToInt64(tran.Total);
                para.clientCode            = "FTI";
                para.clientTransactionCode = Guid.NewGuid().ToString();
                para.metadata              = "METAVALUE";
                para.methodCode            = "SPOSCARD";
                para.orderCode             = Guid.NewGuid().ToString();
                para.orderDescription      = "";
                para.orderId               = Guid.NewGuid().ToString();
                para.partnerCode           = "VNPAY";
                para.serviceCode           = "RETAIL";
                para.terminalCode          = terminalCode;

                var strParaBody = string.Format("{0}amount={1}&clientCode={2}&clientTransactionCode={3}&metadata=METAVALUE&methodCode=SPOSCARD&orderCode={4}&orderDescription={5}&orderId={6}&partnerCode=VNPAY&serviceCode=RETAIL&terminalCode={7}", "b8399f824670b0bf07c84267ca9b1dff", para.amount, para.clientCode, para.clientTransactionCode, para.orderCode, para.orderDescription, para.orderId, para.terminalCode);
                strParaBody   = strParaBody.Replace("METAVALUE", metadata);
                strParaBody   = strParaBody.Replace("\"{", "{").Replace("}\"", "}");
                para.checksum = CallAPI.CreateMD5(strParaBody);

                string strPara = JsonConvert.SerializeObject(para);
                strPara = strPara.Replace("METAVALUE", metadata);
                strPara = strPara.Replace("\"{", "{").Replace("}\"", "}");

                // Call API để tạo Transaction
                ApiResultCARD resultPaymentVNPAYCard = CallAPI.PaymentByCard(strPara);
                // Tạo giao dịch thanh toán bằng VNPAY Card bị lỗi => Thông báo cho user biết lỗi
                if (!resultPaymentVNPAYCard.success)
                {
                    XtraMessageBox.Show(resultPaymentVNPAYCard.message, "Thông báo", MessageBoxButtons.OK);
                    args.Cancel = true;
                    return;
                }

                Thread.Sleep(15000); // Đợi 15s trước khi call API tra cứu kết quả
                bool tryGetDetail = true;
                while (tryGetDetail)
                {
                    Thread.Sleep(5000);

                    // Tạo giao dịch thanh toán bằng VNPAY Card thành công => Gọi API lấy kết quả giao dịch.
                    ParameterRessulAPI paraResult = new ParameterRessulAPI();
                    paraResult.client_code             = para.clientCode;
                    paraResult.client_transaction_code = para.clientTransactionCode;
                    paraResult.ps_transaction_code     = resultPaymentVNPAYCard.data.psTransactionCode;

                    var strParaResultBody = string.Format("{0}client_code={1}&client_transaction_code={2}&ps_transaction_code={3}", "b8399f824670b0bf07c84267ca9b1dff", paraResult.client_code, paraResult.client_transaction_code, paraResult.ps_transaction_code);
                    paraResult.checksum = CallAPI.CreateMD5(strParaResultBody);
                    string strParaResult = JsonConvert.SerializeObject(paraResult);

                    ApiResultOrderDetail resultOrderDetail = CallAPI.GetTransactionDetail(paraResult);
                    if (!resultOrderDetail.success)
                    {
                        XtraMessageBox.Show("Lấy kết quả giao dịch lỗi: " + resultOrderDetail.message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        args.Cancel = true;
                        return;
                    }
                    else
                    {
                        if (resultOrderDetail.data.psResponseCode == null)
                        {
                            tryGetDetail = true;
                        }
                        else if (resultOrderDetail.data.psResponseCode == "000")
                        {
                            XtraMessageBox.Show("Giao dịch thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            transactionkeyVNPAY.AttributeValue = para.clientTransactionCode;
                            tran.TransactionSaleAttributes.Add(transactionkeyVNPAY);
                            tryGetDetail = false;
                            return;
                        }
                        else
                        {
                            XtraMessageBox.Show("Giao dịch thất bại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            tryGetDetail = false;
                            args.Cancel  = true;
                            return;
                        }
                    }
                }
            }

            else if (paytype == TenderType.Custom && id == "VNPAYQRCode")
            {
                // Tạo metadata
                MetaData data = new MetaData();
                data.payerName = tran.TransactionCustomerName;
                data.language  = "vi";
                string metadata = JsonConvert.SerializeObject(data);

                // Tạo parameter call API
                ParameterTransactionAPI para = new ParameterTransactionAPI();
                para.amount                = Money.ToInt64(tran.Total);
                para.clientCode            = "FTI";
                para.clientTransactionCode = Guid.NewGuid().ToString();
                para.metadata              = "METAVALUE";
                para.methodCode            = "QRCODE";
                para.orderCode             = Guid.NewGuid().ToString();
                para.orderDescription      = "";
                para.orderId               = Guid.NewGuid().ToString();
                para.partnerCode           = "VNPAY";
                para.serviceCode           = "RETAIL";
                para.terminalCode          = terminalCode;

                var strParaBody = string.Format("{0}amount={1}&clientCode={2}&clientTransactionCode={3}&metadata=METAVALUE&methodCode=QRCODE&orderCode={4}&orderDescription={5}&orderId={6}&partnerCode=VNPAY&serviceCode=RETAIL&terminalCode={7}", "b8399f824670b0bf07c84267ca9b1dff", para.amount, para.clientCode, para.clientTransactionCode, para.orderCode, para.orderDescription, para.orderId, para.terminalCode);
                strParaBody   = strParaBody.Replace("METAVALUE", metadata);
                strParaBody   = strParaBody.Replace("\"{", "{").Replace("}\"", "}");
                para.checksum = CallAPI.CreateMD5(strParaBody);

                string strPara = JsonConvert.SerializeObject(para);
                strPara = strPara.Replace("METAVALUE", metadata);
                strPara = strPara.Replace("\"{", "{").Replace("}\"", "}");

                // Call API để tạo Transaction
                ApiResultQR resultPaymentVNPAYQR = CallAPI.PaymentByQR(strPara);
                // Tạo giao dịch thanh toán bằng VNPAY QR bị lỗi => Thông báo cho user biết lỗi
                if (!resultPaymentVNPAYQR.success)
                {
                    XtraMessageBox.Show(resultPaymentVNPAYQR.message, "Thông báo", MessageBoxButtons.OK);
                    args.Cancel = true;
                    return;
                }

                Thread.Sleep(15000); // Đợi 15s trước khi call API tra cứu kết quả
                bool tryGetDetail = true;
                while (tryGetDetail)
                {
                    Thread.Sleep(5000);

                    // Tạo giao dịch thanh toán bằng VNPAY Card thành công => Gọi API lấy kết quả giao dịch.
                    ParameterRessulAPI paraResult = new ParameterRessulAPI();
                    paraResult.client_code             = para.clientCode;
                    paraResult.client_transaction_code = para.clientTransactionCode;
                    paraResult.ps_transaction_code     = resultPaymentVNPAYQR.data.psTransactionCode;

                    var strParaResultBody = string.Format("{0}client_code={1}&client_transaction_code={2}&ps_transaction_code={3}", "b8399f824670b0bf07c84267ca9b1dff", paraResult.client_code, paraResult.client_transaction_code, paraResult.ps_transaction_code);
                    paraResult.checksum = CallAPI.CreateMD5(strParaResultBody);
                    string strParaResult = JsonConvert.SerializeObject(paraResult);

                    ApiResultOrderDetail resultOrderDetail = CallAPI.GetTransactionDetail(paraResult);
                    if (!resultOrderDetail.success)
                    {
                        XtraMessageBox.Show("Lấy kết quả giao dịch lỗi: " + resultOrderDetail.message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        args.Cancel = true;
                        return;
                    }
                    else
                    {
                        if (resultOrderDetail.data.psResponseCode == null)
                        {
                            tryGetDetail = true;
                        }
                        else if (resultOrderDetail.data.psResponseCode == "000")
                        {
                            XtraMessageBox.Show("Giao dịch thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            transactionkeyVNPAY.AttributeValue = para.clientTransactionCode;
                            tran.TransactionSaleAttributes.Add(transactionkeyVNPAY);
                            tryGetDetail = false;
                            return;
                        }
                        else
                        {
                            XtraMessageBox.Show("Giao dịch thất bại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            tryGetDetail = false;
                            args.Cancel  = true;
                            return;
                        }
                    }
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="transactionPayment">transactionPayment required for an betting processing</param>
        /// <param name="bettingGuid">Unique betting identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(TransactionPayment transactionPayment, Guid bettingGuid, ref ProcessPaymentResult processPaymentResult)
        {
            #region tempcode
            //WebClient webClient = new WebClient();
            //NameValueCollection form = new NameValueCollection();
            //form.Add("MerchID", loginID);
            //form.Add("Pass", loginPass);
            //form.Add("TrType", "FALSE");
            //form.Add("CardNum", transactionPayment.PaymentMenthod.CreditCardNumber);
            //form.Add("CVV2", transactionPayment.PaymentMenthod.CardCvv2);
            //form.Add("ExpDay", "31");
            //form.Add("ExpMonth", transactionPayment.PaymentMenthod.CardExpirationMonth);
            //form.Add("ExpYear", transactionPayment.PaymentMenthod.CardExpirationYear);
            //form.Add("CardHName", transactionPayment.PaymentMenthod.NameOnCard);
            //form.Add("Amount", transactionPayment.TransactionPaymentTotal.ToString("0.00", CultureInfo.InvariantCulture));
            //form.Add("CurrencyCode", Constant.Payment.CURRENCYCODE);
            //form.Add("Addr", transactionPayment.Customer.Address);
            //form.Add("PostCode",transactionPayment.Customer.PostalCode);
            //form.Add("TransID", transactionPayment.TransactionPaymentId.ToString());
            //form.Add("UserIP",CommonHelper.GetRequestIP());
            //form.Add("UDF1", "Test 1");
            //form.Add("UDF2", "Test 1");
            //form.Add("UDF3", "Test 1");

            //string reply = null;
            //Byte[] responseData = webClient.UploadValues(GetApcPaymentUrl(), form);
            //reply = Encoding.ASCII.GetString(responseData);
            #endregion

            int    transactionMode = (int)TransactMode.Authorization;
            string reply           = webService.DoTransaction(loginID, loginPass, transactionMode.ToString(),
                                                              transactionPayment.PaymentMenthod.CreditCardNumber, transactionPayment.PaymentMenthod.CardCvv2, "", transactionPayment.PaymentMenthod.CardExpirationMonth, transactionPayment.PaymentMenthod.CardExpirationYear,
                                                              transactionPayment.PaymentMenthod.NameOnCard, transactionPayment.TransactionPaymentTotal.ToString("0.00", CultureInfo.InvariantCulture),
                                                              Constant.Payment.CURRENCYCODENUMBER, transactionPayment.Customer.Address, transactionPayment.Customer.PostalCode, transactionPayment.TransactionPaymentId.ToString(),
                                                              CommonHelper.GetRequestIP(), "Authorization 1", "Authorization 2", "Authorization 3");

            if (!String.IsNullOrEmpty(reply))
            {
                reply = reply.Replace("||", "|");
                string[] responseFields = reply.Split('|');
                switch (responseFields[0])
                {
                case "APPROVED":
                    processPaymentResult.AuthorizationTransactionCode   = string.Format("{0}", responseFields[1]);
                    processPaymentResult.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", responseFields[2], responseFields[11]);
                    processPaymentResult.AVSResult = responseFields[0];
                    //responseFields[38];
                    if (transactionMode == (int)TransactMode.Authorization)
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                    }
                    else
                    {
                        processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                    }
                    break;

                default:
                    processPaymentResult.Error     = string.Format("Declined {0}", responseFields[0] + " " + transactionPayment.PaymentMenthod.CreditCardNumber);
                    processPaymentResult.FullError = string.Format("Declined {0}", responseFields[0] + " " + transactionPayment.PaymentMenthod.CreditCardNumber);
                    break;
                }
            }
            else
            {
                processPaymentResult.Error     = "Unknown error";
                processPaymentResult.FullError = "Unknown error";
            }
        }
Пример #27
0
 /// <summary>
 /// Cancels recurring payment
 /// </summary>
 /// <param name="transactionPayment">transactionPayment</param>
 /// <param name="cancelPaymentResult">Cancel payment result</param>
 public void CancelRecurringPayment(TransactionPayment transactionPayment, ref CancelPaymentResult cancelPaymentResult)
 {
 }
Пример #28
0
 /// <summary>
 /// Voids payment
 /// </summary>
 /// <param name="transactionPayment">transactionPayment</param>
 /// <param name="cancelPaymentResult">Cancel payment result</param>
 public void Void(TransactionPayment transactionPayment, ref CancelPaymentResult cancelPaymentResult)
 {
     throw new Exception("Void method not supported");
 }
Пример #29
0
 /// <summary>
 /// Captures payment
 /// </summary>
 /// <param name="transactionPayment">transactionPayment</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void Capture(TransactionPayment transactionPayment, ref ProcessPaymentResult processPaymentResult)
 {
     throw new Exception("Capture method not supported");
 }
Пример #30
0
 /// <summary>
 /// Post process payment (payment gateways that require redirecting)
 /// </summary>
 /// <param name="betting">betting</param>
 /// <returns>The error status, or String.Empty if no errors</returns>
 public string PostProcessPayment(TransactionPayment transactionPayment)
 {
     return(string.Empty);
 }