/// <summary>
 /// Applies the non fee schedule.
 /// </summary>
 /// <param name="paymentResult">The payment result.</param>
 /// <param name="claimCharge">The claim charge.</param>
 /// <returns></returns>
 private void ApplyNonFeeSchedule(PaymentResult paymentResult, ClaimCharge claimCharge)
 {
     if (PaymentTypeFeeSchedule.NonFeeSchedule.HasValue)
     {
         if (claimCharge.Amount.HasValue)
         {
             paymentResult.AdjudicatedValue =
                 (PaymentTypeFeeSchedule.NonFeeSchedule.Value / 100) *
                 claimCharge.Amount.Value;
             paymentResult.ClaimStatus =
                 (byte)Enums.AdjudicationOrVarianceStatuses.Adjudicated;
         }
         else
         {
             paymentResult.ClaimStatus =
                 (byte)Enums.AdjudicationOrVarianceStatuses.ClaimDataError;
         }
     }
     else
     {
         paymentResult.ClaimStatus =
             (byte)Enums.AdjudicationOrVarianceStatuses
             .AdjudicationErrorInvalidPaymentData;
     }
 }
        public override List <PaymentResult> EvaluatePaymentType(IEvaluateableClaim claim, List <PaymentResult> paymentResults, bool isCarveOut, bool isContractFilter)
        {
            if (claim != null)
            {
                foreach (ClaimCharge claimCharge in claim.ClaimCharges.Where(code => (!string.IsNullOrWhiteSpace(code.HcpcsCodeWithModifier.Trim()))))
                {
                    if (isCarveOut && paymentResults.Any(currentPaymentResult => currentPaymentResult.Line == claimCharge.Line && currentPaymentResult.ServiceTypeId == PaymentTypeBase.ServiceTypeId))
                    {
                        break;
                    }

                    if (PaymentTypeBase.ValidLineIds.Contains(claimCharge.Line) && paymentResults.Any(
                            currentPaymentResult => currentPaymentResult.Line == claimCharge.Line && (currentPaymentResult.AdjudicatedValue == null || isCarveOut)))
                    {
                        PaymentResult paymentResult = GetPaymentResult(paymentResults, isCarveOut, claimCharge.Line);

                        if (paymentResult != null)
                        {
                            EvaluateLine(paymentResult, claimCharge);
                        }
                    }
                }
            }
            return(paymentResults);
        }
        /// <summary>
        /// Evaluates the type of the payment.
        /// </summary>
        /// <param name="paymentResult">The payment result.</param>
        /// <param name="claimCharge">The claim charge.</param>
        /// <returns></returns>
        private void EvaluateLine(PaymentResult paymentResult, ClaimCharge claimCharge)
        {
            //Update PaymentResult and set matching ServiceTypeId,PaymentTypeDetailId & PaymentTypeId
            Utilities.UpdatePaymentResult(paymentResult, PaymentTypeFeeSchedule.ServiceTypeId,
                                          PaymentTypeFeeSchedule.PaymentTypeDetailId, PaymentTypeFeeSchedule.PaymentTypeId);

            if (PaymentTypeFeeSchedule.ClaimFieldDoc != null &&
                PaymentTypeFeeSchedule.ClaimFieldDoc.ClaimFieldValues != null &&
                PaymentTypeFeeSchedule.ClaimFieldDoc.ClaimFieldValues.Count > 0)
            {
                string          hcpcsCode       = claimCharge.HcpcsCodeWithModifier.ToUpper();
                ClaimFieldValue claimFieldValue =
                    PaymentTypeFeeSchedule.ClaimFieldDoc.ClaimFieldValues.FirstOrDefault(
                        currentClaimFieldValue =>
                        (currentClaimFieldValue.Identifier.ToUpper() == hcpcsCode));
                if (claimFieldValue == null && hcpcsCode.Trim().Length != 5)
                {
                    claimFieldValue = PaymentTypeFeeSchedule.ClaimFieldDoc.ClaimFieldValues.FirstOrDefault(
                        currentClaimFieldValue =>
                        (currentClaimFieldValue.Identifier.ToUpper() == hcpcsCode.Substring(0, 5)));
                }
                if (claimFieldValue != null)
                {
                    ApplyFeeSchedule(paymentResult, claimFieldValue, claimCharge);
                }
                else
                {
                    ApplyNonFeeSchedule(paymentResult, claimCharge);
                }
            }
        }
        /// <summary>
        /// Applies the type of the charges on payment.
        /// </summary>
        /// <param name="claim">The claim.</param>
        /// <param name="paymentResults">The payment results.</param>
        /// <param name="isCarveOut">if set to <c>true</c> [is carve out].</param>
        /// <param name="claimCharge">The claim charge.</param>
        /// <param name="lineId">The line identifier.</param>
        private void ApplyChargesOnPaymentType(IEvaluateableClaim claim, List <PaymentResult> paymentResults, bool isCarveOut,
                                               ClaimCharge claimCharge, int lineId)
        {
            if (PaymentTypeStopLoss.Threshold != null && (claimCharge != null &&
                                                          (PaymentTypeBase.ValidLineIds.Contains(
                                                               claimCharge.Line) && paymentResults.Any(
                                                               currentPaymentResult =>
                                                               currentPaymentResult.Line ==
                                                               claimCharge.Line &&
                                                               (currentPaymentResult.AdjudicatedValue ==
                                                                null || isCarveOut ||
                                                                currentPaymentResult.ServiceTypeId ==
                                                                PaymentTypeStopLoss.ServiceTypeId))) &&
                                                          claimCharge.Amount >
                                                          PaymentTypeStopLoss.Threshold.Value))
            {
                PaymentResult paymentResult = paymentResults.Any(
                    result =>
                    result.ServiceTypeId == PaymentTypeStopLoss.ServiceTypeId && result.Line == lineId)
                    ? paymentResults.FirstOrDefault(
                    result =>
                    result.ServiceTypeId == PaymentTypeStopLoss.ServiceTypeId &&
                    result.Line == lineId)
                    : GetPaymentResult(paymentResults, isCarveOut, claimCharge.Line);

                GetTotalLinesValue(paymentResult, claimCharge.Amount, claim);
            }
        }
        /// <summary>
        /// Calculates the per day.
        /// </summary>
        /// <param name="paymentResults">The payment results.</param>
        /// <param name="groupCharge">The group charge.</param>
        /// <param name="validPaymentResults">The valid payment results.</param>
        /// <param name="claimCharge">The claimCharge.</param>
        /// <param name="itemIndex">The itemIndex.</param>
        /// <param name="claim"></param>
        /// <returns></returns>
        private int CalculatePerDay(ICollection <PaymentResult> paymentResults, double?groupCharge, IEnumerable <PaymentResult> validPaymentResults, ClaimCharge claimCharge,
                                    int itemIndex, IEvaluateableClaim claim)
        {
            ////Logic to apply stop loss
            if (groupCharge > 0 &&
                (PaymentTypeStopLoss.Threshold != null &&
                 groupCharge > PaymentTypeStopLoss.Threshold.Value &&
                 PaymentTypeStopLoss.Percentage != null))
            {
                PaymentResult paymentResult =
                    validPaymentResults.FirstOrDefault(
                        currentPaymentResult => currentPaymentResult.Line == claimCharge.Line && (currentPaymentResult.AdjudicatedValue == null || currentPaymentResult.ServiceTypeId == PaymentTypeStopLoss.ServiceTypeId));

                if (paymentResult != null)
                {
                    itemIndex = ApplyPerDayFormula(groupCharge, itemIndex, claim, paymentResult);
                }
            }
            else
            {
                PaymentResult paymentResult =
                    validPaymentResults.FirstOrDefault(
                        x => x.Line == claimCharge.Line && x.AdjudicatedValue == null && !x.IsInitialEntry);
                if (paymentResult != null)
                {
                    paymentResults.Remove(paymentResult);
                }
            }
            return(itemIndex);
        }
