public ActionResult MakePayment(CreditCardPaymentRequest objCCReq)
        {
            var resp = new PaymentResponse();

            if (HttpContext.Session["PaymentSessionId"] != null)
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                objCCReq.AuthKey = System.Configuration.ConfigurationManager.AppSettings["MyAccountAuthKey"];
                if (objCCReq.PaymentorAutopay == "PayNow")
                {
                    try
                    {
                        resp = Common.FrontierPayMakePayment(objCCReq);
                        if (objCCReq.SetupAutoPay && resp.ResultCode == 1)
                        {
                            PaymentResponse profileResp = new PaymentResponse();
                            profileResp               = Common.ManagePaymentProfile(objCCReq);
                            resp.profileStatusCode    = profileResp.profileStatusCode;
                            resp.profileStatusMessage = profileResp.profileStatusMessage;
                            return(Json(resp, JsonRequestBehavior.AllowGet));
                        }
                        else
                        {
                            resp.profileStatusCode    = -1;
                            resp.profileStatusMessage = "";
                            return(Json(resp, JsonRequestBehavior.AllowGet));
                        }
                    }
                    catch (Exception exp)
                    {
                        resp.ResultCode    = -3; //Exception
                        resp.ResultMessage = exp.Message;
                        Common.InsertClientErrorLog(objCCReq.CustomerNumber, string.Empty, objCCReq.Source, exp, "PaymentUI - MakePayment");
                        return(Json(resp, JsonRequestBehavior.AllowGet));
                    }
                }
                else if (objCCReq.PaymentorAutopay == "AutoPay")
                {
                    try
                    {
                        resp = Common.ManagePaymentProfile(objCCReq);
                        return(Json(resp, JsonRequestBehavior.AllowGet));
                    }
                    catch (Exception exp)
                    {
                        resp.profileStatusCode    = -3; //Exception
                        resp.profileStatusMessage = exp.Message;
                        Common.InsertClientErrorLog(objCCReq.CustomerNumber, string.Empty, objCCReq.Source, exp, "PaymentUI - MakePayment(AuthoPay)");
                        return(Json(resp, JsonRequestBehavior.AllowGet));
                    }
                }
                return(Json(resp, JsonRequestBehavior.AllowGet));
            }
            else
            {
                resp.ResultCode = -100;
            }
            return(Json(resp, JsonRequestBehavior.AllowGet));
        }
Beispiel #2
0
        private async Task <PaymentResponse> CreatePayment(decimal amount = 100)
        {
            PaymentRequest paymentRequest = new CreditCardPaymentRequest();

            paymentRequest.Amount      = amount;
            paymentRequest.Description = "Description";
            paymentRequest.RedirectUrl = this.DefaultRedirectUrl;

            return(await this._paymentClient.CreatePaymentAsync(paymentRequest));
        }
Beispiel #3
0
        private async Task <PaymentResponse> CreatePayment(string amount = "100.00")
        {
            PaymentRequest paymentRequest = new CreditCardPaymentRequest();

            paymentRequest.Amount      = new Amount(Currency.EUR, amount);
            paymentRequest.Description = "Description";
            paymentRequest.RedirectUrl = this.DefaultRedirectUrl;

            return(await this._paymentClient.CreatePaymentAsync(paymentRequest));
        }
