Exemple #1
0
        string subscriptionID  = String.Empty; // PayPal Standard

        protected void Page_Load(object sender, System.EventArgs e)
        {
            for (int i = 0; i < Request.Form.Count; i++)
            {
                string fValue = Server.UrlDecode(Request.Form[i]);

                switch (Request.Form.GetKey(i).ToLowerInvariant())
                {
                // Customer Variables
                case "payer_business_name": payer_business_name = fValue; break;

                case "residence_country": residence_country = fValue; break;

                case "business": business = fValue; break;

                case "receiver_id": receiver_id = fValue; break;

                case "receiver_email": receiver_email = fValue; break;

                case "payer_email": payer_email = fValue; break;

                case "payer_id": payer_id = fValue; break;

                case "payer_status": payer_status = fValue; break;

                case "payment_date": payment_date = fValue; break;

                case "payment_status": payment_status = fValue; break;

                case "payment_gross": payment_gross = fValue; break;

                case "auth_id": auth_id = fValue; break;

                case "first_name": first_name = fValue; break;

                case "last_name": last_name = fValue; break;

                case "num_cart_items": num_cart_items = fValue; break;

                case "txn_id": txn_id = fValue; break;

                case "receipt_id": receipt_id = fValue; break;

                case "test_ipn": test_ipn = fValue; break;

                case "custom": custom = fValue; break;

                case "invoice": invoice = fValue; break;

                case "memo": memo = fValue; break;

                case "address_name": address_name = fValue; break;

                case "address_street": address_street = fValue; break;

                case "address_city": address_city = fValue; break;

                case "address_state": address_state = fValue; break;

                case "address_zip": address_zip = fValue; break;

                case "address_country": address_country = fValue; break;

                case "address_status": address_status = fValue; break;

                case "pending_reason": pending_reason = fValue; break;

                case "subscr_id": subscriptionID = fValue; break;
                }
            }

            Response.CacheControl = "private";
            Response.Expires      = 0;
            Response.AddHeader("pragma", "no-cache");

            String PM = AppLogic.CleanPaymentMethod(AppLogic.ro_PMPayPal);

            AppLogic.ValidatePM(PM); // this WILL throw a hard security exception on any problem!

            Customer ThisCustomer = ((AspDotNetStorefrontPrincipal)Context.User).ThisCustomer;

            ThisCustomer.RequireCustomerRecord();

            int CustomerID = 0;

            try
            {
                CustomerID = int.Parse(custom);
            }
            catch { }

            if (ThisCustomer.CustomerID != CustomerID)
            {
                ThisCustomer = new Customer(CustomerID, true);
            }

            int OrderNumber = CommonLogic.QueryStringUSInt("OrderNumber");

            if (OrderNumber == 0)
            {
                OrderNumber = DB.GetSqlN("select max(ordernumber) N from orders where paymentmethod = '" + AppLogic.ro_PMPayPal + "' AND charindex(" + DB.SQuote(txn_id) + ",AuthorizationPNREF) > 0");
            }

            if (AppLogic.AppConfigBool("PayPal.UseInstantNotification") && OrderNumber == 0)
            { // try one more time after a pause to see if the IPN goes through
                Thread.Sleep(5000);
                OrderNumber = DB.GetSqlN("select max(ordernumber) N from orders where paymentmethod = '" + AppLogic.ro_PMPayPal + "' AND charindex(" + DB.SQuote(txn_id) + ",AuthorizationPNREF) > 0");
            }


            // The order could already exist if:
            // 1) AppConfigBool("PayPal.UseInstantNotification") = true
            // AND
            // 2) The Instant Payment Notification for this order already occurred
            if (OrderNumber == 0 || !Order.OrderExists(OrderNumber))
            {
                ShoppingCart cart = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);

                // Cart will be empty if order already processed by paypalnotification.aspx (Instant Payment Notification)
                if (!cart.IsEmpty())
                {
                    Address UseBillingAddress = new Address();
                    UseBillingAddress.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryBillingAddressID, AddressTypes.Billing);
                    UseBillingAddress.ClearCCInfo();
                    if (UseBillingAddress.PaymentMethodLastUsed != AppLogic.ro_PMPayPal && UseBillingAddress.PaymentMethodLastUsed != AppLogic.ro_PMPayPalEmbeddedCheckout)
                    {
                        try
                        {
                            AppLogic.ValidatePM(AppLogic.ro_PMPayPal);
                            UseBillingAddress.PaymentMethodLastUsed = AppLogic.ro_PMPayPal;
                        }
                        catch (Exception)
                        {
                            AppLogic.ValidatePM(AppLogic.ro_PMPayPalEmbeddedCheckout);
                            UseBillingAddress.PaymentMethodLastUsed = AppLogic.ro_PMPayPalEmbeddedCheckout;
                        }
                    }
                    UseBillingAddress.UpdateDB();

                    if (AppLogic.AppConfigBool("PayPal.RequireConfirmedAddress"))
                    {
                        Address ShippingAddress = new Address();

                        String[] StreetArray = address_street.Split(new string[1] {
                            "\r\n"
                        }, 2, StringSplitOptions.RemoveEmptyEntries);
                        String Address1 = String.Empty;
                        String Address2 = String.Empty;
                        if (StreetArray.Length > 1)
                        {
                            Address1 = StreetArray[0];
                            Address2 = StreetArray[1];
                        }
                        else
                        {
                            Address1 = address_street;
                        }
                        String[] NameArray = address_name.Split(new string[1] {
                            " "
                        }, 2, StringSplitOptions.RemoveEmptyEntries);
                        String FirstName = String.Empty;
                        String LastName  = String.Empty;
                        if (NameArray.Length > 1)
                        {
                            FirstName = NameArray[0];
                            LastName  = NameArray[1];
                        }
                        else
                        {
                            LastName = address_name;
                        }
                        string sql = String.Format("select top 1 AddressID as N from Address where Address1={0} and Address2={1} and City={2} and State={3} and Zip={4} and Country={5} and FirstName={6} and LastName={7} and CustomerID={8}",
                                                   DB.SQuote(Address1), DB.SQuote(Address2), DB.SQuote(address_city), DB.SQuote(address_state),
                                                   DB.SQuote(address_zip), DB.SQuote(address_country), DB.SQuote(FirstName), DB.SQuote(LastName), CustomerID);
                        int ExistingAddressID = DB.GetSqlN(sql);

                        if (ExistingAddressID == 0 || ThisCustomer.PrimaryShippingAddressID != ExistingAddressID)
                        {
                            string note      = "Note: Customer selected Ship-To address at PayPal.com";
                            string ordernote = DB.GetSqlS("select OrderNotes S from Customer where CustomerID=" + ThisCustomer.CustomerID.ToString());
                            if (!ordernote.Contains(note))
                            {
                                ordernote += System.Environment.NewLine + note;
                                DB.ExecuteSQL("update Customer set OrderNotes=" + DB.SQuote(ordernote) + " where CustomerID=" + ThisCustomer.CustomerID.ToString());
                            }
                        }

                        if (ExistingAddressID == 0)
                        { // Does not exist
                            ShippingAddress.CustomerID = CustomerID;
                            ShippingAddress.FirstName  = FirstName;
                            ShippingAddress.LastName   = LastName;
                            ShippingAddress.Address1   = Address1;
                            ShippingAddress.Address2   = Address2;
                            ShippingAddress.City       = address_city;
                            ShippingAddress.State      = address_state;
                            ShippingAddress.Zip        = address_zip;
                            ShippingAddress.Country    = address_country;
                            ShippingAddress.EMail      = payer_email;
                            ShippingAddress.InsertDB();

                            ShippingAddress.MakeCustomersPrimaryAddress(AddressTypes.Shipping);
                        }
                        else
                        { // Exists already
                            ShippingAddress.LoadFromDB(ExistingAddressID);
                            ShippingAddress.MakeCustomersPrimaryAddress(AddressTypes.Shipping);
                        }
                    }

                    // Reload customer and cart so that we have the addresses right
                    ThisCustomer = new Customer(CustomerID, true);
                    cart         = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);
                    if (!cart.IsEmpty())
                    {
                        if (OrderNumber == 0)
                        {
                            OrderNumber = AppLogic.GetNextOrderNumber();
                        }

                        decimal CartTotal = cart.Total(true);
                        decimal NetTotal  = CartTotal - CommonLogic.IIF(cart.Coupon.CouponType == CouponTypeEnum.GiftCard, CommonLogic.IIF(CartTotal < cart.Coupon.DiscountAmount, CartTotal, cart.Coupon.DiscountAmount), 0);
                        NetTotal = Localization.ParseNativeDecimal(Localization.CurrencyStringForGatewayWithoutExchangeRate(NetTotal));
                        decimal PaymentTotal = CommonLogic.FormNativeDecimal("mc_gross");

                        if (PaymentTotal == 0)
                        {
                            PaymentTotal = CommonLogic.FormNativeDecimal("mc_amount3");
                        }

                        try
                        {
                            //Process as AuthOnly first
                            String status = Gateway.MakeOrder(String.Empty, AppLogic.ro_TXModeAuthOnly, cart, OrderNumber, String.Empty, String.Empty, txn_id, string.Empty);

                            if (status == AppLogic.ro_OK)
                            { // Now, if paid for, process as Captured
                                String TransactionState = AspDotNetStorefrontGateways.Processors.PayPalController.GetTransactionState(payment_status, pending_reason);
                                if (TransactionState == AppLogic.ro_TXStateCaptured)
                                {
                                    Gateway.ProcessOrderAsCaptured(OrderNumber);
                                    DB.ExecuteSQL("update orders set AuthorizationPNREF=AuthorizationPNREF+" + DB.SQuote("|CAPTURE=" + txn_id) + " where OrderNumber=" + OrderNumber.ToString());
                                }
                                else if (TransactionState == AppLogic.ro_TXStatePending)
                                {
                                    DB.ExecuteSQL("update orders set TransactionState=" + DB.SQuote(AppLogic.ro_TXStatePending) + " where OrderNumber=" + OrderNumber.ToString());
                                }

                                if (subscriptionID.Length > 0)
                                {
                                    String         sql = "update orders set RecurringSubscriptionID = @SubscriptionID where OrderNumber = @OrderNumber";
                                    SqlParameter[] orderNumberParams = { new SqlParameter("@SubscriptionID", SqlDbType.NVarChar, 100)
                                                                         {
                                                                             Value = subscriptionID
                                                                         },                                  new SqlParameter("@OrderNumber", SqlDbType.Int)
                                                                         {
                                                                             Value = OrderNumber
                                                                         } };
                                    DB.ExecuteSQL(sql, orderNumberParams);

                                    OrderTransactionCollection ecRecurringOrderTransaction = new OrderTransactionCollection(OrderNumber);
                                    ecRecurringOrderTransaction.AddTransaction("PayPal Standard Checkout Subscription Profile Creation",
                                                                               string.Empty,
                                                                               string.Empty,
                                                                               string.Empty,
                                                                               subscriptionID,
                                                                               AppLogic.ro_PMPayPal,
                                                                               null,
                                                                               NetTotal);
                                }
                            }

                            // The incoming payment should match the cart total, if they don't
                            // the customer may have tampered with the cart to cheat, so flag as fraud
                            // but keep new so the admin will have to review the order.
                            if (Math.Abs(NetTotal - PaymentTotal) > 0.05M) // allow 0.05 descrepency to allow minor rounding errors
                            {
                                Order.MarkOrderAsFraud(OrderNumber, true);
                                DB.ExecuteSQL("update orders set FraudedOn=getdate(), IsNew=1 where OrderNumber=" + OrderNumber.ToString());
                            }
                        }
                        catch // if we failed, did the IPN come back at the same time?
                        {
                            cart = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);
                            if (cart.IsEmpty())
                            {
                                OrderNumber = DB.GetSqlN("select MAX(OrderNumber) N from dbo.orders where CustomerID = " + CustomerID.ToString());
                            }
                        }
                    }
                    else
                    {
                        OrderNumber = DB.GetSqlN("select MAX(OrderNumber) N from dbo.orders where CustomerID = " + CustomerID.ToString());
                    }
                }
                else
                {
                    OrderNumber = DB.GetSqlN("select MAX(OrderNumber) N from dbo.orders where CustomerID = " + CustomerID.ToString());
                }
            }

            Response.Redirect("orderconfirmation.aspx?ordernumber=" + OrderNumber.ToString() + "&paymentmethod=PayPal");
        }