Esempio n. 6
0
        /// <summary>
        /// Helper method needed for reserving and capturing payment in order to refund examples could work
        /// </summary>
        /// <param name="amount"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private CaptureResult ReserveAndCapture(Amount amount, AuthType type)
        {
            var request = new ReserveRequest
            {
                ShopOrderId = "csharpexample" + Guid.NewGuid().ToString(),
                Terminal    = "AltaPay Dev Terminal",
                Amount      = amount,
                PaymentType = type,
                Pan         = "4111000011110000",
                ExpiryMonth = 1,
                ExpiryYear  = 2012,
                Cvc         = "123",
            };

            PaymentResult paymentResult = _api.ReserveAmount(request);

            if (paymentResult.Result != Result.Success)
            {
                throw new Exception("The result was: " + paymentResult.Result + ", message: " + paymentResult.ResultMerchantMessage);
            }

            CaptureRequest captureRequest = new CaptureRequest
            {
                PaymentId = paymentResult.Payment.TransactionId
            };

            CaptureResult captureResult = _api.Capture(captureRequest);

            if (captureResult.Result != Result.Success)
            {
                throw new Exception("The result was: " + captureResult.Result + ", message: " + captureResult.ResultMerchantMessage);
            }

            return(captureResult);
        }
        /// <summary>
        /// Evaluate the total charge at claim level.
        /// </summary>
        /// <param name="claim">The claim.</param>
        /// <param name="paymentResults">The payment results.</param>
        /// <param name="isCarveOut">if set to <c>true</c> [is carve out].</param>
        /// <returns></returns>
        private void EvaluateTotalChargeAtClaimLevel(IEvaluateableClaim claim,
                                                     List <PaymentResult> paymentResults, bool isCarveOut)
        {
            PaymentResult claimPaymentResult = paymentResults.Any(
                result => result.ServiceTypeId == PaymentTypeStopLoss.ServiceTypeId && result.Line == null)
                ? paymentResults.FirstOrDefault(
                result => result.ServiceTypeId == PaymentTypeStopLoss.ServiceTypeId && result.Line == null)
                : GetClaimLevelPaymentResult(paymentResults, isCarveOut);

            if (claimPaymentResult != null)
            {
                if (claim.ClaimTotal.HasValue)
                {
                    claimPaymentResult = GetTotalLinesValue(claimPaymentResult, claim.ClaimTotal, claim);
                    Utilities.UpdateStopLossDetails(claimPaymentResult, claim.SmartBox, PaymentTypeStopLoss, PaymentTypeStopLoss.IsFormulaError);

                    //Remove PaymentResult if its not satisfied thresold condition
                    if (claimPaymentResult.AdjudicatedValue == null &&
                        claimPaymentResult.ClaimStatus == (byte)Enums.AdjudicationOrVarianceStatuses.UnAdjudicated)
                    {
                        paymentResults.Remove(claimPaymentResult);
                    }
                }
                claimPaymentResult.ServiceTypeId = PaymentTypeStopLoss.ServiceTypeId;
            }
        }
