Exemplo n.º 1
0
        public void AuthorizeAndCaptureTest_ExtraOptions()
        {
            const string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><createCustomerProfileTransactionResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages><directResponse>1,1,1,This transaction has been approved.,0PI2II,Y,2210620905,,,25.10,CC,auth_capture,Testing Extra Option,Sue,Zhu,Visa,123 Elm Street,Bellevue,WA,98006,US,,,[email protected],,,,,,,,,,,,,,070CC74A6FDD5EA7951444C547FE7829,,2,,,,,,,,,,,XXXX1111,Visa,,,,,,,,,,,,,,,,</directResponse></createCustomerProfileTransactionResponse>";
            LocalRequestObject.ResponseString = responseString;

            var email = Path.GetRandomFileName() + "@viscom";
            const string description = "CreateCustomerTest Success";
            var customer = CreateCustomer(email, description);

            const string expectedCardNumber = "XXXX1111";
            var paymentProfileId = CreateCustomerPaymentProfile(customer.ProfileID,  "4111111111111111", 1, 2030);

            var txnAmount = getValidAmount();
	    
            var order = new Order(customer.ProfileID, paymentProfileId, "")
                {
                    Amount = txnAmount,
                    ExtraOptions = "x_customer_ip=100.0.0.1&x_cust_id=Testing Extra Options"
                };

            IGatewayResponse actual = null;

            // if choose "USELOCAL", the test should pass with no exception
            // Otherwise, the test might fail for error, i.e. duplicated request.
            try
            {
                actual = _target.AuthorizeAndCapture(order);
            }
            catch (Exception e)
            {
                Console.WriteLine("CustomerGateway.AuthorizeAndCapture() failed: " + e.Message);
            }
            Assert.IsNotNull(actual);
	    
            Assert.AreEqual(txnAmount, actual.Amount);
            Assert.AreEqual(true, actual.Approved);
            Assert.AreEqual(expectedCardNumber, actual.CardNumber);
            Assert.AreEqual("This transaction has been approved.", actual.Message);
            Assert.AreEqual("1", actual.ResponseCode);

            Assert.IsTrue(actual.AuthorizationCode.Trim().Length > 0);
            Assert.IsTrue(long.Parse(actual.TransactionID) > 0);
        }
