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

            try
            {
                var paymentDetail = _paymentDao.FindByOrderId(orderId, companyKey);
                if (paymentDetail == null)
                {
                    // nothing to void
                    return;
                }

                Void(paymentDetail.TransactionId, ref message);
            }
            catch (Exception ex)
            {
                _logger.LogMessage("Can't cancel Braintree preauthorization");
                _logger.LogError(ex);
                message = message + ex.Message;
                //can't cancel transaction, send a command to log later
            }
            finally
            {
                _logger.LogMessage(message);
            }
        }
예제 #2
0
        private PreAuthorizePaymentResponse PreauthorizePaymentIfNecessary(Guid orderId, decimal totalFeeAmount, FeeTypes feeType, string companyKey = null)
        {
            // Check payment instead of PreAuth setting, because we do not preauth in the cases of future bookings
            var paymentInfo = _paymentDao.FindByOrderId(orderId, companyKey);

            if (paymentInfo != null)
            {
                // Already preauthorized on create order, do nothing
                return(new PreAuthorizePaymentResponse {
                    IsSuccessful = true
                });
            }

            var orderDetail = _orderDao.FindById(orderId);

            if (orderDetail == null)
            {
                return(new PreAuthorizePaymentResponse
                {
                    IsSuccessful = false,
                    Message = "Order not found"
                });
            }

            var account = _accountDao.FindById(orderDetail.AccountId);

            // Fees are collected by the local company
            var result = _paymentService.PreAuthorize(null, orderId, account, totalFeeAmount);

            if (result.IsSuccessful)
            {
                // Wait for OrderPaymentDetail to be created
                Thread.Sleep(500);
            }
            else if (result.IsDeclined)
            {
                // Deactivate credit card if it was declined
                _commandBus.Send(new ReactToPaymentFailure
                {
                    AccountId       = orderDetail.AccountId,
                    OrderId         = orderId,
                    IBSOrderId      = orderDetail.IBSOrderId,
                    CreditCardId    = account.DefaultCreditCard.GetValueOrDefault(),
                    OverdueAmount   = totalFeeAmount,
                    TransactionId   = result.TransactionId,
                    TransactionDate = result.TransactionDate,
                    FeeType         = feeType
                });
            }

            return(result);
        }
        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);
            }
        }
예제 #4
0
        public object Get(OrderRequest request)
        {
            var orderDetail = Dao.FindById(request.OrderId);
            var account     = _accountDao.FindById(new Guid(this.GetSession().UserAuthId));

            if (orderDetail == null)
            {
                throw new HttpError(HttpStatusCode.NotFound, "Order Not Found");
            }

            if (account.Id != orderDetail.AccountId)
            {
                throw new HttpError(HttpStatusCode.Unauthorized, "Can't access another account's order");
            }

            var payment = _orderPaymentDao.FindByOrderId(orderDetail.Id, orderDetail.CompanyKey);

            if (payment != null && !payment.IsCancelled && payment.IsCompleted)
            {
                orderDetail.Fare = Convert.ToDouble(payment.Meter);
                orderDetail.Toll = 0;
                orderDetail.Tip  = Convert.ToDouble(payment.Tip);
            }

            var result = new OrderMapper().ToResource(orderDetail);

            var promoUsed = _promotionDao.FindByOrderId(orderDetail.Id);

            if (promoUsed != null)
            {
                result.PromoCode = promoUsed.Code;
            }

            return(result);
        }
        private void SendPaymentConfirmationToDriver(Guid orderId, decimal totalAmountBeforePromotion, decimal taxedMeterAmount, decimal tipAmount, string provider, string authorizationCode)
        {
            // Send message to driver
            var orderStatusDetail = _dao.FindOrderStatusById(orderId);

            if (orderStatusDetail == null)
            {
                throw new InvalidOperationException("Order Status not found");
            }

            // Confirm to IBS that order was payed
            var orderDetail = _dao.FindById(orderId);

            if (orderDetail == null)
            {
                throw new InvalidOperationException("Order not found");
            }

            var payment = _paymentDao.FindByOrderId(orderId, orderDetail.CompanyKey);

            if (payment == null)
            {
                throw new InvalidOperationException("Payment info not found");
            }

            var account = _accountDao.FindById(orderDetail.AccountId);

            if (account == null)
            {
                throw new InvalidOperationException("Order account not found");
            }

            if (provider == PaymentType.CreditCard.ToString())
            {
                var card = _creditCardDao.FindByToken(payment.CardToken);
                if (card == null)
                {
                    throw new InvalidOperationException("Credit card not found");
                }
            }

            _ibs.SendPaymentNotification((double)totalAmountBeforePromotion, (double)taxedMeterAmount, (double)tipAmount, authorizationCode, orderStatusDetail.VehicleNumber, orderStatusDetail.CompanyKey);
        }
