Beispiel #1
0
        public JsonResult FindById(int paymentId)
        {
            var model   = new PaymentTransactionModel();
            var payment = PaymentService.FindPaymentById(paymentId);

            if (payment != null && payment.Transaction != null)
            {
                model = new PaymentTransactionModel
                {
                    PaymentId          = payment.PaymentId,
                    TransactionId      = payment.TransactionId ?? 0,
                    TransactionDate    = payment.Transaction.TransactionDate.HasValue ? payment.Transaction.TransactionDate.ToShortDateString() : string.Empty,
                    DecisionDate       = payment.Transaction.DecisionDate.HasValue ? payment.Transaction.DecisionDate.ToShortDateString() : string.Empty,
                    NotificationDateIC = payment.Transaction.NotificationDateIC.HasValue ? payment.Transaction.NotificationDateIC.ToShortDateString() : string.Empty,
                    ICCaseNumber       = payment.Transaction.ICCaseNumber,
                    TransactionAmount  = payment.Transaction.TransactionAmount.HasValue ? payment.Transaction.TransactionAmount.Value.ToString() : string.Empty,
                    HearingDateIC      = payment.Transaction.HearingDateIC.HasValue ? payment.Transaction.HearingDateIC.ToShortDateString() : string.Empty,
                    MonthlyInstallment = payment.Transaction.MonthlyInstallment.HasValue ? payment.Transaction.MonthlyInstallment.Value.ToString() : string.Empty,
                    NumberOfWeeks      = payment.Transaction.NumberOfWeeks.HasValue ? payment.Transaction.NumberOfWeeks.ToString() : string.Empty,
                    Observaciones      = payment.Transaction.Comment,
                    FromDate           = payment.FromDate.HasValue ? payment.FromDate.ToShortDateString() : string.Empty,
                    ToDate             = payment.ToDate.HasValue ? payment.ToDate.ToShortDateString() : string.Empty,
                    Discount           = payment.Discount.GetValueOrDefault(decimal.Zero).ToString(),
                    PaymentDay         = payment.PaymentDay.GetValueOrDefault(0).ToString()
                };
            }

            return(Json(new BasicDataTablesResult(model), JsonRequestBehavior.AllowGet));
        }
        private async Task <TransactionResultModel> ProcessPaymentByAcquiringBank(ProcessPaymentRequestCommand command, string recipientIban)
        {
            var payerCard = new CardInfo
            {
                Number      = command.CardNumber,
                HolderName  = command.CardHolderName,
                ExpiryMonth = command.ExpiryMonth,
                ExpiryYear  = command.ExpiryYear,
                Cvv         = command.Cvv
            };

            var transaction = new PaymentTransactionModel
            {
                PaymentCard   = payerCard,
                RecipientIban = recipientIban,
                ChargeTotal   = command.ChargeTotal,
                CurrencyCode  = command.CurrencyCode
            };

            _logger.LogDebug("Send payment {transaction} to acquiring bank", transaction);
            var transactionResult = await _acquiringBankClient.ProcessTransactionAsync(transaction);

            _logger.LogDebug("Received payment transaction {result} from acquiring bank", transactionResult);
            return(transactionResult);
        }
Beispiel #3
0
        private void BuildPaymentSummaryPaymentDetails
            (StringBuilder orderDetails, UserSelectedContext customer,
            Core.Models.Profile.Customer cust, int paymentNumber, PaymentTransactionModel payment)
        {
            Core.Models.OnlinePayments.Invoice.EF.Invoice invoice;
            Core.Enumerations.InvoiceType invoiceTyped;
            GetPaymentInvoiceInformation(customer, payment, out invoice, out invoiceTyped);

            if (paymentNumber == 1)
            {
                ApplyPaymentSummaryDetailsWithCustomerTemplate
                    (orderDetails, cust, payment, invoice, invoiceTyped);
            }
            else
            {
                if (paymentNumber % 2 == 1)
                {
                    ApplyPaymentSummaryDetailsTemplate(orderDetails, payment, invoice, invoiceTyped);
                }
                else
                {
                    ApplyPaymentSummaryDetailsAltTemplate(orderDetails, payment, invoice, invoiceTyped);
                }
            }
        }
        public static PaymentTransactionModel ToPaymentTransactionModel(this PaymentTransaction payment, KeithLink.Svc.Core.Models.Profile.Customer customer, TimeSpan cutOffTime)
        {
            PaymentTransactionModel retVal = new PaymentTransactionModel();

            retVal.CustomerName   = customer.CustomerName;
            retVal.CustomerNumber = customer.CustomerNumber;
            retVal.AccountNumber  = payment.AccountNumber;
            retVal.ConfirmationId = payment.ConfirmationId;
            retVal.InvoiceNumber  = payment.InvoiceNumber;
            retVal.PaymentAmount  = payment.PaymentAmount;
            retVal.PaymentDate    = payment.ScheduledPaymentDate;
            retVal.SubmittedDate  = payment.PaymentDate;
            retVal.BranchId       = string.IsNullOrEmpty(payment.Division) ? string.Empty : payment.Division.Substring(0, 3);
            retVal.UserName       = payment.UserName;

            if (payment.ScheduledPaymentDate.HasValue)
            {
                DateTime paymentCutOffTime = payment.ScheduledPaymentDate.Value.Add(cutOffTime);

                retVal.Editable = DateTime.Now < paymentCutOffTime;
            }
            else
            {
                retVal.Editable = true;
            }

            return(retVal);
        }
        public TransactionResultModel Post([FromBody] PaymentTransactionModel model)
        {
            _logger.LogDebug("Process payment transaction {model}", model);
            var status = model.ChargeTotal % 2 == 0 ? TransactionStatus.Accepted : TransactionStatus.Declined;

            return(new TransactionResultModel {
                TransactionId = Guid.NewGuid(), Status = status
            });
        }
