コード例 #1
0
        public ActionResult Create()
        {
            var customer = HttpContext.GetCustomer();

            // We will allow registered customers to create new accounts if they end up on the page but we won't
            // prepopulate and fields so its clear they're creating a new account. Otherwise, we'll try and fill in
            // whatever fields we might have fromt he current customer record.
            var account = !customer.IsRegistered
                                ? new AccountCreateViewModel
            {
                FirstName            = customer.FirstName,
                LastName             = customer.LastName,
                Email                = customer.EMail,
                Phone                = customer.Phone,
                IsOkToEmail          = customer.OKToEMail,
                IsOver13             = customer.IsOver13,
                VatRegistrationId    = customer.VATRegistrationID,
                SaveCreditCardNumber = customer.StoreCCInDB
            }
                                : new AccountCreateViewModel();

            return(View(new AccountCreateIndexViewModel(
                            displayCaptcha: CaptchaSettings.CaptchaIsConfigured() && CaptchaSettings.RequireCaptchaOnCreateAccount,
                            requireEmailConfirmation: AppConfigProvider.GetAppConfigValue <bool>("RequireEmailConfirmation"),
                            displayOver13Selector: AppConfigProvider.GetAppConfigValue <bool>("RequireOver13Checked"))
            {
                Account = account,
                PrimaryBillingAddress = new AccountAddressViewModel(),
                PrimaryShippingAddress = new AccountAddressViewModel()
            }));
        }
コード例 #2
0
        public ActionResult ShippingMethod()
        {
            var customer        = HttpContext.GetCustomer();
            var storeId         = AppLogic.StoreID();
            var cart            = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, storeId);
            var shippingAddress = EffectiveShippingAddressProvider.GetEffectiveShippingAddress(customer);
            var checkoutContext = PersistedCheckoutContextProvider.LoadCheckoutContext(customer);

            var shippingMethodModels = CachedShippingMethodCollectionProvider
                                       .Get(customer, shippingAddress, cart.CartItems, storeId)
                                       .Select(shippingMethod => new ShippingMethodRenderModel(
                                                   id: shippingMethod.Id,
                                                   name: shippingMethod.GetNameForDisplay(),
                                                   rateDisplay: GetShippingMethodRateDisplay(shippingMethod, customer, cart),
                                                   imageFileName: shippingMethod.ImageFileName));

            var selectedShippingMethodModel = shippingMethodModels
                                              .Where(shippingMethod => shippingMethod.Id == checkoutContext.SelectedShippingMethodId)
                                              .FirstOrDefault();

            var model = new SelectShippingMethodViewModel
            {
                RenderModel = new SelectShippingMethodRenderModel(
                    shippingMethods: shippingMethodModels,
                    selectedShippingMethod: selectedShippingMethodModel,
                    showShippingIcons: AppConfigProvider.GetAppConfigValue <bool>("ShowShippingIcons"),
                    cartIsAllFreeShipping: !AppConfigProvider.GetAppConfigValue <bool>("FreeShippingAllowsRateSelection") && cart.IsAllFreeShippingComponents(),
                    numberOfMethodsToShow: AppConfigProvider.GetAppConfigValue <int>("NumberOfShippingMethodsToDisplay"),
                    hideShippingOptions: AppConfigProvider.GetAppConfigValue <bool>("shipping.hide.options")),
                SelectedShippingMethodId = checkoutContext.SelectedShippingMethodId,
            };

            return(PartialView(ViewNames.ShippingMethodPartial, model));
        }
