Пример #1
0
        public PayPalResponse EnsureAccessToken(PayPalSessionData session, PayPalApiSettingsBase settings)
        {
            if (session.AccessToken.IsEmpty() || DateTime.UtcNow >= session.TokenExpiration)
            {
                var result = CallApi("POST", "/v1/oauth2/token", null, settings, "grant_type=client_credentials");

                if (result.Success)
                {
                    session.AccessToken = (string)result.Json.access_token;

                    var expireSeconds = ((string)result.Json.expires_in).ToInt(5 * 60);

                    session.TokenExpiration = DateTime.UtcNow.AddSeconds(expireSeconds);
                }
                else
                {
                    return(result);
                }
            }

            return(new PayPalResponse
            {
                Success = session.AccessToken.HasValue()
            });
        }
Пример #2
0
        public PayPalResponse Refund(PayPalApiSettingsBase settings, PayPalSessionData session, RefundPaymentRequest request)
        {
            var data   = new Dictionary <string, object>();
            var store  = _services.StoreService.GetStoreById(request.Order.StoreId);
            var isSale = request.Order.AuthorizationTransactionResult.Contains("(sale)");

            var path = "/v1/payments/{0}/{1}/refund".FormatInvariant(isSale ? "sale" : "capture", request.Order.CaptureTransactionId);

            var amount = new Dictionary <string, object>();

            amount.Add("total", request.AmountToRefund.FormatInvariant());
            amount.Add("currency", store.PrimaryStoreCurrency.CurrencyCode);

            data.Add("amount", amount);

            var result = CallApi("POST", path, session.AccessToken, settings, data.Any() ? JsonConvert.SerializeObject(data) : null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            //Logger.InsertLog(LogLevel.Information, "PayPal Refund", JsonConvert.SerializeObject(data, Formatting.Indented) + "\r\n\r\n" + (result.Json != null ? result.Json.ToString() : ""));

            return(result);
        }
Пример #3
0
        public PayPalResponse Capture(PayPalApiSettingsBase settings, PayPalSessionData session, CapturePaymentRequest request)
        {
            var data = new Dictionary <string, object>();
            //var isAuthorize = request.Order.AuthorizationTransactionCode.IsCaseInsensitiveEqual("authorize");

            var path = "/v1/payments/authorization/{0}/capture".FormatInvariant(request.Order.AuthorizationTransactionId);

            var store = _services.StoreService.GetStoreById(request.Order.StoreId);

            var amount = new Dictionary <string, object>();

            amount.Add("total", request.Order.OrderTotal.FormatInvariant());
            amount.Add("currency", store.PrimaryStoreCurrency.CurrencyCode);

            data.Add("amount", amount);

            var result = CallApi("POST", path, session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return(result);
        }
Пример #4
0
        public PayPalResponse DeleteWebhook(PayPalApiSettingsBase settings, PayPalSessionData session)
        {
            var result = CallApi("DELETE", "/v1/notifications/webhooks/" + settings.WebhookId, session.AccessToken, settings, null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return(result);
        }
Пример #5
0
        public PayPalResponse GetPayment(PayPalApiSettingsBase settings, PayPalSessionData session)
        {
            var result = CallApi("GET", "/v1/payments/payment/" + session.PaymentId, session.AccessToken, settings, null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return(result);
        }
Пример #6
0
        public PayPalResponse Void(PayPalApiSettingsBase settings, PayPalSessionData session, VoidPaymentRequest request)
        {
            var path = "/v1/payments/authorization/{0}/void".FormatInvariant(request.Order.AuthorizationTransactionId);

            var result = CallApi("POST", path, session.AccessToken, settings, null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return(result);
        }
Пример #7
0
        public PayPalResponse CreateWebhook(PayPalApiSettingsBase settings, PayPalSessionData session, string url)
        {
            var data   = new Dictionary <string, object>();
            var events = new List <Dictionary <string, object> >();

            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.AUTHORIZATION.VOIDED" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.CAPTURE.COMPLETED" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.CAPTURE.DENIED" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.CAPTURE.PENDING" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.CAPTURE.REFUNDED" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.CAPTURE.REVERSED" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.SALE.COMPLETED" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.SALE.DENIED" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.SALE.PENDING" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.SALE.REFUNDED" }
            });
            events.Add(new Dictionary <string, object> {
                { "name", "PAYMENT.SALE.REVERSED" }
            });

            data.Add("url", url);
            data.Add("event_types", events);

            var result = CallApi("POST", "/v1/notifications/webhooks", session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return(result);
        }
Пример #8
0
        public PayPalResponse ExecutePayment(PayPalApiSettingsBase settings, PayPalSessionData session)
        {
            var data = new Dictionary <string, object>();

            data.Add("payer_id", session.PayerId);

            var result = CallApi("POST", "/v1/payments/payment/{0}/execute".FormatInvariant(session.PaymentId), session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;

                //Logger.InsertLog(LogLevel.Information, "PayPal PLUS", JsonConvert.SerializeObject(data, Formatting.Indented) + "\r\n\r\n" + result.Json.ToString());
            }

            return(result);
        }
        public PayPalResponse ExecutePayment(PayPalApiSettingsBase settings, PayPalSessionData session)
        {
            var data = new Dictionary<string, object>();
            data.Add("payer_id", session.PayerId);

            var result = CallApi("POST", "/v1/payments/payment/{0}/execute".FormatInvariant(session.PaymentId), session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;

                //Logger.InsertLog(LogLevel.Information, "PayPal PLUS", JsonConvert.SerializeObject(data, Formatting.Indented) + "\r\n\r\n" + result.Json.ToString());
            }

            return result;
        }
        public PayPalResponse Void(PayPalApiSettingsBase settings, PayPalSessionData session, VoidPaymentRequest request)
        {
            var path = "/v1/payments/authorization/{0}/void".FormatInvariant(request.Order.AuthorizationTransactionId);

            var result = CallApi("POST", path, session.AccessToken, settings, null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return result;
        }
        public PayPalResponse Capture(PayPalApiSettingsBase settings, PayPalSessionData session, CapturePaymentRequest request)
        {
            var data = new Dictionary<string, object>();
            //var isAuthorize = request.Order.AuthorizationTransactionCode.IsCaseInsensitiveEqual("authorize");

            var path = "/v1/payments/authorization/{0}/capture".FormatInvariant(request.Order.AuthorizationTransactionId);

            var store = _services.StoreService.GetStoreById(request.Order.StoreId);

            var amount = new Dictionary<string, object>();
            amount.Add("total", request.Order.OrderTotal.FormatInvariant());
            amount.Add("currency", store.PrimaryStoreCurrency.CurrencyCode);

            data.Add("amount", amount);

            var result = CallApi("POST", path, session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return result;
        }
Пример #12
0
        public PayPalResponse CreatePayment(
            PayPalApiSettingsBase settings,
            PayPalSessionData session,
            List <OrganizedShoppingCartItem> cart,
            string providerSystemName,
            string returnUrl,
            string cancelUrl)
        {
            var store        = _services.StoreContext.CurrentStore;
            var customer     = _services.WorkContext.CurrentCustomer;
            var language     = _services.WorkContext.WorkingLanguage;
            var currencyCode = store.PrimaryStoreCurrency.CurrencyCode;

            var dateOfBirth = customer.GetAttribute <DateTime?>(SystemCustomerAttributeNames.DateOfBirth);

            Discount orderAppliedDiscount;
            List <AppliedGiftCard> appliedGiftCards;
            int     redeemedRewardPoints = 0;
            decimal redeemedRewardPointsAmount;
            decimal orderDiscountInclTax;
            decimal totalOrderItems = decimal.Zero;

            var includingTax = (_services.WorkContext.GetTaxDisplayTypeFor(customer, store.Id) == TaxDisplayType.IncludingTax);

            var shipping = (_orderTotalCalculationService.GetShoppingCartShippingTotal(cart) ?? decimal.Zero);

            var paymentFee = _paymentService.GetAdditionalHandlingFee(cart, providerSystemName);

            var total = (_orderTotalCalculationService.GetShoppingCartTotal(cart, out orderDiscountInclTax, out orderAppliedDiscount, out appliedGiftCards,
                                                                            out redeemedRewardPoints, out redeemedRewardPointsAmount) ?? decimal.Zero);

            var data          = new Dictionary <string, object>();
            var redirectUrls  = new Dictionary <string, object>();
            var payer         = new Dictionary <string, object>();
            var payerInfo     = new Dictionary <string, object>();
            var transaction   = new Dictionary <string, object>();
            var amount        = new Dictionary <string, object>();
            var amountDetails = new Dictionary <string, object>();
            var items         = new List <Dictionary <string, object> >();
            var itemList      = new Dictionary <string, object>();

            // "PayPal PLUS only supports transaction type “Sale” (instant settlement)"
            if (providerSystemName == PayPalPlusProvider.SystemName)
            {
                data.Add("intent", "sale");
            }
            else
            {
                data.Add("intent", settings.TransactMode == TransactMode.AuthorizeAndCapture ? "sale" : "authorize");
            }

            if (settings.ExperienceProfileId.HasValue())
            {
                data.Add("experience_profile_id", settings.ExperienceProfileId);
            }

            // redirect urls
            if (returnUrl.HasValue())
            {
                redirectUrls.Add("return_url", returnUrl);
            }

            if (cancelUrl.HasValue())
            {
                redirectUrls.Add("cancel_url", cancelUrl);
            }

            if (redirectUrls.Any())
            {
                data.Add("redirect_urls", redirectUrls);
            }

            // payer, payer_info
            if (dateOfBirth.HasValue)
            {
                payerInfo.Add("birth_date", dateOfBirth.Value.ToString("yyyy-MM-dd"));
            }
            if (customer.BillingAddress != null)
            {
                payerInfo.Add("billing_address", CreateAddress(customer.BillingAddress, false));
            }

            payer.Add("payment_method", "paypal");
            payer.Add("payer_info", payerInfo);
            data.Add("payer", payer);

            // line items
            foreach (var item in cart)
            {
                decimal unitPriceTaxRate = decimal.Zero;
                decimal unitPrice        = _priceCalculationService.GetUnitPrice(item, true);
                decimal productPrice     = _taxService.GetProductPrice(item.Item.Product, unitPrice, includingTax, customer, out unitPriceTaxRate);

                var line = new Dictionary <string, object>();
                line.Add("quantity", item.Item.Quantity);
                line.Add("name", item.Item.Product.GetLocalized(x => x.Name, language.Id, true, false).Truncate(127));
                line.Add("price", productPrice.FormatInvariant());
                line.Add("currency", currencyCode);
                line.Add("sku", item.Item.Product.Sku.Truncate(50));
                items.Add(line);

                totalOrderItems += (productPrice * item.Item.Quantity);
            }

            var itemsPlusMisc = (totalOrderItems + shipping + paymentFee);

            if (total != itemsPlusMisc)
            {
                var line = new Dictionary <string, object>();
                line.Add("quantity", "1");
                line.Add("name", T("Plugins.SmartStore.PayPal.Other").Text.Truncate(127));
                line.Add("price", (total - itemsPlusMisc).FormatInvariant());
                line.Add("currency", currencyCode);
                items.Add(line);

                totalOrderItems += (total - itemsPlusMisc);
            }

            itemList.Add("items", items);
            if (customer.ShippingAddress != null)
            {
                itemList.Add("shipping_address", CreateAddress(customer.ShippingAddress, true));
            }

            // transactions
            amountDetails.Add("shipping", shipping.FormatInvariant());
            amountDetails.Add("subtotal", totalOrderItems.FormatInvariant());
            if (!includingTax)
            {
                // "To avoid rounding errors we recommend not submitting tax amounts on line item basis.
                // Calculated tax amounts for the entire shopping basket may be submitted in the amount objects.
                // In this case the item amounts will be treated as amounts excluding tax.
                // In a B2C scenario, where taxes are included, no taxes should be submitted to PayPal."

                SortedDictionary <decimal, decimal> taxRates = null;
                var taxTotal = _orderTotalCalculationService.GetTaxTotal(cart, out taxRates);

                amountDetails.Add("tax", taxTotal.FormatInvariant());
            }
            if (paymentFee != decimal.Zero)
            {
                amountDetails.Add("handling_fee", paymentFee.FormatInvariant());
            }

            amount.Add("total", total.FormatInvariant());
            amount.Add("currency", currencyCode);
            amount.Add("details", amountDetails);

            transaction.Add("amount", amount);
            transaction.Add("item_list", itemList);
            transaction.Add("invoice_number", session.OrderGuid.ToString());

            data.Add("transactions", new List <Dictionary <string, object> > {
                transaction
            });

            var result = CallApi("POST", "/v1/payments/payment", session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            //Logger.InsertLog(LogLevel.Information, "PayPal PLUS", JsonConvert.SerializeObject(data, Formatting.Indented) + "\r\n\r\n" + (result.Json != null ? result.Json.ToString() : ""));

            return(result);
        }
        public PayPalResponse CreateWebhook(PayPalApiSettingsBase settings, PayPalSessionData session, string url)
        {
            var data = new Dictionary<string, object>();
            var events = new List<Dictionary<string, object>>();

            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.AUTHORIZATION.VOIDED" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.CAPTURE.COMPLETED" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.CAPTURE.DENIED" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.CAPTURE.PENDING" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.CAPTURE.REFUNDED" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.CAPTURE.REVERSED" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.SALE.COMPLETED" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.SALE.DENIED" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.SALE.PENDING" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.SALE.REFUNDED" } });
            events.Add(new Dictionary<string, object> { { "name", "PAYMENT.SALE.REVERSED" } });

            data.Add("url", url);
            data.Add("event_types", events);

            var result = CallApi("POST", "/v1/notifications/webhooks", session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return result;
        }
        public PayPalResponse CreatePayment(
			PayPalApiSettingsBase settings,
			PayPalSessionData session,
			List<OrganizedShoppingCartItem> cart,
			string providerSystemName,
			string returnUrl,
			string cancelUrl)
        {
            var store = _services.StoreContext.CurrentStore;
            var customer = _services.WorkContext.CurrentCustomer;
            var language = _services.WorkContext.WorkingLanguage;
            var currencyCode = store.PrimaryStoreCurrency.CurrencyCode;

            var dateOfBirth = customer.GetAttribute<DateTime?>(SystemCustomerAttributeNames.DateOfBirth);

            Discount orderAppliedDiscount;
            List<AppliedGiftCard> appliedGiftCards;
            int redeemedRewardPoints = 0;
            decimal redeemedRewardPointsAmount;
            decimal orderDiscountInclTax;
            decimal totalOrderItems = decimal.Zero;

            var includingTax = (_services.WorkContext.GetTaxDisplayTypeFor(customer, store.Id) == TaxDisplayType.IncludingTax);

            var shipping = (_orderTotalCalculationService.GetShoppingCartShippingTotal(cart) ?? decimal.Zero);

            var paymentFee = _paymentService.GetAdditionalHandlingFee(cart, providerSystemName);

            var total = (_orderTotalCalculationService.GetShoppingCartTotal(cart, out orderDiscountInclTax, out orderAppliedDiscount, out appliedGiftCards,
                out redeemedRewardPoints, out redeemedRewardPointsAmount) ?? decimal.Zero);

            var data = new Dictionary<string, object>();
            var redirectUrls = new Dictionary<string, object>();
            var payer = new Dictionary<string, object>();
            var payerInfo = new Dictionary<string, object>();
            var transaction = new Dictionary<string, object>();
            var amount = new Dictionary<string, object>();
            var amountDetails = new Dictionary<string, object>();
            var items = new List<Dictionary<string, object>>();
            var itemList = new Dictionary<string, object>();

            // "PayPal PLUS only supports transaction type “Sale” (instant settlement)"
            if (providerSystemName == PayPalPlusProvider.SystemName)
                data.Add("intent", "sale");
            else
                data.Add("intent", settings.TransactMode == TransactMode.AuthorizeAndCapture ? "sale" : "authorize");

            if (settings.ExperienceProfileId.HasValue())
                data.Add("experience_profile_id", settings.ExperienceProfileId);

            // redirect urls
            if (returnUrl.HasValue())
                redirectUrls.Add("return_url", returnUrl);

            if (cancelUrl.HasValue())
                redirectUrls.Add("cancel_url", cancelUrl);

            if (redirectUrls.Any())
                data.Add("redirect_urls", redirectUrls);

            // payer, payer_info
            if (dateOfBirth.HasValue)
            {
                payerInfo.Add("birth_date", dateOfBirth.Value.ToString("yyyy-MM-dd"));
            }
            if (customer.BillingAddress != null)
            {
                payerInfo.Add("billing_address", CreateAddress(customer.BillingAddress, false));
            }

            payer.Add("payment_method", "paypal");
            payer.Add("payer_info", payerInfo);
            data.Add("payer", payer);

            // line items
            foreach (var item in cart)
            {
                decimal unitPriceTaxRate = decimal.Zero;
                decimal unitPrice = _priceCalculationService.GetUnitPrice(item, true);
                decimal productPrice = _taxService.GetProductPrice(item.Item.Product, unitPrice, includingTax, customer, out unitPriceTaxRate);

                var line = new Dictionary<string, object>();
                line.Add("quantity", item.Item.Quantity);
                line.Add("name", item.Item.Product.GetLocalized(x => x.Name, language.Id, true, false).Truncate(127));
                line.Add("price", productPrice.FormatInvariant());
                line.Add("currency", currencyCode);
                line.Add("sku", item.Item.Product.Sku.Truncate(50));
                items.Add(line);

                totalOrderItems += (productPrice * item.Item.Quantity);
            }

            var itemsPlusMisc = (totalOrderItems + shipping + paymentFee);

            if (total != itemsPlusMisc)
            {
                var line = new Dictionary<string, object>();
                line.Add("quantity", "1");
                line.Add("name", T("Plugins.SmartStore.PayPal.Other").Text.Truncate(127));
                line.Add("price", (total - itemsPlusMisc).FormatInvariant());
                line.Add("currency", currencyCode);
                items.Add(line);

                totalOrderItems += (total - itemsPlusMisc);
            }

            itemList.Add("items", items);
            if (customer.ShippingAddress != null)
            {
                itemList.Add("shipping_address", CreateAddress(customer.ShippingAddress, true));
            }

            // transactions
            amountDetails.Add("shipping", shipping.FormatInvariant());
            amountDetails.Add("subtotal", totalOrderItems.FormatInvariant());
            if (!includingTax)
            {
                // "To avoid rounding errors we recommend not submitting tax amounts on line item basis.
                // Calculated tax amounts for the entire shopping basket may be submitted in the amount objects.
                // In this case the item amounts will be treated as amounts excluding tax.
                // In a B2C scenario, where taxes are included, no taxes should be submitted to PayPal."

                SortedDictionary<decimal, decimal> taxRates = null;
                var taxTotal = _orderTotalCalculationService.GetTaxTotal(cart, out taxRates);

                amountDetails.Add("tax", taxTotal.FormatInvariant());
            }
            if (paymentFee != decimal.Zero)
            {
                amountDetails.Add("handling_fee", paymentFee.FormatInvariant());
            }

            amount.Add("total", total.FormatInvariant());
            amount.Add("currency", currencyCode);
            amount.Add("details", amountDetails);

            transaction.Add("amount", amount);
            transaction.Add("item_list", itemList);
            transaction.Add("invoice_number", session.OrderGuid.ToString());

            data.Add("transactions", new List<Dictionary<string, object>> { transaction });

            var result = CallApi("POST", "/v1/payments/payment", session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            //Logger.InsertLog(LogLevel.Information, "PayPal PLUS", JsonConvert.SerializeObject(data, Formatting.Indented) + "\r\n\r\n" + (result.Json != null ? result.Json.ToString() : ""));

            return result;
        }
        public PayPalResponse UpsertCheckoutExperience(PayPalApiSettingsBase settings, PayPalSessionData session, Store store)
        {
            PayPalResponse result;
            var name = store.Name;
            var logo = _pictureService.Value.GetPictureById(store.LogoPictureId);
            var path = "/v1/payment-experience/web-profiles";

            var data = new Dictionary<string, object>();
            var presentation = new Dictionary<string, object>();
            var inpuFields = new Dictionary<string, object>();

            // find existing profile id, only one profile per profile name possible
            if (settings.ExperienceProfileId.IsEmpty())
            {
                result = CallApi("GET", path, session.AccessToken, settings, null);
                if (result.Success && result.Json != null)
                {
                    foreach (var profile in result.Json)
                    {
                        var profileName = (string)profile.name;
                        if (profileName.IsCaseInsensitiveEqual(name))
                        {
                            settings.ExperienceProfileId = (string)profile.id;
                            break;
                        }
                    }
                }
            }

            presentation.Add("brand_name", name);
            presentation.Add("locale_code", _services.WorkContext.WorkingLanguage.UniqueSeoCode.EmptyNull().ToUpper());

            if (logo != null)
                presentation.Add("logo_image", _pictureService.Value.GetPictureUrl(logo, showDefaultPicture: false, storeLocation: store.Url));

            inpuFields.Add("allow_note", false);
            inpuFields.Add("no_shipping", 0);
            inpuFields.Add("address_override", 1);

            data.Add("name", name);
            data.Add("presentation", presentation);
            data.Add("input_fields", inpuFields);

            if (settings.ExperienceProfileId.HasValue())
                path = string.Concat(path, "/", HttpUtility.UrlPathEncode(settings.ExperienceProfileId));

            result = CallApi(settings.ExperienceProfileId.HasValue() ? "PUT" : "POST", path, session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success)
            {
                if (result.Json != null)
                    result.Id = (string)result.Json.id;
                else
                    result.Id = settings.ExperienceProfileId;
            }

            return result;
        }
Пример #16
0
        public PayPalResponse DeleteCheckoutExperience(PayPalApiSettingsBase settings, PayPalSessionData session)
        {
            var result = CallApi("DELETE", "/v1/payment-experience/web-profiles/" + settings.ExperienceProfileId, session.AccessToken, settings, null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return(result);
        }
        public PayPalResponse DeleteCheckoutExperience(PayPalApiSettingsBase settings, PayPalSessionData session)
        {
            var result = CallApi("DELETE", "/v1/payment-experience/web-profiles/" + settings.ExperienceProfileId, session.AccessToken, settings, null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return result;
        }
        public PayPalResponse EnsureAccessToken(PayPalSessionData session, PayPalApiSettingsBase settings)
        {
            if (session.AccessToken.IsEmpty() || DateTime.UtcNow >= session.TokenExpiration)
            {
                var result = CallApi("POST", "/v1/oauth2/token", null, settings, "grant_type=client_credentials");

                if (result.Success)
                {
                    session.AccessToken = (string)result.Json.access_token;

                    var expireSeconds = ((string)result.Json.expires_in).ToInt(5 * 60);

                    session.TokenExpiration = DateTime.UtcNow.AddSeconds(expireSeconds);
                }
                else
                {
                    return result;
                }
            }

            return new PayPalResponse
            {
                Success = session.AccessToken.HasValue()
            };
        }
        public PayPalResponse DeleteWebhook(PayPalApiSettingsBase settings, PayPalSessionData session)
        {
            var result = CallApi("DELETE", "/v1/notifications/webhooks/" + settings.WebhookId, session.AccessToken, settings, null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return result;
        }
Пример #20
0
        public PayPalResponse UpsertCheckoutExperience(PayPalApiSettingsBase settings, PayPalSessionData session, Store store)
        {
            PayPalResponse result;
            var            name = store.Name;
            var            logo = _pictureService.Value.GetPictureById(store.LogoPictureId);
            var            path = "/v1/payment-experience/web-profiles";

            var data         = new Dictionary <string, object>();
            var presentation = new Dictionary <string, object>();
            var inpuFields   = new Dictionary <string, object>();

            // find existing profile id, only one profile per profile name possible
            if (settings.ExperienceProfileId.IsEmpty())
            {
                result = CallApi("GET", path, session.AccessToken, settings, null);
                if (result.Success && result.Json != null)
                {
                    foreach (var profile in result.Json)
                    {
                        var profileName = (string)profile.name;
                        if (profileName.IsCaseInsensitiveEqual(name))
                        {
                            settings.ExperienceProfileId = (string)profile.id;
                            break;
                        }
                    }
                }
            }

            presentation.Add("brand_name", name);
            presentation.Add("locale_code", _services.WorkContext.WorkingLanguage.UniqueSeoCode.EmptyNull().ToUpper());

            if (logo != null)
            {
                presentation.Add("logo_image", _pictureService.Value.GetPictureUrl(logo, showDefaultPicture: false, storeLocation: store.Url));
            }

            inpuFields.Add("allow_note", false);
            inpuFields.Add("no_shipping", 0);
            inpuFields.Add("address_override", 1);

            data.Add("name", name);
            data.Add("presentation", presentation);
            data.Add("input_fields", inpuFields);

            if (settings.ExperienceProfileId.HasValue())
            {
                path = string.Concat(path, "/", HttpUtility.UrlPathEncode(settings.ExperienceProfileId));
            }

            result = CallApi(settings.ExperienceProfileId.HasValue() ? "PUT" : "POST", path, session.AccessToken, settings, JsonConvert.SerializeObject(data));

            if (result.Success)
            {
                if (result.Json != null)
                {
                    result.Id = (string)result.Json.id;
                }
                else
                {
                    result.Id = settings.ExperienceProfileId;
                }
            }

            return(result);
        }
        public PayPalResponse GetPayment(PayPalApiSettingsBase settings, PayPalSessionData session)
        {
            var result = CallApi("GET", "/v1/payments/payment/" + session.PaymentId, session.AccessToken, settings, null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            return result;
        }
Пример #22
0
        public FinancingOptions GetFinancingOptions(
            PayPalInstalmentsSettings settings,
            PayPalSessionData session,
            string origin,
            decimal amount,
            PayPalPromotion?promotion = null)
        {
            Guard.NotNull(settings, nameof(settings));
            Guard.NotNull(session, nameof(session));
            Guard.NotEmpty(origin, nameof(origin));

            var store = _services.StoreContext.CurrentStore;

            // Get promotion type.
            if (!promotion.HasValue)
            {
                switch (origin)
                {
                case "productpage":
                    promotion = settings.ProductPagePromotion;
                    break;

                case "cart":
                    promotion = settings.CartPagePromotion;
                    break;

                case "paymentinfo":
                    promotion = settings.PaymentListPromotion;
                    break;
                }
            }

            if (!promotion.HasValue || settings.ClientId.IsEmpty() || settings.Secret.IsEmpty())
            {
                return(null);
            }

            // Get financing amount.
            if (origin == "cart" || origin == "paymentinfo")
            {
                var     cart      = _services.WorkContext.CurrentCustomer.GetCartItems(ShoppingCartType.ShoppingCart, store.Id);
                decimal?cartTotal = _orderTotalCalculationService.GetShoppingCartTotal(cart, usePaymentMethodAdditionalFee: false);
                if (!cartTotal.HasValue)
                {
                    _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out _, out _, out _, out amount);
                }
                else
                {
                    amount = cartTotal.Value;
                }
            }

            if (!settings.IsAmountFinanceable(amount))
            {
                return(null);
            }

            // Get financing options from API.
            var result = new FinancingOptions(origin)
            {
                Promotion = promotion,
                Lender    = settings.Lender
            };

            var sourceCurrency = store.PrimaryStoreCurrency;
            var targetCurrency = _services.WorkContext.WorkingCurrency;

            result.NetLoanAmount = new Money(_currencyService.ConvertCurrency(amount, sourceCurrency, targetCurrency, store), targetCurrency);

            if (promotion == PayPalPromotion.FinancingExample)
            {
                var response = EnsureAccessToken(session, settings);
                if (response.Success)
                {
                    var index             = 0;
                    var dc                = decimal.Zero;
                    var data              = new Dictionary <string, object>();
                    var transactionAmount = new Dictionary <string, object>();
                    transactionAmount.Add("value", amount.FormatInvariant());
                    transactionAmount.Add("currency_code", store.PrimaryStoreCurrency.CurrencyCode);

                    var merchantCountry = _countryService.Value.GetCountryById(_companyInfoSettings.Value.CountryId) ?? _countryService.Value.GetAllCountries().FirstOrDefault();
                    data.Add("financing_country_code", merchantCountry.TwoLetterIsoCode);
                    data.Add("transaction_amount", transactionAmount);

                    response = CallApi("POST", "/v1/credit/calculated-financing-options", settings, session, JsonConvert.SerializeObject(data));

                    if (response.Success && response.Json.financing_options != null)
                    {
                        foreach (var fo in response.Json.financing_options[0].qualifying_financing_options)
                        {
                            var option = new FinancingOptions.Option();

                            option.MonthlyPayment = Parse((string)fo.monthly_payment.value, sourceCurrency, targetCurrency, store);

                            if (option.MonthlyPayment.Amount > decimal.Zero)
                            {
                                if (decimal.TryParse(((string)fo.credit_financing.apr).EmptyNull(), NumberStyles.Number, CultureInfo.InvariantCulture, out dc))
                                {
                                    option.AnnualPercentageRate = dc;
                                }
                                if (decimal.TryParse(((string)fo.credit_financing.nominal_rate).EmptyNull(), NumberStyles.Number, CultureInfo.InvariantCulture, out dc))
                                {
                                    option.NominalRate = dc;
                                }

                                option.Term          = ((string)fo.credit_financing.term).ToInt();
                                option.MinAmount     = Parse((string)fo.min_amount.value, sourceCurrency, targetCurrency, store);
                                option.TotalInterest = Parse((string)fo.total_interest.value, sourceCurrency, targetCurrency, store);
                                option.TotalCost     = Parse((string)fo.total_cost.value, sourceCurrency, targetCurrency, store);

                                // PayPal review: do not display last instalment.
                                //var instalments = fo.estimated_installments as JArray;
                                //var lastInstalment = instalments?.LastOrDefault()?.SelectToken("total_payment.value")?.ToString();
                                //option.LastInstalment = Parse(lastInstalment, sourceCurrency, targetCurrency, store);

                                //if (option.LastInstalment.Amount == decimal.Zero)
                                //{
                                //    option.LastInstalment = new Money(option.MonthlyPayment.Amount, targetCurrency);
                                //}

                                result.Qualified.Add(option);
                            }
                        }

                        result.Qualified = result.Qualified
                                           .OrderBy(x => x.Term)
                                           .ThenBy(x => x.MonthlyPayment.Amount)
                                           .ToList();

                        result.Qualified.Each(x => x.Index = ++index);
                    }
                }
            }

            return(result);
        }
        public PayPalResponse Refund(PayPalApiSettingsBase settings, PayPalSessionData session, RefundPaymentRequest request)
        {
            var data = new Dictionary<string, object>();
            var store = _services.StoreService.GetStoreById(request.Order.StoreId);
            var isSale = request.Order.AuthorizationTransactionResult.Contains("(sale)");

            var path = "/v1/payments/{0}/{1}/refund".FormatInvariant(isSale ? "sale" : "capture", request.Order.CaptureTransactionId);

            var amount = new Dictionary<string, object>();
            amount.Add("total", request.AmountToRefund.FormatInvariant());
            amount.Add("currency", store.PrimaryStoreCurrency.CurrencyCode);

            data.Add("amount", amount);

            var result = CallApi("POST", path, session.AccessToken, settings, data.Any() ? JsonConvert.SerializeObject(data) : null);

            if (result.Success && result.Json != null)
            {
                result.Id = (string)result.Json.id;
            }

            //Logger.InsertLog(LogLevel.Information, "PayPal Refund", JsonConvert.SerializeObject(data, Formatting.Indented) + "\r\n\r\n" + (result.Json != null ? result.Json.ToString() : ""));

            return result;
        }