Beispiel #4
0
        private async Task <Result <CreditCardPaymentResult> > MakePayment(CreditCardPaymentRequest request, PaymentCommandType commandType)
        {
            try
            {
                var requestContent = GetSignedContent();
                var client         = _clientFactory.CreateClient(HttpClientNames.Payfort);
                using var response = await client.PostAsync(_options.PaymentUrl, requestContent);

                return(await GetContent(response)
                       .Bind(GetJObject)
                       .Bind(_payfortResponseParser.ParsePaymentResponse));
            }
            catch (Exception ex)
            {
                _logger.LogPayfortClientException(ex);
                return(Result.Failure <CreditCardPaymentResult>("Payment error"));
            }


            HttpContent GetSignedContent()
            {
                var paymentRequest = new PayfortPaymentRequest(
                    signature: string.Empty,
                    accessCode: _options.AccessCode,
                    merchantIdentifier: _options.Identifier,
                    merchantReference: request.MerchantReference,
                    amount: ToPayfortAmount(request.Amount, request.Currency),
                    currency: request.Currency.ToString(),
                    customerName: request.CustomerName,
                    customerEmail: request.CustomerEmail,
                    customerIp: request.CustomerIp,
                    language: request.LanguageCode,
                    returnUrl: _options.ReturnUrl,
                    settlementReference: request.ReferenceCode,
                    tokenName: request.Token.Code,
                    rememberMe: ToPayfortBoolean(request.Token.Type == PaymentTokenTypes.Stored),
                    cardSecurityCode: GetSecurityCode(),
                    command: GetCommand()
                    );

                var jObject = JObject.FromObject(paymentRequest, PayfortSerializationSettings.Serializer);

                var(_, _, signature, _) = _signatureService.Calculate(jObject, SignatureTypes.Request);
                paymentRequest          = new PayfortPaymentRequest(paymentRequest, signature);
                var json = JsonConvert.SerializeObject(paymentRequest, PayfortSerializationSettings.SerializerSettings);

                return(new StringContent(json, Encoding.UTF8, "application/json"));


                // Is not needed for new card.
                string GetSecurityCode() => request.IsNewCard ? null : request.SecurityCode;

                string GetCommand() => commandType == PaymentCommandType.Purchase ? "PURCHASE" : "AUTHORIZATION";
            }
        }
Beispiel #5
0
        private async Task <PaymentResponse> CreatePayment(decimal amount = 100)
        {
            PaymentRequest paymentRequest = new CreditCardPaymentRequest
            {
                Amount      = amount,
                Description = "Description",
                RedirectUrl = fixture.DefaultRedirectUrl
            };

            return(await fixture.PaymentClient.CreatePaymentAsync(paymentRequest));
        }
Beispiel #6
0
        private async Task <PaymentResponse> CreatePayment(string amount = "100.00")
        {
            PaymentRequest paymentRequest = new CreditCardPaymentRequest
            {
                Amount      = new Amount(Currency.EUR, amount),
                Description = "Description",
                RedirectUrl = DefaultRedirectUrl
            };

            return(await PaymentClient.CreatePaymentAsync(paymentRequest));
        }
        private static BillTo CreateBillTo(CreditCardPaymentRequest req)
        {
            // Create the BillTo object.
            BillTo Bill = new BillTo();

            Bill.BillToStreet  = req.BillingInformation.BillingAddress;
            Bill.BillToStreet2 = req.BillingInformation.BillingAddressLine2;
            Bill.BillToCity    = req.BillingInformation.BillingCity;
            Bill.BillToState   = req.BillingInformation.BillingState;
            Bill.BillToZip     = req.BillingInformation.BilingZipcode;
            return(Bill);
        }
Beispiel #8
0
        public void CreditCardPaymentTest_Succcess()
        {
            var Request = new CreditCardPaymentRequest
            {
                Amount        = 10,
                AccountNumber = "4111111111111111",
                Expiration    = DateTime.Today.AddYears(1).ToString("MM/YYYY"),
                Comment       = "Test Transacction",
                IPAddress     = "127.0.0.1",
            };
            var response = provider.CreditCardPayment(Request);

            Assert.AreEqual(Request.Amount, response.Amount);
            Assert.IsTrue(response.Success);
            Assert.AreEqual("0", response.ResponseCode);
        }