Exemple #2
0
        public override string RecurringBillingCreateSubscription(String SubscriptionDescription, Customer ThisCustomer, Address UseBillingAddress, Address UseShippingAddress, Decimal RecurringAmount, DateTime StartDate, int RecurringInterval, DateIntervalTypeEnum RecurringIntervalType, int OriginalRecurringOrderNumber, string XID, IDictionary <string, string> TransactionContext, out String RecurringSubscriptionID, out String RecurringSubscriptionCommand, out String RecurringSubscriptionResult)
        {
            string result = string.Empty;

            try
            {
                //Re-Use the Internal Gateway Recurring Billing logic for calculating how much of the order is recurring
                ShoppingCart recurringCart = new ShoppingCart(ThisCustomer.SkinID, ThisCustomer, CartTypeEnum.RecurringCart, OriginalRecurringOrderNumber, false);

                CreditCardDetailsType creditCard = new CreditCardDetailsType();

                if (UseBillingAddress.CardNumber != null && UseBillingAddress.CardNumber.Length > 0)
                {
                    creditCard.CreditCardNumber  = UseBillingAddress.CardNumber;
                    creditCard.ExpMonth          = Localization.ParseUSInt(UseBillingAddress.CardExpirationMonth);
                    creditCard.ExpYear           = Localization.ParseUSInt(UseBillingAddress.CardExpirationYear);
                    creditCard.ExpMonthSpecified = true;
                    creditCard.ExpYearSpecified  = true;
                    creditCard.CVV2 = XID;

                    if (UseBillingAddress.CardType == "AmericanExpress")
                    {
                        creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), "Amex", true);
                    }
                    else
                    {
                        creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), UseBillingAddress.CardType, true);
                    }
                    creditCard.CreditCardTypeSpecified = true;
                }
                else
                {
                    creditCard.CreditCardTypeSpecified = false;
                }

                BasicAmountType recurringAmount = new BasicAmountType();
                recurringAmount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
                recurringAmount.Value      = RecurringAmount.ToString();

                DateIntervalTypeEnum recurringIntervalType = recurringCart.CartItems[0].RecurringIntervalType;                 //We currently only support 1 interval per recurring order, so grabbing the first as a default should be safe
                int recurringInterval = recurringCart.CartItems[0].RecurringInterval;

                BillingPeriodDetailsType billingPeriodDetails = PayPalController.GetECRecurringPeriodDetails(recurringIntervalType, recurringInterval);
                billingPeriodDetails.Amount = recurringAmount;
                billingPeriodDetails.TotalBillingCyclesSpecified = false;

                ScheduleDetailsType scheduleDetails = new ScheduleDetailsType();
                scheduleDetails.Description                        = string.Format("Recurring order created on {0} from {1}", System.DateTime.Now.ToShortDateString(), AppLogic.AppConfig("StoreName"));
                scheduleDetails.MaxFailedPayments                  = 0;
                scheduleDetails.MaxFailedPaymentsSpecified         = true;
                scheduleDetails.AutoBillOutstandingAmount          = AutoBillType.NoAutoBill;
                scheduleDetails.AutoBillOutstandingAmountSpecified = true;
                scheduleDetails.PaymentPeriod                      = billingPeriodDetails;

                RecurringPaymentsProfileDetailsType profileDetails = new RecurringPaymentsProfileDetailsType();
                profileDetails.SubscriberName   = ThisCustomer.FirstName + " " + ThisCustomer.LastName;
                profileDetails.BillingStartDate = StartDate;

                CreateRecurringPaymentsProfileRequestDetailsType profileRequestDetails = new CreateRecurringPaymentsProfileRequestDetailsType();
                profileRequestDetails.ScheduleDetails = scheduleDetails;
                profileRequestDetails.RecurringPaymentsProfileDetails = profileDetails;
                profileRequestDetails.CreditCard = creditCard;

                if (!(UseBillingAddress.CardNumber != null && UseBillingAddress.CardNumber.Length > 0))
                {
                    profileRequestDetails.Token = XID;
                }

                if (recurringCart.IsAllDownloadComponents())
                {
                    PaymentDetailsItemType paymentDetailsItem = new PaymentDetailsItemType();
                    paymentDetailsItem.ItemCategory          = ItemCategoryType.Digital;
                    paymentDetailsItem.ItemCategorySpecified = true;

                    List <PaymentDetailsItemType> paymentDetailsList = new List <PaymentDetailsItemType>();
                    paymentDetailsList.Add(paymentDetailsItem);

                    profileRequestDetails.PaymentDetailsItem = paymentDetailsList.ToArray();
                }

                CreateRecurringPaymentsProfileRequestType profileRequest = new CreateRecurringPaymentsProfileRequestType();
                profileRequest.Version = API_VER;
                profileRequest.CreateRecurringPaymentsProfileRequestDetails = profileRequestDetails;

                CreateRecurringPaymentsProfileReq request = new CreateRecurringPaymentsProfileReq();
                request.CreateRecurringPaymentsProfileRequest = profileRequest;

                CreateRecurringPaymentsProfileResponseType profileResponse = new CreateRecurringPaymentsProfileResponseType();
                profileResponse = IPayPal.CreateRecurringPaymentsProfile(request);

                if (profileResponse != null && profileResponse.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    if (profileResponse.Errors != null)
                    {
                        bool first = true;
                        for (int ix = 0; ix < profileResponse.Errors.Length; ix++)
                        {
                            if (!first)
                            {
                                result += ", ";
                            }
                            result += profileResponse.Errors[ix].LongMessage;
                            first   = false;
                        }
                    }
                }

                RecurringSubscriptionID      = (profileResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID == null ? "No ProfileID provided" : profileResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID);
                RecurringSubscriptionCommand = string.Empty;
                RecurringSubscriptionResult  = (profileResponse.CreateRecurringPaymentsProfileResponseDetails.DCCProcessorResponse == null ? "No response provided" : profileResponse.CreateRecurringPaymentsProfileResponseDetails.DCCProcessorResponse);

                //Log the transaction
                OrderTransactionCollection ecRecurringOrderTransaction = new OrderTransactionCollection(OriginalRecurringOrderNumber);
                ecRecurringOrderTransaction.AddTransaction("PayPal Express Checkout Recurring Profile Creation",
                                                           request.ToString(),
                                                           result,
                                                           string.Empty,
                                                           (profileResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID == null ? "No ProfileID provided" : profileResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID),
                                                           AppLogic.ro_PMPayPalExpress,
                                                           null,
                                                           RecurringAmount);
            }
            catch
            {
                result = "Recurring Profile Creation Failed.";
                RecurringSubscriptionID      = string.Empty;
                RecurringSubscriptionCommand = string.Empty;
                RecurringSubscriptionResult  = result;
            }
            return(result);
        }