예제 #6
0
        private bool SettleOverduePayment(Guid orderId, AccountDetail accountDetail, decimal amount, string companyKey, bool isFee, string kountSessionId, string customerIpAddress)
        {
            var payment = _orderPaymentDao.FindByOrderId(orderId, companyKey);
            var reAuth  = payment != null;

            var preAuthResponse = _paymentService.PreAuthorize(companyKey, orderId, accountDetail, amount, reAuth, isSettlingOverduePayment: true);

            if (preAuthResponse.IsSuccessful)
            {
                // Wait for payment to be created
                Thread.Sleep(500);

                var commitResponse = _paymentService.CommitPayment(
                    companyKey,
                    orderId,
                    accountDetail,
                    amount,
                    amount,
                    amount,
                    0,
                    preAuthResponse.TransactionId,
                    preAuthResponse.ReAuthOrderId,
                    false,
                    kountSessionId,
                    customerIpAddress);

                if (commitResponse.IsSuccessful)
                {
                    // Go fetch declined order, and send its receipt
                    var paymentDetail = _orderPaymentDao.FindByOrderId(orderId, companyKey);
                    var promotion     = _promotionDao.FindByOrderId(orderId);

                    var orderDetail = _orderDao.FindById(orderId);

                    decimal tipAmount             = 0;
                    decimal meterAmountWithoutTax = amount;
                    decimal taxAmount             = 0;

                    if (!isFee)
                    {
                        if (!orderDetail.IsManualRideLinq)
                        {
                            var pairingInfo = _orderDao.FindOrderPairingById(orderId);
                            tipAmount = FareHelper.GetTipAmountFromTotalIncludingTip(amount, pairingInfo.AutoTipPercentage ?? _serverSettings.ServerData.DefaultTipPercentage);
                            var meterAmount = amount - tipAmount;

                            var fareObject = FareHelper.GetFareFromAmountInclTax(meterAmount,
                                                                                 _serverSettings.ServerData.VATIsEnabled
                                    ? _serverSettings.ServerData.VATPercentage
                                    : 0);

                            meterAmountWithoutTax = fareObject.AmountExclTax;
                            taxAmount             = fareObject.TaxAmount;
                        }
                        else
                        {
                            var ridelinqOrderDetail = _orderDao.GetManualRideLinqById(orderId);
                            taxAmount             = Convert.ToDecimal(ridelinqOrderDetail.Tax ?? 0);
                            meterAmountWithoutTax = amount - taxAmount;
                            tipAmount             = Convert.ToDecimal(ridelinqOrderDetail.Tip);
                        }
                    }

                    _commandBus.Send(new CaptureCreditCardPayment
                    {
                        IsSettlingOverduePayment = true,
                        NewCardToken             = paymentDetail.CardToken,
                        AccountId              = accountDetail.Id,
                        PaymentId              = paymentDetail.PaymentId,
                        Provider               = _paymentService.ProviderType(companyKey, orderId),
                        TotalAmount            = amount,
                        MeterAmount            = meterAmountWithoutTax,
                        TipAmount              = tipAmount,
                        TaxAmount              = taxAmount,
                        TollAmount             = Convert.ToDecimal(orderDetail.Toll ?? 0),
                        SurchargeAmount        = Convert.ToDecimal(orderDetail.Surcharge ?? 0),
                        AuthorizationCode      = commitResponse.AuthorizationCode,
                        TransactionId          = commitResponse.TransactionId,
                        PromotionUsed          = promotion != null ? promotion.PromoId : default(Guid?),
                        AmountSavedByPromotion = promotion != null ? promotion.AmountSaved : 0,
                        FeeType = isFee ? FeeTypes.Booking : FeeTypes.None
                    });

                    _commandBus.Send(new SettleOverduePayment
                    {
                        AccountId    = accountDetail.Id,
                        OrderId      = orderId,
                        CreditCardId = accountDetail.DefaultCreditCard.GetValueOrDefault()
                    });

                    return(true);
                }

                // Payment failed, void preauth
                _paymentService.VoidPreAuthorization(companyKey, orderId);
            }

            return(false);
        }