Beispiel #9
0
        public async Task WhenRetrievingAListOfPaymentsPaymentSubclassesShouldBeInitialized()
        {
            // Given: We create a new payment
            CreditCardPaymentRequest paymentRequest = new CreditCardPaymentRequest()
            {
                Amount      = new Amount(Currency.EUR, "100.00"),
                Description = "Description",
                RedirectUrl = this.DefaultRedirectUrl
            };

            await this._paymentClient.CreatePaymentAsync(paymentRequest);

            // When: We retrieve it in a list
            ListResponse <PaymentResponse> result = await this._paymentClient.GetPaymentListAsync(null, 5);

            // Then: We expect a list with a single ideal payment
            Assert.IsAssignableFrom <CreditCardPaymentResponse>(result.Items.First());
        }
        public Task <Result <CreditCardPaymentResult> > AuthorizeMoneyForService(CreditCardPaymentRequest request,
                                                                                 AgentContext agent)
        {
            return(AuthorizeInPaymentSystem(request)
                   .Tap(WriteAuditLog));


            async Task <Result <CreditCardPaymentResult> > AuthorizeInPaymentSystem(CreditCardPaymentRequest paymentRequest)
            {
                var(_, isFailure, paymentResult, error) = await _payfortService.Authorize(paymentRequest);

                if (isFailure)
                {
                    return(Result.Failure <CreditCardPaymentResult>(error));
                }

                return(paymentResult.Status == CreditCardPaymentStatuses.Failed
                    ? Result.Failure <CreditCardPaymentResult>($"Payment error: {paymentResult.Message}")
                    : Result.Success(paymentResult));
            }

            Task WriteAuditLog(CreditCardPaymentResult result) => WriteAuthorizeAuditLog(result, agent.AgentId, request.Currency);
        }
        public PaymentResponse CreditCardPayment(CreditCardPaymentRequest req)
        {
            StringBuilder request = new StringBuilder();

            request.Append($"TRXTYPE=S");
            request.Append($"&ACCT={req.AccountNumber}");
            request.Append($"&EXPDATE={req.Expiration.Replace("/", "")}");
            request.Append($"&TENDER=C");
            if (string.IsNullOrWhiteSpace(req.InvoiceNumber))
            {
                req.InvoiceNumber = _confirmationNumberGenerator.GenerateConfirmationNumber();
            }
            request.Append($"&INVNUM={Uri.EscapeDataString(req.InvoiceNumber)}");
            request.Append($"&AMT={req.Amount:0.##}");
            request.Append($"&USER={User}");
            request.Append($"&VENDOR={Vendor}");
            request.Append($"&PARTNER={Partner}");
            request.Append($"&PWD={Password}");
            if (string.IsNullOrWhiteSpace(req.Comment))
            {
                request.Append($"&COMMENT1=");
            }
            else
            {
                request.Append($"&COMMENT1={Uri.EscapeDataString(req.Comment)}");
            }
            if (req.BillingInformation != null)
            {
                if (!string.IsNullOrWhiteSpace(req.BillingInformation.BillToFirstName))
                {
                    request.Append($"&BILLTOFIRSTNAME={req.BillingInformation.BillToFirstName}");
                }
                if (!string.IsNullOrWhiteSpace(req.BillingInformation.BillToLastName))
                {
                    request.Append($"&BILLTOLASTNAME={req.BillingInformation.BillToLastName}");
                }
                if (!string.IsNullOrWhiteSpace(req.BillingInformation.BilingZipcode))
                {
                    request.Append($"&BILLTOZIP={req.BillingInformation.BilingZipcode}");
                }
                if (!string.IsNullOrWhiteSpace(req.BillingInformation.BillingAddress))
                {
                    request.Append($"&BILLTOSTREET={req.BillingInformation.BillingAddress}");
                }
                if (!string.IsNullOrWhiteSpace(req.BillingInformation.BillingCity))
                {
                    request.Append($"&BILLTOCITY={req.BillingInformation.BillingCity}");
                }
                if (!string.IsNullOrWhiteSpace(req.BillingInformation.BillingState))
                {
                    request.Append($"&BILLTOSTATE={req.BillingInformation.BillingState}");
                }
            }
            request.Append("&VERBOSITY=HIGH");
            PayflowNETAPI PayflowNETAPI = new PayflowNETAPI(Host, Port, Timeout);

            string PayflowResponse = PayflowNETAPI.SubmitTransaction(request.ToString(), PayflowUtility.RequestId);
            var    results         = PayflowResponse.Split(new char[] { '&' }).Select(x => new { Name = x.Split('=')[0], Value = x.Split('=')[1] });
            var    RESPMSG         = results.Where(x => x.Name == "RESPMSG").DefaultIfEmpty(null).Single();

            if (RESPMSG != null)
            {
                if (RESPMSG.Value == "Approved")
                {
                    return(new PaymentResponse
                    {
                        Amount = req.Amount,
                        AuthCode = results.Where(x => x.Name == "AUTHCODE").DefaultIfEmpty(null).Single().Value,
                        Transaction = results.Where(x => x.Name == "PNREF").DefaultIfEmpty(null).Single().Value,
                        Success = true,
                        Message = RESPMSG.Value,
                        ProviderResponse = PayflowResponse
                    });
                }
            }
            return(new PaymentResponse
            {
                ProviderResponse = PayflowResponse,
                Amount = req.Amount,
                Message = RESPMSG == null ? "Payment Provider did not provide valid response" : RESPMSG.Value,
                ResponseText = RESPMSG == null ? "Payment Provider did not provide valid response" : RESPMSG.Value,
                Success = false,
            });
        }