Exemple #3
0
        public static String MakeECRecurringProfile(ShoppingCart cart, int orderNumber, String payPalToken, String payerID, DateTime nextRecurringShipDate)
        {
            PayPalAPISoapBinding   IPayPalRefund;
            PayPalAPIAASoapBinding IPayPal;

            PayPalController.GetPaypalRequirements(out IPayPalRefund, out IPayPal);
            String result = String.Empty;

            CreateRecurringPaymentsProfileReq                ECRecurringRequest  = new CreateRecurringPaymentsProfileReq();
            CreateRecurringPaymentsProfileRequestType        varECRequest        = new CreateRecurringPaymentsProfileRequestType();
            CreateRecurringPaymentsProfileRequestDetailsType varECRequestDetails = new CreateRecurringPaymentsProfileRequestDetailsType();
            CreateRecurringPaymentsProfileResponseType       ECRecurringResponse = new CreateRecurringPaymentsProfileResponseType();

            //Re-Use the Internal Gateway Recurring Billing logic for calculating how much of the order is recurring
            ShoppingCart cartRecur       = new ShoppingCart(cart.ThisCustomer.SkinID, cart.ThisCustomer, CartTypeEnum.RecurringCart, orderNumber, false);
            Decimal      CartTotalRecur  = Decimal.Round(cartRecur.Total(true), 2, MidpointRounding.AwayFromZero);
            Decimal      RecurringAmount = CartTotalRecur - CommonLogic.IIF(cartRecur.Coupon.CouponType == CouponTypeEnum.GiftCard, CommonLogic.IIF(CartTotalRecur < cartRecur.Coupon.DiscountAmount, CartTotalRecur, cartRecur.Coupon.DiscountAmount), 0);

            DateIntervalTypeEnum ecRecurringIntervalType = cartRecur.CartItems[0].RecurringIntervalType;                //We currently only support 1 interval per recurring order, so grabbing the first as a default should be safe
            int ecRecurringInterval = cartRecur.CartItems[0].RecurringInterval;

            BasicAmountType ecRecurringAmount = new BasicAmountType();

            ecRecurringAmount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
            ecRecurringAmount.Value      = RecurringAmount.ToString();

            BillingPeriodDetailsType varECSchedulePaymentDetails = GetECRecurringPeriodDetails(ecRecurringIntervalType, ecRecurringInterval);

            varECSchedulePaymentDetails.Amount = ecRecurringAmount;
            varECSchedulePaymentDetails.TotalBillingCyclesSpecified = false;

            ScheduleDetailsType varECSchedule = new ScheduleDetailsType();

            //Need a better description, but it must match the one sent in StartEC
            varECSchedule.Description                        = "Recurring order created on " + System.DateTime.Now.ToShortDateString() + " from " + AppLogic.AppConfig("StoreName");
            varECSchedule.MaxFailedPayments                  = 0; //Cancel the order if a recurrence fails
            varECSchedule.MaxFailedPaymentsSpecified         = true;
            varECSchedule.AutoBillOutstandingAmount          = AutoBillType.NoAutoBill;
            varECSchedule.AutoBillOutstandingAmountSpecified = true;
            varECSchedule.PaymentPeriod                      = varECSchedulePaymentDetails;

            RecurringPaymentsProfileDetailsType varECProfileDetails = new RecurringPaymentsProfileDetailsType();

            varECProfileDetails.SubscriberName   = cart.ThisCustomer.FirstName + " " + cart.ThisCustomer.LastName;
            varECProfileDetails.BillingStartDate = nextRecurringShipDate;

            varECRequestDetails.ScheduleDetails = varECSchedule;
            varECRequestDetails.Token           = payPalToken;
            varECRequestDetails.RecurringPaymentsProfileDetails = varECProfileDetails;

            if (cart.IsAllDownloadComponents())
            {
                PaymentDetailsItemType varECPaymentDetails = new PaymentDetailsItemType();
                varECPaymentDetails.ItemCategory          = ItemCategoryType.Digital;
                varECPaymentDetails.ItemCategorySpecified = true;

                List <PaymentDetailsItemType> ECPaymentDetailsList = new List <PaymentDetailsItemType>();

                ECPaymentDetailsList.Add(varECPaymentDetails);

                varECRequestDetails.PaymentDetailsItem = ECPaymentDetailsList.ToArray();
            }

            varECRequest.Version = API_VER;
            varECRequest.CreateRecurringPaymentsProfileRequestDetails = varECRequestDetails;

            ECRecurringRequest.CreateRecurringPaymentsProfileRequest = varECRequest;

            ECRecurringResponse = IPayPal.CreateRecurringPaymentsProfile(ECRecurringRequest);

            if (ECRecurringResponse.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                if (ECRecurringResponse.Errors != null)
                {
                    bool first = true;
                    for (int ix = 0; ix < ECRecurringResponse.Errors.Length; ix++)
                    {
                        if (!first)
                        {
                            result += ", ";
                        }
                        result += ECRecurringResponse.Errors[ix].LongMessage;
                        first   = false;
                    }
                }
            }

            //Log the transaction
            OrderTransactionCollection ecRecurringOrderTransaction = new OrderTransactionCollection(orderNumber);

            ecRecurringOrderTransaction.AddTransaction("PayPal Express Checkout Recurring Profile Creation",
                                                       ECRecurringRequest.ToString(),
                                                       result,
                                                       payerID,                                                                                                                                                                                       //PNREF = payerID
                                                       (ECRecurringResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID == null ? "No ProfileID provided" : ECRecurringResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID), //Code = ProfileID
                                                       AppLogic.ro_PMPayPalExpress,
                                                       null,
                                                       RecurringAmount);

            return(result);
        }