예제 #7
0
        public RefundPaymentResponse RefundWebPayment(string companyKey, Guid orderId)
        {
            var paymentDetail = _paymentDao.FindByOrderId(orderId, companyKey);

            if (paymentDetail == null)
            {
                // No payment to refund
                var message = string.Format("Cannot refund because no payment was found for order {0}.", orderId);
                _logger.LogMessage(message);

                return(new RefundPaymentResponse
                {
                    IsSuccessful = false,
                    Last4Digits = string.Empty,
                    Message = message
                });
            }

            try
            {
                // Get captured payment
                var payment = Payment.Get(GetAPIContext(GetAccessToken()), paymentDetail.TransactionId);

                var refund = new Refund
                {
                    amount = new Amount
                    {
                        currency = payment.transactions[0].amount.currency,
                        total    = payment.transactions[0].amount.total
                    }
                };

                var sale = new Sale {
                    id = payment.transactions[0].related_resources[0].sale.id
                };
                sale.Refund(GetAPIContext(GetAccessToken()), refund);

                return(new RefundPaymentResponse
                {
                    IsSuccessful = true,
                    Last4Digits = string.Empty
                });
            }
            catch (Exception ex)
            {
                var exceptionMessage = ex.Message;

                var paymentException = ex as PaymentsException;
                if (paymentException != null && paymentException.Details != null)
                {
                    exceptionMessage = paymentException.Details.message;
                }

                _logger.LogMessage(string.Format("PayPal refund for transaction {0} failed. {1}", paymentDetail.TransactionId, exceptionMessage));

                return(new RefundPaymentResponse
                {
                    IsSuccessful = false,
                    Last4Digits = string.Empty,
                    Message = exceptionMessage
                });
            }
        }
        public object Post(SendReceiptAdmin request)
        {
            var order = _orderDao.FindById(request.OrderId);

            if (order == null || !(order.IsManualRideLinq || order.IBSOrderId.HasValue))
            {
                throw new HttpError(HttpStatusCode.BadRequest, ErrorCode.OrderNotInIbs.ToString());
            }

            AccountDetail account;

            // if the admin is requesting the receipt then it won't be for the logged in user
            if (!request.RecipientEmail.IsNullOrEmpty())
            {
                account = _accountDao.FindById(order.AccountId);
            }
            else
            {
                account = _accountDao.FindById(new Guid(this.GetSession().UserAuthId));
                if (account.Id != order.AccountId)
                {
                    throw new HttpError(HttpStatusCode.Unauthorized, "Not your order");
                }
            }

            // If the order was created in another company, need to fetch the correct IBS account
            var ibsAccountId = _accountDao.GetIbsAccountId(account.Id, order.CompanyKey);

            if (!(ibsAccountId.HasValue || order.IsManualRideLinq))
            {
                throw new HttpError(HttpStatusCode.BadRequest, ErrorCode.IBSAccountNotFound.ToString());
            }

            var ibsOrder = !order.IsManualRideLinq
                ? _ibsServiceProvider.Booking(order.CompanyKey).GetOrderDetails(order.IBSOrderId.Value, ibsAccountId.Value, order.Settings.Phone)
                : null;

            var orderPayment = _orderPaymentDao.FindByOrderId(order.Id, order.CompanyKey);
            var pairingInfo  = _orderDao.FindOrderPairingById(order.Id);
            var orderStatus  = _orderDao.FindOrderStatusById(request.OrderId);

            double?fareAmount;
            double?tollAmount = null;
            double?tipAmount;
            double?taxAmount;
            double?surcharge;
            double?bookingFees = null;
            double?extraAmount = null;
            PromotionUsageDetail promotionUsed = null;

            ReadModel.CreditCardDetails creditCard = null;

            var ibsOrderId = orderStatus.IBSOrderId;

            Commands.SendReceipt.CmtRideLinqReceiptFields cmtRideLinqFields = null;

            if (orderPayment != null && orderPayment.IsCompleted)
            {
                fareAmount  = Convert.ToDouble(orderPayment.Meter);
                tipAmount   = Convert.ToDouble(orderPayment.Tip);
                taxAmount   = Convert.ToDouble(orderPayment.Tax);
                surcharge   = Convert.ToDouble(orderPayment.Surcharge);
                bookingFees = Convert.ToDouble(orderPayment.BookingFees);

                // promotion can only be used with in app payment
                promotionUsed = _promotionDao.FindByOrderId(request.OrderId);

                creditCard = orderPayment.CardToken.HasValue()
                    ? _creditCardDao.FindByToken(orderPayment.CardToken)
                    : null;
            }
            else if (order.IsManualRideLinq)
            {
                var manualRideLinqDetail = _orderDao.GetManualRideLinqById(order.Id);
                fareAmount  = manualRideLinqDetail.Fare;
                ibsOrderId  = manualRideLinqDetail.TripId;
                tollAmount  = manualRideLinqDetail.Toll;
                extraAmount = manualRideLinqDetail.Extra;
                tipAmount   = manualRideLinqDetail.Tip;
                taxAmount   = manualRideLinqDetail.Tax;
                surcharge   = manualRideLinqDetail.Surcharge;
                orderStatus.DriverInfos.DriverId = manualRideLinqDetail.DriverId.ToString();
                order.DropOffAddress             = _geocoding.TryToGetExactDropOffAddress(orderStatus, manualRideLinqDetail.LastLatitudeOfVehicle, manualRideLinqDetail.LastLongitudeOfVehicle, order.DropOffAddress, order.ClientLanguageCode);

                cmtRideLinqFields = new Commands.SendReceipt.CmtRideLinqReceiptFields
                {
                    TripId                 = manualRideLinqDetail.TripId,
                    DriverId               = manualRideLinqDetail.DriverId.ToString(),
                    Distance               = manualRideLinqDetail.Distance,
                    AccessFee              = manualRideLinqDetail.AccessFee,
                    PickUpDateTime         = manualRideLinqDetail.StartTime,
                    DropOffDateTime        = manualRideLinqDetail.EndTime,
                    LastFour               = manualRideLinqDetail.LastFour,
                    FareAtAlternateRate    = manualRideLinqDetail.FareAtAlternateRate,
                    RateAtTripEnd          = (int)(manualRideLinqDetail.RateAtTripEnd.GetValueOrDefault()),
                    RateAtTripStart        = (int)(manualRideLinqDetail.RateAtTripStart.GetValueOrDefault()),
                    LastLatitudeOfVehicle  = order.DropOffAddress.Latitude,
                    LastLongitudeOfVehicle = order.DropOffAddress.Longitude,
                    TipIncentive           = order.TipIncentive ?? 0
                };
            }
            else if (pairingInfo != null && pairingInfo.AutoTipPercentage.HasValue)
            {
                var tripInfo = GetTripInfo(pairingInfo.PairingToken);
                if (tripInfo != null && !tripInfo.ErrorCode.HasValue && tripInfo.EndTime.HasValue)
                {
                    // this is for CMT RideLinq only, no VAT

                    fareAmount = Math.Round(((double)tripInfo.Fare / 100), 2);
                    var tollHistory = tripInfo.TollHistory != null
                        ? tripInfo.TollHistory.Sum(p => p.TollAmount)
                        : 0;

                    tollAmount  = Math.Round(((double)tollHistory / 100), 2);
                    extraAmount = Math.Round(((double)tripInfo.Extra / 100), 2);
                    tipAmount   = Math.Round(((double)tripInfo.Tip / 100), 2);
                    taxAmount   = Math.Round(((double)tripInfo.Tax / 100), 2);
                    surcharge   = Math.Round(((double)tripInfo.Surcharge / 100), 2);
                    orderStatus.DriverInfos.DriverId = tripInfo.DriverId.ToString();

                    cmtRideLinqFields = new Commands.SendReceipt.CmtRideLinqReceiptFields
                    {
                        TripId              = tripInfo.TripId,
                        DriverId            = tripInfo.DriverId.ToString(),
                        Distance            = tripInfo.Distance,
                        AccessFee           = Math.Round(((double)tripInfo.AccessFee / 100), 2),
                        PickUpDateTime      = tripInfo.StartTime,
                        DropOffDateTime     = tripInfo.EndTime,
                        LastFour            = tripInfo.LastFour,
                        FareAtAlternateRate = Math.Round(((double)tripInfo.FareAtAlternateRate / 100), 2),
                        RateAtTripEnd       = tripInfo.RateAtTripEnd,
                        RateAtTripStart     = tripInfo.RateAtTripStart,
                        Tolls        = tripInfo.TollHistory,
                        TipIncentive = (order.TipIncentive.HasValue) ? order.TipIncentive.Value : 0
                    };
                }
                else
                {
                    fareAmount = ibsOrder.Fare;
                    tollAmount = ibsOrder.Toll;
                    tipAmount  = FareHelper.CalculateTipAmount(ibsOrder.Fare.GetValueOrDefault(0),
                                                               pairingInfo.AutoTipPercentage.Value);
                    taxAmount = ibsOrder.VAT;
                    surcharge = order.Surcharge;
                }

                orderPayment = null;
                creditCard   = pairingInfo.TokenOfCardToBeUsedForPayment.HasValue()
                    ? _creditCardDao.FindByToken(pairingInfo.TokenOfCardToBeUsedForPayment)
                    : null;
            }
            else
            {
                fareAmount = ibsOrder.Fare;
                tollAmount = ibsOrder.Toll;
                tipAmount  = ibsOrder.Tip;
                taxAmount  = ibsOrder.VAT;
                surcharge  = order.Surcharge;

                orderPayment = null;
            }

            var orderReport = _reportDao.GetOrderReportWithOrderId(order.Id);

            var sendReceiptCommand = SendReceiptCommandBuilder.GetSendReceiptCommand(
                order,
                account,
                ibsOrderId,
                (orderReport != null ? orderReport.VehicleInfos.Number : ibsOrder.VehicleNumber),
                orderStatus.DriverInfos,
                fareAmount,
                tollAmount,
                extraAmount,
                surcharge,
                bookingFees,
                tipAmount,
                taxAmount,
                orderPayment,
                promotionUsed != null
                        ? Convert.ToDouble(promotionUsed.AmountSaved)
                        : (double?)null,
                promotionUsed,
                creditCard,
                cmtRideLinqFields);

            // Since the user or an admin requested the receipt, we should bypass the normal notification settings.
            sendReceiptCommand.BypassNotificationSettings = true;

            if (!request.RecipientEmail.IsNullOrEmpty())
            {
                sendReceiptCommand.EmailAddress = request.RecipientEmail;
            }
            _commandBus.Send(sendReceiptCommand);

            return(new HttpResult(HttpStatusCode.OK, "OK"));
        }
