public IViewComponentResult Invoke()
        {
            var model = new PaymentInfoModel();
            //load settings for a chosen store scope
            //ensure that we have 2 (or more) stores
            var storeId                   = _storeContext.CurrentStore.Id;
            var store                     = _storeService.GetStoreById(storeId);
            var orderSettings             = _settingService.LoadSetting <OrderSettings>(storeId);
            var payPalPlusPaymentSettings = _settingService.LoadSetting <PayPalPlusPaymentSettings>(storeId);

            string host = payPalPlusPaymentSettings.EnviromentSandBox;

            if (payPalPlusPaymentSettings.UseSandbox == false)
            {
                host = payPalPlusPaymentSettings.EnviromentLive;
            }

            //get current shopping cart
            var shoppingCart = _workContext.CurrentCustomer.ShoppingCartItems
                               .Where(shoppingCartItem => shoppingCartItem.ShoppingCartType == ShoppingCartType.ShoppingCart)
                               .ToList();
            //.LimitPerStore(_storeContext.CurrentStore.Id).ToList();

            decimal totalAdjust = 0;
            //items
            var items = GetItems(shoppingCart, _workContext.CurrentCustomer, _storeContext.CurrentStore.Id, payPalPlusPaymentSettings.Currency);

            //amount details
            var amountDetails = GetAmountDetails(shoppingCart, items, out totalAdjust);

            try
            {
                Task.Run(async() =>
                {
                    AuthToken authToken = await GetAccessToken(host, payPalPlusPaymentSettings.ClientId, payPalPlusPaymentSettings.SecretId);

                    PayPalPaymentCreatedResponse createdPayment = await CreatePaypalPaymentAsync(host, authToken, _workContext.CurrentCustomer, payPalPlusPaymentSettings, amountDetails, items, totalAdjust);

                    var approval_url = createdPayment.links.FirstOrDefault(x => x.rel == "approval_url").href;
                    if (authToken != null)
                    {
                        // Guarda el apiContext
                        _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, "authTokenPPP", Newtonsoft.Json.JsonConvert.SerializeObject(authToken), _storeContext.CurrentStore.Id);
                        // Guarda Pago
                        _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, "createdPaymentPPP", Newtonsoft.Json.JsonConvert.SerializeObject(createdPayment), _storeContext.CurrentStore.Id);

                        model.Scriptppp = GetScriptPayment(_workContext.CurrentCustomer, authToken, createdPayment, storeId);
                    }
                    model.OnePageCheckoutEnabled = orderSettings.OnePageCheckoutEnabled;
                    model.Respuesta = authToken.Access_Token;
                    model.Error     = false;
                }).Wait();
            }
            catch (Exception e)
            {
                model.Respuesta = e.Message;
                model.Error     = true;
            }
            return(View("~/Plugins/Payments.PayPalPlus/Views/PaymentInfo.cshtml", model));
        }
        protected string GetScriptPayment(Customer customer, AuthToken authToken, PayPalPaymentCreatedResponse createdPayment, int storeId)
        {
            var    payPalPlusPaymentSettings = _settingService.LoadSetting <PayPalPlusPaymentSettings>(storeId);
            string mode = "sandbox";

            if (payPalPlusPaymentSettings.UseSandbox == false)
            {
                mode = "Live";
            }


            string scriptppp = _localizationService.GetResource("Plugins.Payments.PayPalPlus.Fields.scriptOne");

            if (!_orderSettings.OnePageCheckoutEnabled)
            {
                scriptppp = _localizationService.GetResource("Plugins.Payments.PayPalPlus.Fields.scriptPage");
            }

            scriptppp = scriptppp.Replace("{UrlTiendaAproval}", createdPayment.links.FirstOrDefault(x => x.rel == "approval_url").href);
            scriptppp = scriptppp.Replace("{Country}", payPalPlusPaymentSettings.CountryTwoLetters);
            scriptppp = scriptppp.Replace("{PayerEmail}", customer.Email);
            scriptppp = scriptppp.Replace("{PayerFirstName}", _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute));
            scriptppp = scriptppp.Replace("{PayerLastName}", _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute));
            scriptppp = scriptppp.Replace("{PayerPhone}", _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute));
            scriptppp = scriptppp.Replace("{Mode}", mode);
            scriptppp = scriptppp.Replace("{DisallowRememberedCards}", payPalPlusPaymentSettings.DisallowRememberedCards.ToString().ToLower());
            scriptppp = scriptppp.Replace("{Language}", payPalPlusPaymentSettings.Language);
            scriptppp = scriptppp.Replace("{RCards}", _genericAttributeService.GetAttribute <string>(customer, "PPPTokenCards"));
            scriptppp = scriptppp.Replace("{IFrameHeight}", payPalPlusPaymentSettings.IFrameHeight + "px");
            scriptppp = scriptppp.Replace("\r\n", "");
            return(scriptppp);
        }