Exemple #4
0
        public ActionResult Index(FormCollection collection)
        {
            SysLog.LogMessage(
                message: "Received a recurring payment notification from PayPal Express.",
                details: Gateway.ListFormCollectionKeyValuePairs(collection),
                messageType: MessageTypeEnum.Informational,
                messageSeverity: MessageSeverityEnum.Alert);

            if (!PostIsValid())
            {
                return(Content(string.Empty));
            }

            var paymentStatus       = collection["payment_status"] ?? string.Empty;
            var transactionId       = collection["txn_id"] ?? string.Empty;
            var pendingReason       = collection["pending_reason"] ?? string.Empty;
            var parentTransactionId = collection["parent_txn_id"] ?? string.Empty;
            var transactionType     = collection["txn_type"] ?? string.Empty;
            var payerId             = collection["payer_id"] ?? string.Empty;
            var profileId           = collection["recurring_payment_id"] ?? string.Empty;
            var subscriptionId      = collection["subscr_id"] ?? string.Empty;
            var paymentTotal        = CommonLogic.FormNativeDecimal("mc_gross");

            //Recurring notification
            if (transactionType.ToLowerInvariant().Contains("recurring") ||
                transactionType.ToLowerInvariant().Contains("subscr_cancel"))
            {
                HandlePayPalExpressCheckoutRecurringNotification(transactionType, payerId, profileId, subscriptionId);
            }

            // Normal notification
            var transactionState    = PayPalController.GetTransactionState(paymentStatus, pendingReason);
            var existingOrderNumber = GetPPECOriginalOrderNumber(profileId, subscriptionId);

            if (existingOrderNumber > 0 && !Order.OrderExists(existingOrderNumber))
            {
                existingOrderNumber = 0;
            }

            if (existingOrderNumber == 0)               //Was it a PayPal Express order?
            {
                existingOrderNumber = DB.GetSqlN(
                    string.Format("SELECT MIN(OrderNumber) N FROM Orders WHERE (PaymentMethod = '{0}') AND CHARINDEX({1}, AuthorizationPNREF) > 0",
                                  AppLogic.ro_PMPayPalExpress,
                                  string.IsNullOrEmpty(parentTransactionId)
                                                ? DB.SQuote(transactionId)
                                                : DB.SQuote(parentTransactionId)));
            }

            if (existingOrderNumber == 0)            //Last try - look up by paypal payments advanced checkout transaction
            {
                if (!string.IsNullOrEmpty(parentTransactionId))
                {
                    existingOrderNumber = OrderTransaction.LookupOrderNumber(null, null, null, null, parentTransactionId, null, null);
                }
                else if (!string.IsNullOrEmpty(transactionId))
                {
                    existingOrderNumber = OrderTransaction.LookupOrderNumber(null, null, null, null, transactionId, null, null);
                }
            }

            if (existingOrderNumber == 0)
            {
                return(Content(string.Empty));
            }

            if (transactionState == AppLogic.ro_TXStateVoided)
            {
                VoidPPOrder(existingOrderNumber);
            }
            else if (transactionState == AppLogic.ro_TXStateCaptured)
            {
                CapturePPOrder(existingOrderNumber, transactionId, paymentTotal);
            }
            else if (transactionState == AppLogic.ro_TXStateRefunded)
            {
                RefundPPOrder(existingOrderNumber, transactionId, paymentTotal);
            }
            else if (transactionState == AppLogic.ro_TXStatePending)
            {
                DB.ExecuteSQL(string.Format("UPDATE Orders SET CapturedOn = NULL, TransactionState = {0} WHERE OrderNumber = {1}", DB.SQuote(AppLogic.ro_TXStatePending), existingOrderNumber));
            }

            OrderTransactionCollection transactions = new OrderTransactionCollection(existingOrderNumber);

            transactions.AddTransaction(transactionState, null, null, null, transactionId, AppLogic.ro_PMPayPalExpress + " IPN", null, paymentTotal);

            return(Content(string.Empty));
        }
        string subscriptionID  = String.Empty; // PayPal Standard

        private void Page_Load(object sender, System.EventArgs e)
        {
            //String postData = String.IsNullOrEmpty(Request.Form.ToString()) ? Request.QueryString.ToString() : Request.Form.ToString();
            //SysLog.LogMessage("Paypal notification posted to.", postData, MessageTypeEnum.Informational, MessageSeverityEnum.Alert);

            for (int i = 0; i < Request.Form.Count; i++)
            {
                string fValue = Server.UrlDecode(Request.Form[i]);

                switch (Request.Form.GetKey(i).ToLowerInvariant())
                {
                // Customer Variables
                case "payment_status": payment_status = fValue; break;

                case "txn_id": txn_id = fValue; break;

                case "custom": custom = fValue; break;

                case "invoice": invoice = fValue; break;

                case "pending_reason": pending_reason = fValue; break;

                case "address_name": address_name = fValue; break;

                case "address_street": address_street = fValue; break;

                case "address_city": address_city = fValue; break;

                case "address_state": address_state = fValue; break;

                case "address_zip": address_zip = fValue; break;

                case "address_country": address_country = fValue; break;

                case "payer_email": payer_email = fValue; break;

                case "parent_txn_id": parent_txn_id = fValue; break;

                case "txn_type": txn_type = fValue; break;

                case "payer_id": payerID = fValue; break;

                case "recurring_payment_id": profileID = fValue; break;

                case "subscr_id": subscriptionID = fValue; break;
                }
            }

            // PayPal Express Checkout recurring notification
            if (txn_type.ToLowerInvariant().Contains("recurring") || txn_type.ToLowerInvariant().Contains("subscr_cancel") && PostIsValid())
            {
                HandlePayPalExpressCheckoutRecurringNotification();
            }

            // Non-recurring notification
            int CustomerID = Localization.ParseNativeInt(custom);

            if (CustomerID > 0 && PostIsValid())
            {
                String status = AppLogic.ro_OK;

                String TransactionState = AspDotNetStorefrontGateways.Processors.PayPalController.GetTransactionState(payment_status, pending_reason);

                int ExistingOrderNumber = Localization.ParseNativeInt(invoice);

                if (ExistingOrderNumber > 0 && !Order.OrderExists(ExistingOrderNumber))
                { // It only is existing if it exists.
                    ExistingOrderNumber = 0;
                }

                if (ExistingOrderNumber == 0)
                {
                    if (!String.IsNullOrEmpty(parent_txn_id))
                    {
                        ExistingOrderNumber = DB.GetSqlN("select min(ordernumber) N from orders where (paymentmethod = '" + AppLogic.ro_PMPayPal + "' OR paymentmethod = '" + AppLogic.ro_PMPayPalEmbeddedCheckout + "') AND charindex(" + DB.SQuote(parent_txn_id) + ",AuthorizationPNREF) > 0");
                    }
                    else
                    {
                        ExistingOrderNumber = DB.GetSqlN("select min(ordernumber) N from orders where (paymentmethod = '" + AppLogic.ro_PMPayPal + "' OR paymentmethod = '" + AppLogic.ro_PMPayPalEmbeddedCheckout + "') AND charindex(" + DB.SQuote(txn_id) + ",AuthorizationPNREF) > 0");
                    }
                }

                if (ExistingOrderNumber == 0) //last try - look up by paypal payments advanced checkout transaction
                {
                    if (!String.IsNullOrEmpty(parent_txn_id))
                    {
                        ExistingOrderNumber = OrderTransaction.LookupOrderNumber(null, null, null, null, parent_txn_id, null, null);
                    }
                    else if (!String.IsNullOrEmpty(txn_id))
                    {
                        ExistingOrderNumber = OrderTransaction.LookupOrderNumber(null, null, null, null, txn_id, null, null);
                    }
                }

                // Order won't exist yet if they never followed the link from paypal back to the store.
                if (ExistingOrderNumber == 0)
                {
                    if (TransactionState == AppLogic.ro_TXStateAuthorized ||
                        TransactionState == AppLogic.ro_TXStatePending ||
                        TransactionState == AppLogic.ro_TXStateCaptured)
                    {
                        Customer     ThisCustomer = new Customer(CustomerID, true);
                        ShoppingCart cart         = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);



                        // Cart will be empty if order already processed by paypalok.aspx
                        if (!cart.IsEmpty())
                        {
                            Address UseBillingAddress = new Address();
                            UseBillingAddress.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryBillingAddressID, AddressTypes.Billing);
                            UseBillingAddress.ClearCCInfo();
                            if (UseBillingAddress.PaymentMethodLastUsed != AppLogic.ro_PMPayPal && UseBillingAddress.PaymentMethodLastUsed != AppLogic.ro_PMPayPalEmbeddedCheckout)
                            {
                                try
                                {
                                    AppLogic.ValidatePM(AppLogic.ro_PMPayPal);
                                    UseBillingAddress.PaymentMethodLastUsed = AppLogic.ro_PMPayPal;
                                }
                                catch (Exception)
                                {
                                    AppLogic.ValidatePM(AppLogic.ro_PMPayPalEmbeddedCheckout);
                                    UseBillingAddress.PaymentMethodLastUsed = AppLogic.ro_PMPayPalEmbeddedCheckout;
                                }
                            }
                            UseBillingAddress.UpdateDB();

                            if (AppLogic.AppConfigBool("PayPal.RequireConfirmedAddress"))
                            {
                                Address ShippingAddress = new Address();

                                String[] StreetArray = address_street.Split(new string[1] {
                                    "\r\n"
                                }, 2, StringSplitOptions.RemoveEmptyEntries);
                                String Address1 = String.Empty;
                                String Address2 = String.Empty;
                                if (StreetArray.Length > 1)
                                {
                                    Address1 = StreetArray[0];
                                    Address2 = StreetArray[1];
                                }
                                else
                                {
                                    Address1 = address_street;
                                }
                                String[] NameArray = address_name.Split(new string[1] {
                                    " "
                                }, 2, StringSplitOptions.RemoveEmptyEntries);
                                String FirstName = String.Empty;
                                String LastName  = String.Empty;
                                if (NameArray.Length > 1)
                                {
                                    FirstName = NameArray[0];
                                    LastName  = NameArray[1];
                                }
                                else
                                {
                                    LastName = address_name;
                                }
                                string sql = String.Format("select top 1 AddressID as N from Address where Address1={0} and Address2={1} and City={2} and State={3} and Zip={4} and Country={5} and FirstName={6} and LastName={7} and CustomerID={8}",
                                                           DB.SQuote(Address1), DB.SQuote(Address2), DB.SQuote(address_city), DB.SQuote(address_state),
                                                           DB.SQuote(address_zip), DB.SQuote(address_country), DB.SQuote(FirstName), DB.SQuote(LastName), CustomerID);
                                int ExistingAddressID = DB.GetSqlN(sql);

                                if (ExistingAddressID == 0 || ThisCustomer.PrimaryShippingAddressID != ExistingAddressID)
                                {
                                    string note      = "Note: Customer selected Ship-To address at PayPal.com";
                                    string ordernote = DB.GetSqlS("select OrderNotes S from Customer where CustomerID=" + ThisCustomer.CustomerID.ToString());
                                    if (!ordernote.Contains(note))
                                    {
                                        ordernote += System.Environment.NewLine + note;
                                        DB.ExecuteSQL("update Customer set OrderNotes=" + DB.SQuote(ordernote) + " where CustomerID=" + ThisCustomer.CustomerID.ToString());
                                    }
                                }

                                if (ExistingAddressID == 0)
                                { // Does not exist
                                    ShippingAddress.CustomerID = CustomerID;
                                    ShippingAddress.FirstName  = FirstName;
                                    ShippingAddress.LastName   = LastName;
                                    ShippingAddress.Address1   = Address1;
                                    ShippingAddress.Address2   = Address2;
                                    ShippingAddress.City       = address_city;
                                    ShippingAddress.State      = address_state;
                                    ShippingAddress.Zip        = address_zip;
                                    ShippingAddress.Country    = address_country;
                                    ShippingAddress.EMail      = payer_email;
                                    ShippingAddress.InsertDB();

                                    ShippingAddress.MakeCustomersPrimaryAddress(AddressTypes.Shipping);
                                }
                                else
                                { // Exists already
                                    ShippingAddress.LoadFromDB(ExistingAddressID);
                                    ShippingAddress.MakeCustomersPrimaryAddress(AddressTypes.Shipping);
                                }
                            }

                            // Reload customer and cart so that we have the addresses right
                            ThisCustomer = new Customer(CustomerID, true);
                            cart         = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);
                            decimal CartTotal = cart.Total(true);
                            decimal NetTotal  = CartTotal - CommonLogic.IIF(cart.Coupon.CouponType == CouponTypeEnum.GiftCard, CommonLogic.IIF(CartTotal < cart.Coupon.DiscountAmount, CartTotal, cart.Coupon.DiscountAmount), 0);
                            NetTotal = Localization.ParseNativeDecimal(Localization.CurrencyStringForGatewayWithoutExchangeRate(NetTotal));
                            decimal PaymentTotal = CommonLogic.FormNativeDecimal("mc_gross");

                            // Cart will be empty if order already processed by paypalok.aspx
                            if (!cart.IsEmpty() && NetTotal > 0.0M)
                            {
                                //Process as AuthOnly first
                                int OrderNumber = AppLogic.GetNextOrderNumber();
                                status = Gateway.MakeOrder(String.Empty, AppLogic.ro_TXModeAuthOnly, cart, OrderNumber, String.Empty, String.Empty, txn_id, String.Empty);

                                if (status == AppLogic.ro_OK)
                                {
                                    if (subscriptionID.Length > 0)
                                    {
                                        String         sql = "update orders set RecurringSubscriptionID = @SubscriptionID where OrderNumber = @OrderNumber";
                                        SqlParameter[] orderNumberParams = { new SqlParameter("@SubscriptionID", SqlDbType.NVarChar, 100)
                                                                             {
                                                                                 Value = subscriptionID
                                                                             },                                  new SqlParameter("@OrderNumber", SqlDbType.Int)
                                                                             {
                                                                                 Value = OrderNumber
                                                                             } };
                                        DB.ExecuteSQL(sql, orderNumberParams);

                                        OrderTransactionCollection ecRecurringOrderTransaction = new OrderTransactionCollection(OrderNumber);
                                        ecRecurringOrderTransaction.AddTransaction("PayPal Standard Checkout Subscription Profile Creation",
                                                                                   string.Empty,
                                                                                   string.Empty,
                                                                                   string.Empty,
                                                                                   subscriptionID,
                                                                                   AppLogic.ro_PMPayPal,
                                                                                   null,
                                                                                   NetTotal);
                                    }

                                    if (TransactionState == AppLogic.ro_TXStateCaptured)
                                    { // Now, if paid for, process as Captured
                                        Gateway.ProcessOrderAsCaptured(OrderNumber);
                                        DB.ExecuteSQL("update orders set AuthorizationPNREF=AuthorizationPNREF+" + DB.SQuote("|CAPTURE=" + txn_id) + " where OrderNumber=" + OrderNumber.ToString());
                                    }
                                    else if (TransactionState == AppLogic.ro_TXStatePending)
                                    {
                                        DB.ExecuteSQL("update orders set TransactionState=" + DB.SQuote(AppLogic.ro_TXStatePending) + " where OrderNumber=" + OrderNumber.ToString());
                                    }
                                }

                                // The incoming payment should match the cart total, if they don't
                                // the customer may have tampered with the cart to cheat, so flag as fraud
                                // but keep new so the admin will have to review the order.
                                if (Math.Abs(NetTotal - PaymentTotal) > 0.05M) // allow 0.05 descrepency to allow minor rounding errors
                                {
                                    Order.MarkOrderAsFraud(OrderNumber, true);
                                    DB.ExecuteSQL("update orders set FraudedOn=getdate(), IsNew=1 where OrderNumber=" + OrderNumber.ToString());
                                }
                                else
                                {
                                    // Finalize the order here since they may never click through to orderconfirmation.aspx
                                    Order  ord = new Order(OrderNumber, ThisCustomer.LocaleSetting);
                                    String PM  = AppLogic.CleanPaymentMethod(ord.PaymentMethod);
                                    if (!ord.AlreadyConfirmed)
                                    {
                                        DB.ExecuteSQL("update Customer set OrderOptions=NULL, OrderNotes=NULL, FinalizationData=NULL where CustomerID=" + CustomerID.ToString());

                                        if (ord.TransactionIsCaptured() && ord.HasGiftRegistryComponents())
                                        {
                                            ord.FinalizeGiftRegistryComponents();
                                        }
                                        AppLogic.SendOrderEMail(ThisCustomer, OrderNumber, false, PM, true, null, null);
                                        DB.ExecuteSQL("Update Orders set AlreadyConfirmed=1 where OrderNumber=" + OrderNumber.ToString());
                                    }
                                }
                            }
                        }
                    }
                }
                else  // we have an existing order
                {
                    if (TransactionState == AppLogic.ro_TXStateVoided)
                    {
                        IPNVoid(ExistingOrderNumber);
                    }
                    else if (TransactionState == AppLogic.ro_TXStateCaptured)
                    {
                        IPNCapture(ExistingOrderNumber, txn_id, CommonLogic.FormNativeDecimal("mc_gross"));
                    }
                    else if (TransactionState == AppLogic.ro_TXStateRefunded)
                    {
                        IPNRefund(ExistingOrderNumber, txn_id, CommonLogic.FormNativeDecimal("mc_gross"));
                    }
                    else if (TransactionState == AppLogic.ro_TXStatePending)
                    { // eChecks could have had the order placed in Captured state with Express Checkout
                        DB.ExecuteSQL("update orders set CapturedOn=NULL, TransactionState=" + DB.SQuote(AppLogic.ro_TXStatePending) + " where OrderNumber=" + ExistingOrderNumber.ToString());
                    }

                    OrderTransactionCollection transactions = new OrderTransactionCollection(ExistingOrderNumber);
                    transactions.AddTransaction(TransactionState, null, null, null, txn_id, AppLogic.ro_PMPayPal + " IPN", null, CommonLogic.FormNativeDecimal("mc_gross"));
                }
            }
        }