Beispiel #12
0
        //Create Profile if autopay selected CreditCard
        public static PaymentResponse ManagePaymentProfile(CreditCardPaymentRequest payment)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var    payResponse = new PaymentResponse();
            string batchCode   = System.Configuration.ConfigurationManager.AppSettings["CardManageProfileBatchCode"];

            try
            {
                FrontierPayClient objFrontierPay = new FrontierPayClient();
                WebEnrollmentNewDesign.PayService.PaymentProfileResponse frontierPaymentProfileResponse = new WebEnrollmentNewDesign.PayService.PaymentProfileResponse();

                if (payment.CardNumber.Trim().StartsWith("4")) // Visa
                {
                    payment.CardType = "VISA";
                }
                else if (payment.CardNumber.Trim().StartsWith("5") || payment.CardNumber.Trim().StartsWith("2"))  // Master Card
                {
                    payment.CardType = "MASTERCARD";
                }
                else if (payment.CardNumber.Trim().StartsWith("3")) //American Express
                {
                    payment.CardType = "AMEX";
                }
                else if (payment.CardNumber.Trim().StartsWith("6")) //Discover
                {
                    payment.CardType = "DISCOVER";
                }
                else
                {
                    payment.CardType = "NA";
                }

                var payObject = new WebEnrollmentNewDesign.PayService.PaymentProfileRequest()
                {
                    AuthKey          = payment.AuthKey,
                    BatchCode        = batchCode,
                    ConfirmationType = payment.ConfirmationType,
                    CustomerNumber   = payment.CustomerNumber,

                    CardType        = payment.CardType,
                    CardName        = payment.CardName,
                    CardNumber      = Encrypt(payment.CardNumber),
                    ExpirationMonth = payment.Expiry.Substring(0, 2),
                    ExpirationYear  = payment.Expiry.Substring(3, 2),
                    CVCCode         = Encrypt(payment.VerificationCode),
                    CardZip         = payment.ZipCode,
                    CardEncrypted   = "Y",
                    RequestType     = "CREDITCARD",
                    RequestAction   = "UPDATE",
                    Email           = payment.Email,
                    PhoneNumber     = payment.ContactNumber,
                    Source          = payment.Source,
                    FirstName       = payment.FirstName,
                    LastName        = payment.LastName
                };

                try
                {
                    frontierPaymentProfileResponse = objFrontierPay.ManagePaymentProfile(payObject);
                }
                catch (Exception ex)
                {
                    InsertClientErrorLog(payment.CustomerNumber, batchCode, payment.Source, ex, "Common_ManagePaymentProfile");
                }

                if (frontierPaymentProfileResponse.Message == null || string.IsNullOrEmpty(frontierPaymentProfileResponse.Message))
                {
                    frontierPaymentProfileResponse.Message = "An Error has occured. Please try again later.";
                }

                payResponse.ResultMessage        = frontierPaymentProfileResponse.Message;
                payResponse.ResultCode           = Convert.ToInt32(frontierPaymentProfileResponse.Status);
                payResponse.profileStatusMessage = frontierPaymentProfileResponse.Message;
                payResponse.profileStatusCode    = Convert.ToInt32(frontierPaymentProfileResponse.Status);

                return(payResponse);
            }
            catch (Exception ex)
            {
                payResponse.ResultCode    = -3;
                payResponse.ResultMessage = ex.Message;
                InsertClientErrorLog(payment.CustomerNumber, batchCode, payment.Source, ex, "Common_ManagePaymentProfile");
                return(payResponse);
            }
        }