Exemplo n.º 2
0
        public void TestSdkUpgradeCustomerOrder()
        {
            var random = new AnetRandom();
            var counter = random.Next(1, (int)(Math.Pow(2, 24)));
            const int maxAmount = 10000;// 214747;
            var amount = new decimal(counter > maxAmount ? (counter % maxAmount) : counter);
            var email = string.Format("user.{0}@authorize.net", counter);
            var description = string.Format("Description for Customer: {0}", counter);
            var merchantCustomerId = string.Format("CustomerId: {0}", counter);
            const string cardNumber = "4111111111111111";
            const string  cvv = "";
            var address = new Address
                {
                    First = string.Format("FName:{0}", counter),
                    Last = string.Format("LName:{0}", counter),
                    Company = "Visa",
                    Street = "123 Elm Street",
                    City = "Bellevue",
                    State = "WA",
                    Country = "US",
                    Zip = "98006"
                };

            //Save the customer first
            var gw = new CustomerGateway(ApiLogin, TransactionKey);

            var customer = gw.CreateCustomer(email, description, merchantCustomerId);
            var creditCardToken = gw.AddCreditCard(customer.ProfileID, cardNumber, DateTime.UtcNow.Month, DateTime.UtcNow.AddYears(1).Year, cvv, address);

            //Create order
            var order = new Order(customer.ProfileID, creditCardToken, "")
                {
                    Amount = amount,
                    CardCode = cvv,
                    ExtraOptions = "x_duplicate_window=0"
                };

            var result = (GatewayResponse)gw.AuthorizeAndCapture(order);
            Assert.IsNotNull(result, "GateWay response for Order AuthCapture is null");

            var buffer = new StringBuilder();

            buffer.Append( "IGateWayResponse->");
            buffer.AppendFormat( "  SplitTenderId:{0}", result.SplitTenderId);
            buffer.AppendFormat( ", MD5Hash:{0}", result.MD5Hash);
            buffer.AppendFormat( ", CCVResponse:{0}", result.CCVResponse);
            buffer.AppendFormat( ", Code:{0}", result.Code);
            buffer.AppendFormat( ", TransactionType:{0}", result.TransactionType);
            buffer.AppendFormat( ", AuthorizationCode:{0}", result.AuthorizationCode);
            buffer.AppendFormat( ", Method:{0}", result.Method);
            buffer.AppendFormat( ", Amount:{0}", result.Amount);
            buffer.AppendFormat( ", Tax:{0}", result.Tax);
            buffer.AppendFormat( ", TransactionID:{0}", result.TransactionID);
            buffer.AppendFormat( ", InvoiceNumber:{0}", result.InvoiceNumber);
            buffer.AppendFormat( ", Description:{0}", result.Description);
            buffer.AppendFormat( ", ResponseCode:{0}", result.ResponseCode);
            buffer.AppendFormat( ", CardNumber:{0}", result.CardNumber);
            buffer.AppendFormat( ", CardType:{0}", result.CardType);
            buffer.AppendFormat( ", CAVResponse:{0}", result.CAVResponse);
            buffer.AppendFormat( ", AVSResponse:{0}", result.AVSResponse);
            buffer.AppendFormat( ", SubCode:{0}", result.SubCode);
            buffer.AppendFormat( ", Message:{0}", result.Message);
            buffer.AppendFormat( ", Approved:{0}", result.Approved);
            buffer.AppendFormat( ", Declined:{0}", result.Declined);
            buffer.AppendFormat( ", Error:{0}", result.Error);
            buffer.AppendFormat( ", HeldForReview:{0}", result.HeldForReview);
            buffer.AppendFormat( ", FirstName:{0}", result.FirstName);
            buffer.AppendFormat( ", LastName:{0}", result.LastName);
            buffer.AppendFormat( ", Email:{0}", result.Email);
            buffer.AppendFormat( ", Company:{0}", result.Company);
            buffer.AppendFormat( ", Address:{0}", result.Address);
            buffer.AppendFormat( ", City:{0}", result.City);
            buffer.AppendFormat( ", State:{0}", result.State);
            buffer.AppendFormat( ", ZipCode:{0}", result.ZipCode);
            buffer.AppendFormat( ", Country:{0}", result.Country);
            buffer.AppendFormat( ", ShipFirstName:{0}", result.ShipFirstName);
            buffer.AppendFormat( ", ShipLastName:{0}", result.ShipLastName);
            buffer.AppendFormat( ", ShipCompany:{0}", result.ShipCompany);
            buffer.AppendFormat( ", ShipAddress:{0}", result.ShipAddress);
            buffer.AppendFormat( ", ShipCity:{0}", result.ShipCity);
            buffer.AppendFormat( ", ShipState:{0}", result.ShipState);
            buffer.AppendFormat( ", ShipZipCode:{0}", result.ShipZipCode);
            buffer.AppendFormat( ", ShipCountry:{0}", result.ShipCountry);

            Console.WriteLine(buffer);

            Assert.IsNotNull(result.MD5Hash);
            Assert.IsNotNullOrEmpty(result.TransactionType);
            Assert.IsNotNullOrEmpty(result.AuthorizationCode);
            Assert.IsNotNullOrEmpty(result.Method);
            Assert.AreEqual("CC", result.Method);
            Assert.IsNotNullOrEmpty(result.TransactionID);
            Assert.AreEqual("1", result.ResponseCode);
            Assert.AreEqual( "XXXX1111", result.CardNumber);
            Assert.AreEqual( "Visa", result.CardType);
            Assert.AreEqual("This transaction has been approved.", result.Message);
            Assert.IsTrue(result.Approved);
            Assert.IsFalse(result.Declined);
        }
Exemplo n.º 3
0
        public void AuthorizeAndCaptureTest_InvoiceDescriptionPONumber()
        {
            const string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><createCustomerProfileTransactionResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages><directResponse>1,1,1,This transaction has been approved.,Q5G0UI,Y,2207641147,Invoice#123,Testing InvoiceDescriptionPONumber,25.10,CC,auth_capture,,,,,,,,,,,,[email protected],,,,,,,,,,,,,PO23456,BEEEB7C9F2F22B9955338A7E19427369,,2,,,,,,,,,,,XXXX1111,Visa,,,,,,,,,,,,,,,,</directResponse></createCustomerProfileTransactionResponse>";
            LocalRequestObject.ResponseString = responseString;

            var email = Path.GetRandomFileName() + "@viscom";
            const string description = "CreateCustomerTest Success";
            var customer = CreateCustomer(email, description);

            const string expectedCardNumber = "XXXX1111";
            var paymentProfileId = CreateCustomerPaymentProfile(customer.ProfileID,  "4111111111111111", 1, 2030);

            var txnAmount = getValidAmount();
            const string invoiceNumber = "Invoice#123";

            var order = new Order(customer.ProfileID, paymentProfileId, "")
                {
                    Amount = txnAmount,
                    InvoiceNumber = invoiceNumber,
                    Description = "Testing InvoiceDescriptionPONumber",
                    PONumber = "PO23456"
                };

            IGatewayResponse actual = null;

            // if choose "USELOCAL", the test should pass with no exception
            // Otherwise, the test might fail for error, i.e. duplicated request.
            try
            {
                actual = _target.AuthorizeAndCapture(order);
            }
            catch (Exception e)
            {
                Console.WriteLine("CustomerGateway.AuthorizeAndCapture() failed: " + e.Message);
            }
            Assert.IsNotNull(actual);

            Assert.AreEqual(txnAmount, actual.Amount);
            Assert.AreEqual(true, actual.Approved);
            Assert.AreEqual(expectedCardNumber, actual.CardNumber);
            Assert.AreEqual("This transaction has been approved.", actual.Message);
            Assert.AreEqual("1", actual.ResponseCode);
            Assert.AreEqual(invoiceNumber, actual.InvoiceNumber);

            Assert.IsTrue(actual.AuthorizationCode.Trim().Length > 0);
            Assert.IsTrue(long.Parse(actual.TransactionID) > 0);
        }