예제 #9
0
        internal BasePaymentResponse CapturePaymentForPrepaidOrder(
            string companyKey,
            Guid orderId,
            AccountDetail account,
            decimal appEstimateWithTip,
            int tipPercentage,
            decimal bookingFees,
            string cvv)
        {
            // Note: No promotion on web
            var tipAmount   = FareHelper.GetTipAmountFromTotalIncludingTip(appEstimateWithTip, tipPercentage);
            var totalAmount = appEstimateWithTip + bookingFees;
            var meterAmount = appEstimateWithTip - tipAmount;

            var preAuthResponse = _paymentService.PreAuthorize(companyKey, orderId, account, totalAmount, isForPrepaid: true, cvv: cvv);

            if (preAuthResponse.IsSuccessful)
            {
                // Wait for payment to be created
                Thread.Sleep(500);

                var commitResponse = _paymentService.CommitPayment(
                    companyKey,
                    orderId,
                    account,
                    totalAmount,
                    totalAmount,
                    meterAmount,
                    tipAmount,
                    preAuthResponse.TransactionId,
                    preAuthResponse.ReAuthOrderId,
                    isForPrepaid: true);

                if (commitResponse.IsSuccessful)
                {
                    var paymentDetail = _orderPaymentDao.FindByOrderId(orderId, companyKey);

                    var fareObject = FareHelper.GetFareFromAmountInclTax(meterAmount,
                                                                         _serverSettings.ServerData.VATIsEnabled
                            ? _serverSettings.ServerData.VATPercentage
                            : 0);

                    _commandBus.Send(new CaptureCreditCardPayment
                    {
                        AccountId         = account.Id,
                        PaymentId         = paymentDetail.PaymentId,
                        Provider          = _paymentService.ProviderType(companyKey, orderId),
                        TotalAmount       = totalAmount,
                        MeterAmount       = fareObject.AmountExclTax,
                        TipAmount         = tipAmount,
                        TaxAmount         = fareObject.TaxAmount,
                        AuthorizationCode = commitResponse.AuthorizationCode,
                        TransactionId     = commitResponse.TransactionId,
                        IsForPrepaidOrder = true,
                        BookingFees       = bookingFees
                    });
                }
                else
                {
                    // Payment failed, void preauth
                    _paymentService.VoidPreAuthorization(companyKey, orderId, true);

                    return(new BasePaymentResponse
                    {
                        IsSuccessful = false,
                        Message = commitResponse.Message
                    });
                }
            }
            else
            {
                return(new BasePaymentResponse
                {
                    IsSuccessful = false,
                    Message = preAuthResponse.Message
                });
            }

            return(new BasePaymentResponse {
                IsSuccessful = true
            });
        }