Beispiel #13
0
        //Credit Card Payment
        public static PaymentResponse FrontierPayMakePayment(CreditCardPaymentRequest req)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var    payResponse = new PaymentResponse();
            string batchCode   = System.Configuration.ConfigurationManager.AppSettings["BatchCode"];

            try
            {
                if (req.CustomerNumber != null && req.CustId != 0)
                {
                    FrontierPayClient objFrontierPay = new FrontierPayClient();
                    WebEnrollmentNewDesign.PayService.FrontierPayResponse frontierPayResponse = new WebEnrollmentNewDesign.PayService.FrontierPayResponse();

                    if (req.CardNumber.Trim().StartsWith("4")) // Visa
                    {
                        req.CardType = "001";
                    }
                    else if (req.CardNumber.Trim().StartsWith("5") || req.CardNumber.Trim().StartsWith("2"))  // Master Card
                    {
                        req.CardType = "002";
                    }
                    else if (req.CardNumber.Trim().StartsWith("3")) //American Express
                    {
                        req.CardType = "003";
                    }
                    else if (req.CardNumber.Trim().StartsWith("6")) //Discover
                    {
                        req.CardType = "004";
                    }
                    else
                    {
                        req.CardType = "000";
                    }

                    var payObject = new WebEnrollmentNewDesign.PayService.FrontierPayRequest()
                    {
                        AuthKey          = req.AuthKey,
                        CustomerNumber   = req.CustomerNumber,
                        BatchCode        = batchCode,
                        SetupAutoPay     = "N",
                        PostReceipt      = "Y",
                        ConfirmationType = req.ConfirmationType,

                        AccountName     = req.CardName,
                        CardType        = req.CardType,
                        CardNumber      = Common.Encrypt(req.CardNumber),
                        ExpirationMonth = req.Expiry.Substring(0, 2),
                        ExpirationYear  = "20" + req.Expiry.Substring(3, 2),
                        CVCCode         = Common.Encrypt(req.VerificationCode),
                        ZipCode         = req.ZipCode,
                        Amount          = Convert.ToString(req.Amount),
                        Email           = req.Email,
                        PhoneNumber     = req.ContactNumber,
                        Source          = req.Source,
                        SiteIdentifier  = req.SiteIdentifier
                    };
                    List <WebEnrollmentNewDesign.PayService.AddAdjustmentRequest> lstAdj = new List <WebEnrollmentNewDesign.PayService.AddAdjustmentRequest>();
                    decimal TotfeeAmt = 0;
                    if (req.IsCFWaived == "0" && req.Source == "Superscreen") //Convenience Fee is not waived
                    {
                        if (req.Addr_State.ToUpper() == "TX")
                        {
                            decimal CustomerServiceConvenienceFee_Amount = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["CustomerServiceConvenienceFee_Amount"].ToString());
                            decimal CreditCardProcessingFee_Amount       = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["CreditCardProcessingFee_Amount"].ToString());
                            if (CustomerServiceConvenienceFee_Amount > 0 || CreditCardProcessingFee_Amount > 0)
                            {
                                payObject.AddAdjustment = "Y";
                                if (CustomerServiceConvenienceFee_Amount > 0)
                                {
                                    WebEnrollmentNewDesign.PayService.AddAdjustmentRequest adj1 = new WebEnrollmentNewDesign.PayService.AddAdjustmentRequest();
                                    adj1.AdjustmentAmount = Convert.ToString(CustomerServiceConvenienceFee_Amount);
                                    adj1.ReasonCode       = System.Configuration.ConfigurationManager.AppSettings["CustomerServiceConvenienceFee_ReasonCode"].ToString();
                                    adj1.Note             = "";
                                    lstAdj.Add(adj1);
                                }
                                if (CreditCardProcessingFee_Amount > 0)
                                {
                                    WebEnrollmentNewDesign.PayService.AddAdjustmentRequest adj2 = new WebEnrollmentNewDesign.PayService.AddAdjustmentRequest();
                                    adj2.AdjustmentAmount = Convert.ToString(CreditCardProcessingFee_Amount);
                                    adj2.ReasonCode       = System.Configuration.ConfigurationManager.AppSettings["CreditCardProcessingFee_ReasonCode"].ToString();
                                    adj2.Note             = "";
                                    lstAdj.Add(adj2);
                                }
                                TotfeeAmt = (CustomerServiceConvenienceFee_Amount);//CustomerServiceConvenienceFee_Amount

                                payObject.AddAdjustmentRequestDetails = lstAdj;
                            }
                            else
                            {
                                payObject.AddAdjustment = "N";
                            }
                        }
                    }
                    if (req.IsWriteoffAmount == 1)
                    {
                        if (payObject.AddAdjustment != "Y")
                        {
                            payObject.AddAdjustment = "Y";
                        }

                        WebEnrollmentNewDesign.PayService.AddAdjustmentRequest adjbaddebit = new WebEnrollmentNewDesign.PayService.AddAdjustmentRequest();
                        adjbaddebit.AdjustmentAmount = Convert.ToString(req.Amount - TotfeeAmt);
                        adjbaddebit.ReasonCode       = System.Configuration.ConfigurationManager.AppSettings["BadDebtReversal_ReasonCode"].ToString();
                        adjbaddebit.Note             = "";
                        lstAdj.Add(adjbaddebit);
                        payObject.AddAdjustmentRequestDetails = lstAdj;
                    }
                    else
                    {
                        //IS Settled Amount
                        decimal PaidAmount = (req.Amount - TotfeeAmt);
                        if (req.IsSettledAmount == 1 && req.IsWriteoffAmount == 0 && req.ARBalanceAmount > PaidAmount && req.Addr_State.ToUpper() == "TX")
                        {
                            if (payObject.AddAdjustment != "Y")
                            {
                                payObject.AddAdjustment = "Y";
                            }
                            WebEnrollmentNewDesign.PayService.AddAdjustmentRequest adjsettledamtreq = new WebEnrollmentNewDesign.PayService.AddAdjustmentRequest();
                            adjsettledamtreq.AdjustmentAmount = Convert.ToString(req.ARBalanceAmount - PaidAmount);
                            adjsettledamtreq.ReasonCode       = System.Configuration.ConfigurationManager.AppSettings["IsSettled_ReasonCode"].ToString();
                            adjsettledamtreq.Note             = "";
                            lstAdj.Add(adjsettledamtreq);
                            //   payObject.AddAdjustmentRequestDetails = lstAdj;
                        }
                    }

                    try
                    {
                        frontierPayResponse = objFrontierPay.PayByCard(payObject);
                    }
                    catch (Exception ex)
                    {
                        InsertClientErrorLog(req.CustomerNumber, batchCode, req.Source, ex, "Common_FrontierPayMakePayment");
                    }

                    payResponse.ResultMessage = frontierPayResponse.ResponseMessage;
                    payResponse.ResultCode    = Convert.ToInt32(frontierPayResponse.StatusCode);
                    payResponse.AuthCode      = frontierPayResponse.ConfirmationNo;
                }
                else
                {
                    payResponse.ResultCode    = -1;
                    payResponse.ResultMessage = "Invalid Request";
                }
                return(payResponse);
            }
            catch (Exception ex)
            {
                payResponse.ResultCode    = -3;
                payResponse.ResultMessage = ex.Message;
                InsertClientErrorLog(req.CustomerNumber, batchCode + "CardName: " + req.CardName + ";CardType" + req.CardType, req.Source, ex, "Common_FrontierPayMakePayment");
                return(payResponse);
            }
        }