Esempio n. 8
0
        public PaymentResult ProcessPayment(Models.Order order, string token)
        {
            var price   = order.OrderDetails.Select(c => c.Quantity * c.Product.Price).Sum();
            var options = new ChargeCreateOptions
            {
                Amount      = (long)(price * 100),
                Currency    = "usd",
                Description = "Charge",
                Source      = token,
            };

            var    service       = new ChargeService();
            Charge charge        = null;
            var    paymentResult = new PaymentResult();

            try
            {
                charge = service.Create(options);
                paymentResult.IsSuccessful = charge.Status == "succeeded";
            }
            catch (StripeException exception)
            {
                paymentResult.Error        = exception.StripeError.Message;
                paymentResult.IsSuccessful = false;
                _logger.LogInformation($"Charge has failed|{exception.StripeError.Message}");
            }

            if (paymentResult.IsSuccessful)
            {
                order.PaymentMethod = Models.PaymentMethod.Card;
                CreateOrder(order);
            }

            return(paymentResult);
        }
Esempio n. 9
0
        public async Task <IActionResult> Withdraw(WithdrawalViewModel model)
        {
            User user = await UserManager.FindByIdAsync(UserId);

            if (user == null)
            {
                return(Unauthorized());
            }

            if (model.Amount > user.Wallet.AvailableBalance)
            {
                return(BadRequest("Insufficient funds"));
            }
            if (!user.BankAccounts.Any(b => b.IsActive && b.Id == model.BankAccountId))
            {
                return(NotFound("No bank account was found with the provided Id"));
            }

            var request = Mapper.Map <BankTransactionRequest>(model);

            request.User = user;

            PaymentResult result = await PaymentService.UseBank(request, PaymentType.Withdrawal);

            switch (result.Status)
            {
            case PaymentStatus.Pending:
                return(Accepted());

            default: return(BadRequest(result.Message));
            }
        }
Esempio n. 10
0
        public void TestSuccessfulEftPayment()
        {
            //Arrange
            IPaymentsDao paymentsDao = new PaymentsDao();

            var creditCardHandler = new CreditCardPaymentTypeHandler(new CreditCardService(), paymentsDao);
            var eftHandler        = new EftPaymentTypeHandler(new EftProcessor(), paymentsDao);
            var checkHandler      = new CheckPaymentTypeHandler(paymentsDao);

            creditCardHandler.NextPaymentHandler = eftHandler;
            eftHandler.NextPaymentHandler        = checkHandler;

            var paymentProcessor = new PaymentProcessor(creditCardHandler);

            EftPaymentData eftPaymentData = new EftPaymentData()
            {
                CustomerAccountNumber = "00012345",
                PaymentDate           = DateTime.Today,
                PaymentType           = PaymentType.EFT,
                Amount            = 100.00m,
                RoutingNumber     = SampleData.BANK_ROUTING_ONE,
                BankAccountNumber = SampleData.BANK_ACCOUNT_ONE,
                AccountType       = BankAccountType.CHECKING
            };

            // Act
            PaymentResult result = paymentProcessor.ProcessPayment(eftPaymentData);

            // Assert
            Assert.True(result.Success);
            Assert.Equal(20, result.ReferenceNumber);
        }