Beispiel #6
0
        public async Task <IActionResult> List(DataSourceRequest command, PaymentTransactionListModel model)
        {
            if (await _groupService.IsStaff(_workContext.CurrentCustomer))
            {
                model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
            }
            DateTime?startDateValue = (model.StartDate == null) ? null
                : (DateTime?)_dateTimeService.ConvertToUtcTime(model.StartDate.Value, _dateTimeService.CurrentTimeZone);

            DateTime?endDateValue = (model.EndDate == null) ? null
                : (DateTime?)_dateTimeService.ConvertToUtcTime(model.EndDate.Value, _dateTimeService.CurrentTimeZone);

            var paymentTransactions = await _paymentTransactionService.SearchPaymentTransactions(
                customerEmail : model.SearchCustomerEmail,
                ts : model.SearchTransactionStatus >= 0?(TransactionStatus)model.SearchTransactionStatus : null,
                createdFromUtc : startDateValue,
                createdToUtc : endDateValue,
                storeId : model.StoreId,
                pageIndex : command.Page - 1,
                pageSize : command.PageSize);

            var dataModel = new List <PaymentTransactionModel>();

            foreach (var item in paymentTransactions)
            {
                var order = await _orderService.GetOrderByGuid(item.OrderGuid);

                var trmodel = new PaymentTransactionModel();
                trmodel.Id                      = item.Id;
                trmodel.OrderCode               = item.OrderCode;
                trmodel.CustomerEmail           = item.CustomerEmail;
                trmodel.CustomerId              = item.CustomerId;
                trmodel.CurrencyCode            = item.CurrencyCode;
                trmodel.TransactionAmount       = item.TransactionAmount;
                trmodel.PaidAmount              = item.PaidAmount;
                trmodel.PaymentMethodSystemName = item.PaymentMethodSystemName;
                trmodel.RefundedAmount          = item.RefundedAmount;
                trmodel.OrderId                 = order?.Id;
                trmodel.OrderNumber             = order?.OrderNumber;
                trmodel.CreatedOn               = _dateTimeService.ConvertToUserTime(item.CreatedOnUtc, DateTimeKind.Utc);
                trmodel.TransactionStatus       = item.TransactionStatus;
                trmodel.Status                  = item.TransactionStatus.GetTranslationEnum(_translationService, _workContext);
                dataModel.Add(trmodel);
            }

            var gridModel = new DataSourceResult
            {
                Data  = dataModel.ToList(),
                Total = paymentTransactions.TotalCount,
            };

            return(Json(gridModel));
        }
Beispiel #7
0
        private void ApplyPaymentSummaryDetailsTemplate(StringBuilder orderDetails, PaymentTransactionModel payment, Core.Models.OnlinePayments.Invoice.EF.Invoice invoice, Core.Enumerations.InvoiceType invoiceTyped)
        {
            MessageTemplateModel detail2Template = _messageTemplateLogic.ReadForKey
                                                       (Constants.MESSAGE_TEMPLATE_MULTI_PAYMENTDETAIL2);

            orderDetails.Append(detail2Template.Body.Inject(new
            {
                InvoiceType   = invoiceTyped,
                InvoiceNumber = payment.InvoiceNumber,
                InvoiceDate   = invoice.InvoiceDate,
                DueDate       = invoice.DueDate,
                PaymentAmount = payment.PaymentAmount
            }));
        }
Beispiel #8
0
        public string RegisterPayment(PaymentTransactionModel model)
        {
            var request = new RestRequest("/api/Payment/Transaction", Method.POST);

            request.RequestFormat  = DataFormat.Json;
            request.JsonSerializer = new RestSharpJsonNetSerializer();
            request.AddBody(model);

            var response = RestClient.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw CreateException(response);
            }

            return(JsonConvert.DeserializeObject <string>(response.Content));
        }