Exemplo n.º 4
0
        public TransactionResponse PayWithVault(int peopleId, decimal amt, string description, int tranid, string type)
        {
            var paymentInfo = db.PaymentInfos.Single(pp => pp.PeopleId == peopleId);
            if (paymentInfo == null)
                return new TransactionResponse
                {
                    Approved = false,
                    Message = "missing payment info",
                };

            string paymentProfileId;
            if (type == PaymentType.Ach)
                paymentProfileId = paymentInfo.AuNetCustPayBankId.ToString();
            else if (type == PaymentType.CreditCard)
                paymentProfileId = paymentInfo.AuNetCustPayId.ToString();
            else
                throw new ArgumentException($"Type {type} not supported", nameof(type));

            var order = new Order(paymentInfo.AuNetCustId.ToString(), paymentProfileId, null)
            {
                Description = description,
                Amount = amt,
                InvoiceNumber = tranid.ToString()
            };
            var response = CustomerGateway.AuthorizeAndCapture(order);

            return new TransactionResponse
            {
                Approved = response.Approved,
                AuthCode = response.AuthorizationCode,
                Message = response.Message,
                TransactionId = response.TransactionID
            };
        }
Exemplo n.º 5
0
 public void TestCheckForErrorscreateCustomerProfileTransactionResponse()
 {
     const string profileId = "24231938";
     const string paymentProfileId = "22219473";
     var gateway = new CustomerGateway(ApiLogin, TransactionKey);
     var order = new Order(profileId, paymentProfileId, "") {Amount = (decimal) 25.10};
     var response = gateway.AuthorizeAndCapture(order);
     Assert.IsNotNull(response);
 }
Exemplo n.º 6
0
        public TransactionResponse AuthCreditCardVault(int peopleId, decimal amt, string description, int tranid)
        {
            var paymentInfo = db.PaymentInfos.Single(pp => pp.PeopleId == peopleId);
            if (paymentInfo?.AuNetCustPayId == null)
                return new TransactionResponse
                {
                    Approved = false,
                    Message = "missing payment info",
                };

            var paymentProfileId = paymentInfo.AuNetCustPayId.ToString();

            var order = new Order(paymentInfo.AuNetCustId.ToString(), paymentProfileId, null)
            {
                Description = description,
                Amount = amt,
                InvoiceNumber = tranid.ToString()
            };
            var response = CustomerGateway.Authorize(order);

            return new TransactionResponse
            {
                Approved = response.Approved,
                AuthCode = response.AuthorizationCode,
                Message = response.Message,
                TransactionId = response.TransactionID
            };
        }