Esempio n. 11
0
        public void TestSuccessfulCreditCardPayment()
        {
            //Arrange
            IPaymentsDao paymentsDao = new PaymentsDao();

            var creditCardHandler = new CreditCardPaymentTypeHandler(new CreditCardService(), paymentsDao);
            var eftHandler        = new EftPaymentTypeHandler(new EftProcessor(), paymentsDao);
            var checkHandler      = new CheckPaymentTypeHandler(paymentsDao);

            creditCardHandler.NextPaymentHandler = eftHandler;
            eftHandler.NextPaymentHandler        = checkHandler;

            var paymentProcessor = new PaymentProcessor(creditCardHandler);

            CreditCardPaymentData creditCardPayment = new CreditCardPaymentData()
            {
                CreditCardNumber = SampleData.CARD_NUMBER_ONE,
                ExpirationDate   = "10/2019",
                Cvv = "755",
                CustomerAccountNumber = "00012345",
                PaymentDate           = DateTime.Today,
                BillingZipCode        = "60067",
                CardholderName        = "John Doe",
                PaymentType           = PaymentType.CREDIT_CARD,
                Amount = 100.00m
            };

            // Act
            PaymentResult result = paymentProcessor.ProcessPayment(creditCardPayment);

            // Assert
            Assert.True(result.Success);
            Assert.Equal(10, result.ReferenceNumber);
        }
        protected override PaymentResult ProcessOrder(Subscription model)
        {
            PaymentResult result = null;

            // If Payment is done then activate the membership and sent a mail to user.
            if (!string.IsNullOrEmpty(model.MemberName))
            {
                switch (model.SubscriptionType)
                {
                case Models.Constants.SubscriptionType.ACTIVATION:
                    result = HandleNewActivation(model);
                    break;

                case Models.Constants.SubscriptionType.UPGRADE:
                    result = Upgrade(model);
                    break;

                default:
                    break;
                }
            }
            else
            {
                throw new InvalidOperationException();
            }
            return(result);
        }
        public PaymentResult OfflinePay([FromBody] PaymentResult paymentResult)
        {
            paymentResult.AssertNotNull("paymentResult");

            if (paymentResult.BuyerId < 0)
            {
                throw new ArgumentOutOfRangeException("payment:BuyerId", "Not support BuyerId is 0.");
            }

            var paymentEngine = ObjectIOCFactory.GetSingleton <PaymentEngine>();
            var tradeJournal  = paymentEngine.OfflinePay(paymentResult);

            if (null != tradeJournal)
            {
                return(new PaymentResult()
                {
                    Success = true, TradeCode = tradeJournal.TradeCode
                });
            }
            else
            {
                return(new PaymentResult()
                {
                    Success = false, ErrorMessage = "OfflinePay failed."
                });
            }
        }
Esempio n. 14
0
        private PaymentResult GetAdditionaData(PaymentResult paymentResult)
        {
            var paymentResultAdditionalData = paymentResult.AdditionalData;

            foreach (var additionalData in paymentResultAdditionalData)
            {
                switch (additionalData.Key)
                {
                case AdditionalData.AvsResult:
                    paymentResult.AvsResult = additionalData.Value;
                    break;

                case AdditionalData.PaymentMethod:
                    paymentResult.PaymentMethod = additionalData.Value;
                    break;

                case AdditionalData.BoletoData:
                    paymentResult.BoletoData = additionalData.Value;
                    break;

                case AdditionalData.CardBin:
                    paymentResult.CardBin = additionalData.Value;
                    break;

                case AdditionalData.CardHolderName:
                    paymentResult.CardHolderName = additionalData.Value;
                    break;
                }
            }
            return(paymentResult);
        }
Esempio n. 15
0
        public async Task <ServiceObjectResult <PaymentResult> > ExecutePayment(PaymentRequest paymentRequest)
        {
            var sendPaymentResponse = await _bankRequestClient.SendPayment(paymentRequest);

            if (!sendPaymentResponse.Success || sendPaymentResponse.Result?.PaymentIdentifier == null)
            {
                return(ServiceObjectResult <PaymentResult> .Failed(null, sendPaymentResponse.Errors ?? new List <string> {
                    ErrorCodeStrings.InternalError
                }));
            }

            if (!Enum.TryParse <PaymentStatus>(sendPaymentResponse.Result.Status, out var paymentStatus))
            {
                return(ServiceObjectResult <PaymentResult> .Failed(null, ErrorMessages.UnableToProcessPayment));
            }

            var paymentResult = new PaymentResult
            {
                PaymentIdentifier = sendPaymentResponse.Result.PaymentIdentifier,
                CardNumber        = paymentRequest.CardNumber,
                Amount            = paymentRequest.Amount,
                Status            = paymentStatus,
                Timestamp         = DateTime.UtcNow
            };

            return(ServiceObjectResult <PaymentResult> .Succeeded(paymentResult));
        }
        /// <summary>
        /// Applies the fee schedule.
        /// </summary>
        /// <param name="paymentResult">The payment result.</param>
        /// <param name="claimFieldValue">The claim field value.</param>
        /// <param name="claimCharge">The claim charge.</param>
        private void ApplyFeeSchedule(PaymentResult paymentResult, ClaimFieldValue claimFieldValue, ClaimCharge claimCharge)
        {
            double amount;

            if (!string.IsNullOrEmpty(claimFieldValue.Value) && Double.TryParse(claimFieldValue.Value, out amount))
            {
                if (PaymentTypeFeeSchedule.FeeSchedule.HasValue)
                {
                    double percentageAmount = (PaymentTypeFeeSchedule.FeeSchedule.Value /
                                               100) * amount;
                    paymentResult.AdjudicatedValue = (PaymentTypeFeeSchedule.IsObserveUnits) ?
                                                     percentageAmount * claimCharge.Units : percentageAmount;
                    paymentResult.ClaimStatus =
                        (byte)Enums.AdjudicationOrVarianceStatuses.Adjudicated;
                }
                else
                {
                    paymentResult.ClaimStatus =
                        (byte)Enums.AdjudicationOrVarianceStatuses
                        .AdjudicationErrorInvalidPaymentData;
                }
            }
            else
            {
                paymentResult.ClaimStatus =
                    (byte)Enums.AdjudicationOrVarianceStatuses
                    .AdjudicationErrorInvalidPaymentData;
            }
        }