Beispiel #9
0
        public IHttpActionResult Get(string transactionTokenOrReceipt)
        {
            using (var dbContext = new DataContext())
            {
                var paymentTransaction = dbContext.PaymentTransactions
                                         .Include(f => f.TransactionItems)
                                         .FirstOrDefault(f => f.TransactionToken == transactionTokenOrReceipt || f.Receipt == transactionTokenOrReceipt);
                if (paymentTransaction == null)
                {
                    return(this.BadRequestEx(Error.PaymentTransactionDoesNotExist));
                }

                var model = new PaymentTransactionModel();
                model.TransactionToken        = paymentTransaction.TransactionToken;
                model.Receipt                 = paymentTransaction.Receipt;
                model.ReceiptTimestamp        = paymentTransaction.ReceiptTimestamp;
                model.TerminalUUID            = paymentTransaction.PaymentTerminal.UUID;
                model.TerminalType            = (TerminalType)paymentTransaction.PaymentTerminal.TerminalType;
                model.Amount                  = paymentTransaction.Amount;
                model.CustomerContactNumber   = paymentTransaction.CustomerContactNumber;
                model.CustomerFirstName       = paymentTransaction.CustomerFirstName;
                model.CustomerIDNumber        = paymentTransaction.CustomerIDNumber;
                model.CustomerLastName        = paymentTransaction.CustomerLastName;
                model.PaymentSource           = (PaymentMethod)paymentTransaction.PaymentMethod;
                model.CredentialID            = paymentTransaction.CredentialID;
                model.CreatedTimestamp        = paymentTransaction.CreatedTimestamp;
                model.ModifiedTimestamp       = paymentTransaction.ModifiedTimestamp;
                model.Status                  = (PaymentTransactionStatus)paymentTransaction.Status;
                model.PaymentTransactionItems =
                    paymentTransaction.TransactionItems.Select(f =>
                                                               new PaymentTransactionItemModel
                {
                    Amount                = f.Amount,
                    Description           = f.Description,
                    EntityReferenceTypeID = f.EntityReferenceTypeID,
                    ReferenceNumber       = f.ReferenceNumber,
                    TransactionToken      = f.TransactionToken,
                    Status                = (PaymentTransactionStatus)f.Status
                })
                    .ToList();

                return(Ok(model));
            }
        }
Beispiel #10
0
        private void btnPayment_Click(object sender, EventArgs e)
        {
            Logger.Info("Payment section open.");
            if (paymentTransactionModel == null)
            {
                paymentTransactionModel = new PaymentTransactionModel();
            }
            FrmPaymentTransaction paymentTransaction = new FrmPaymentTransaction(paymentTransactionModel);
            DialogResult          callback           = paymentTransaction.ShowDialog(this);

            if (DialogResult.OK == callback)
            {
                Logger.Info("Payment mode information submitted.");
            }
            else
            {
                paymentTransactionModel = null;
                Logger.Info("Payment mode information cleared.");
            }
        }