Beispiel #14
0
 public Task <Result <CreditCardPaymentResult> > Authorize(CreditCardPaymentRequest request) => MakePayment(request, PaymentCommandType.Authorization);
Beispiel #15
0
 public Task <Result <CreditCardPaymentResult> > Pay(CreditCardPaymentRequest request) => MakePayment(request, PaymentCommandType.Purchase);
        public PaymentResponse CreditCardPayment(CreditCardPaymentRequest req)
        {
            var resp      = new PaymentResponse();
            var RequestID = PayflowUtility.RequestId;
            PayflowConnectionData Connection = new PayflowConnectionData(Host, Port <= 0 ? 443 : Port, Timeout <= 30 ? 30 : Timeout, "", 0, "", "");
            UserInfo PaymentProcessorUser    = new UserInfo(User, Vendor, Partner, Password);
            int      trxCount = 1;
            bool     RespRecd = false;


            if (string.IsNullOrEmpty(req.InvoiceNumber))
            {
                req.InvoiceNumber = _confirmationNumberGenerator.GenerateConfirmationNumber();
            }


            Currency Amt = new Currency(req.Amount)
            {
                NoOfDecimalDigits = 0
            };
            Invoice Inv = new Invoice
            {
                Amt      = Amt,
                Comment1 = req.Comment
            };

            //Set the BillTo object into invoice.
            if (req.BillingInformation != null)
            {
                Inv.BillTo = CreateBillTo(req);
            }

            CreditCard CC = new CreditCard(req.AccountNumber, req.Expiration.Replace("/", ""));

            CC.Cvv2 = req.CVC;

            // Create Card Tender data object.
            CardTender Card = new CardTender(CC);  // credit card

            // Notice we set the request id earlier in the application and outside our loop.  This way if a response was not received
            // but PayPal processed the original request, you'll receive the original response with DUPLICATE set.
            SaleTransaction Trans = new SaleTransaction(PaymentProcessorUser, Connection, Inv, Card, RequestID);

            Trans.Verbosity = String.IsNullOrEmpty(Verbosity) ? "HIGH" : Verbosity;
            while (trxCount <= 3 && !RespRecd)
            {
                // Submit the Transaction
                Response Resp = Trans.SubmitTransaction();

                // Display the transaction response parameters.
                if (Resp != null)
                {
                    RespRecd = true;  // Got a response.

                    // Get the Transaction Response parameters.
                    TransactionResponse TrxnResponse = Resp.TransactionResponse;

                    if (TrxnResponse != null)
                    {
                        resp = ProcessResponse(TrxnResponse);
                    }
                }
                else
                {
                    trxCount++;
                }
            }

            if (!RespRecd)
            {
                resp.Message = "Payment not processed.  Please contact Customer Service";
            }

            return(resp);
        }
        public PaymentResponse ProcessCreditCardPayment(CreditCardPaymentRequest request)
        {
            if (request.Card == null)
            {
                return(new PaymentResponse
                {
                    Success = false,
                    Message = PaymentErrorsEnum.CreditCardNotFound.GetDescription()
                });
            }

            creditCardType creditCard = new creditCardType
            {
                cardCode       = request.Card.CVC,
                cardNumber     = request.Card.CardNumber,
                expirationDate = request.Card.ExpDate,
            };

            customerAddressType shipAddress = null;
            customerAddressType billAddress = null;

            if (request.BillAddress != null)
            {
                billAddress = new customerAddressType
                {
                    firstName = request.BillAddress.FirstName,
                    lastName  = request.BillAddress.LastName,
                    city      = request.BillAddress.City,
                    country   = request.BillAddress.Country,
                    address   = request.BillAddress.Address,
                    zip       = request.BillAddress.Zip
                };
            }

            if (request.ShipAddress != null)
            {
                shipAddress = new customerAddressType
                {
                    firstName = request.ShipAddress.FirstName,
                    lastName  = request.ShipAddress.LastName,
                    city      = request.ShipAddress.City,
                    country   = request.ShipAddress.Country,
                    address   = request.ShipAddress.Address,
                    zip       = request.ShipAddress.Zip
                };
            }

            List <lineItemType> lines = new List <lineItemType>();

            if (request.LineItems?.Count > 0)
            {
                List <InvoiceLine> requestLines = request.LineItems;

                for (int i = 0; i < request.LineItems.Count; i++)
                {
                    lines.Add(new lineItemType
                    {
                        itemId    = requestLines[i].Id,
                        name      = requestLines[i].Name,
                        unitPrice = requestLines[i].Price,
                        quantity  = requestLines[i].Quantity
                    });
                }
            }

            paymentType paymentType = new paymentType
            {
                Item = creditCard
            };

            Init(request);

            transactionRequestType requestType = new transactionRequestType
            {
                amount    = request.Amount,
                billTo    = billAddress,
                shipTo    = shipAddress,
                payment   = paymentType,
                lineItems = lines.ToArray()
            };

            createTransactionRequest transactionRequest = new createTransactionRequest
            {
                transactionRequest = requestType
            };

            createTransactionController controller = new createTransactionController(transactionRequest);

            controller.Execute();

            var response = controller.GetApiResponse();

            if (response == null)
            {
                return new PaymentResponse
                       {
                           Success = false,
                           Message = PaymentErrorsEnum.NullResponse.GetDescription()
                       }
            }
            ;

            if (response.messages.resultCode == messageTypeEnum.Ok)
            {
                if (response.transactionResponse.messages != null)
                {
                    string message       = response.transactionResponse.messages[0].description;
                    string transactionId = response.transactionResponse.transId;
                    string authCode      = response.transactionResponse.authCode;

                    return(new PaymentResponse
                    {
                        Success = true,
                        TransactionId = transactionId,
                        AuthKey = authCode,
                        Message = message
                    });
                }
                else
                {
                    string message;

                    if (response.transactionResponse.errors != null)
                    {
                        message = response.transactionResponse.errors[0].errorText;
                    }
                    else
                    {
                        message = PaymentErrorsEnum.TransactionFailed.GetDescription();
                    }

                    return(new PaymentResponse
                    {
                        Success = false,
                        Message = message
                    });
                }
            }
            else
            {
                string message;

                if (response.transactionResponse?.errors != null)
                {
                    message = response.transactionResponse.errors[0].errorText;
                }
                else
                {
                    message = response.messages.message[0].text;
                }

                return(new PaymentResponse
                {
                    Success = false,
                    Message = message
                });
            }
        }
    }