Esempio n. 17
0
        /// <summary>
        /// 校验支付结果参数及签名是否合法(请勿修改本代码)
        /// </summary>
        /// <param name="data">通联支付数据</param>
        /// <returns></returns>
        public static bool VerifyResultSign(AllinpayData data)
        {
            PaymentResult paymentResult = new PaymentResult();

            paymentResult.setMerchantId(data.GetValue("merchantId"));
            paymentResult.setVersion(data.GetValue("version"));
            paymentResult.setLanguage(data.GetValue("language"));
            paymentResult.setSignType(data.GetValue("signType"));
            paymentResult.setPayType(data.GetValue("payType"));
            paymentResult.setIssuerId(data.GetValue("issuerId"));
            paymentResult.setPaymentOrderId(data.GetValue("paymentOrderId"));
            paymentResult.setOrderNo(data.GetValue("orderNo"));
            paymentResult.setOrderDatetime(data.GetValue("orderDatetime"));
            paymentResult.setOrderAmount(data.GetValue("orderAmount"));
            paymentResult.setPayDatetime(data.GetValue("payDatetime"));
            paymentResult.setPayAmount(data.GetValue("payAmount"));
            paymentResult.setExt1(data.GetValue("ext1"));
            paymentResult.setExt2(data.GetValue("ext2"));
            paymentResult.setPayResult(data.GetValue("payResult"));
            paymentResult.setErrorCode(data.GetValue("errorCode"));
            paymentResult.setReturnDatetime(data.GetValue("returnDatetime"));
            paymentResult.setKey(AppConfig.Global.AllinpayKey);
            paymentResult.setSignMsg(data.GetValue("signMsg"));
            string certPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, AppConfig.Global.AllinpaySSLCertPath);

            paymentResult.setCertPath(certPath);
            bool verifyResult = paymentResult.verify();

            return(verifyResult);
        }
        public override List <PaymentResult> EvaluatePaymentType(IEvaluateableClaim claim, List <PaymentResult> paymentResults, bool isCarveOut, bool isContractFilter)
        {
            if (claim != null)
            {
                foreach (ClaimCharge claimCharge in claim.ClaimCharges)
                {
                    if (isCarveOut && paymentResults.Any(currentPaymentResult => currentPaymentResult.Line == claimCharge.Line && currentPaymentResult.ServiceTypeId == PaymentTypeBase.ServiceTypeId))
                    {
                        break;
                    }

                    if (PaymentTypeBase.ValidLineIds.Contains(claimCharge.Line) && paymentResults.Any(
                            paymentResult => paymentResult.Line == claimCharge.Line && (paymentResult.AdjudicatedValue == null || isCarveOut)))
                    {
                        PaymentResult paymentResult = GetPaymentResult(paymentResults, isCarveOut, claimCharge.Line);

                        if (paymentResult != null)
                        {
                            EvaluateLine(paymentResult, claimCharge, claim.MedicareLabFeeSchedules);
                        }
                    }
                }
            }
            return(paymentResults);
        }
Esempio n. 19
0
        /// <summary>
        /// Example for performing simple partial capture request.
        /// Amount sent to be partialy captured has to be less than total amount of the payment
        /// </summary>
        public void SimplePartialCapture()
        {
            //Reserving amount in order to capture method example could be successful
            PaymentResult paymentResult = ReserveAmount(Amount.Get(1200.00, Currency.EUR), AuthType.payment);
            //Transaction ID is returned from the gateway when payment request was successful
            string transactionId = paymentResult.Payment.TransactionId;

            //initialize capture request class, this class is used for forwarding all the data needed for capture request
            //for simple partial capture amount property should be set with amount less than total amount
            CaptureRequest captureRequest = new CaptureRequest
            {
                PaymentId = transactionId,
                Amount    = Amount.Get(600.00, Currency.EUR)
            };

            //call capture method
            CaptureResult captureResult = _api.Capture(captureRequest);

            //Result property contains information if the request was successful or not
            if (captureResult.Result == Result.Success)
            {
                //capture was successful
                Transaction transaction = captureResult.Payment;
            }
            else
            {
                //capture unsuccessful
                //error messages contain information about what went wrong
                string errorMerchantMessage = captureResult.ResultMerchantMessage;
                string errorMessage         = captureResult.ResultMessage;
            }
        }