コード例 #3
0
        public IEnumerable <string> Register(HttpContextBase httpContext, IEnumerable <ClientScriptResource> resources)
        {
            var normalizedResources = resources.Select(resource => NormalizeResource(httpContext, resource));

            // Non-deferred registrations are rendered immediately and not registered for deferred rendering.
            var deferredRenderingEnabled = AppConfigProvider.GetAppConfigValue <bool>(DeferredRenderingEnabledAppConfigName);

            if (!deferredRenderingEnabled)
            {
                return(ClientScriptResourceHandler.Render(normalizedResources, RenderMode.Immediate));
            }

            var resourceCollection = GetOrderedResourceCollection(httpContext);

            foreach (var resource in normalizedResources)
            {
                var index = (int?)httpContext.Items[HttpContextIndexKey] ?? 0;
                if (resourceCollection.Add(new OrderedClientScriptResource(index, resource)))
                {
                    httpContext.Items[HttpContextIndexKey] = index + 1;
                }
            }

            return(Enumerable.Empty <string>());
        }
コード例 #4
0
        public Result ValidateCaptchaResponse(string token, string customerIpAddress)
        {
            if (string.IsNullOrEmpty(token))
            {
                return(Result.Fail(new CaptchaException(AppLogic.GetString("Global.CaptchaInvalid"))));
            }

            using (var client = new HttpClient())
            {
                try
                {
                    var content = new FormUrlEncodedContent(new Dictionary <string, string>
                    {
                        { "secret", AppConfigProvider.GetAppConfigValue("reCAPTCHA.SecretKey") },
                        { "response", token },
                        { "remoteip", customerIpAddress }
                    });

                    var response = client.PostAsync(AppConfigProvider.GetAppConfigValue("reCAPTCHA.VerifyURL"), content).Result;

                    if (!response.IsSuccessStatusCode)
                    {
                        SysLog.LogMessage("reCAPTCHA validation call failed.", response.ReasonPhrase, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                        return(Result.Fail(new CaptchaException(AppLogic.GetString("Global.CaptchaValidationFailed"))));
                    }

                    var responseObject = Newtonsoft.Json
                                         .JsonConvert
                                         .DeserializeObject <ReCaptchaResponse>(response.Content.ReadAsStringAsync().Result.Replace('-', '_'));         //Google's response object has weird property names

                    if (!responseObject.Success)
                    {
                        SysLog.LogMessage("reCAPTCHA validation failed.", responseObject.Error_Codes.ToDelimitedString(), MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                        return(Result.Fail(new CaptchaException(AppLogic.GetString("Global.CaptchaInvalid"))));
                    }

                    return(Result.Ok());
                }
                catch (Exception exception)
                {
                    SysLog.LogException(exception, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                    return(Result.Fail(new CaptchaException(exception.Message)));
                }
            }
        }
コード例 #5
0
        public SignifydConfiguration Create()
        {
            var enabled           = AppConfigProvider.GetAppConfigValue <bool>("Signifyd.Enabled");
            var apiUrl            = AppConfigProvider.GetAppConfigValue("Signifyd.API.Url");
            var accessToken       = AppConfigProvider.GetAppConfigValue("Signifyd.Team.Key");
            var declineActionVoid = AppConfigProvider.GetAppConfigValue <bool>("Signifyd.DeclineAction.Void");

            if (enabled &&
                (string.IsNullOrEmpty(apiUrl) || string.IsNullOrEmpty(accessToken)))
            {
                throw new Exception("Signifyd is not configured properly - please see documentation.");
            }

            return(new SignifydConfiguration(
                       enabled: enabled,
                       apiUrl: apiUrl,
                       accessToken: accessToken,
                       declineActionVoid: declineActionVoid));
        }
コード例 #6
0
        public IStringResourceProvider Create()
        {
            var showResourceKeysOnly = AppConfigProvider.GetAppConfigValue <bool>("ShowStringResourceKeys");

            if (showResourceKeysOnly)
            {
                return(new KeyOnlyStringResourceProvider());
            }

            var currentLocale = System.Web.HttpContext
                                .Current
                                .GetCustomer()
                                .LocaleSetting;

            return(new LocalizedStringResourceProvider(currentLocale));
        }
コード例 #7
0
        public ActionResult ThreeDSecure()
        {
            //Braintree has its own 3dSecure form
            if (AppLogic.ActivePaymentGatewayCleaned() == Gateway.ro_GWBRAINTREE)
            {
                var customer = HttpContext.GetCustomer();
                var context  = PersistedCheckoutContextProvider.LoadCheckoutContext(customer);
                var cart     = new ShoppingCart(customer.SkinID, customer, CartTypeEnum.ShoppingCart, 0, false);

                var braintreeModel = new BraintreeThreeDSecureViewModel(
                    nonce: context.Braintree.Nonce,
                    scriptUrl: AppConfigProvider.GetAppConfigValue("Braintree.ScriptUrl"),
                    token: context.Braintree.Token,
                    total: cart.Total(true).ToString());

                return(View(ViewNames.BraintreeThreeDSecureForm, braintreeModel));
            }
            //Sage Pay PI has its own 3dSecure form
            if (AppLogic.ActivePaymentGatewayCleaned() == Gateway.ro_GWSAGEPAYPI)
            {
                var customer = HttpContext.GetCustomer();
                var sagePayPiThreeDSecureViewModel = new SagePayPiThreeDSecureViewModel(
                    paReq: customer.ThisCustomerSession[AppLogic.SagePayPiPaReq],
                    termUrl: customer.ThisCustomerSession[AppLogic.SagePayPiTermUrl],
                    md: customer.ThisCustomerSession[AppLogic.SagePayPiMd],
                    acsUrl: customer.ThisCustomerSession[AppLogic.SagePayPiAcsUrl]
                    );

                return(View(ViewNames.SagePayPiThreeDSecureForm, sagePayPiThreeDSecureViewModel));
            }

            var threeDSecureModel = new ThreeDSecureFrameViewModel
            {
                FrameUrl = Url.Action(ActionNames.ThreeDSecureForm, ControllerNames.ThreeDSecure, null, this.Request.Url.Scheme)
            };

            return(View(threeDSecureModel));
        }
コード例 #8
0
ファイル: AppConfig.cs プロジェクト: giagiigi/WE
        public string RenderToken(TokenHandlerContext context)
        {
            if (!Tokens.Contains(context.Token, StringComparer.OrdinalIgnoreCase))
            {
                return(null);
            }

            if (!context.Parameters.ContainsKey(NameParam) || string.IsNullOrWhiteSpace(context.Parameters[NameParam]))
            {
                throw new TokenParameterMissingException(NameParam);
            }

            var appConfigName = context
                                .Parameters[NameParam]
                                .Trim();

            return(AppConfigProvider.GetAppConfigValue(appConfigName));
        }
コード例 #9
0
        public bool?HasStateChanged(DependencyState establishedState)
        {
            if (!(establishedState.Context is CheckoutShippingSelectionDependencyStateContext))
            {
                return(null);
            }

            var currentState = GetState(establishedState.Context);
            var stateChanged = currentState.State != establishedState.State;

            if (stateChanged && AppConfigProvider.GetAppConfigValue <bool>("ObjectCacheDebuggingEnabled"))
            {
                Debug.WriteLine(string.Format(
                                    "ObjCache - Checkout Shipping Selection Changed - Customer {0}",
                                    ((CheckoutShippingSelectionDependencyStateContext)establishedState.Context).CustomerId));
            }

            return(stateChanged);
        }
コード例 #10
0
ファイル: QueryDependency.cs プロジェクト: giagiigi/WE
        public bool?HasStateChanged(DependencyState establishedState)
        {
            if (!(establishedState.Context is QueryDependencyStateContext))
            {
                return(null);
            }

            var currentState = GetState((QueryDependencyStateContext)establishedState.Context);
            var stateChanged = currentState.State != establishedState.State;

            if (stateChanged && AppConfigProvider.GetAppConfigValue <bool>("ObjectCacheDebuggingEnabled"))
            {
                Debug.WriteLine(string.Format(
                                    "ObjCache - Query Changed - {0}",
                                    ((QueryDependencyStateContext)establishedState.Context).Query));
            }

            return(stateChanged);
        }
コード例 #11
0
        string BuildDefaultRedirectUrl(string defaultUrlAppConfigName)
        {
            var defaultUrl = AppConfigProvider.GetAppConfigValue(defaultUrlAppConfigName);

            Uri redirectUri;

            if (string.IsNullOrWhiteSpace(defaultUrl) || !Uri.TryCreate(defaultUrl, UriKind.RelativeOrAbsolute, out redirectUri))
            {
                return("~/");
            }

            // If the URL is absolute or rooted, use it as-is.
            if (redirectUri.IsAbsoluteUri ||
                redirectUri.OriginalString.StartsWith("/") ||
                redirectUri.OriginalString.StartsWith("~"))
            {
                return(defaultUrl);
            }

            // If the URL relative and unrooted, it will be appended
            // to the current URL, which is undesirable. In that case,
            // prepend the virtual root.
            return($"~/{defaultUrl}");
        }
コード例 #12
0
ファイル: eWay.cs プロジェクト: vijayamazon/CaniGold.Store
        public override string ProcessCard(
            int orderNumber,
            int customerId,
            decimal orderTotal,
            bool useLiveTransactions,
            TransactionModeEnum transactionMode,
            AspDotNetStorefrontCore.Address billingAddress,
            string cardExtraCode,
            AspDotNetStorefrontCore.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)
        {
            AVSResult             = string.Empty;
            authorizationResult   = string.Empty;
            authorizationCode     = string.Empty;
            authorizationTransId  = string.Empty;
            transactionCommandOut = string.Empty;
            transactionResponse   = string.Empty;

            try
            {
                if (AppConfigProvider.GetAppConfigValue("Localization.StoreCurrency") != "AUD" &&
                    AppConfigProvider.GetAppConfigValue("Localization.StoreCurrency") != "NZD")
                {
                    return("eWAY requires that the store currency be either AUD or NZD.");
                }

                var cardDetails = new CardDetails()
                {
                    Name        = $"{billingAddress.FirstName} {billingAddress.LastName}",
                    Number      = billingAddress.CardNumber,
                    ExpiryMonth = FormatExpiryMonth(billingAddress.CardExpirationMonth),
                    ExpiryYear  = FormatExpiryYear(billingAddress.CardExpirationYear),
                    CVN         = cardExtraCode
                };

                var address = new eWAY.Rapid.Models.Address()
                {
                    Street1    = billingAddress.Address1,
                    Street2    = billingAddress.Address2,
                    City       = billingAddress.City,
                    State      = billingAddress.State,
                    PostalCode = billingAddress.Zip,
                    Country    = AppLogic.GetCountryTwoLetterISOCode(billingAddress.Country),
                };

                var customer = new eWAY.Rapid.Models.Customer()
                {
                    FirstName   = billingAddress.FirstName,
                    LastName    = billingAddress.LastName,
                    Email       = billingAddress.EMail,
                    Phone       = billingAddress.Phone,
                    CardDetails = cardDetails,
                    Address     = address
                };

                var paymentDetails = new PaymentDetails()
                {
                    TotalAmount   = DecimalToFixedPoint(orderTotal),
                    InvoiceNumber = orderNumber.ToString(),
                    CurrencyCode  = Currency.GetDefaultCurrency()
                };

                var transaction = new Transaction()
                {
                    Customer        = customer,
                    PaymentDetails  = paymentDetails,
                    TransactionType = TransactionTypes.Purchase,
                    Capture         = transactionMode == TransactionModeEnum.authcapture
                                                ? true
                                                : false
                };

                transactionCommandOut = SanitizeTransaction(
                    XmlCommon.SerializeObject(transaction, transaction.GetType()),
                    new Dictionary <string, string>()
                {
                    { $">{billingAddress.CardNumber}</", $">{AppLogic.SafeDisplayCardNumber(billingAddress.CardNumber, "Orders", 0)}</" },
                    { $">{cardExtraCode}</", ">***</" },
                });

                var response = GetRapidClient()
                               .Create(PaymentMethod.Direct, transaction);

                if (response.TransactionStatus == null)
                {
                    return("Error calling payment gateway.");
                }

                transactionResponse = XmlCommon.SerializeObject(response, response.GetType());

                authorizationResult = response.TransactionStatus.ProcessingDetails?.ResponseMessage;

                if ((response.TransactionStatus.Status ?? false) == false)
                {
                    var errorCode = string.IsNullOrWhiteSpace(authorizationResult) &&
                                    response.Errors != null
                                                ? string.Join(" ", response.Errors)
                                                : authorizationResult;

                    return($"There was a problem processing the credit card transaction.  Error code: {errorCode}");
                }

                AVSResult            = response.TransactionStatus.VerificationResult?.CVN.ToString();
                authorizationCode    = response.TransactionStatus.ProcessingDetails.AuthorisationCode;
                authorizationTransId = response.TransactionStatus.TransactionID.ToString();
            }
            catch (Exception exception)
            {
                SysLog.LogException(exception, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                return("Error calling payment gateway.");
            }

            return(AppLogic.ro_OK);
        }
コード例 #13
0
        public ActionResult Webhook(WebhookPayload webhookPayload)
        {
            if (AppConfigProvider.GetAppConfigValue <bool>("Signifyd.Log.Enabled"))
            {
                SysLog.LogMessage(
                    message: "Received a webhook call from Signifyd.",
                    details: webhookPayload.ToString(),
                    messageType: MessageTypeEnum.Informational,
                    messageSeverity: MessageSeverityEnum.Alert);
            }

            var signifydConfiguration = SignifydConfigurationProvider.Create();

            if (!VerifyAuthenticity(signifydConfiguration))
            {
                return(null);
            }

            // Get current order status
            var orderStatus = DB.GetSqlS("select GuaranteedStatus S from [SignifydOrderStatus] where OrderNumber = @orderNumber", new SqlParameter("@orderNumber", (int)webhookPayload.OrderId));

            // if not found, report error and bail
            if (string.IsNullOrEmpty(orderStatus))
            {
                if (AppConfigProvider.GetAppConfigValue <bool>("Signifyd.Log.Enabled"))
                {
                    SysLog.LogException(new Exception($"Signifyd called Webhook for non-existent order {webhookPayload.OrderId}"), MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                }
                return(null);
            }

            var orderDisposition = (GuaranteeDisposition)Enum.Parse(typeof(GuaranteeDisposition), orderStatus, true);

            switch (Request.Headers[RequestHeaderSignifydTopic])
            {
            case TopicGuaranteeCompletion:

                var order = new Order((int)webhookPayload.OrderId);

                if (webhookPayload.GuaranteeDisposition == GuaranteeDisposition.APPROVED &&
                    (orderDisposition == GuaranteeDisposition.PENDING ||
                     orderDisposition == GuaranteeDisposition.INREVIEW))
                {
                    OrderApproved(order, AppLogic.TransactionModeIsAuthCapture());
                }

                if (webhookPayload.GuaranteeDisposition == GuaranteeDisposition.DECLINED &&
                    (orderDisposition == GuaranteeDisposition.PENDING ||
                     orderDisposition == GuaranteeDisposition.INREVIEW))
                {
                    OrderDeclined(order, signifydConfiguration.DeclineActionVoid);
                }

                DB.ExecuteSQL("update [SignifydOrderStatus] set GuaranteedStatus = @guaranteeStatus where OrderNumber = @orderNumber",
                              new[]
                {
                    new SqlParameter("@guaranteeStatus", webhookPayload.GuaranteeDisposition.ToString()),
                    new SqlParameter("@orderNumber", (int)webhookPayload.OrderId)
                });

                break;

            case TopicCaseCreation:
                break;

            case TopicCaseRescore:
                break;

            case TopicCaseReview:
                break;

            case TopicClaimReviewed:
                break;

            case TopicTest:
                break;

            default:
                SysLog.LogException(new Exception($"Unrecognized Signifyd webhook topic: {Request.Headers[RequestHeaderSignifydTopic]}"), MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                break;
            }

            return(null);
        }
コード例 #14
0
        public ActionResult GoogleCustomerReviewsOptInSurvey(int orderNumber)
        {
            if (!AppConfigProvider.GetAppConfigValue <bool>("GoogleCustomerReviewsEnabled") ||
                string.IsNullOrEmpty(AppConfigProvider.GetAppConfigValue("GoogleCustomerReviewsMerchantID")))
            {
                return(Content(string.Empty));
            }

            long number;
            var  customer = HttpContext.GetCustomer();
            var  order    = new Order(orderNumber, customer.LocaleSetting);

            var model = new GoogleCustomerReviewsOptInSurveyViewModel(
                orderNumber: orderNumber,
                email: !string.IsNullOrEmpty(customer.EMail)
                                        ? customer.EMail
                                        : "*****@*****.**",
                countryCode: AppLogic.GetCountryTwoLetterISOCode(order.ShippingAddress.m_Country),
                deliveryDate: DateTime
                .Now
                .AddDays(AppConfigProvider.GetAppConfigValue <int>("GoogleCustomerReviewsDeliveryLeadTime"))
                .ToString("yyyy-MM-dd"),
                badgeEnabled: AppConfigProvider.GetAppConfigValue <bool>("GoogleCustomerReviewsBadgeEnabled"),
                merchantId: long.TryParse(AppConfigProvider.GetAppConfigValue("GoogleCustomerReviewsMerchantID"), out number)
                                        ? number
                                        : 0,
                language: AppConfigProvider.GetAppConfigValue("GoogleCustomerReviewsLanguage"),
                surveyPosition: AppConfigProvider.GetAppConfigValue("GoogleCustomerReviewsOptInSurveyPosition"));

            return(PartialView(ViewNames.GoogleCustomerReviewsOptInSurveyPartial, model));
        }
コード例 #15
0
 public SiteMapSettings LoadSiteMapSettings()
 => new SiteMapSettings(
     showCategories: AppLogic.IsAdminSite || AppConfigProvider.GetAppConfigValue <bool>("SiteMap.ShowCategories"),
     showSections: AppLogic.IsAdminSite || AppConfigProvider.GetAppConfigValue <bool>("SiteMap.ShowSections"),
     showManufacturers: AppLogic.IsAdminSite || AppConfigProvider.GetAppConfigValue <bool>("SiteMap.ShowManufacturers"),
     showTopics: AppLogic.IsAdminSite || AppConfigProvider.GetAppConfigValue <bool>("SiteMap.ShowTopics"),
     showProducts: AppLogic.IsAdminSite || AppConfigProvider.GetAppConfigValue <bool>("SiteMap.ShowProducts"),
     showCustomerService: AppLogic.IsAdminSite || AppConfigProvider.GetAppConfigValue <bool>("SiteMap.ShowCustomerService"),
     productFiltering: AppConfigProvider.GetAppConfigValue <bool>("AllowProductFiltering"),
     entityFiltering: AppConfigProvider.GetAppConfigValue <bool>("AllowEntityFiltering"),
     topicFiltering: AppConfigProvider.GetAppConfigValue <bool>("AllowTopicFiltering"),
     inventoryThreshold: AppConfigProvider.GetAppConfigValue <int>("HideProductsWithLessThanThisInventoryLevel"),
     entityChangeFrequency: AppConfigProvider.GetAppConfigValue("SiteMapFeed.EntityChangeFreq"),
     entityPriority: AppConfigProvider.GetAppConfigValue("SiteMapFeed.EntityPriority"),
     objectChangeFrequency: AppConfigProvider.GetAppConfigValue("SiteMapFeed.ObjectChangeFreq"),
     objectPriority: AppConfigProvider.GetAppConfigValue("SiteMapFeed.ObjectPriority"),
     topicChangeFrequency: AppConfigProvider.GetAppConfigValue("SiteMapFeed.TopicChangeFreq"),
     topicPriority: AppConfigProvider.GetAppConfigValue("SiteMapFeed.TopicPriority"));
コード例 #16
0
        public override string CaptureOrder(Order order)
        {
            var result        = AppLogic.ro_OK;
            var transactionId = LookupSagePayPiTransactionId(order.OrderNumber);

            if (string.IsNullOrEmpty(transactionId))
            {
                return(StringResourceProvider.GetString("admin.sagepaypi.notransactionid"));
            }

            var jsonObject = new JObject(
                new JProperty("instructionType", "release"),
                new JProperty("amount", GetSmallestCurrencyUnit(order.OrderBalance, Localization.StoreCurrency()))
                );

            var transactionUrl = string.Format(
                "{0}transactions/{1}",
                AppConfigProvider.GetAppConfigValue <bool>("UseLiveTransactions")
                                        ? AppConfigProvider.GetAppConfigValue("SagePayPi.LiveUrl")
                                        : AppConfigProvider.GetAppConfigValue("SagePayPi.TestUrl"),
                transactionId);

            var instructionsTransactionUrl = $"{transactionUrl}/instructions";
            var apiResponse = SagePayPiApiCall(jsonObject.ToString(), instructionsTransactionUrl, "POST");
            var formattedTransactionResponse = JObject.Parse(apiResponse);
            var responseHasError             = ResponseHasError(formattedTransactionResponse, "instructionType", "release");

            DB.ExecuteSQL("update orders set CaptureTXCommand = @CaptureTXCommand where OrderNumber = @OrderNumber",
                          new SqlParameter("@CaptureTXCommand", $"{order.CaptureTXCommand}" +
                                           $"{Environment.NewLine}" +
                                           $"{Environment.NewLine}" +
                                           $"POST Method - URL: {instructionsTransactionUrl}, " +
                                           $"Request: {jsonObject}"),
                          new SqlParameter("@OrderNumber", order.OrderNumber));

            DB.ExecuteSQL("update orders set CaptureTXResult = @CaptureTXResult where OrderNumber = @OrderNumber",
                          new SqlParameter("@CaptureTXResult", $"{order.CaptureTXResult}" +
                                           $"{Environment.NewLine}" +
                                           $"{Environment.NewLine}" +
                                           $"{formattedTransactionResponse}"),
                          new SqlParameter("@OrderNumber", order.OrderNumber));

            if (responseHasError)
            {
                var error = GetResponseError(formattedTransactionResponse, "description");

                if (error.EqualsIgnoreCase(StringResourceProvider.GetString("sagepaypi.error.unknownresponseerror")))
                {
                    error = GetResponseError(formattedTransactionResponse, "errors");
                }

                if (error.EqualsIgnoreCase("Transaction status not applicable"))
                {
                    error = StringResourceProvider.GetString("admin.sagepaypi.error.nolongercapturable");
                }

                result = error;
            }
            return(result);
        }
コード例 #17
0
        public override string CaptureOrder(AspDotNetStorefrontCore.Order order)
        {
            var useLiveTransactions = AppConfigProvider.GetAppConfigValue <bool>("UseLiveTransactions");

            var orderTotal = order.Total();

            orderTotal.ValidateNumberOfDigits(15);             // Accept.js limit

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.priorAuthCaptureTransaction.ToString(),
                amount          = orderTotal,
                amountSpecified = true,
                refTransId      = order.AuthorizationPNREF,
            };

            if (useLiveTransactions)
            {
                transactionRequest.solution = new solutionType
                {
                    id = SolutionId
                }
            }
            ;

            var request = new createTransactionRequest
            {
                transactionRequest     = transactionRequest,
                merchantAuthentication = GetMerchantAuthentication(useLiveTransactions)
            };

            //Save the command we're sending
            order.CaptureTXCommand = JsonConvert.SerializeObject(request);

            var controller = new createTransactionController(request);

            controller.Execute(
                GetRunEnvironment(useLiveTransactions));

            var response = controller.GetApiResponse();

            if (response == null)
            {
                return("NO RESPONSE FROM GATEWAY!");
            }

            //Save the response
            order.CaptureTXResult = JsonConvert.SerializeObject(response);

            if (response.messages.resultCode != messageTypeEnum.Ok)
            {
                return(response.transactionResponse?.errors?[0].errorText
                       ?? response.messages.message[0].text);
            }

            if (response.transactionResponse.messages == null)
            {
                return(response.transactionResponse.errors?[0].errorText
                       ?? "Unspecified Error");
            }

            return(AppLogic.ro_OK);
        }
コード例 #18
0
 public bool ShippingAddressMustMatchBillingAddress(CheckoutEngine.StateMachineContext context)
 {
     return(!AppConfigProvider.GetAppConfigValue <bool>("AllowShipToDifferentThanBillTo"));
 }
コード例 #19
0
        public CheckoutAccountStatus GetCheckoutAccountStatus(Customer customer, string email)
        {
            var guestCheckoutType = AppConfigProvider.GetAppConfigValue <GuestCheckoutType>("GuestCheckout");

            // If the customer is already logged in, we've got everything we need.
            // Just set the mode to "Registered" to indicate we have a "locked" registered customer.
            if (customer.IsRegistered)
            {
                return(new CheckoutAccountStatus(
                           email: customer.EMail,
                           state: CheckoutAccountState.Registered,
                           nextAction: CheckoutAccountAction.None,
                           requireRegisteredCustomer: false));
            }

            // If the customer is not logged in and hasn't given us an email, we don't have anything to work with yet.
            // Set the mode to "EnterEmail" to indicate we need that first.
            if (string.IsNullOrWhiteSpace(email))
            {
                return(new CheckoutAccountStatus(
                           email: string.Empty,
                           state: CheckoutAccountState.Unvalidated,
                           nextAction: CheckoutAccountAction.MustProvideEmail,
                           requireRegisteredCustomer: false));
            }

            // If we have an email address and we're forcing guest checkouts, then we will never need anything more.
            // Set the mode to "Guest" to indicate we have a "locked" guest customer.
            if (guestCheckoutType == GuestCheckoutType.PasswordNeverRequestedAtCheckout)
            {
                return(new CheckoutAccountStatus(
                           email: email,
                           state: CheckoutAccountState.Guest,
                           nextAction: CheckoutAccountAction.None,
                           requireRegisteredCustomer: false));
            }

            // If we got this far, it means we have an email that may or may not be registered. The remaining modes
            // depends on knowing which.
            var emailIsAlreadyRegistered = Customer.EmailInUse(
                email: email,
                customerId: customer.CustomerID,
                excludeUnregisteredUsers: true);

            // Finally, decide if we require a logged in user.
            var cart = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var requireRegisteredCustomer =
                cart.HasRecurringComponents() ||
                guestCheckoutType == GuestCheckoutType.Disabled ||
                (emailIsAlreadyRegistered && guestCheckoutType != GuestCheckoutType.AllowRegisteredCustomers);

            // Now we can return a status that indicates the following:
            //	- The email address is already registered and the user must login to continue using it
            //	- The email address is already registered, but the user may continue using it without logging in
            //	- The email address is unregistered, but must create an account to continue using it
            //	- The email address is unregistered and the user may continue using it without creating an account
            return(new CheckoutAccountStatus(
                       email: email,
                       state: requireRegisteredCustomer
                                        ? CheckoutAccountState.Unvalidated
                                        : CheckoutAccountState.Guest,
                       nextAction: emailIsAlreadyRegistered
                                        ? CheckoutAccountAction.CanLogin
                                        : CheckoutAccountAction.CanCreateAccount,
                       requireRegisteredCustomer: requireRegisteredCustomer));
        }
コード例 #20
0
 public ActionResult Index()
 {
     return(PartialView(ViewNames.Captcha,
                        new CaptchaViewModel(AppConfigProvider.GetAppConfigValue("reCAPTCHA.SiteKey"))));
 }
コード例 #21
0
 public bool IsEnabled(string country)
 {
     return(AppConfigProvider.GetAppConfigValue <bool>("Address.UsePostalCodeLookupService") &&
            !AppLogic.GetCountryIsInternational(country));
 }