Exemple #6
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            for (int i = 0; i < Request.Form.Count; i++)
            {
                string fValue = Server.UrlDecode(Request.Form[i]);

                switch (Request.Form.GetKey(i).ToLowerInvariant())
                {
                // Customer Variables
                case "payment_status": payment_status = fValue; break;

                case "txn_id": txn_id = fValue; break;

                case "custom": custom = fValue; break;

                case "invoice": invoice = fValue; break;

                case "pending_reason": pending_reason = fValue; break;

                case "address_name": address_name = fValue; break;

                case "address_street": address_street = fValue; break;

                case "address_city": address_city = fValue; break;

                case "address_state": address_state = fValue; break;

                case "address_zip": address_zip = fValue; break;

                case "address_country": address_country = fValue; break;

                case "payer_email": payer_email = fValue; break;

                case "parent_txn_id": parent_txn_id = fValue; break;
                }
            }

            int CustomerID = Localization.ParseNativeInt(custom);

            if (CustomerID > 0)
            {
                //Validate the post by querying PayPal
                byte[] param   = Request.BinaryRead(Request.ContentLength);
                string formStr = Encoding.ASCII.GetString(param);
                formStr += "&cmd=_notify-validate";

                string verify_url = String.Empty;

                if (AppLogic.AppConfigBool("UseLiveTransactions"))
                {
                    verify_url = AppLogic.AppConfig("PayPal.LiveServer");
                }
                else
                {
                    verify_url = AppLogic.AppConfig("PayPal.TestServer");
                }

                byte[] data = Encoding.ASCII.GetBytes(formStr);

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(verify_url);
                webRequest.Method        = "POST";
                webRequest.ContentType   = "application/x-www-form-urlencoded";
                webRequest.ContentLength = data.Length;

                Stream reqStream = webRequest.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();

                WebResponse webResponse;
                string      rawResponse = String.Empty;
                try
                {
                    webResponse = webRequest.GetResponse();
                    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                    rawResponse = sr.ReadToEnd();
                    sr.Close();
                    webResponse.Close();
                }
                catch (Exception exc)
                {
                    Response.Write("Error connecting with gateway. Please try again later.");
                    err_msg += exc.Message + "\n\n";
                }

                if (rawResponse.Equals("VERIFIED", StringComparison.InvariantCultureIgnoreCase))
                {
                    String status = AppLogic.ro_OK;

                    String TransactionState = AspDotNetStorefrontGateways.Processors.PayPalController.GetTransactionState(payment_status, pending_reason);

                    int ExistingOrderNumber = Localization.ParseNativeInt(invoice);

                    if (ExistingOrderNumber > 0 && !Order.OrderExists(ExistingOrderNumber))
                    { // It only is existing if it exists.
                        ExistingOrderNumber = 0;
                    }

                    if (ExistingOrderNumber == 0)
                    {
                        if (!String.IsNullOrEmpty(parent_txn_id))
                        {
                            ExistingOrderNumber = DB.GetSqlN("select min(ordernumber) N from orders where (paymentmethod = '" + AppLogic.ro_PMPayPal + "' OR paymentmethod = '" + AppLogic.ro_PMPayPalEmbeddedCheckout + "') AND charindex(" + DB.SQuote(parent_txn_id) + ",AuthorizationPNREF) > 0");
                        }
                        else
                        {
                            ExistingOrderNumber = DB.GetSqlN("select min(ordernumber) N from orders where (paymentmethod = '" + AppLogic.ro_PMPayPal + "' OR paymentmethod = '" + AppLogic.ro_PMPayPalEmbeddedCheckout + "') AND charindex(" + DB.SQuote(txn_id) + ",AuthorizationPNREF) > 0");
                        }
                    }

                    if (ExistingOrderNumber == 0) //last try - look up by paypal embedded checkout transaction
                    {
                        if (!String.IsNullOrEmpty(parent_txn_id))
                        {
                            ExistingOrderNumber = OrderTransaction.LookupOrderNumber(null, null, null, null, parent_txn_id, null, null);
                        }
                        else if (!String.IsNullOrEmpty(txn_id))
                        {
                            ExistingOrderNumber = OrderTransaction.LookupOrderNumber(null, null, null, null, txn_id, null, null);
                        }
                    }

                    // Order won't exist yet if they never followed the link from paypal back to the store.
                    if (ExistingOrderNumber == 0)
                    {
                        if (TransactionState == AppLogic.ro_TXStateAuthorized ||
                            TransactionState == AppLogic.ro_TXStatePending ||
                            TransactionState == AppLogic.ro_TXStateCaptured)
                        {
                            Customer     ThisCustomer = new Customer(CustomerID, true);
                            ShoppingCart cart         = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);



                            // Cart will be empty if order already processed by paypalok.aspx
                            if (!cart.IsEmpty())
                            {
                                Address UseBillingAddress = new Address();
                                UseBillingAddress.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryBillingAddressID, AddressTypes.Billing);
                                UseBillingAddress.ClearCCInfo();
                                if (UseBillingAddress.PaymentMethodLastUsed != AppLogic.ro_PMPayPal && UseBillingAddress.PaymentMethodLastUsed != AppLogic.ro_PMPayPalEmbeddedCheckout)
                                {
                                    try
                                    {
                                        AppLogic.ValidatePM(AppLogic.ro_PMPayPal);
                                        UseBillingAddress.PaymentMethodLastUsed = AppLogic.ro_PMPayPal;
                                    }
                                    catch (Exception)
                                    {
                                        AppLogic.ValidatePM(AppLogic.ro_PMPayPalEmbeddedCheckout);
                                        UseBillingAddress.PaymentMethodLastUsed = AppLogic.ro_PMPayPalEmbeddedCheckout;
                                    }
                                }
                                UseBillingAddress.UpdateDB();

                                if (AppLogic.AppConfigBool("PayPal.RequireConfirmedAddress"))
                                {
                                    Address ShippingAddress = new Address();

                                    String[] StreetArray = address_street.Split(new string[1] {
                                        "\r\n"
                                    }, 2, StringSplitOptions.RemoveEmptyEntries);
                                    String Address1 = String.Empty;
                                    String Address2 = String.Empty;
                                    if (StreetArray.Length > 1)
                                    {
                                        Address1 = StreetArray[0];
                                        Address2 = StreetArray[1];
                                    }
                                    else
                                    {
                                        Address1 = address_street;
                                    }
                                    String[] NameArray = address_name.Split(new string[1] {
                                        " "
                                    }, 2, StringSplitOptions.RemoveEmptyEntries);
                                    String FirstName = String.Empty;
                                    String LastName  = String.Empty;
                                    if (NameArray.Length > 1)
                                    {
                                        FirstName = NameArray[0];
                                        LastName  = NameArray[1];
                                    }
                                    else
                                    {
                                        LastName = address_name;
                                    }
                                    string sql = String.Format("select top 1 AddressID as N from Address where Address1={0} and Address2={1} and City={2} and State={3} and Zip={4} and Country={5} and FirstName={6} and LastName={7} and CustomerID={8}",
                                                               DB.SQuote(Address1), DB.SQuote(Address2), DB.SQuote(address_city), DB.SQuote(address_state),
                                                               DB.SQuote(address_zip), DB.SQuote(address_country), DB.SQuote(FirstName), DB.SQuote(LastName), CustomerID);
                                    int ExistingAddressID = DB.GetSqlN(sql);

                                    if (ExistingAddressID == 0 || ThisCustomer.PrimaryShippingAddressID != ExistingAddressID)
                                    {
                                        string note      = "Note: Customer selected Ship-To address at PayPal.com";
                                        string ordernote = DB.GetSqlS("select OrderNotes S from Customer where CustomerID=" + ThisCustomer.CustomerID.ToString());
                                        if (!ordernote.Contains(note))
                                        {
                                            ordernote += System.Environment.NewLine + note;
                                            DB.ExecuteSQL("update Customer set OrderNotes=" + DB.SQuote(ordernote) + " where CustomerID=" + ThisCustomer.CustomerID.ToString());
                                        }
                                    }

                                    if (ExistingAddressID == 0)
                                    { // Does not exist
                                        ShippingAddress.CustomerID = CustomerID;
                                        ShippingAddress.FirstName  = FirstName;
                                        ShippingAddress.LastName   = LastName;
                                        ShippingAddress.Address1   = Address1;
                                        ShippingAddress.Address2   = Address2;
                                        ShippingAddress.City       = address_city;
                                        ShippingAddress.State      = address_state;
                                        ShippingAddress.Zip        = address_zip;
                                        ShippingAddress.Country    = address_country;
                                        ShippingAddress.EMail      = payer_email;
                                        ShippingAddress.InsertDB();

                                        ShippingAddress.MakeCustomersPrimaryAddress(AddressTypes.Shipping);
                                    }
                                    else
                                    { // Exists already
                                        ShippingAddress.LoadFromDB(ExistingAddressID);
                                        ShippingAddress.MakeCustomersPrimaryAddress(AddressTypes.Shipping);
                                    }
                                }

                                // Reload customer and cart so that we have the addresses right
                                ThisCustomer = new Customer(CustomerID, true);
                                cart         = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);
                                decimal CartTotal = cart.Total(true);
                                decimal NetTotal  = CartTotal - CommonLogic.IIF(cart.Coupon.CouponType == CouponTypeEnum.GiftCard, CommonLogic.IIF(CartTotal < cart.Coupon.DiscountAmount, CartTotal, cart.Coupon.DiscountAmount), 0);
                                NetTotal = Localization.ParseNativeDecimal(Localization.CurrencyStringForGatewayWithoutExchangeRate(NetTotal));
                                decimal PaymentTotal = CommonLogic.FormNativeDecimal("mc_gross");

                                // Cart will be empty if order already processed by paypalok.aspx
                                if (!cart.IsEmpty() && NetTotal > 0.0M)
                                {
                                    //Process as AuthOnly first
                                    int OrderNumber = AppLogic.GetNextOrderNumber();
                                    status = Gateway.MakeOrder(String.Empty, AppLogic.ro_TXModeAuthOnly, cart, OrderNumber, String.Empty, String.Empty, txn_id, String.Empty);

                                    if (status == AppLogic.ro_OK)
                                    {
                                        if (TransactionState == AppLogic.ro_TXStateCaptured)
                                        { // Now, if paid for, process as Captured
                                            Gateway.ProcessOrderAsCaptured(OrderNumber);
                                            DB.ExecuteSQL("update orders set AuthorizationPNREF=AuthorizationPNREF+" + DB.SQuote("|CAPTURE=" + txn_id) + " where OrderNumber=" + OrderNumber.ToString());
                                        }
                                        else if (TransactionState == AppLogic.ro_TXStatePending)
                                        {
                                            DB.ExecuteSQL("update orders set TransactionState=" + DB.SQuote(AppLogic.ro_TXStatePending) + " where OrderNumber=" + OrderNumber.ToString());
                                        }
                                    }

                                    // The incoming payment should match the cart total, if they don't
                                    // the customer may have tampered with the cart to cheat, so flag as fraud
                                    // but keep new so the admin will have to review the order.
                                    if (Math.Abs(NetTotal - PaymentTotal) > 0.05M) // allow 0.05 descrepency to allow minor rounding errors
                                    {
                                        Order.MarkOrderAsFraud(OrderNumber, true);
                                        DB.ExecuteSQL("update orders set FraudedOn=getdate(), IsNew=1 where OrderNumber=" + OrderNumber.ToString());
                                    }
                                    else
                                    {
                                        // Finalize the order here since they may never click through to orderconfirmation.aspx
                                        Order  ord = new Order(OrderNumber, ThisCustomer.LocaleSetting);
                                        String PM  = AppLogic.CleanPaymentMethod(ord.PaymentMethod);
                                        if (!ord.AlreadyConfirmed)
                                        {
                                            DB.ExecuteSQL("update Customer set OrderOptions=NULL, OrderNotes=NULL, FinalizationData=NULL where CustomerID=" + CustomerID.ToString());

                                            if (ord.TransactionIsCaptured() && ord.HasGiftRegistryComponents())
                                            {
                                                ord.FinalizeGiftRegistryComponents();
                                            }
                                            AppLogic.SendOrderEMail(ThisCustomer, OrderNumber, false, PM, true, null, null);
                                            DB.ExecuteSQL("Update Orders set AlreadyConfirmed=1 where OrderNumber=" + OrderNumber.ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else  // we have an existing order
                    {
                        if (TransactionState == AppLogic.ro_TXStateVoided)
                        {
                            IPNVoid(ExistingOrderNumber);
                        }
                        else if (TransactionState == AppLogic.ro_TXStateCaptured)
                        {
                            IPNCapture(ExistingOrderNumber, txn_id, CommonLogic.FormNativeDecimal("mc_gross"));
                        }
                        else if (TransactionState == AppLogic.ro_TXStateRefunded)
                        {
                            IPNRefund(ExistingOrderNumber, txn_id, CommonLogic.FormNativeDecimal("mc_gross"));
                        }
                        else if (TransactionState == AppLogic.ro_TXStatePending)
                        { // eChecks could have had the order placed in Captured state with Express Checkout
                            DB.ExecuteSQL("update orders set CapturedOn=NULL, TransactionState=" + DB.SQuote(AppLogic.ro_TXStatePending) + " where OrderNumber=" + ExistingOrderNumber.ToString());
                        }

                        OrderTransactionCollection transactions = new OrderTransactionCollection(ExistingOrderNumber);
                        transactions.AddTransaction(TransactionState, null, null, null, txn_id, AppLogic.ro_PMPayPal + " IPN", null, CommonLogic.FormNativeDecimal("mc_gross"));
                    }
                }
                else
                {
                }
            }
        }
        public string ProcessCallBack()
        {
            string PM = AppLogic.CleanPaymentMethod(AppLogic.ro_PMCreditCard);

            AppLogic.ValidatePM(PM); // this WILL throw a hard security exception on any problem!

            //recalculate total for verification
            decimal cartTotal  = cart.Total(true);
            decimal orderTotal = cartTotal - CommonLogic.IIF(cart.Coupon.CouponType == CouponTypeEnum.GiftCard, CommonLogic.IIF(cartTotal < cart.Coupon.DiscountAmount, cartTotal, cart.Coupon.DiscountAmount), 0);

            orderTotal = Localization.ParseNativeDecimal(Localization.CurrencyStringForGatewayWithoutExchangeRate(orderTotal));

            if (!ThisCustomer.HasCustomerRecord)
            {
                FirstPay.order_id = 0;
                throw new System.Security.SecurityException("Customer not signed in to complete transaction.");
            }

            if (!Success)
            {
                string IP = "";
                if (cart != null)
                {
                    IP = cart.ThisCustomer.LastIPAddress;
                }

                string sql = "insert into FailedTransaction(CustomerID,OrderNumber,IPAddress,OrderDate,PaymentGateway,PaymentMethod,TransactionCommand,TransactionResult) values(" + ThisCustomer.CustomerID.ToString() + "," + OrderNumber.ToString() + "," + DB.SQuote(IP) + ",getdate()," + DB.SQuote("1stPay") + "," + DB.SQuote(AppLogic.ro_PMCreditCard) + "," + DB.SQuote("") + "," + DB.SQuote(ParamString) + ")";
                DB.ExecuteSQL(sql);
                return(ReturnFirstPayError());
            }

            //Need to add this to check that the transaction processed through the gateway and that the charged amount matches the orderTotal.
            ConfirmTransaction(orderTotal); // this WILL throw a hard security exception on any problem!


            if (cart.IsEmpty())
            {
                ErrorMessage er = new ErrorMessage("Could not complete the transaction because the shopping cart was empty.");
                var          checkoutController = CheckOutPageControllerFactory.CreateCheckOutPageController(ThisCustomer, cart);
                return(checkoutController.GetCheckoutPaymentPage() + "?errormsg=" + er.MessageId);
            }

            //the callback is valid. make the order.
            int orderNumber = OrderNumber;

            //Setup param list
            List <SqlParameter> sqlParams = new List <SqlParameter>();

            try
            {
                ThisCustomer.PrimaryBillingAddress.PaymentMethodLastUsed = AppLogic.ro_PMCreditCard;
                ThisCustomer.PrimaryBillingAddress.UpdateDB();
                //Process as AuthOnly first
                string status = Gateway.MakeOrder(AppLogic.ro_PMCreditCard, AppLogic.TransactionModeIsAuthOnly() ? AppLogic.ro_TXModeAuthOnly : AppLogic.ro_TXModeAuthCapture, cart, orderNumber, "", "", ReferenceNumber, "");

                if (status == AppLogic.ro_OK)
                {
                    string AVSResult            = AVSResponse;
                    string AuthorizationCode    = AuthCode;
                    string AuthorizationTransID = ReferenceNumber;

                    //Add all the params needed.
                    sqlParams.Add(new SqlParameter("@AuthorizationTransId", AuthorizationTransID));
                    sqlParams.Add(new SqlParameter("@AVSResult", AVSResult));
                    sqlParams.Add(new SqlParameter("@AuthorizationCode", AuthorizationCode));
                    sqlParams.Add(new SqlParameter("@CCType", CCType));
                    sqlParams.Add(new SqlParameter("@CCExpMonth", CCExpMonth));
                    sqlParams.Add(new SqlParameter("@CCExpYear", CCExpYear));
                    sqlParams.Add(new SqlParameter("@CCNumberLast4", CCNumberLast4));
                    sqlParams.Add(new SqlParameter("@OrderNumber", orderNumber));
                    sqlParams.Add(new SqlParameter("@TransactionState", ADNSFTransactionState));

                    if (CVV2Response.Length > 0)
                    {
                        AVSResult += ", CV Result: " + CVV2Response;
                    }

                    // Now, if paid for, process as Captured
                    if (ADNSFTransactionState == AppLogic.ro_TXStateAuthorized)
                    {
                        string sql = "Update Orders Set AuthorizationPNREF=@AuthorizationTransId"
                                     + ", AVSResult=@AVSResult"
                                     + ", AuthorizationCode=@AuthorizationCode"
                                     + ", CardType=@CCType"
                                     + ", CardExpirationMonth=@CCExpMonth"
                                     + ", CardExpirationYear=@CCExpYear"
                                     + ", Last4=@CCNumberLast4"
                                     + " Where OrderNumber=@OrderNumber;";


                        DB.ExecuteSQL(sql, sqlParams.ToArray());
                    }
                    if (ADNSFTransactionState == AppLogic.ro_TXStateCaptured)
                    {
                        string sql = "Update Orders Set AuthorizationPNREF=@AuthorizationTransId + '|CAPTURE=' + @AuthorizationTransId"
                                     + ", AVSResult=@AVSResult"
                                     + ", AuthorizationCode=@AuthorizationCode"
                                     + ", CardType=@CCType"
                                     + ", CardExpirationMonth=@CCExpMonth"
                                     + ", CardExpirationYear=@CCExpYear"
                                     + ", Last4=@CCNumberLast4"
                                     + ", CapturedOn=getdate()"
                                     + " Where OrderNumber=@OrderNumber;";

                        Gateway.ProcessOrderAsCaptured(orderNumber);
                        DB.ExecuteSQL(sql, sqlParams.ToArray());
                    }
                    else if (ADNSFTransactionState == AppLogic.ro_TXStateError)
                    {
                        DB.ExecuteSQL("update orders set TransactionState=@TransactionState where OrderNumber=@OrderNumber;", sqlParams.ToArray());
                    }

                    if (!string.IsNullOrEmpty(ReferenceNumber))
                    {
                        OrderTransactionCollection transactions = new OrderTransactionCollection(orderNumber);
                        transactions.AddTransaction(ADNSFTransactionState, null, ParamString, AuthorizationTransID, AuthorizationCode, AppLogic.ro_PMCreditCard, gateway.DisplayName(ThisCustomer.LocaleSetting), orderTotal);
                    }
                }
                else if (status != AppLogic.ro_3DSecure) // If the status is anything but Ok or 3DSecure then send them back to the checkout process and display the error status
                {
                    ErrorMessage er = new ErrorMessage(status);
                    var          checkoutController = CheckOutPageControllerFactory.CreateCheckOutPageController(ThisCustomer, cart);
                    return(checkoutController.GetCheckoutPaymentPage() + "?errormsg=" + er.MessageId);
                }

                if (Math.Abs(orderTotal - Total) > 0.05M) // allow 0.05 descrepency to allow minor rounding errors
                {
                    Order.MarkOrderAsFraud(orderNumber, true);
                    DB.ExecuteSQL("update orders set FraudedOn=getdate(), IsNew=1 where OrderNumber=@OrderNumber;", sqlParams.ToArray());
                }
            }
            catch // if we failed, did the IPN come back at the same time?
            {
                cart = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);
                if (cart.IsEmpty())
                {
                    using (SqlConnection dbconn = DB.dbConn())
                    {
                        dbconn.Open();
                        using (SqlCommand cmd = new SqlCommand("select MAX(OrderNumber) N from dbo.orders where CustomerID = @CustomerId;", dbconn))
                        {
                            cmd.Parameters.Add(new SqlParameter("@CustomerId", ThisCustomer.CustomerID));
                            orderNumber = cmd.ExecuteScalar() as int? ?? 0;
                        }
                    }
                }
            }
            return("orderconfirmation.aspx?ordernumber=" + orderNumber + "&paymentmethod=CreditCard");
        }
Exemple #8
0
        //Settle should be run here if site is setup for auth/capture, Payment Module will always be processing a transactions as an Auth
        public override string ProcessCard(int orderNumber, int customerID, Decimal orderTotal, bool useLiveTransactions, TransactionModeEnum transactionMode, Address useBillingAddress, string cardExtraCode, Address useShippingAddress, string CAVV, string ECI, string XID, out string AVSResult, out string authorizationResult, out string authorizationCode, out string authorizationTransID, out string transactionCommandOut, out string transactionResponse)
        {
            Customer ThisCustomer = new Customer(customerID, true);

            authorizationResult = AVSResult = authorizationCode = authorizationTransID = transactionCommandOut = transactionResponse = "";
            string approvalCode            = "";
            string AVSCode                 = AVSResult = "";
            string CVCode                  = "";
            string responseCode            = "";
            string responseError           = "";
            string responseReferenceNumber = "";
            string authResponse            = "";
            string TransID                 = "";
            string TransStatus             = "";
            string result                  = AppLogic.ro_OK;

            if (ThisCustomer != null && ThisCustomer.CustomerID > 0)
            {
                if (ThisCustomer.IsAdminUser && (AppLogic.ExceedsFailedTransactionsThreshold(ThisCustomer) || AppLogic.IPIsRestricted(ThisCustomer.LastIPAddress)))
                {
                    return(AppLogic.GetString("gateway.FailedTransactionThresholdExceeded", ThisCustomer.SkinID, ThisCustomer.LocaleSetting));
                }
            }

            Encoding           encoding           = System.Text.Encoding.GetEncoding(1252);
            FirstPayXmlCommand transactionCommand = new FirstPayXmlCommand(transaction_center_id.ToString(), gateway_id, processor_id);

            if (transactionMode == TransactionModeEnum.authcapture)
            {
                transactionCommand.Settle(XID, Localization.CurrencyStringForGatewayWithoutExchangeRate(orderTotal));
            }
            else
            {
                transactionCommand.Query(orderNumber.ToString(), DateTime.Today.AddDays(-1), DateTime.Today.AddDays(1));
            }

            string rawResponseString = "";
            FirstPayXmlResponse xmlResponse;

            if (GetXmlResponse(transactionCommand.InnerXml, out rawResponseString, out xmlResponse))
            {
                if (xmlResponse.Fields.Count > 0)
                {
                    responseCode            = xmlResponse.Fields.ContainsKey("status1") ? xmlResponse.Fields["status1"] : (xmlResponse.Fields.ContainsKey("trans_status1") ? xmlResponse.Fields["trans_status1"] : "");
                    authResponse            = xmlResponse.Fields.ContainsKey("response1") ? xmlResponse.Fields["response1"] : "";
                    responseError           = xmlResponse.Fields.ContainsKey("error1") ? xmlResponse.Fields["error1"] : (xmlResponse.Fields.ContainsKey("error") ? xmlResponse.Fields["error"] : "");
                    TransStatus             = xmlResponse.Fields.ContainsKey("trans_status1") ? xmlResponse.Fields["trans_status1"] : null;
                    responseReferenceNumber = xmlResponse.Fields.ContainsKey("reference_number1") ? xmlResponse.Fields["reference_number1"] : "";
                }

                // rawResponseString now has gateway response
                transactionResponse = rawResponseString;

                authorizationCode    = approvalCode;
                authorizationResult  = rawResponseString;
                authorizationTransID = TransID;
                AVSResult            = AVSCode;
                if (CVCode.Length > 0)
                {
                    AVSResult += ", CV Result: " + CVCode;
                }
                transactionCommandOut = transactionCommand.InnerXml.Replace(gateway_id, "***");

                if (responseCode == "1" && (string.IsNullOrEmpty(TransStatus) || TransStatus == "1"))
                {
                    result = AppLogic.ro_OK;
                }
                else if (responseCode == "2")
                {
                    result = "DECLINED";
                    if (authResponse.Length > 0)
                    {
                        result += ". " + authResponse;
                    }
                }
                else if (responseCode == "0")
                {
                    result = "Error: " + authResponse + " | " + responseError;
                }
                else
                {
                    result = "System Error: " + rawResponseString;
                }

                if (transactionMode == TransactionModeEnum.authcapture)
                {
                    OrderTransactionCollection transactions = new OrderTransactionCollection(orderNumber);
                    transactions.AddTransaction(AppLogic.ro_TXStateCaptured, transactionCommand.InnerXml.Replace(gateway_id, "***"), rawResponseString, responseReferenceNumber, responseCode, AppLogic.ro_PMCreditCard, DisplayName(ThisCustomer.LocaleSetting), orderTotal);
                }
            }
            else
            {
                result = "Error calling 1stPay gateway.";
            }
            if (result != AppLogic.ro_OK)
            {
                string         IP        = "";
                SqlParameter[] sqlParams = { new SqlParameter("@CustomerID", customerID)
                                             ,                               new SqlParameter("@OrderNumber", orderNumber)
                                             ,                               new SqlParameter("@IP", IP)
                                             ,                               new SqlParameter("@Gateway", DisplayName(ThisCustomer.LocaleSetting))
                                             ,                               new SqlParameter("@PaymentMethod", AppLogic.ro_PMCreditCard)
                                             ,                               new SqlParameter("@Command", transactionCommandOut)
                                             ,                               new SqlParameter("@Result", transactionResponse) };

                if (ThisCustomer != null)
                {
                    IP = ThisCustomer.LastIPAddress;
                }
                string sql = "insert into FailedTransaction(CustomerID,OrderNumber,IPAddress,OrderDate,PaymentGateway,PaymentMethod,TransactionCommand,TransactionResult) "
                             + "values(@CustomerID,@OrderNumber,@IP,getdate(),@Gateway,@PaymentMethod,@Command,@Result)";

                using (SqlConnection dbconn = DB.dbConn())
                {
                    dbconn.Open();
                    using (SqlCommand cmd = new SqlCommand(sql, dbconn))
                    {
                        cmd.Parameters.AddRange(sqlParams.ToArray());
                        cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    }
                }
            }

            return(result);
        }
Exemple #9
0
        // if RefundAmount == 0.0M, then then ENTIRE order amount will be refunded!
        public override string RefundOrder(int originalOrderNumber, int newOrderNumber, decimal refundAmount, string refundReason, Address useBillingAddress)
        {
            string result = AppLogic.ro_OK;
            bool   useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");

            //Will add parameters to this as we get data back from other querys etc. So I don't have to repeat code
            List <SqlParameter> sqlParams = new List <SqlParameter>();

            sqlParams.Add(new SqlParameter("@OrderNumber", originalOrderNumber));

            using (SqlConnection dbconn = DB.dbConn())
            {
                dbconn.Open();
                using (SqlCommand cmd = new SqlCommand("update orders set RefundTXCommand=NULL, RefundTXResult=NULL where OrderNumber=@OrderNumber;", dbconn))
                {
                    cmd.Parameters.AddRange(sqlParams.ToArray());
                    cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                }
            }

            string   TransID           = "";
            string   AuthorizationCode = "";
            Decimal  OrderTotal        = System.Decimal.Zero;
            Order    order             = new Order(originalOrderNumber);
            Customer ThisCustomer      = new Customer(order.CustomerID);

            using (SqlConnection dbconn = DB.dbConn())
            {
                dbconn.Open();
                using (SqlCommand cmd = new SqlCommand("select * from orders with (NOLOCK)  where OrderNumber=@OrderNumber;", dbconn))
                {
                    cmd.Parameters.AddRange(sqlParams.ToArray());
                    using (IDataReader rs = cmd.ExecuteReader())
                    {
                        if (rs.Read())
                        {
                            TransID           = DB.RSField(rs, "AuthorizationPNREF");
                            AuthorizationCode = DB.RSField(rs, "AuthorizationCode");
                            OrderTotal        = DB.RSFieldDecimal(rs, "OrderTotal");
                        }
                    }
                    cmd.Parameters.Clear();
                }
            }

            if (TransID.Length == 0 || TransID == "0")
            {
                result = "Invalid or Empty Transaction ID";
            }
            else
            {
                try
                {
                    string[] TXInfo = TransID.Split('|');

                    Encoding           encoding           = System.Text.Encoding.GetEncoding(1252);
                    FirstPayXmlCommand transactionCommand = new FirstPayXmlCommand(transaction_center_id.ToString(), gateway_id, processor_id);

                    transactionCommand.Credit(TXInfo[0], Localization.CurrencyStringForGatewayWithoutExchangeRate(refundAmount == System.Decimal.Zero ? OrderTotal : refundAmount));

                    string rawResponseString = "";
                    FirstPayXmlResponse xmlResponse;

                    if (GetXmlResponse(transactionCommand.InnerXml, out rawResponseString, out xmlResponse))
                    {
                        string responseCode            = "";
                        string responseError           = "";
                        string authResponse            = "";
                        string responseReferenceNumber = "";

                        if (xmlResponse.Fields.Count > 0)
                        {
                            responseCode            = xmlResponse.Fields.ContainsKey("status1") ? xmlResponse.Fields["status1"] : "";
                            authResponse            = xmlResponse.Fields.ContainsKey("response1") ? xmlResponse.Fields["response1"] : "";
                            responseError           = xmlResponse.Fields.ContainsKey("error1") ? xmlResponse.Fields["error1"] : "";
                            responseReferenceNumber = xmlResponse.Fields.ContainsKey("reference_number1") ? xmlResponse.Fields["reference_number1"] : "";
                        }

                        if (responseCode == "1")
                        {
                            result = AppLogic.ro_OK;
                        }
                        else if (responseCode == "2")
                        {
                            result = "REJECTED";
                            if (authResponse.Length > 0)
                            {
                                result += ". " + authResponse;
                                result += " : This order may not have settled yet, try void instead.";
                            }
                        }
                        else if (responseCode == "0")
                        {
                            result = "Error: " + authResponse + " | " + responseError;
                        }
                        else
                        {
                            result = "System Error: " + rawResponseString;
                        }

                        OrderTransactionCollection transactions = new OrderTransactionCollection(order.OrderNumber);
                        transactions.AddTransaction(AppLogic.ro_TXStateRefunded, transactionCommand.InnerXml.Replace(gateway_id, "***"), rawResponseString, responseReferenceNumber, responseCode, AppLogic.ro_PMCreditCard, DisplayName(ThisCustomer.LocaleSetting), order.OrderBalance);

                        sqlParams.Add(new SqlParameter("@Result", result));
                        sqlParams.Add(new SqlParameter("@Command", transactionCommand.InnerXml.Replace(gateway_id, "***")));

                        if (result == AppLogic.ro_OK)
                        {
                            using (SqlConnection dbconn = DB.dbConn())
                            {
                                dbconn.Open();
                                using (SqlCommand cmd = new SqlCommand("update orders set RefundTXResult=@Result, RefundTXCommand=@Command where OrderNumber=@OrderNumber;", dbconn))
                                {
                                    cmd.Parameters.AddRange(sqlParams.ToArray());
                                    cmd.ExecuteNonQuery();
                                    cmd.Parameters.Clear();
                                }
                            }
                        }
                        else
                        {
                            using (SqlConnection dbconn = DB.dbConn())
                            {
                                dbconn.Open();
                                using (SqlCommand cmd = new SqlCommand("update orders set RefundTXResult=@Result, RefundTXCommand=@Command where OrderNumber=@OrderNumber;", dbconn))
                                {
                                    cmd.Parameters.AddRange(sqlParams.ToArray());
                                    cmd.ExecuteNonQuery();
                                    cmd.Parameters.Clear();
                                }
                            }
                        }
                    }
                    else
                    {
                        result = "Error calling 1stPay gateway.";
                    }
                }
                catch (Exception ex)
                {
                    result = ex.Message;
                }
            }
            return(result);
        }
Exemple #10
0
        public override string CaptureOrder(Order order)
        {
            string   result = AppLogic.ro_OK;
            bool     useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            Customer ThisCustomer        = new Customer(order.CustomerID, true);

            order.CaptureTXCommand = "";
            order.CaptureTXResult  = "";

            string  TransID           = order.AuthorizationPNREF;
            Decimal OrderTotal        = order.OrderBalance;
            string  AuthorizationCode = order.AuthorizationCode;

            order.CaptureTXCommand = TransID;

            if (string.IsNullOrEmpty(TransID) || TransID.Length == 0 || TransID == "0")
            {
                result = "Invalid or Empty Transaction ID";
            }
            else
            {
                try
                {
                    string[] TXInfo = TransID.Split('|');

                    Encoding           encoding           = System.Text.Encoding.GetEncoding(1252);
                    FirstPayXmlCommand transactionCommand = new FirstPayXmlCommand(transaction_center_id.ToString(), gateway_id, processor_id);

                    transactionCommand.Settle(TXInfo[0], Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal));

                    string rawResponseString = "";
                    FirstPayXmlResponse xmlResponse;

                    if (GetXmlResponse(transactionCommand.InnerXml, out rawResponseString, out xmlResponse))
                    {
                        string responseCode            = "";
                        string responseError           = "";
                        string authResponse            = "";
                        string responseReferenceNumber = "";

                        if (xmlResponse.Fields.Count > 0)
                        {
                            responseCode            = xmlResponse.Fields.ContainsKey("status1") ? xmlResponse.Fields["status1"] : "";
                            authResponse            = xmlResponse.Fields.ContainsKey("response1") ? xmlResponse.Fields["response1"] : "";
                            responseError           = xmlResponse.Fields.ContainsKey("error1") ? xmlResponse.Fields["error1"] : "";
                            responseReferenceNumber = xmlResponse.Fields.ContainsKey("reference_number1") ? xmlResponse.Fields["reference_number1"] : "";
                        }

                        if (responseCode == "1")
                        {
                            result = AppLogic.ro_OK;
                        }
                        else if (responseCode == "2")
                        {
                            result = "REJECTED";
                            if (authResponse.Length > 0)
                            {
                                result += ". " + authResponse;
                            }
                        }
                        else if (responseCode == "0")
                        {
                            result = "Error: " + authResponse + " | " + responseError;
                        }
                        else
                        {
                            result = "System Error: " + rawResponseString;
                        }

                        OrderTransactionCollection transactions = new OrderTransactionCollection(order.OrderNumber);
                        transactions.AddTransaction(AppLogic.ro_TXStateCaptured, transactionCommand.InnerXml.Replace(gateway_id, "***"), rawResponseString, responseReferenceNumber, responseCode, AppLogic.ro_PMCreditCard, DisplayName(ThisCustomer.LocaleSetting), OrderTotal);
                    }
                    else
                    {
                        result = "Error calling 1stPay gateway.";
                    }
                    order.CaptureTXResult  = result;
                    order.CaptureTXCommand = transactionCommand.InnerXml.Replace(gateway_id, "***");
                }
                catch (Exception ex)
                {
                    result = ex.Message;
                }
            }
            return(result);
        }
Exemple #11
0
        public string GetFramedHostedCheckout(ShoppingCart cart)
        {
            //fill in code here to display error when none USD currency.
            if ("USD" != Currency.GetDefaultCurrency())
            {
                return("This gateway only supports US Dollars.");
            }

            string  response;
            string  AuthServer = AppLogic.AppConfig("1stPay.PaymentModuleURL");
            decimal cartTotal  = cart.Total(true);

            total = cartTotal - CommonLogic.IIF(cart.Coupon.CouponType == CouponTypeEnum.GiftCard
                                                , CommonLogic.IIF(cartTotal < cart.Coupon.DiscountAmount, cartTotal, cart.Coupon.DiscountAmount)
                                                , 0);
            email          = cart.ThisCustomer.EMail;
            operation_type = TransactionType.ecom_auth;

            //Try to load up the address to be passed into the iframe for the customer
            Address address = new Address(cart.ThisCustomer.CustomerID);

            if (cart.CartItems.Count > 0 && cart.CartItems[0].BillingAddressID > 0)
            {
                address.LoadFromDB(cart.CartItems[0].BillingAddressID);
            }
            else
            {
                address.LoadFromDB(cart.FirstItemShippingAddressID());
            }

            //Load up default
            if (address.AddressID < 1)
            {
                address.LoadFromDB(cart.ThisCustomer.PrimaryBillingAddressID);
            }

            if (address.AddressID > 0)
            {
                name    = (address.FirstName + " " + address.LastName).Trim();
                street  = address.Address1;
                street2 = address.Address2;
                city    = address.City;
                state   = address.State;
                zip     = address.Zip;
                country = address.Country;
                phone   = address.Phone;
            }

            if (cim_on)
            {
                cim_ref_num = cart.ThisCustomer.CustomerGUID;
            }

            if (level_ii_on)
            {
                //Level 2 fields wants the shipping rather than billing zip so load that up.
                Address shipAddress = new Address(cart.ThisCustomer.CustomerID);
                shipAddress.LoadFromDB(cart.FirstItemShippingAddressID());

                //Load up default
                if (shipAddress.AddressID < 1)
                {
                    shipAddress.LoadFromDB(cart.ThisCustomer.PrimaryShippingAddressID);
                }

                tax_amount   = cart.TaxTotal();
                shipping_zip = shipAddress.Zip;
            }

            string RequestID = System.Guid.NewGuid().ToString("N");
            string rawResponseString;

            int  MaxTries       = AppLogic.AppConfigUSInt("GatewayRetries") + 1;
            int  CurrentTry     = 0;
            bool CallSuccessful = false;

            //Make sure the server is up.
            do
            {
                CurrentTry++;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(AuthServer + string.Format("?transaction_center_id={0}&embedded={1}&operation_type={2}&respond_inline={3}"
                                                                                                        , transaction_center_id
                                                                                                        , embedded
                                                                                                        , operation_type
                                                                                                        , Convert.ToInt32(respond_inline)
                                                                                                        ));
                myRequest.Method        = "POST";
                myRequest.ContentType   = "text/namevalue";
                myRequest.ContentLength = 0;
                myRequest.Timeout       = 30000;
                try
                {
                    HttpWebResponse myResponse;
                    myResponse = (HttpWebResponse)myRequest.GetResponse();
                    using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
                    {
                        rawResponseString = sr.ReadToEnd();
                        sr.Close();
                    }
                    myResponse.Close();

                    CallSuccessful = ValidStatusCodes.Any(vsc => myResponse.StatusCode == vsc);
                }
                catch
                {
                    CallSuccessful = false;
                }
            }while (!CallSuccessful && CurrentTry < MaxTries);

            if (CallSuccessful && order_id < 1)
            {
                order_id = AppLogic.GetNextOrderNumber();
            }


            if (CallSuccessful)
            {
                StringBuilder transactionCommand        = BuildPortalTransactionCommand();
                OrderTransactionCollection transactions = new OrderTransactionCollection(order_id);

                //If we haven't already logged the transaction command for this same order/iframe url combo then add it to the transaction log.
                if (!transactions.Transactions.Any(t => t.TransactionType == (AppLogic.TransactionModeIsAuthCapture() ? AppLogic.ro_TXModeAuthCapture : AppLogic.ro_TXModeAuthOnly) &&
                                                   t.TransactionCommand == transactionCommand.ToString() &&
                                                   t.PaymentGateway == DisplayName(cart.ThisCustomer.LocaleSetting) &&
                                                   t.Amount == total
                                                   ))
                {
                    transactions.AddTransaction(AppLogic.TransactionModeIsAuthCapture() ? AppLogic.ro_TXModeAuthCapture : AppLogic.ro_TXModeAuthOnly, transactionCommand.ToString(), null, null, null, AppLogic.ro_PMCreditCard, DisplayName(cart.ThisCustomer.LocaleSetting), total);
                }

                response = GetFrameSrc(0, 500, transactionCommand.ToString());
            }
            else
            {
                response = "Unable to connect to the server, please try again later.";
            }

            return(response);
        }