Exemplo n.º 7
0
        /// <summary>
        /// Authorizes and Captures a transaction using the supplied profile information, abstracted through an Order object. Using the Order
        /// you can add line items, specify shipping and tax, etc.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <returns></returns>
        public IGatewayResponse AuthorizeAndCapture(Order order)
        {
            var req = new createCustomerProfileTransactionRequest();

            var trans = new profileTransAuthCaptureType();

            trans.customerProfileId = order.CustomerProfileID;
            trans.customerPaymentProfileId = order.PaymentProfileID;
            trans.amount = order.Total;

            if (!String.IsNullOrEmpty(order.ShippingAddressProfileID)) {
                trans.customerShippingAddressId = order.ShippingAddressProfileID;
            }

            if (order.SalesTaxAmount > 0)
                trans.tax = new extendedAmountType {
                    amount = order.SalesTaxAmount,
                    description = order.SalesTaxName,
                    name = order.SalesTaxName
                };

            if (order.ShippingAmount > 0)
                trans.shipping = new extendedAmountType {
                    amount = order.ShippingAmount,
                    description = order.ShippingName,
                    name = order.ShippingName
                };

            //line items
            if (order._lineItems.Count > 0) {
                trans.lineItems = order._lineItems.ToArray();
            }

            if (order.TaxExempt.HasValue) {
                trans.taxExempt = order.TaxExempt.Value;
                trans.taxExemptSpecified = true;
            }

            if (order.RecurringBilling.HasValue) {
                trans.recurringBilling = order.RecurringBilling.Value;
                trans.recurringBillingSpecified = true;
            }
            if(!String.IsNullOrEmpty(order.CardCode))
                trans.cardCode = order.CardCode;

            req.transaction = new profileTransactionType();
            req.transaction.Item = trans;

            var response = (createCustomerProfileTransactionResponse)_gateway.Send(req);

            return new GatewayResponse(response.directResponse.Split(','));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Authorizes and Captures a transaction using the supplied profile information with Tax and Shipping specified. If you want
        /// to add more detail here, use the 3rd option - which is to add an Order object
        /// </summary>
        /// <param name="profileID">The profile ID.</param>
        /// <param name="paymentProfileID">The payment profile ID.</param>
        /// <param name="amount">The amount.</param>
        /// <param name="tax">The tax.</param>
        /// <param name="shipping">The shipping.</param>
        /// <returns></returns>
        public IGatewayResponse AuthorizeAndCapture(string profileID, string paymentProfileID, decimal amount, decimal tax, decimal shipping)
        {
            var order = new Order(profileID, paymentProfileID,"");
            order.Amount = amount;

            if (tax > 0){
                order.SalesTaxAmount = tax;
                order.SalesTaxName = "Sales Tax";
            }

            if (shipping > 0) {
                order.ShippingAmount = shipping;
                order.ShippingName = "Shipping";
            }

            return AuthorizeAndCapture(order);
        }
        private void ProcessNewOrder(int cartId)
        {
            //bool dupTransaction = false;
            hccCart CurrentCart = null;

            try
            {
                // TODO: Check the cart for more then one recurring item

                CurrentCart = hccCart.GetById(cartId);

                hccUserProfile profile  = hccUserProfile.GetParentProfileBy(CurrentCart.AspNetUserID.Value);
                hccAddress     billAddr = null;

                var ppName =
                    hccUserProfile.GetParentProfileBy((Guid)hccCart.GetById(cartId).AspNetUserID).ParentProfileName;
                var pName = hccUserProfile.GetParentProfileBy((Guid)hccCart.GetById(cartId).AspNetUserID).ASPUser.Email;

                //if (CurrentCart.StatusID == (int)Enums.CartStatus.Unfinalized)
                if (CurrentCart.StatusID == (int)Enums.CartStatus.Unfinalized)
                {
                    if (profile != null)
                    {
                        AuthNetConfig ANConfig = new AuthNetConfig();
                        hccUserProfilePaymentProfile activePaymentProfile = profile.ActivePaymentProfile;
                        bool isDuplicateTransaction = false;
                        bool isAuthNet = false;

                        if (ANConfig.Settings.TestMode)
                        {
                            CurrentCart.IsTestOrder = true;
                        }

                        // Check for existing account balance, calculate total balance
                        if (CurrentCart.PaymentDue > 0.00m)
                        {
                            try
                            {
                                // if total balance remains
                                CustomerInformationManager cim = new CustomerInformationManager();

                                if (activePaymentProfile != null)
                                {
                                    // do not validate, per Duncan, YouTrack HC1-339
                                    //string valProfile = cim.ValidateProfile(profile.AuthNetProfileID,
                                    //    activePaymentProfile.AuthNetPaymentProfileID, AuthorizeNet.ValidationMode.TestMode);

                                    AuthorizeNet.Order order = new AuthorizeNet.Order(profile.AuthNetProfileID,
                                                                                      activePaymentProfile.AuthNetPaymentProfileID, null);

                                    // charge CIM account with PaymentDue balance
                                    order.Amount        = CurrentCart.PaymentDue;
                                    order.InvoiceNumber = CurrentCart.PurchaseNumber.ToString();
                                    order.Description   = "Healthy Chef Creations Purchase #" +
                                                          CurrentCart.PurchaseNumber.ToString();
                                    // Add a PO number to make purchases unique as subsequent transactions with the same amount are rejected by Auth.net as duplicate
                                    // order.PONumber = "PO" + CurrentCart.PurchaseNumber.ToString();

                                    AuthorizeNet.IGatewayResponse rsp = cim.AuthorizeAndCapture(order);

                                    try
                                    {
                                        CurrentCart.AuthNetResponse = rsp.ResponseCode + "|" + rsp.Approved.ToString()
                                                                      + "|" + rsp.AuthorizationCode + "|" +
                                                                      rsp.InvoiceNumber + "|" + rsp.Message
                                                                      + "|" + rsp.TransactionID + "|" +
                                                                      rsp.Amount.ToString() + "|" + rsp.CardNumber;
                                    }
                                    catch (Exception)
                                    {
                                    }

                                    if (rsp.ResponseCode.StartsWith("1"))
                                    {
                                        CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                        CurrentCart.ModifiedDate     = DateTime.Now;
                                        CurrentCart.PurchaseBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                        CurrentCart.PurchaseDate     = DateTime.Now;
                                        CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                        CurrentCart.StatusID         = (int)Enums.CartStatus.Paid;

                                        isAuthNet = true;
                                    }
                                    else if (rsp.Message.Contains("E00027")) // Duplicate transaction
                                    {
                                        order = new AuthorizeNet.Order(profile.AuthNetProfileID,
                                                                       activePaymentProfile.AuthNetPaymentProfileID, null)
                                        {
                                            Amount = CurrentCart.PaymentDue - .01m,
                                            // Subtract a penny from payment to make the value distinct
                                            InvoiceNumber = CurrentCart.PurchaseNumber.ToString(),
                                            Description   =
                                                "Healthy Chef Creations Purchase #" +
                                                CurrentCart.PurchaseNumber.ToString()
                                        };

                                        // charge CIM account with PaymentDue balance
                                        rsp = cim.AuthorizeAndCapture(order);

                                        try
                                        {
                                            CurrentCart.AuthNetResponse = rsp.ResponseCode + "|" +
                                                                          rsp.Approved.ToString()
                                                                          + "|" + rsp.AuthorizationCode + "|" +
                                                                          rsp.InvoiceNumber + "|" + rsp.Message
                                                                          + "|" + rsp.TransactionID + "|" +
                                                                          rsp.Amount.ToString() + "|" + rsp.CardNumber;

                                            if (rsp.ResponseCode.StartsWith("1"))
                                            {
                                                //CurrentCart.PaymentDue = CurrentCart.PaymentDue - .01m;
                                                CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                                CurrentCart.ModifiedDate     = DateTime.Now;
                                                CurrentCart.PurchaseBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                                CurrentCart.PurchaseDate     = DateTime.Now;
                                                CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                                CurrentCart.StatusID         = (int)Enums.CartStatus.Paid;

                                                isAuthNet = true;
                                            }
                                            else
                                            {
                                                lblConfirmFeedback.Text += "Authorize.Net " + rsp.Message + @" (" +
                                                                           ppName + @", " + pName + @")" + @"<br />";
                                                // CurrentCart.AuthNetResponse;
                                                lblConfirmFeedback.ForeColor = System.Drawing.Color.Red;
                                            }
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        lblConfirmFeedback.Text += "Authorize.Net " + rsp.Message + @" (" + ppName +
                                                                   @", " + pName + @")" + @"<br />";
                                        // CurrentCart.AuthNetResponse;
                                        lblConfirmFeedback.ForeColor = System.Drawing.Color.Red;
                                    }
                                    CurrentCart.Save();
                                }
                                else
                                {
                                    lblConfirmFeedback.Text += "No payment profile found." + @" (" + ppName + @", " +
                                                               pName + @")" + @"<br />";
                                }
                            }
                            catch (Exception ex)
                            {
                                lblConfirmFeedback.Text += "Authorize.Net " + ex.Message + @" (" + ppName + @", " +
                                                           pName + @")" + @"<br />";
                                lblConfirmFeedback.ForeColor = System.Drawing.Color.Red;
                                if (ex is InvalidOperationException)
                                {
                                    if (CurrentCart.IsTestOrder)
                                    {
                                        CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                        CurrentCart.ModifiedDate     = DateTime.Now;
                                        CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                        CurrentCart.AuthNetResponse  = ex.Message;
                                        CurrentCart.StatusID         = (int)Enums.CartStatus.Unfinalized;
                                        CurrentCart.Save();
                                    }
                                    else
                                    {
                                        BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(ex.Message, this, ex);
                                        lblConfirmFeedback.Visible = true;
                                        lblConfirmFeedback.Text   += "Authorize.Net " + ex.Message + @" (" + ppName +
                                                                     @", " + pName + @")" + @"<br />";
                                        lblConfirmFeedback.ForeColor = System.Drawing.Color.Red;
                                    }
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                        else
                        {
                            // no balance left to pay on order, set as paid
                            CurrentCart.AuthNetResponse = "Paid with account balance.";
                            CurrentCart.ModifiedBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                            CurrentCart.ModifiedDate    = DateTime.Now;
                            CurrentCart.PurchaseBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                            CurrentCart.PurchaseDate    = DateTime.Now;
                            CurrentCart.StatusID        = (int)Enums.CartStatus.Paid;
                            CurrentCart.Save();
                        }

                        if ((Enums.CartStatus)CurrentCart.StatusID == Enums.CartStatus.Paid)
                        //&& !isDuplicateTransaction
                        {
                            hccLedger ledger = new hccLedger
                            {
                                //PaymentDue = dupTransaction ? CurrentCart.PaymentDue : CurrentCart.PaymentDue - .01m,
                                //TotalAmount = dupTransaction ? CurrentCart.TotalAmount : CurrentCart.TotalAmount - .01m,
                                PaymentDue   = CurrentCart.PaymentDue,
                                TotalAmount  = CurrentCart.TotalAmount,
                                AspNetUserID = CurrentCart.AspNetUserID.Value,
                                AsscCartID   = CurrentCart.CartID,
                                CreatedBy    = (Guid)Helpers.LoggedUser.ProviderUserKey,
                                CreatedDate  = DateTime.Now,
                                Description  =
                                    "Cart Order Payment - Purchase Number: " + CurrentCart.PurchaseNumber.ToString(),
                                TransactionTypeID = (int)Enums.LedgerTransactionType.Purchase
                            };

                            if (CurrentCart.IsTestOrder)
                            {
                                ledger.Description += " - Test Mode";
                            }

                            if (CurrentCart.CreditAppliedToBalance > 0)
                            {
                                profile.AccountBalance   = profile.AccountBalance - CurrentCart.CreditAppliedToBalance;
                                ledger.CreditFromBalance = CurrentCart.CreditAppliedToBalance;
                            }

                            hccLedger lastLedger =
                                hccLedger.GetByMembershipID(profile.MembershipID, null)
                                .OrderByDescending(a => a.CreatedDate)
                                .FirstOrDefault();
                            bool isDuplicateLedger = false;

                            if (lastLedger != null)
                            {
                                if (ledger.CreatedBy == lastLedger.CreatedBy &&
                                    ledger.CreditFromBalance == lastLedger.CreditFromBalance &&
                                    ledger.Description == lastLedger.Description &&
                                    ledger.PaymentDue == lastLedger.PaymentDue &&
                                    ledger.TransactionTypeID == lastLedger.TransactionTypeID &&
                                    ledger.TotalAmount == lastLedger.TotalAmount)
                                {
                                    isDuplicateLedger = true;
                                }
                            }

                            if (!isDuplicateLedger)
                            {
                                ledger.PostBalance = profile.AccountBalance;
                                ledger.Save();
                                profile.Save();

                                // create snapshot here
                                hccCartSnapshot snap = new hccCartSnapshot
                                {
                                    CartId                  = cartId,
                                    MembershipId            = profile.MembershipID,
                                    LedgerId                = ledger.LedgerID,
                                    AccountBalance          = profile.AccountBalance,
                                    AuthNetProfileId        = profile.AuthNetProfileID,
                                    CreatedBy               = (Guid)Helpers.LoggedUser.ProviderUserKey,
                                    CreatedDate             = DateTime.Now,
                                    DefaultCouponId         = profile.DefaultCouponId,
                                    Email                   = profile.ASPUser.Email,
                                    FirstName               = profile.FirstName,
                                    LastName                = profile.LastName,
                                    ProfileName             = profile.ProfileName,
                                    AuthNetPaymentProfileId =
                                        (isAuthNet == true ? activePaymentProfile.AuthNetPaymentProfileID : string.Empty),
                                    CardTypeId = (isAuthNet == true ? activePaymentProfile.CardTypeID : 0),
                                    CCLast4    = (isAuthNet == true ? activePaymentProfile.CCLast4 : string.Empty),
                                    ExpMon     = (isAuthNet == true ? activePaymentProfile.ExpMon : 0),
                                    ExpYear    = (isAuthNet == true ? activePaymentProfile.ExpYear : 0),
                                    NameOnCard = (isAuthNet == true ? activePaymentProfile.NameOnCard : string.Empty)
                                };
                                snap.Save();

                                hccUserProfile parentProfile =
                                    hccUserProfile.GetParentProfileBy(CurrentCart.AspNetUserID.Value);
                                if (parentProfile.BillingAddressID.HasValue)
                                {
                                    billAddr = hccAddress.GetById(parentProfile.BillingAddressID.Value);
                                }

                                hccAddress snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.BillingSnap,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = parentProfile.ProfileName
                                };
                                snapBillAddr.Save();

                                // copy and replace of all addresses for snapshot
                                List <hccCartItem> cartItems = hccCartItem.GetBy(CurrentCart.CartID);

                                cartItems.ToList().ForEach(delegate(hccCartItem ci)
                                {
                                    hccAddress shipAddr = null;
                                    if (ci.UserProfile.ShippingAddressID.HasValue)
                                    {
                                        shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                                    }

                                    if (shipAddr != null)
                                    {
                                        hccAddress snapShipAddr = new hccAddress
                                        {
                                            Address1              = shipAddr.Address1,
                                            Address2              = shipAddr.Address2,
                                            AddressTypeID         = (int)Enums.AddressType.ShippingSnap,
                                            City                  = shipAddr.City,
                                            Country               = shipAddr.Country,
                                            DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                            FirstName             = shipAddr.FirstName,
                                            IsBusiness            = shipAddr.IsBusiness,
                                            LastName              = shipAddr.LastName,
                                            Phone                 = shipAddr.Phone,
                                            PostalCode            = shipAddr.PostalCode,
                                            State                 = shipAddr.State,
                                            ProfileName           = ci.UserProfile.ProfileName
                                        };
                                        snapShipAddr.Save();
                                        ci.SnapShipAddrId = snapShipAddr.AddressID;
                                    }

                                    ci.SnapBillAddrId = snapBillAddr.AddressID;
                                    ci.Save();
                                });


                                try
                                {
                                    Email.EmailController ec = new Email.EmailController();
                                    ec.SendMail_OrderConfirmationMerchant(profile.FirstName + " " + profile.LastName,
                                                                          CurrentCart.ToHtml(), cartId);
                                    ec.SendMail_OrderConfirmationCustomer(profile.ASPUser.Email,
                                                                          profile.FirstName + " " + profile.LastName, CurrentCart.ToHtml());
                                }
                                catch (Exception ex)
                                {
                                    BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send Mail Failed", this, ex);
                                } //throw; }

                                //if (IsForPublic)
                                //{
                                //    Response.Redirect(string.Format("~/cart/order-confirmation.aspx?pn={0}&tl={1}&tx={2}&ts={3}&ct={4}&st={5}&cy={6}",
                                //        CurrentCart.PurchaseNumber, CurrentCart.TotalAmount, CurrentCart.TaxableAmount, CurrentCart.ShippingAmount,
                                //        billAddr.City, billAddr.State, billAddr.Country), false);
                                //}
                                //else
                                //{
                                //    CurrentCart = hccCart.GetCurrentCart(profile.ASPUser);
                                //    CurrentCartId = CurrentCart.CartID;

                                //    pnlCartDisplay.Visible = true;
                                //    pnlConfirm.Visible = false;

                                //    Clear();
                                //    Bind();
                                //}
                                //OnCartSaved(new CartEventArgs(CurrentCartId));
                            }
                        }
                        //else
                        //{
                        //    BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Duplicate transaction attempted: " + CurrentCart.PurchaseNumber.ToString(), this, new Exception("Duplicate transaction attempted by:" + Helpers.LoggedUser.UserName));
                        //}
                    }
                    else
                    {
                        Response.Redirect("~/login.aspx", true);
                    }
                }
                //else
                //{
                //if (IsForPublic)
                //{
                //    //Response.Redirect("~/cart/order-confirmation.aspx?cid=" + CurrentCartId.ToString(), false);
                //    Response.Redirect(string.Format("~/cart/order-confirmation.aspx?pn={0}&tl={1}&tx={2}&ts={3}&ct={4}&st={5}&cy={6}",
                //                    CurrentCart.PurchaseNumber, CurrentCart.TotalAmount, CurrentCart.TaxableAmount, CurrentCart.ShippingAmount,
                //                    billAddr.City, billAddr.State, billAddr.Country), false);
                //}
                //else
                //{
                //    CurrentCart = hccCart.GetCurrentCart(profile.ASPUser);
                //    CurrentCartId = CurrentCart.CartID;

                //    pnlCartDisplay.Visible = true;
                //    pnlConfirm.Visible = false;

                //    Clear();
                //    Bind();

                //    OnCartSaved(new CartEventArgs(CurrentCartId));
                //}
                //}
            }
            catch (Exception ex)
            {
                BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(ex.Data + " " + ex.InnerException, this,
                                                                        new Exception("Recurring order error in method ProcessNewOrder: " + Helpers.LoggedUser.UserName));
            }
        }
        private AuthorizeNet.Order CreatePaymentOrder(IOrderGroup orderGroup, TransactionData transactionData, ITokenizedPayment payment, decimal orderAmount)
        {
            var customer = _authorizeTokenExService.CreateCustomer(transactionData.invoiceNum, payment.BillingAddress);

            var address = Utilities.ToAuthorizeNetAddress(payment.BillingAddress);

            customer.BillingAddress = address;
            _authorizeTokenExService.UpdateCustomer(customer);

            var shippingAddress = orderGroup.Forms.First().Shipments.First().ShippingAddress;

            if (shippingAddress == null)
            {
                throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", "Shipping address was not specified.");
            }

            var paymentProfileId  = AddCreditCard(orderGroup, customer.ProfileID, payment.Token, payment.ExpirationMonth, payment.ExpirationYear);
            var shippingAddressId = AddShippingAddress(customer.ProfileID, Utilities.ToAuthorizeNetAddress(shippingAddress));

            var currency         = orderGroup.Currency;
            var market           = _marketService.GetMarket(orderGroup.MarketId);
            var merchantCurrency = _authorizeTokenExService.GetMerchantCurrency();
            var shippingTotal    = Utilities.ConvertMoney(orderGroup.GetShippingTotal(_orderGroupCalculator), merchantCurrency);
            var salesTaxTotal    = Utilities.ConvertMoney(
                new Money(orderGroup.Forms.Sum(form => form.Shipments.Sum(shipment =>
                                                                          _shippingCalculator.GetSalesTax(shipment, market, currency).Amount)), currency).Round(),
                merchantCurrency);
            var taxTotal = Utilities.ConvertMoney(orderGroup.GetTaxTotal(_orderGroupCalculator), merchantCurrency);

            var order = new AuthorizeNet.Order(customer.ProfileID, paymentProfileId, shippingAddressId)
            {
                Amount         = orderAmount - taxTotal,
                SalesTaxAmount = salesTaxTotal,
                PONumber       = transactionData.purchaseOrderNum,
                InvoiceNumber  = transactionData.invoiceNum,
                ShippingAmount = shippingTotal + (orderGroup.PricesIncludeTax ? 0 : taxTotal - salesTaxTotal)
            };

            var orderedLineItems    = orderGroup.GetAllLineItems().OrderBy(x => x.Quantity).ToList();
            var largestQuantityItem = orderedLineItems.LastOrDefault();

            var lineItemsAmount             = 0m;
            var amountWithoutLargestQtyItem = 0m;
            var settleSubTotalExclTax       = orderAmount - order.ShippingAmount - order.SalesTaxAmount;
            var isFirstLineItem             = true;
            var factor        = (decimal)Math.Pow(10, DecimalDigit);
            var roundingDelta = 1 / factor;
            var itemPriceExcludingTaxMapping = GetPriceExcludingTax(orderGroup);

            foreach (var lineItem in orderedLineItems)
            {
                var itemCode     = lineItem.Code;
                var itemQuantity = Convert.ToInt32(lineItem.Quantity);
                var displayName  = string.IsNullOrEmpty(lineItem.DisplayName) ? itemCode : lineItem.DisplayName;
                var description  = (lineItem as Mediachase.Commerce.Orders.LineItem)?.Description ?? string.Empty;

                if (lineItem.IsGift)
                {
                    itemCode    = $"Gift: {itemCode}";
                    displayName = $"Gift: {displayName}";
                    description = $"Gift: {description}";
                }

                itemCode    = Utilities.StripPreviewText(itemCode, 31);
                displayName = Utilities.StripPreviewText(displayName, 31);
                description = Utilities.StripPreviewText(description, 255);

                // Calculate unit price.
                var unitPrice = Utilities.ConvertMoney(
                    new Money(currency.Round(itemPriceExcludingTaxMapping[lineItem.LineItemId] / lineItem.Quantity, DecimalDigit), currency),
                    merchantCurrency);

                lineItemsAmount += unitPrice * lineItem.Quantity;

                if (lineItem.LineItemId != largestQuantityItem.LineItemId)
                {
                    amountWithoutLargestQtyItem = lineItemsAmount;
                }

                // In case we have Rounding Differences between rounding Total Amount (orderAmount - amount requested for settlement)
                // and rounding each lineItem unit price (amount authorized), need to recalculate unit price of item has largest quantity.
                if (lineItem.LineItemId == largestQuantityItem.LineItemId && lineItemsAmount < settleSubTotalExclTax)
                {
                    // Choose largestQuantityItem to make the unitPrice difference before and after recalculate smallest.
                    unitPrice = (settleSubTotalExclTax - amountWithoutLargestQtyItem) / largestQuantityItem.Quantity;

                    // Round up to make sure amount authorized >= requested for settlement amount.
                    unitPrice = merchantCurrency.Round(unitPrice + roundingDelta, DecimalDigit);
                }

                if (!isFirstLineItem)
                {
                    // If the lineitem price to add to the total exceed the Amount chosen
                    // for the payment. The line item price is adjusted, since it will be covered by other payment method.
                    if (unitPrice * lineItem.Quantity + order.Total > order.Amount)
                    {
                        var lineItemPrice = orderAmount - order.Total;

                        // If this is the last item, then we need to round up to make sure amount authorized >= requested for settlement amount.
                        if (lineItem.LineItemId == largestQuantityItem.LineItemId)
                        {
                            unitPrice = merchantCurrency.Round(lineItemPrice / lineItem.Quantity + roundingDelta, DecimalDigit);
                        }
                        else
                        {
                            unitPrice = merchantCurrency.Round(lineItemPrice / lineItem.Quantity, DecimalDigit);
                        }
                    }
                }

                // Note that order total calculated from authorized.net order constructor is recalculated by adding line items.
                order.AddLineItem(itemCode, displayName, description, itemQuantity, unitPrice, null);

                // We need to handle the case of first line item after being added to the order
                // since order total is recalculated when is added to the order.
                if (isFirstLineItem)
                {
                    // If with the first line item the amount chosen for the payment is exceeding
                    // the price added to the line item then should be the amount chosen.
                    if (order.Total > orderAmount)
                    {
                        // In case the order has only one line item, then we need to round up to make sure amount authorized >= requested for settlement amount.
                        if (lineItem.LineItemId == largestQuantityItem.LineItemId)
                        {
                            unitPrice = merchantCurrency.Round(settleSubTotalExclTax / lineItem.Quantity + roundingDelta, DecimalDigit);
                        }
                        else
                        {
                            unitPrice = merchantCurrency.Round(settleSubTotalExclTax / lineItem.Quantity, DecimalDigit);
                        }

                        order.RemoveLineItem(itemCode);
                        order.AddLineItem(itemCode, displayName, description, itemQuantity, unitPrice, null);
                    }
                }
                isFirstLineItem = false;
            }
            payment.Properties[AuthorizeTokenExGateway.ProviderProfileIdPropertyName] = customer.ProfileID;

            return(order);
        }