public void VoidPreAuthorization(string companyKey, Guid orderId, bool isForPrepaid = false)
        {
            var message = string.Empty;

            try
            {
                // we must do a completion with $0 (see eSELECTplus_DotNet_IG.pdf, Process Flow for PreAuth / Capture Transactions)
                var paymentDetail = _paymentDao.FindByOrderId(orderId, companyKey);
                if (paymentDetail == null)
                {
                    // nothing to void
                    return;
                }

                var monerisSettings = _serverPaymentSettings.MonerisPaymentSettings;

                var completionCommand = new Completion(orderId.ToString(), 0.ToString("F"), paymentDetail.TransactionId, CryptType_SSLEnabledMerchant);
                var commitRequest     = MonerisHttpRequestWrapper.NewHttpsPostRequest(monerisSettings.Host, monerisSettings.StoreId, monerisSettings.ApiToken, completionCommand);
                var commitReceipt     = commitRequest.GetAndLogReceipt(_logger);

                RequestSuccesful(commitReceipt, out message);
            }
            catch (Exception ex)
            {
                _logger.LogMessage("Can't cancel Moneris preauthorization");
                _logger.LogError(ex);
                message = message + ex.Message;
                //can't cancel transaction, send a command to log later
            }
            finally
            {
                _logger.LogMessage(message);
            }
        }
        public DeleteTokenizedCreditcardResponse DeleteTokenizedCreditcard(string cardToken)
        {
            var monerisSettings = _serverPaymentSettings.MonerisPaymentSettings;

            try
            {
                var deleteCommand = new ResDelete(cardToken);
                var deleteRequest = MonerisHttpRequestWrapper.NewHttpsPostRequest(monerisSettings.Host, monerisSettings.StoreId,
                                                                                  monerisSettings.ApiToken, deleteCommand);
                var receipt = deleteRequest.GetAndLogReceipt(_logger);

                string message;
                var    success = RequestSuccesful(receipt, out message);

                return(new DeleteTokenizedCreditcardResponse
                {
                    IsSuccessful = success,
                    Message = success
                        ? "Success"
                        : message
                });
            }
            catch (AggregateException ex)
            {
                ex.Handle(x =>
                {
                    _logger.LogError(x);
                    return(true);
                });
                return(new DeleteTokenizedCreditcardResponse
                {
                    IsSuccessful = false,
                    Message = ex.InnerExceptions.First().Message
                });
            }
            catch (Exception ex)
            {
                return(new DeleteTokenizedCreditcardResponse
                {
                    IsSuccessful = false,
                    Message = ex.Message
                });
            }
        }
 public MonerisPaymentService(ICommandBus commandBus,
                              ILogger logger,
                              IOrderPaymentDao paymentDao,
                              IServerSettings serverSettings,
                              ServerPaymentSettings serverPaymentSettings,
                              IPairingService pairingService,
                              ICreditCardDao creditCardDao,
                              IOrderDao orderDao)
 {
     _commandBus            = commandBus;
     _logger                = logger;
     _paymentDao            = paymentDao;
     _serverSettings        = serverSettings;
     _serverPaymentSettings = serverPaymentSettings;
     _pairingService        = pairingService;
     _creditCardDao         = creditCardDao;
     _orderDao              = orderDao;
     MonerisHttpRequestWrapper.SetLogger(_logger);
 }
        private void Void(Guid orderId, string transactionId, ref string message)
        {
            var monerisSettings = _serverPaymentSettings.MonerisPaymentSettings;

            var correctionCommand = new PurchaseCorrection(orderId.ToString(), transactionId, CryptType_SSLEnabledMerchant);
            var correctionRequest = MonerisHttpRequestWrapper.NewHttpsPostRequest(monerisSettings.Host, monerisSettings.StoreId, monerisSettings.ApiToken, correctionCommand);
            var correctionReceipt = correctionRequest.GetAndLogReceipt(_logger);

            string monerisMessage;
            var    correctionSuccess = RequestSuccesful(correctionReceipt, out monerisMessage);

            if (!correctionSuccess)
            {
                message = string.Format("{0} and {1}", message, monerisMessage);
                throw new Exception("Moneris Purchase Correction failed");
            }

            message = message + " The transaction has been cancelled.";
        }
        public CommitPreauthorizedPaymentResponse CommitPayment(string companyKey, Guid orderId, AccountDetail account, decimal preauthAmount, decimal amount, decimal meterAmount, decimal tipAmount, string transactionId, string reAuthOrderId = null, bool isForPrepaid = false, string kountSessionId = null, string customerIpAddress = null)
        {
            string authorizationCode   = null;
            var    commitTransactionId = transactionId;

            try
            {
                var authResponse = ReAuthorizeIfNecessary(companyKey, orderId, account, preauthAmount, amount);
                if (!authResponse.IsSuccessful)
                {
                    return(new CommitPreauthorizedPaymentResponse
                    {
                        IsSuccessful = false,
                        IsDeclined = authResponse.IsDeclined,
                        TransactionId = commitTransactionId,
                        TransactionDate = authResponse.TransactionDate,
                        Message = string.Format("Moneris Re-Auth of amount {0} failed.", amount)
                    });
                }

                if (authResponse.TransactionId.HasValue())
                {
                    commitTransactionId = authResponse.TransactionId;
                }

                string orderIdentifier;
                if (reAuthOrderId.HasValue())
                {
                    // Settling overdue payment
                    orderIdentifier = reAuthOrderId;
                }
                else if (authResponse.ReAuthOrderId.HasValue())
                {
                    // Normal re-auth
                    orderIdentifier = authResponse.ReAuthOrderId;
                }
                else
                {
                    // Normal flow
                    orderIdentifier = orderId.ToString();
                }

                var monerisSettings   = _serverPaymentSettings.MonerisPaymentSettings;
                var completionCommand = new Completion(orderIdentifier, amount.ToString("F"), commitTransactionId, CryptType_SSLEnabledMerchant);

                var orderStatus = _orderDao.FindOrderStatusById(orderId);

                var descriptor = monerisSettings.UseCarIdInTransaction
                    ? orderStatus.SelectOrDefault(status => status.VehicleNumber)
                    : orderStatus.SelectOrDefault(status => status.DriverInfos).SelectOrDefault(driverInfos => driverInfos.DriverId);

                if (descriptor.HasValueTrimmed())
                {
                    //add driver id or vehicleNumber to "memo" field
                    completionCommand.SetDynamicDescriptor(descriptor);
                }

                var commitRequest = MonerisHttpRequestWrapper.NewHttpsPostRequest(monerisSettings.Host, monerisSettings.StoreId, monerisSettings.ApiToken, completionCommand);
                var commitReceipt = commitRequest.GetAndLogReceipt(_logger);

                string message;
                var    isSuccessful   = RequestSuccesful(commitReceipt, out message);
                var    isCardDeclined = IsCardDeclined(commitReceipt);

                if (isSuccessful)
                {
                    authorizationCode   = commitReceipt.GetAuthCode();
                    commitTransactionId = commitReceipt.GetTxnNumber();
                }

                // we must return the latest transaction id in case of a successful commit
                // since this is the one we need to void if there's a problem while contacting driver
                return(new CommitPreauthorizedPaymentResponse
                {
                    IsSuccessful = isSuccessful,
                    AuthorizationCode = authorizationCode,
                    Message = message,
                    TransactionId = commitTransactionId,
                    IsDeclined = isCardDeclined,
                    TransactionDate = GetTransactionDate(commitReceipt)
                });
            }
            catch (Exception ex)
            {
                return(new CommitPreauthorizedPaymentResponse
                {
                    IsSuccessful = false,
                    TransactionId = commitTransactionId,
                    Message = ex.Message
                });
            }
        }
        public PreAuthorizePaymentResponse PreAuthorize(string companyKey, Guid orderId, AccountDetail account, decimal amountToPreAuthorize, bool isReAuth = false, bool isSettlingOverduePayment = false, bool isForPrepaid = false, string cvv = null)
        {
            var      message         = string.Empty;
            var      transactionId   = string.Empty;
            DateTime?transactionDate = null;

            try
            {
                bool isSuccessful;
                var  isCardDeclined = false;
                var  creditCard     = _creditCardDao.FindById(account.DefaultCreditCard.GetValueOrDefault());

                var order = _orderDao.FindOrderStatusById(orderId);

                // We cannot re-use the same id has a previously failed payment
                var shouldGenerateNewOrderId = isReAuth || isSettlingOverduePayment;

                var orderIdentifier = shouldGenerateNewOrderId
                    ? string.Format("{0}-{1}", orderId, GenerateShortUid())
                    : orderId.ToString();

                if (amountToPreAuthorize > 0)
                {
                    // PreAuthorize transaction
                    var monerisSettings = _serverPaymentSettings.MonerisPaymentSettings;

                    var customerId = monerisSettings.UseCarIdInTransaction
                        ? order.SelectOrDefault(o => o.VehicleNumber)
                        : order != null?order.DriverInfos.SelectOrDefault(driverInfos => driverInfos.DriverId) : null;

                    var preAuthorizeCommand = new ResPreauthCC(creditCard.Token, orderIdentifier, customerId, amountToPreAuthorize.ToString("F"), CryptType_SSLEnabledMerchant);
                    AddCvvInfo(preAuthorizeCommand, cvv);

                    var info = new AvsInfo();
                    if (_serverPaymentSettings.EnableAddressVerification)
                    {
                        info.SetAvsStreetName(creditCard.StreetName);
                        info.SetAvsStreetNumber(creditCard.StreetNumber);
                        info.SetAvsZipCode(creditCard.ZipCode);
                        info.SetAvsCustPhone(creditCard.Phone);
                        info.SetAvsEmail(creditCard.Email);
                        preAuthorizeCommand.SetAvsInfo(info);
                    }

                    var preAuthRequest = MonerisHttpRequestWrapper.NewHttpsPostRequest(monerisSettings.Host, monerisSettings.StoreId, monerisSettings.ApiToken, preAuthorizeCommand);
                    var preAuthReceipt = preAuthRequest.GetAndLogReceipt(_logger);

                    isSuccessful    = RequestSuccesful(preAuthReceipt, out message);
                    isCardDeclined  = IsCardDeclined(preAuthReceipt);
                    transactionId   = preAuthReceipt.GetTxnNumber();
                    transactionDate = GetTransactionDate(preAuthReceipt);
                }
                else
                {
                    // if we're preauthorizing $0, we skip the preauth with payment provider
                    // but we still send the InitiateCreditCardPayment command
                    // this should never happen in the case of a real preauth (hence the minimum of $50)
                    isSuccessful = true;
                }

                if (isSuccessful && !isReAuth)
                {
                    var paymentId = Guid.NewGuid();
                    _commandBus.Send(new InitiateCreditCardPayment
                    {
                        PaymentId     = paymentId,
                        Amount        = amountToPreAuthorize,
                        TransactionId = transactionId,
                        OrderId       = orderId,
                        CardToken     = creditCard.Token,
                        Provider      = PaymentProvider.Moneris,
                        IsNoShowFee   = false,
                        CompanyKey    = companyKey
                    });
                }

                return(new PreAuthorizePaymentResponse
                {
                    IsSuccessful = isSuccessful,
                    Message = message,
                    TransactionId = transactionId,
                    ReAuthOrderId = shouldGenerateNewOrderId ? orderIdentifier : null,
                    IsDeclined = isCardDeclined,
                    TransactionDate = transactionDate,
                });
            }
            catch (Exception e)
            {
                _logger.LogMessage(string.Format("Error during preauthorization (validation of the card) for client {0}: {1} - {2}", account.Email, message, e));
                _logger.LogError(e);

                return(new PreAuthorizePaymentResponse
                {
                    IsSuccessful = false,
                    Message = message
                });
            }
        }