Esempio n. 20
0
        public override PayrollResult Evaluate(PayrollPeriod period, PayTagGateway tagConfig, IDictionary <TagRefer, PayrollResult> results)
        {
            bool pensionSaving = false;

            PaymentResult resultPension = (PaymentResult)GetResultBy(results, TAG_PENSION_CONT);

            decimal paymentIncome = 0m;

            if (!Interest())
            {
                paymentIncome = 0m;
            }
            else
            {
                IncomeBaseResult resultIncome = (IncomeBaseResult)GetResultBy(results, TAG_AMOUNT_BASE);

                pensionSaving = resultPension.Interest();
                paymentIncome = Math.Max(0m, resultIncome.EmployeeBase());
            }
            decimal contPaymentValue = InsuranceContribution(period, paymentIncome, pensionSaving);

            var resultValues = new Dictionary <string, object>()
            {
                { "payment", contPaymentValue }
            };

            return(new PaymentDeductionResult(TagCode, Code, this, resultValues));
        }
Esempio n. 21
0
        /// <summary>
        /// Example for performing charge subscription request with Agreement.
        /// </summary>
        public void ChargeSubscriptionWithAgreement()
        {
            //Set up an agreement / setupSubscription / Reserving amount in order to charge it later
            PaymentResult createPaymentResult = ReserveAmount(Amount.Get(7777.00, Currency.EUR), AuthType.subscription, "IT_AGREEMENTS_UI_");
            //Transaction ID is returned from the gateway when payment request was successful
            string transactionId = createPaymentResult.Payment.TransactionId;

            //WaitForDataToFlowIntoReporting
            Thread.Sleep(3000);
            //initialise charge subscription request class, this class is used for forwarding all the data needed for charging an agreement / charge subscription request
            var chargeSubscriptionRequest = new ChargeSubscriptionRequest()
            {
                AgreementId = transactionId,
                Amount      = Amount.Get(7777, Currency.XXX),
                AgreementUnscheduledType = AgreementUnscheduledType.incremental,
            };

            //call capture method
            SubscriptionResult subscriptionResult = _api.ChargeSubscription(chargeSubscriptionRequest);

            //Result property contains information if the request was successful or not
            if ((subscriptionResult.Result == Result.Success) && (createPaymentResult.Payment.TransactionId == subscriptionResult.Payment.TransactionId) && (subscriptionResult.Payment.TransactionStatus == "recurring_confirmed") && (subscriptionResult.RecurringPayment.TransactionStatus == "captured"))
            {
                //subscription charge was successful
                Transaction transaction = subscriptionResult.Payment;
            }
            else
            {
                //capture unsuccessful
                //error messages contain information about what went wrong
                string errorMerchantMessage = subscriptionResult.ResultMerchantMessage;
                string errorMessage         = subscriptionResult.ResultMessage;
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Helper method needed for reserving amount in order to capture examples could work
        /// </summary>
        /// <param name="amount"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private PaymentResult ReserveAmount(Amount amount, AuthType type, string includeAgreementConfig = "")
        {
            var sixMonthsFromNowDate = DateTime.Now.AddMonths(6);
            var request = new ReserveRequest
            {
                ShopOrderId = includeAgreementConfig + "csharpexample" + Guid.NewGuid().ToString(),
                Terminal    = "AltaPay Dev Terminal",
                Amount      = amount,
                PaymentType = type,
                Pan         = "4111000011110000",
                ExpiryMonth = sixMonthsFromNowDate.Month,
                ExpiryYear  = sixMonthsFromNowDate.Year,
                Cvc         = "123",
            };

            if (includeAgreementConfig != "")
            {
                var agreementConfig = new AgreementConfig();
                agreementConfig.AgreementType            = AgreementType.unscheduled;
                agreementConfig.AgreementUnscheduledType = AgreementUnscheduledType.incremental;
                request.AgreementConfig = agreementConfig;
            }

            PaymentResult result = _api.ReserveAmount(request);

            if (result.Result != Result.Success)
            {
                throw new Exception("The result was: " + result.Result + ", message: " + result.ResultMerchantMessage);
            }

            return(result);
        }
Esempio n. 23
0
        public async Task ProcessPayment_HappyPath()
        {
            PaymentResult paymentResult = new PaymentResult()
            {
                ExternalPaymentReference = Guid.NewGuid().ToString(),
                PaymentStatus            = PaymentStatus.Approved,
                PaymentId = Guid.NewGuid().ToString()
            };


            PaymentItem payment = CreateValidPaymentItem();

            _mockBank.Setup(x => x.ProcessPaymentAsync(It.IsAny <PaymentItem>())).ReturnsAsync(paymentResult);
            _mockDataAccess.Setup(x => x.SavePaymentItemAsync(It.IsAny <PaymentItem>())).ReturnsAsync(payment);

            MerchantId merchantId = new MerchantId()
            {
                UUID = Guid.NewGuid().ToString()
            };

            PaymentHelper paymentHelper = new PaymentHelper(_mockLogger.Object, _mockBank.Object, _mockDataAccess.Object);
            PaymentResult result        = await paymentHelper.ProcessPaymentAsync(merchantId, payment).ConfigureAwait(false);

            Assert.NotNull(result);
        }
Esempio n. 24
0
        public async Task ProcessPayment_DataStoreError()
        {
            PaymentResult paymentResult = new PaymentResult()
            {
                ExternalPaymentReference = Guid.NewGuid().ToString(),
                PaymentStatus            = PaymentStatus.Approved,
                PaymentId = Guid.NewGuid().ToString()
            };

            PaymentItem payment = CreateValidPaymentItem();

            _mockBank.Setup(x => x.ProcessPaymentAsync(It.IsAny <PaymentItem>())).ReturnsAsync(paymentResult);
            _mockDataAccess.Setup(x => x.SavePaymentItemAsync(It.IsAny <PaymentItem>())).ReturnsAsync((PaymentItem)null);


            MerchantId merchantId = new MerchantId()
            {
                UUID = Guid.NewGuid().ToString()
            };

            PaymentHelper paymentHelper = new PaymentHelper(_mockLogger.Object, _mockBank.Object, _mockDataAccess.Object);

            await Assert.ThrowsAsync <ArgumentOutOfRangeException>(() =>
                                                                   paymentHelper.ProcessPaymentAsync(merchantId, payment)).ConfigureAwait(false);
        }
Esempio n. 25
0
        public void CallingMerchantApiWithSuccessfulParametersReturnsAPaymentWithAPaymentId(Boolean callReservationOfFixedAmount)
        {
            PaymentResult result = GetMerchantApiResult(Guid.NewGuid().ToString(), 1.23, callReservationOfFixedAmount);

            Assert.IsNotNull(result.Payment.TransactionId);
            Assert.IsTrue(result.Payment.TransactionId.Length > 0);
        }
Esempio n. 26
0
        public void CallingMerchantApiWithSuccessfulParametersReturnsAPaymentWithTheCorrectShopOrderId(Boolean callReservationOfFixedAmount)
        {
            string        orderid = Guid.NewGuid().ToString();
            PaymentResult result  = GetMerchantApiResult(orderid, 1.23, callReservationOfFixedAmount);

            Assert.AreEqual(orderid, result.Payment.ShopOrderId);
        }
Esempio n. 27
0
        public void CallingMerchantApiWithErrorParametersReturnsErrorResult(Boolean callReservationOfFixedAmount)
        {
            PaymentResult result = GetMerchantApiResult(Guid.NewGuid().ToString(), 5.67, callReservationOfFixedAmount);

            Assert.AreEqual(Result.Error, result.Result);
            Assert.AreEqual("Internal Error", result.ResultMessage);
        }
Esempio n. 28
0
        public void CallingMerchantApiWithFailParametersReturnsFailedResult(Boolean callReservationOfFixedAmount)
        {
            PaymentResult result = GetMerchantApiResult(Guid.NewGuid().ToString(), 5.66, callReservationOfFixedAmount);

            Assert.AreEqual(Result.Failed, result.Result);
            Assert.AreEqual("Card Declined", result.ResultMessage);
        }
Esempio n. 29
0
        public void CallingMerchantApiWithCardTokenResultsInSuccessfullResult(Boolean callReservationOfFixedAmount)
        {
            PaymentResult result       = GetMerchantApiResult(Guid.NewGuid().ToString(), 1.23, callReservationOfFixedAmount);
            PaymentResult secondResult = GetMerchantApiResultCardToken(Guid.NewGuid().ToString(), 1.23, result.Payment.CreditCardToken, callReservationOfFixedAmount);

            Assert.AreEqual(Result.Success, secondResult.Result);
        }
Esempio n. 30
0
        static void Main(string[] args)
        {
            LogManager.Global = new LogManager(true, new TextLogger(null, LogLevel.Everything, "Wiffzack", Console.Out));

            XmlDocument configuration = new XmlDocument();

            configuration.LoadXml(_configuration);

            XmlDocument paymentSettings = new XmlDocument();

            paymentSettings.LoadXml(_paymentSettings);

            ICommandEnvironment environment = new ZVTCommandEnvironment(configuration.DocumentElement);

            environment.StatusReceived += new IntermediateStatusDelegate(environment_StatusReceived);
            ClassifyCommandResult(environment.CreateInitialisationCommand(null).Execute());

            PaymentResult result = environment.CreatePaymentCommand(paymentSettings.DocumentElement).Execute();

            ClassifyCommandResult(result);
            XmlDocument authorisationIdentifier = new XmlDocument();

            authorisationIdentifier.AppendChild(authorisationIdentifier.CreateElement("Data"));
            result.Data.WriteXml(authorisationIdentifier.DocumentElement);

            ClassifyCommandResult(environment.CreateReversalCommand(authorisationIdentifier.DocumentElement).Execute());

            //ClassifyCommandResult(environment.CreateReportCommand(null).Execute());


            Console.ReadLine();
        }
 public static void Encode(IByteWriter stream, PaymentResult encodedPaymentResult) {
 XdrEncoding.EncodeInt32((int)encodedPaymentResult.Discriminant.InnerValue, stream);
 switch (encodedPaymentResult.Discriminant.InnerValue) {
 case PaymentResultCode.PaymentResultCodeEnum.PAYMENT_SUCCESS:
 break;
 default:
 break;
 }
 }
 public static PaymentResult Decode(IByteReader stream) {
   PaymentResult decodedPaymentResult = new PaymentResult();
 decodedPaymentResult.Discriminant = PaymentResultCode.Decode(stream);
 switch (decodedPaymentResult.Discriminant.InnerValue) {
 case PaymentResultCode.PaymentResultCodeEnum.PAYMENT_SUCCESS:
 break;
 default:
 break;
 }
   return decodedPaymentResult;
 }
Esempio n. 33
0
        public override PaymentResult ParseResult(NameValueCollection parameters)
        {
            var result = new PaymentResult
                             {
                                 ResponseResult = new ContentResult {Content = "TRUE"},
                                 IsSuccessfull = parameters["tr_status"] == "TRUE",
                                 PaymentId = int.Parse(parameters["tr_crc"]),
                                 ProviderPaymentId = parameters["tr_id"]
                             };

            return result;
        }
Esempio n. 34
0
        // Methods
        public PaymentResult SubmitPayment(Payment payment)
        {
            PaymentResult paymentResult = new PaymentResult();

            try
            {
                TransactionRequest request = new TransactionRequest
                {
                    Amount = payment.Amount,
                    CreditCard = new TransactionCreditCardRequest
                    {
                        Number = payment.CCNumber,
                        CVV = payment.CVV,
                        ExpirationMonth = payment.ExpirationMonth,
                        ExpirationYear = payment.ExpirationYear
                    },
                    Options = new TransactionOptionsRequest
                    {
                        SubmitForSettlement = true
                    }
                };

                Result<Transaction> result = authentication.GetGateway().Transaction.Sale(request);

                if (result.IsSuccess())
                {
                    Transaction transaction = result.Target;
                    paymentResult.IsSuccess = true;
                    paymentResult.TransactionId = transaction.Id;
                }
                else if (result.Transaction != null)
                {
                    paymentResult.IsSuccess = false;
                    paymentResult.PaymentError = new PaymentError();

                    paymentResult.PaymentError.ErrorType = PaymentErrorTypeEnum.ProcessingError;
                    paymentResult.PaymentError.ErrorMessage = "Message: " + result.Message;
                    Transaction transaction = result.Transaction;
                    paymentResult.TransactionId = transaction.Id;

                    paymentResult.PaymentError.ErrorMessage += "\n\nError processing transaction:" +
                        "\n  Status: " + transaction.Status +
                        "\n  Code: " + transaction.ProcessorResponseCode +
                        "\n  Text: " + transaction.ProcessorResponseText;
                }
                else
                {
                    paymentResult.IsSuccess = false;
                    paymentResult.PaymentError = new PaymentError();

                    paymentResult.PaymentError.ErrorType = PaymentErrorTypeEnum.NoTransaction;
                    paymentResult.PaymentError.ErrorMessage = "Message: " + result.Message;

                    foreach (ValidationError error in result.Errors.DeepAll())
                    {
                        paymentResult.PaymentError.ErrorMessage += "\n\nAttribute: " + error.Attribute +
                        "\n  Code: " + error.Code +
                        "\n  Message: " + error.Message;
                    }
                }
            }
            catch (Exception e)
            {
                paymentResult.IsSuccess = false;
                paymentResult.PaymentError = new PaymentError();

                paymentResult.PaymentError.ErrorType = PaymentErrorTypeEnum.ApplicationError;
                paymentResult.PaymentError.ErrorMessage = e.Message;
            }

            return paymentResult;
        }
Esempio n. 35
0
 public PayViewModel(PaymentResult PaymentResult, PaymentModel Payment) {
     this.paymentResult = PaymentResult;
     this.payment = Payment;
 }
 public void GivenPaymentSystemWillReturnResult(PaymentResult paymentResult)
 {
     var mockPayment = ScenarioContext.Current.Get<Mock<IPayment>>();
     mockPayment.Setup(it => it.ChargeCreditCard(It.IsAny<PaymentInformation>()))
         .Returns<PaymentInformation>(it => paymentResult);
 }
Esempio n. 37
0
 private static void doPaymentPluginAction(PaymentModel pm, PaymentResult pr) {
     List<IPaymentActionPlugin> plugins = PluginLoader.GetPluginSingletons<IPaymentActionPlugin>();
     foreach (var plugin in plugins) {
         plugin.Action(pr.ToString(), pm);
     }
 }