示例#3
0
 public async Task <string> getRedirectURLToPayPal(decimal total, string currency)
 {
     try
     {
         return(Task.Run(async() =>
         {
             HttpClient http = GetPaypalHttpClient();
             PayPalAccessToken accessToken = await GetPayPalAccessTokenAsync(http);
             PayPalPaymentCreatedResponse createdPayment = await CreatePaypalPaymentAsync(http, accessToken, total, currency);
             return createdPayment.links.First(x => x.rel == "approval_url").href;
         }).Result);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex, "Failed to login to PayPal");
         return(null);
     }
 }
示例#4
0
        private async Task <PayPalPaymentCreatedResponse> CreatePaypalPaymentAsync(HttpClient http, PayPalAccessToken accessToken, decimal total, string currency)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/v1/payments/payment");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.access_token);
            var payment = JObject.FromObject(new
            {
                intent        = "sale",
                redirect_urls = new
                {
                    returl_url = configuration["PayPal:returnUrl"],
                    cancel_url = configuration["PayPal:cancelUrl"]
                },
                payer        = new { payment_method = "paypal" },
                transactions = JArray.FromObject(new[]
                {
                    new
                    {
                        amount = new
                        {
                            total    = total,
                            currency = currency
                        }
                    }
                })
            });

            request.Content = new StringContent(JsonConvert.SerializeObject(payment), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await http.SendAsync(request);

            string content = await response.Content.ReadAsStringAsync();

            PayPalPaymentCreatedResponse paypalPaymentCreated = JsonConvert.DeserializeObject <PayPalPaymentCreatedResponse>(content);

            return(paypalPaymentCreated);
        }
        private async Task <PayPalPaymentCreatedResponse> CreatePaypalPaymentAsync(string host, AuthToken accessToken, Customer customer, PayPalPlusPaymentSettings paypalPlusPaymentSettings, DetailsAmountInfo amountInfo, List <Item> items, decimal totalAdjust)
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpClient http = new HttpClient
            {
                BaseAddress = new Uri(host),
                Timeout     = TimeSpan.FromSeconds(30),
            };

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "v1/payments/payment");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Access_Token);
            request.Headers.Add("PayPal-Partner-Attribution-Id", "TecnofinPPP_Cart");
            // var model = new CreatePaymentModel();
            var    shippingOption     = _genericAttributeService.GetAttribute <ShippingOption>(customer, NopCustomerDefaults.SelectedShippingOptionAttribute, _storeContext.CurrentStore.Id);
            string shippingpreference = "SET_PROVIDED_ADDRESS";

            if (shippingOption == null || shippingOption.ShippingRateComputationMethodSystemName == "Pickup.PickupInStore")
            {
                shippingpreference = "NO_SHIPPING";
            }

            //get total discount amount
            var orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(customer.ShoppingCartItems.ToList(),
                                                                                out decimal discountAmount,
                                                                                out List <DiscountForCaching> _, out List <AppliedGiftCard> _, out int _, out decimal _);

            if (discountAmount <= decimal.Zero)
            {
                discountAmount = 0;
            }
            var shippingRateComputationMethods = _shippingPluginManager
                                                 .LoadActivePlugins(customer, _storeContext.CurrentStore.Id);

            _orderTotalCalculationService.GetShoppingCartSubTotal(customer.ShoppingCartItems.ToList(), false,
                                                                  out decimal subdiscountAmount,
                                                                  out List <DiscountForCaching> subdiscountforCath, out decimal subTotalSinDescuento, out decimal subtotalConDescuento, out SortedDictionary <decimal, decimal> taxRates);
            var taxTotal      = _orderTotalCalculationService.GetTaxTotal(customer.ShoppingCartItems.ToList(), shippingRateComputationMethods, true);
            var shipping      = _orderTotalCalculationService.GetShoppingCartShippingTotal(customer.ShoppingCartItems.ToList(), shippingRateComputationMethods);
            var shippingTotal = shipping ?? 0;

            //List<RestObjects.Item> items = new List<RestObjects.Item>();
            //foreach (var ic in customer.ShoppingCartItems)
            //{
            //    var item = new RestObjects.Item
            //    {
            //        currency = paypalPlusPaymentSettings.Currency,
            //        name = ic.Product.Name,
            //        description = ic.Product.Name,
            //        quantity = ic.Quantity.ToString(),
            //        price = Math.Round(ic.Product.Price, 2).ToString(),
            //        sku = ic.Product.Sku,

            //    };
            //    items.Add(item);
            //}
            var itemList = new RestObjects.Items();

            itemList.items = items;
            if (shippingpreference == "SET_PROVIDED_ADDRESS")
            {
                var address = customer.ShippingAddress;
                itemList.shipping_address = new RestObjects.ShippingAddressInfo()
                {
                    city           = address.City,
                    country_code   = address.Country.TwoLetterIsoCode,
                    postal_code    = address.ZipPostalCode,
                    phone          = address.PhoneNumber,
                    state          = address.StateProvince.Name,
                    recipient_name = "direccion",
                    line1          = address.Address1,
                    line2          = address.Address2,
                };
            }

            List <RestObjects.Transactions> transactions = new List <RestObjects.Transactions>();

            RestObjects.Transactions transaction = new RestObjects.Transactions()
            {
                amount = new RestObjects.AmountInfo
                {
                    currency = paypalPlusPaymentSettings.Currency,
                    details  = amountInfo,
                    total    = Math.Round(totalAdjust, 2).ToString(),
                    //details = new DetailsAmountInfo
                    //{
                    //    subtotal = Math.Round(subtotalConDescuento, 2).ToString(),
                    //    shipping = Math.Round(shippingTotal, 2).ToString(),
                    //    shipping_discount = Math.Round(discountAmount, 2).ToString(), // ver descuentos
                    //},
                    //total = Math.Round(orderTotal.Value, 2).ToString(),
                },

                description     = "Compra en:" + _storeContext.CurrentStore.Name,
                custom          = "Compra en:" + _storeContext.CurrentStore.Name,
                notify_url      = new Uri(new Uri(_storeContext.CurrentStore.Url), "Plugins/PaymentPayPalPlus/IPNHandler").ToString(),
                payment_options = new RestObjects.PaymentOptions(),
                item_list       = itemList,
            };
            transactions.Add(transaction);

            RestObjects.Payment paymentRest = new RestObjects.Payment
            {
                intent = "sale",
                application_context = new RestObjects.AplicationContext()
                {
                    shipping_preference = shippingpreference
                },
                payer         = new RestObjects.Payer(),
                transactions  = transactions,
                redirect_urls = new RestObjects.RedirectUrlsInfo
                {
                    return_url = $"{_webHelper.GetStoreLocation()}Plugins/PaymentPayPalPlus/AprovalOrder",
                    cancel_url = $"{_webHelper.GetStoreLocation()}Plugins/PaymentPayPalPlus/CancelOrder",
                },
            };
            var data = Newtonsoft.Json.JsonConvert.SerializeObject(paymentRest);
            PayPalPaymentCreatedResponse paypalPaymentCreated = new PayPalPaymentCreatedResponse();

            try
            {
                request.Content = new StringContent(data, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await http.SendAsync(request);

                string content = await response.Content.ReadAsStringAsync();

                paypalPaymentCreated = JsonConvert.DeserializeObject <PayPalPaymentCreatedResponse>(content);
            }
            catch (TaskCanceledException etce)
            {
                _logger.Error("PayPalPlus IPN. error_ ", new NopException(etce.Message));
            }

            return(paypalPaymentCreated);
        }