Beispiel #11
0
        public async Task <IActionResult> PartiallyPaidPopup(string id, bool online, PaymentTransactionModel model)
        {
            var paymentTransaction = await _paymentTransactionService.GetById(id);

            if (paymentTransaction == null)
            {
                return(RedirectToAction("List", "PaymentTransaction"));
            }

            if (await _groupService.IsStaff(_workContext.CurrentCustomer) && paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
            {
                return(RedirectToAction("List", "PaymentTransaction"));
            }

            try
            {
                double amountToPaid = model.AmountToPaid;
                if (amountToPaid <= 0)
                {
                    throw new GrandException("Enter amount to refund");
                }

                double maxAmountToPaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount;
                if (amountToPaid > maxAmountToPaid)
                {
                    amountToPaid = maxAmountToPaid;
                }

                await _mediator.Send(new PartiallyPaidOfflineCommand { PaymentTransaction = paymentTransaction, AmountToPaid = amountToPaid });

                ViewBag.RefreshPage = true;
                return(View(model));
            }
            catch (Exception exc)
            {
                Error(exc, false);
                return(View(model));
            }
        }
Beispiel #12
0
        public async Task <IActionResult> PartiallyPaidPopup(string id, bool online)
        {
            var paymentTransaction = await _paymentTransactionService.GetById(id);

            if (paymentTransaction == null)
            {
                return(RedirectToAction("List", "PaymentTransaction"));
            }

            if (await _groupService.IsStaff(_workContext.CurrentCustomer) && paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
            {
                return(RedirectToAction("List", "PaymentTransaction"));
            }

            var model = new PaymentTransactionModel();

            model.Id = paymentTransaction.Id;
            model.MaxAmountToPaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount;
            model.CurrencyCode    = paymentTransaction.CurrencyCode;

            return(View(model));
        }
Beispiel #13
0
 private void ResetTransportationDetails()
 {
     Logger.Info("Reset transportation information.");
     paymentTransactionModel = null;
 }
Beispiel #14
0
 private void GetPaymentInvoiceInformation(UserSelectedContext customer, PaymentTransactionModel payment, out Core.Models.OnlinePayments.Invoice.EF.Invoice invoice, out Core.Enumerations.InvoiceType invoiceTyped)
 {
     invoice = _invoiceRepo.GetInvoiceHeader(DivisionHelper.GetDivisionFromBranchId
                                                 (customer.BranchId), customer.CustomerId, payment.InvoiceNumber);
     invoiceTyped = KeithLink.Svc.Core.Extensions.InvoiceExtensions.DetermineType(invoice.InvoiceType);
 }
Beispiel #15
0
        public async Task <IActionResult> Edit(string id)
        {
            var paymentTransaction = await _paymentTransactionService.GetById(id);

            if (paymentTransaction == null)
            {
                return(RedirectToAction("List", "PaymentTransaction"));
            }

            if (await _groupService.IsStaff(_workContext.CurrentCustomer) && paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
            {
                return(RedirectToAction("List", "PaymentTransaction"));
            }

            var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);

            var model = new PaymentTransactionModel();

            model.Id                      = paymentTransaction.Id;
            model.OrderCode               = paymentTransaction.OrderCode;
            model.CustomerEmail           = paymentTransaction.CustomerEmail;
            model.CustomerId              = paymentTransaction.CustomerId;
            model.CurrencyCode            = paymentTransaction.CurrencyCode;
            model.TransactionAmount       = paymentTransaction.TransactionAmount;
            model.PaidAmount              = paymentTransaction.PaidAmount;
            model.PaymentMethodSystemName = paymentTransaction.PaymentMethodSystemName;
            model.RefundedAmount          = paymentTransaction.RefundedAmount;
            model.OrderId                 = order?.Id;
            model.OrderNumber             = order?.OrderNumber;
            model.CreatedOn               = _dateTimeService.ConvertToUserTime(paymentTransaction.CreatedOnUtc, DateTimeKind.Utc);
            model.TransactionStatus       = paymentTransaction.TransactionStatus;
            model.Status                  = paymentTransaction.TransactionStatus.GetTranslationEnum(_translationService, _workContext);
            model.IPAddress               = paymentTransaction.IPAddress;
            model.Description             = paymentTransaction.Description;
            model.AdditionalInfo          = paymentTransaction.AdditionalInfo;


            //payment method buttons
            //model.CanCancelOrder = await _mediator.Send(new CanCancelOrderQuery() { Order = order });
            model.CanCapture = await _mediator.Send(new CanCaptureQuery()
            {
                PaymentTransaction = paymentTransaction
            });

            model.CanMarkAsPaid = await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery()
            {
                PaymentTransaction = paymentTransaction
            });

            model.CanRefund = await _mediator.Send(new CanRefundQuery()
            {
                PaymentTransaction = paymentTransaction
            });

            model.CanRefundOffline = await _mediator.Send(new CanRefundOfflineQuery()
            {
                PaymentTransaction = paymentTransaction
            });

            model.CanPartiallyRefund = await _mediator.Send(new CanPartiallyRefundQuery()
            {
                PaymentTransaction = paymentTransaction, AmountToRefund = 0
            });

            model.CanPartiallyRefundOffline = await _mediator.Send(new CanPartiallyRefundOfflineQuery()
            {
                PaymentTransaction = paymentTransaction, AmountToRefund = 0
            });

            model.CanPartiallyPaidOffline = await _mediator.Send(new CanPartiallyPaidOfflineQuery()
            {
                PaymentTransaction = paymentTransaction, AmountToPaid = 0
            });

            model.CanVoid = await _mediator.Send(new CanVoidQuery()
            {
                PaymentTransaction = paymentTransaction
            });

            model.CanVoidOffline = await _mediator.Send(new CanVoidOfflineQuery()
            {
                PaymentTransaction = paymentTransaction
            });

            model.MaxAmountToRefund = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;
            model.MaxAmountToPaid   = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount;

            return(View(model));
        }
Beispiel #16
0
 public FrmPaymentTransaction(PaymentTransactionModel model)
 {
     InitializeComponent();
     _paymentTransaction = model;
 }
Beispiel #17
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new ProcessPaymentResult();
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            try
            {
                PrepareGBS();

                //var creditCard = new creditCardType
                //{
                //    cardNumber = processPaymentRequest.CreditCardNumber,
                //    expirationDate =
                //        processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear,
                //    cardCode = processPaymentRequest.CreditCardCvv2
                //};

                ////standard api call to retrieve response
                //var paymentType = new paymentType { Item = creditCard };

                //transactionTypeEnum transactionType;

                //switch (_authorizeNetPaymentSettings.TransactMode)
                //{
                //    case TransactMode.Authorize:
                //        transactionType = transactionTypeEnum.authOnlyTransaction;
                //        break;
                //    case TransactMode.AuthorizeAndCapture:
                //        transactionType = transactionTypeEnum.authCaptureTransaction;
                //        break;
                //    default:
                //        throw new NopException("Not supported transaction mode");
                //}

                //var billTo = new customerAddressType
                //{
                //    firstName = customer.BillingAddress.FirstName,
                //    lastName = customer.BillingAddress.LastName,
                //    email = customer.BillingAddress.Email,
                //    address = customer.BillingAddress.Address1,
                //    city = customer.BillingAddress.City,
                //    zip = customer.BillingAddress.ZipPostalCode
                //};

                //if (!string.IsNullOrEmpty(customer.BillingAddress.Company))
                //    billTo.company = customer.BillingAddress.Company;

                //if (customer.BillingAddress.StateProvince != null)
                //    billTo.state = customer.BillingAddress.StateProvince.Abbreviation;

                //if (customer.BillingAddress.Country != null)
                //    billTo.country = customer.BillingAddress.Country.TwoLetterIsoCode;

                //var transactionRequest = new transactionRequestType
                //{
                //    transactionType = transactionType.ToString(),
                //    amount = Math.Round(processPaymentRequest.OrderTotal, 2),
                //    payment = paymentType,
                //    currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode,
                //    billTo = billTo,
                //    customerIP = _webHelper.GetCurrentIpAddress(),
                //    order = new orderType
                //    {
                //        //x_invoice_num is 20 chars maximum. hece we also pass x_description
                //        invoiceNumber = processPaymentRequest.OrderGuid.ToString().Substring(0, 20),
                //        description = string.Format("Full order #{0}", processPaymentRequest.OrderGuid)
                //    }
                //};

                //var request = new createTransactionRequest { transactionRequest = transactionRequest };

                //// instantiate the contoller that will call the service
                //var controller = new createTransactionController(request);
                //controller.Execute();

                //// get the response from the service (errors contained if any)



                //NOP WEB SERVICE CALL START HERE --------------------------------------------------------------------------------------------------------------------
                //create nop payment object from user data
                PaymentTransactionModel payment = new PaymentTransactionModel();
                payment.firstName     = customer.BillingAddress.FirstName;
                payment.lastName      = customer.BillingAddress.LastName;
                payment.streetAddress = customer.BillingAddress.Address1;
                payment.billingCity   = customer.BillingAddress.City;
                payment.postalCode    = customer.BillingAddress.ZipPostalCode;
                payment.countryCode   = customer.BillingAddress.Country.Name;
                if (payment.countryCode == "United States")
                {
                    payment.countryCode = "US";
                }
                else
                {
                    payment.countryCode = "US";
                }
                payment.cardExpireMonth = processPaymentRequest.CreditCardExpireMonth.ToString().Length == 1 ? "0" + processPaymentRequest.CreditCardExpireMonth.ToString() : processPaymentRequest.CreditCardExpireMonth.ToString(); //prepend 0 for single digit months
                payment.cardExpireYear  = processPaymentRequest.CreditCardExpireYear.ToString();
                payment.cardNum         = processPaymentRequest.CreditCardNumber;
                payment.orderAmount     = processPaymentRequest.OrderTotal.ToString();
                payment.pcDestZip       = (customer.ShippingAddress != null && customer.ShippingAddress.ZipPostalCode != null) ? customer.ShippingAddress.ZipPostalCode : String.Empty;
                Object value = null;
                NopResourceDisplayNameAttribute orderNumberKeyGBS = new NopResourceDisplayNameAttribute(("Account.CustomerOrders.OrderNumber"));
                if (processPaymentRequest.CustomValues.TryGetValue(orderNumberKeyGBS.DisplayName, out value))
                {
                    payment.orderID   = processPaymentRequest.CustomValues[orderNumberKeyGBS.DisplayName].ToString();
                    payment.pcOrderID = processPaymentRequest.CustomValues[orderNumberKeyGBS.DisplayName].ToString();
                }
                else
                {
                    payment.orderID   = "NA";
                    payment.pcOrderID = "NA";
                }
                payment.state   = customer.BillingAddress.StateProvince.Abbreviation;
                payment.tax     = _orderTotalCalculationService.GetTaxTotal((IList <ShoppingCartItem>)customer.ShoppingCartItems, false).ToString();
                payment.sandBox = _gbsPaymentSettings.UseSandbox;


                if (Convert.ToBoolean(processPaymentRequest.CustomValues["SavedProfile"]) == true)
                {
                    payment.createProfile = false;
                    payment.useProfile    = true;
                    payment.profileID     = processPaymentRequest.CustomValues["ProfileID"].ToString();
                }
                else
                {
                    payment.createProfile = true;
                    payment.useProfile    = false;
                    payment.profileID     = "";
                }


                //will need to be able to switch between sand and production version
                string address = _gbsPaymentSettings.GBSPaymentWebServiceAddress;



                GBSPaymentServiceClient gateway = new GBSPaymentServiceClient();

                //calls to GBSPaymentGateway function
                var response = gateway.AuthorizeAndCapture(payment, address, _gbsPaymentSettings.LoginId, _gbsPaymentSettings.Password);


                //use returned GBSTransactionResponse to tell nop what occured in submit
                switch (response.responseCode)
                {
                case GBSTransactionResponse.ResponseCodeType.Approved:
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                    break;

                case GBSTransactionResponse.ResponseCodeType.Declined:
                case GBSTransactionResponse.ResponseCodeType.Error:
                    result.NewPaymentStatus = PaymentStatus.Voided;
                    break;

                default:
                    result.NewPaymentStatus = PaymentStatus.Voided;
                    break;
                }
                //validate
                if (GetErrors(response, result.Errors))
                {
                    return(result);
                }

                if (_gbsPaymentSettings.TransactMode == TransactMode.Authorize)
                {
                    result.AuthorizationTransactionCode = string.Format("{0},{1}", response.transactId, response.authCode);
                }
                //if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture)
                //    result.CaptureTransactionId = string.Format("{0},{1}", response.transactionResponse.transId, response.transactionResponse.authCode);

                result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.responseCode, response.authCode);
                //result.AvsResult = response.transactionResponse.avsResultCode;
                //result.NewPaymentStatus = _authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize ? PaymentStatus.Authorized : PaymentStatus.Paid;

                //var congrats = "Congrats the payment was successful, now insert profile id into DB";

                bool storeProfile = Convert.ToBoolean(processPaymentRequest.CustomValues["StoreProfile"]);

                if (payment.createProfile == true && storeProfile == true)
                {
                    string nickName = String.IsNullOrEmpty(processPaymentRequest.CustomValues["NickName"].ToString()) ? "" : processPaymentRequest.CustomValues["NickName"].ToString();
                    nickName = nickName.Replace("'", "''");

                    string last4Digits = response.accountNum.ToString();
                    last4Digits = last4Digits.Substring(last4Digits.Length - 4);

                    DBManager manager = new DBManager();
                    Dictionary <string, string> paramDic = new Dictionary <string, string>();
                    paramDic.Add("@CustomerID", customer.Id.ToString());
                    paramDic.Add("@ProfileID", response.customerRefNum.ToString());
                    paramDic.Add("@NickName", nickName);
                    paramDic.Add("@Last4Digits", last4Digits);
                    paramDic.Add("@CardType", response.cardBrand.ToString());
                    paramDic.Add("@ExpMonth", payment.cardExpireMonth);
                    paramDic.Add("@ExpYear", payment.cardExpireYear);

                    string insert = "INSERT INTO Profiles (CustomerID, ProfileID, NickName, Last4Digits, CardType, ExpMonth, ExpYear) ";
                    insert += "VALUES ('" + customer.Id + "', '" + response.customerRefNum + "', '" + nickName + "', '" + last4Digits + "', '" + response.cardBrand + "', '" + payment.cardExpireMonth + "', '" + payment.cardExpireYear + "')";
                    try
                    {
                        manager.SetParameterizedQueryNoData(insert, paramDic);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            _logger.Error("Payment Plugin Error inserting profile on auth : " + ex.Message + ": query = " + insert, ex, null);
                        }
                        catch (Exception ex1) {
                            _logger.Error("Payment Plugin Error inserting profile on auth with additional failure to log the sql statement : " + ex.Message, ex, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Payment Plugin Error : " + ex.Message, ex, null);
                throw new Exception("Payment Plugin Exception: " + ex.Message, ex);
            }

            return(result);
        }
Beispiel #18
0
        public ActionResult CourtPayment(PaymentSummary model)
        {
            ViewBag.Districts = AuthenticatedUser.UserData.Districts;

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var paymentDate = DateTime.Now;

            if (!DateTime.TryParseExact(model.PaymentDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out paymentDate))
            {
                ModelState.AddModelError("PaymentDate", "Invalid Payment Date.");

                return(View(model));
            }

            try
            {
                PaymentSummary cachedModel = Session["PaymentSummary"] as PaymentSummary;
                model.Fines = cachedModel.Fines;

                var paymentTransaction = new PaymentTransactionModel();
                paymentTransaction.CredentialID          = AuthenticatedUser.SessionData.CredentialID;
                paymentTransaction.CustomerContactNumber = model.MobileNumber;
                paymentTransaction.CustomerIDNumber      = string.Empty;
                paymentTransaction.CustomerFirstName     = model.FirstName;
                paymentTransaction.CustomerLastName      = model.LastName;
                paymentTransaction.PaymentSource         = model.PaymentMethod;
                paymentTransaction.Receipt                 = model.PaymentReference;
                paymentTransaction.ReceiptTimestamp        = paymentDate;
                paymentTransaction.CourtID                 = model.CourtID;
                paymentTransaction.TerminalType            = Core.Gateway.Models.Enums.TerminalType.InternalServer;
                paymentTransaction.TerminalUUID            = "IMS";
                paymentTransaction.Amount                  = model.Fines.Sum(f => f.OutstandingAmount).Value;
                paymentTransaction.PaymentTransactionItems =
                    model.Fines.Select(f =>
                                       new PaymentTransactionItemModel
                {
                    ReferenceNumber       = f.ReferenceNumber,
                    Amount                = f.OutstandingAmount.Value,
                    TransactionToken      = string.Empty,
                    EntityReferenceTypeID = long.Parse(f.ReferenceNumber[1].ToString()),
                    Description           = "Notice issued."
                })
                    .ToList();

                var paymentService   = new PaymentService(AuthenticatedUser.SessionToken);
                var transactionToken = paymentService.RegisterPayment(paymentTransaction);

                var confirmedPayment = new ConfirmedPaymentModel();
                confirmedPayment.CustomerContactNumber = model.MobileNumber;
                confirmedPayment.CustomerIDNumber      = string.Empty;
                confirmedPayment.CustomerFirstName     = model.FirstName;
                confirmedPayment.CustomerLastName      = model.LastName;
                confirmedPayment.PaymentSource         = model.PaymentMethod;
                confirmedPayment.Receipt          = model.PaymentReference;
                confirmedPayment.TerminalType     = Core.Gateway.Models.Enums.TerminalType.InternalServer;
                confirmedPayment.TerminalUUID     = "IMS";
                confirmedPayment.Amount           = paymentTransaction.Amount;
                confirmedPayment.TransactionToken = transactionToken;

                paymentService.SettlePayment(confirmedPayment);

                Session.Remove("PaymentSummary");

                return(RedirectToAction("Index"));
            }
            catch (GatewayException ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);

                return(View(model));
            }
        }
Beispiel #19
0
        public async Task <IActionResult> PartiallyRefundPopup(string id, bool online, PaymentTransactionModel model)
        {
            var paymentTransaction = await _paymentTransactionService.GetById(id);

            if (paymentTransaction == null)
            {
                return(RedirectToAction("List", "PaymentTransaction"));
            }

            if (await _groupService.IsStaff(_workContext.CurrentCustomer) && paymentTransaction.StoreId != _workContext.CurrentCustomer.StaffStoreId)
            {
                return(RedirectToAction("List", "PaymentTransaction"));
            }

            try
            {
                double amountToRefund = model.AmountToRefund;
                if (amountToRefund <= 0)
                {
                    throw new GrandException("Enter amount to refund");
                }

                double maxAmountToRefund = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;
                if (amountToRefund > maxAmountToRefund)
                {
                    amountToRefund = maxAmountToRefund;
                }

                var errors = new List <string>();
                if (online)
                {
                    errors = (await _mediator.Send(new PartiallyRefundCommand {
                        PaymentTransaction = paymentTransaction, AmountToRefund = amountToRefund
                    })).ToList();
                }
                else
                {
                    await _mediator.Send(new PartiallyRefundOfflineCommand { PaymentTransaction = paymentTransaction, AmountToRefund = amountToRefund });
                }

                if (errors.Count == 0)
                {
                    //success
                    ViewBag.RefreshPage = true;
                    return(View(model));
                }
                //error
                foreach (var error in errors)
                {
                    Error(error, false);
                }
                return(View(model));
            }
            catch (Exception exc)
            {
                Error(exc, false);
                return(View(model));
            }
        }
Beispiel #20
0
        public IHttpActionResult RegisterTransaction(PaymentTransactionModel model)
        {
            if (model.Amount != model.PaymentTransactionItems.Sum(f => f.Amount))
            {
                return(this.BadRequestEx(Error.PaymentTransactionInvalidAmount));
            }

            using (var dbContext = new DataContext())
            {
                var paymentTerminal = dbContext.PaymentTerminals.FirstOrDefault(f => f.TerminalType == (Data.Enums.TerminalType)model.TerminalType && f.UUID == model.TerminalUUID);
                if (paymentTerminal == null)
                {
                    return(this.BadRequestEx(Error.PaymentTerminalDoesNotExist));
                }

                if (paymentTerminal.Status != Data.Enums.Status.Active)
                {
                    return(this.BadRequestEx(Error.PaymentTerminalIsNotActive));
                }

                if (dbContext.PaymentTransactions.Any(f => f.Receipt == model.Receipt))
                {
                    return(this.BadRequestEx(Error.PaymentTransactionAlreadyExist));
                }

                foreach (var modelItem in model.PaymentTransactionItems)
                {
                    var register = dbContext.Registers.AsNoTracking().FirstOrDefault(f => f.ReferenceNumber == modelItem.ReferenceNumber);
                    if (register == null)
                    {
                        return(this.BadRequestEx(Error.RegisterItemDoesNotExist));
                    }

                    if (register.RegisterStatus >= 3000)
                    {
                        return(this.BadRequestEx(Error.RegisterItemNotPayable));
                    }

                    if (string.IsNullOrWhiteSpace(modelItem.TransactionToken))
                    {
                        var generatedReferenceNumber = dbContext.GeneratedReferenceNumbers.FirstOrDefault(f => f.ReferenceNumber == modelItem.ReferenceNumber);
                        if (generatedReferenceNumber != null)
                        {
                            modelItem.TransactionToken = generatedReferenceNumber.ExternalToken;
                        }
                    }
                }

                PaymentTransaction paymentTransaction = null;

                if (model.PaymentTransactionItems.Count == 1)
                {
                    var transactionToken = model.PaymentTransactionItems.First().TransactionToken;

                    paymentTransaction                       = dbContext.PaymentTransactions.FirstOrDefault(f => f.TransactionToken == transactionToken && f.Status == Data.Enums.PaymentTransactionStatus.Added);
                    paymentTransaction.Receipt               = model.Receipt;
                    paymentTransaction.ReceiptTimestamp      = model.ReceiptTimestamp;
                    paymentTransaction.CourtID               = model.CourtID;
                    paymentTransaction.TerminalID            = paymentTerminal.ID;
                    paymentTransaction.CustomerContactNumber = model.CustomerContactNumber;
                    paymentTransaction.CustomerFirstName     = model.CustomerFirstName;
                    paymentTransaction.CustomerIDNumber      = model.CustomerIDNumber;
                    paymentTransaction.CustomerLastName      = model.CustomerLastName;
                    paymentTransaction.PaymentMethod         = (Data.Enums.PaymentMethod)model.PaymentSource;
                }
                else
                {
                    paymentTransaction                       = new PaymentTransaction();
                    paymentTransaction.Receipt               = model.Receipt;
                    paymentTransaction.ReceiptTimestamp      = model.ReceiptTimestamp;
                    paymentTransaction.CourtID               = model.CourtID;
                    paymentTransaction.TerminalID            = paymentTerminal.ID;
                    paymentTransaction.Amount                = model.Amount;
                    paymentTransaction.CreatedTimestamp      = DateTime.Now;
                    paymentTransaction.CustomerContactNumber = model.CustomerContactNumber;
                    paymentTransaction.CustomerFirstName     = model.CustomerFirstName;
                    paymentTransaction.CustomerIDNumber      = model.CustomerIDNumber;
                    paymentTransaction.CustomerLastName      = model.CustomerLastName;
                    paymentTransaction.PaymentMethod         = (Data.Enums.PaymentMethod)model.PaymentSource;
                    paymentTransaction.Status                = Data.Enums.PaymentTransactionStatus.Added;

                    foreach (var modelItem in model.PaymentTransactionItems)
                    {
                        var paymentTransactionItem = new PaymentTransactionItem();
                        paymentTransactionItem.PaymentTransaction    = paymentTransaction;
                        paymentTransactionItem.ReferenceNumber       = modelItem.ReferenceNumber;
                        paymentTransactionItem.TransactionToken      = modelItem.TransactionToken;
                        paymentTransactionItem.EntityReferenceTypeID = long.Parse(modelItem.ReferenceNumber[1].ToString());
                        paymentTransactionItem.Description           = modelItem.Description;
                        paymentTransactionItem.Amount = modelItem.Amount;
                        paymentTransactionItem.Status = Data.Enums.PaymentTransactionStatus.Added;

                        dbContext.PaymentTransactionItems.Add(paymentTransactionItem);
                    }

                    if (model.PaymentSource == PaymentMethod.DumaPay)
                    {
                        var paymentProvider    = resolvePaymentProvider();
                        var transactionIDModel =
                            paymentProvider.RegisterTransaction(
                                new ThirdParty.Payment.Models.TransactionModel
                        {
                            CustomerFirstName  = paymentTransaction.CustomerFirstName,
                            CustomerLastName   = paymentTransaction.CustomerLastName,
                            CompanyRef         = string.Empty,
                            CompanyAccRef      = paymentTransaction.Receipt,
                            Amount             = paymentTransaction.Amount,
                            UserID             = SessionModel.UserName,
                            ServiceDescription = "Payment Basket Registered",
                            ServiceType        = 6067
                        });

                        paymentTransaction.TransactionToken     = transactionIDModel.TransactionToken;
                        paymentTransaction.TransactionReference = transactionIDModel.TransactionReference;
                    }
                    else // Cash
                    {
                        paymentTransaction.TransactionToken     = Guid.NewGuid().ToString();
                        paymentTransaction.TransactionReference = string.Empty;
                    }

                    dbContext.PaymentTransactions.Add(paymentTransaction);
                }

                dbContext.SaveChanges();

                PaymentTransactionHub.SendStatusChanged(
                    paymentTransaction.TransactionToken,
                    (PaymentTransactionStatus)paymentTransaction.Status,
                    paymentTransaction.Amount);

                return(Ok(paymentTransaction.TransactionToken));
            }
        }
        //GBSPaymentGateway() {}


        public GBSTransactionResponse AuthorizeAndCapture(PaymentTransactionModel payment, string address)
        {
            GBSTransactionResponse authTransaction = new GBSTransactionResponse();

            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("Content-Type", "application/json");
                string responseString = client.UploadString(address, payment.ToJSON());

                XmlDocument xml = new XmlDocument();
                xml.LoadXml(responseString);

                XmlNode procStatusNode                 = xml.SelectSingleNode("//ProcStatus");
                XmlNode approvalStatusNode             = xml.SelectSingleNode("//ApprovalStatus");
                XmlNode statusMessageNode              = xml.SelectSingleNode("//StatusMsg");
                XmlNode responseMessageNode            = xml.SelectSingleNode("//RespMsg");
                XmlNode transactionReferenceNumberNode = xml.SelectSingleNode("//TxRefNum");
                XmlNode authorizationCodeNode          = xml.SelectSingleNode("//AuthCode");

                authTransaction.transactId = transactionReferenceNumberNode.InnerXml;
                authTransaction.authCode   = authorizationCodeNode.InnerXml; //String.IsNullOrEmpty(authorizationCodeNode.InnerXml) ? "000000" :



                switch (procStatusNode.InnerXml)
                {
                case "0":
                    authTransaction.resultCode = GBSTransactionResponse.ResultCodeType.Success;
                    switch (approvalStatusNode.InnerXml)
                    {
                    case "0":         //Declined
                        authTransaction.responseCode = GBSTransactionResponse.ResponseCodeType.Declined;
                        authTransaction.messages.Add(statusMessageNode.InnerXml);
                        authTransaction.messages.Add(responseMessageNode.InnerXml);
                        break;

                    case "1":         //Approved
                        authTransaction.responseCode = GBSTransactionResponse.ResponseCodeType.Approved;
                        authTransaction.messages.Add(statusMessageNode.InnerXml);
                        authTransaction.messages.Add(responseMessageNode.InnerXml);
                        break;

                    default:         //Error
                        authTransaction.responseCode = GBSTransactionResponse.ResponseCodeType.Error;
                        authTransaction.errors.Add(statusMessageNode.InnerXml);
                        authTransaction.errors.Add(responseMessageNode.InnerXml);
                        break;
                    }
                    break;

                default:
                    authTransaction.resultCode   = GBSTransactionResponse.ResultCodeType.Failure;
                    authTransaction.responseCode = GBSTransactionResponse.ResponseCodeType.Error;
                    authTransaction.errors.Add(statusMessageNode.InnerXml);
                    authTransaction.errors.Add(responseMessageNode.InnerXml);
                    break;
                }

                switch (authTransaction.resultCode)
                {
                case GBSTransactionResponse.ResultCodeType.Success:

                    switch (authTransaction.responseCode)
                    {
                    case GBSTransactionResponse.ResponseCodeType.Approved:
                        //do nothing
                        break;

                    case GBSTransactionResponse.ResponseCodeType.Declined:
                        break;

                    case GBSTransactionResponse.ResponseCodeType.Error:
                        break;

                    default:
                        break;
                    }
                    break;

                case GBSTransactionResponse.ResultCodeType.Failure:
                    break;

                default:
                    break;
                }



                return(authTransaction);
            }
            catch (Exception ex)
            {
                //authOutput.Value = ex.Message + " ERROR!! ";
                return(new GBSTransactionResponse());
            }
        }