/// <summary>
        /// ExpressCheckout (prepare order)
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice"/> to be paid</param>
        /// <param name="payment">The <see cref="IPayment"/> record</param>
        /// <returns>The <see cref="IPaymentResult"/></returns>
        public IPaymentResult ExpressCheckout(IInvoice invoice, IPayment payment)
        {
            var setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
            {
                ReturnURL      = String.Format("{0}/umbraco/MerchelloPayPal/PayPalApi/AuthorizePayment?InvoiceKey={1}&PaymentKey={2}", GetWebsiteUrl(), invoice.Key, payment.Key),
                CancelURL      = GetWebsiteUrl(),
                PaymentDetails = new List <PaymentDetailsType> {
                    GetPaymentDetails(invoice)
                }
            };

            try
            {
                var response = GetPayPalService().SetExpressCheckout(new SetExpressCheckoutReq {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails)
                });
                if (response.Ack == AckCodeType.SUCCESS)
                {
                    payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.OrderConfirmUrl, "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + response.Token);
                    return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, true));
                }

                var errorMessage = response.Errors.Count > 0 ? response.Errors[0].LongMessage : "An unknown error";
                return(new PaymentResult(Attempt <IPayment> .Fail(payment, new Exception(errorMessage)), invoice, false));
            }
            catch (Exception ex)
            {
                return(new PaymentResult(Attempt <IPayment> .Fail(payment, ex), invoice, false));
            }
        }
Example #2
0
        private void PopulatePaymentDetails(SetExpressCheckoutRequestDetailsType ecDetails)
        {
            var paymentInfo = new PaymentDetailsType();
            var total       = 0.0;
            var currency    = CurrencyCodeType.GBP;
            var address     = new AddressType
            {
                Name            = Checkout.BillingInfo.FirstName + " " + Checkout.BillingInfo.SurName,
                Street1         = Checkout.BillingInfo.FirmName + " " + Checkout.BillingInfo.BuildingName + " " + Checkout.BillingInfo.StreetName,
                CityName        = Checkout.BillingInfo.City,
                StateOrProvince = Checkout.BillingInfo.County,
                PostalCode      = Checkout.BillingInfo.PostCode
            };

            paymentInfo.ShipToAddress = address;

            foreach (var item in Cart)
            {
                var itemInformation = new PaymentDetailsItemType();
                itemInformation.Name     = string.Format("{0}", item.Name);
                itemInformation.Quantity = item.Quantity;
                itemInformation.Amount   = new BasicAmountType(currency, item.UnitPriceInStr);
                total += item.TotalPrice;
                paymentInfo.PaymentDetailsItem.Add(itemInformation);
            }

            var tax = total * 20 / 100;

            paymentInfo.ItemTotal  = new BasicAmountType(currency, total.ToString());
            paymentInfo.OrderTotal = new BasicAmountType(currency, (total + tax).ToString());
            paymentInfo.TaxTotal   = new BasicAmountType(currency, (total * 20 / 100).ToString());
            ecDetails.PaymentDetails.Add(paymentInfo);
        }
Example #3
0
        public static SetExpressCheckoutReq GetSetExpressCheckoutReq(Order order, string returnUrl, string cancelUrl)
        {
            SetExpressCheckoutRequestDetailsType requestDetails = new SetExpressCheckoutRequestDetailsType
            {
                ReturnURL     = returnUrl,
                CancelURL     = cancelUrl,
                NoShipping    = "1",
                Custom        = order.OrderID.ToString(),
                PaymentAction = PaymentActionCodeType.Sale,
                OrderTotal    = new BasicAmountType()
                {
                    currencyID = CurrencyCodeType.USD,
                    Value      = order.Amount.ToString(CultureInfo.InvariantCulture)
                }
            };

            SetExpressCheckoutReq request = new SetExpressCheckoutReq()
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                {
                    Version = ConfigurationManager.AppSettings["PayPalAPIVersion"],
                    SetExpressCheckoutRequestDetails = requestDetails
                }
            };

            return(request);
        }
        public SetExpressCheckoutRequestDetailsType CreateExpressCheckoutReqDetailsType(IPayment payment, PayPalConfiguration payPalConfiguration)
        {
            var setExpressChkOutReqDetails = new SetExpressCheckoutRequestDetailsType
            {
                BillingAddress = AddressHandling.ToAddressType(payment.BillingAddress),
                BuyerEmail     = payment.BillingAddress.Email
            };

            TransactionType transactionType;

            if (Enum.TryParse(payment.TransactionType, out transactionType))
            {
                if (transactionType == TransactionType.Authorization)
                {
                    setExpressChkOutReqDetails.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
                }
                else if (transactionType == TransactionType.Sale)
                {
                    setExpressChkOutReqDetails.PaymentAction = PaymentActionCodeType.SALE;
                }
            }

            if (payPalConfiguration.AllowChangeAddress != "1")
            {
                setExpressChkOutReqDetails.AddressOverride = "1";
            }

            if (payPalConfiguration.AllowGuest == "1")
            {
                setExpressChkOutReqDetails.SolutionType = SolutionTypeType.SOLE;
                setExpressChkOutReqDetails.LandingPage  = LandingPageType.BILLING;
            }

            return(setExpressChkOutReqDetails);
        }
        /// <summary>
        /// Sets paypal express checkout
        /// </summary>
        /// <param name="OrderTotal">Order total</param>
        /// <param name="ReturnURL">Return URL</param>
        /// <param name="CancelURL">Cancel URL</param>
        /// <returns>Express checkout URL</returns>
        public string SetExpressCheckout(decimal OrderTotal, string ReturnURL, string CancelURL)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            SetExpressCheckoutReq req = new SetExpressCheckoutReq();

            req.SetExpressCheckoutRequest         = new SetExpressCheckoutRequestType();
            req.SetExpressCheckoutRequest.Version = this.APIVersion;
            SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType();

            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails = details;
            if (transactionMode == TransactMode.Authorize)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.PaymentActionSpecified = true;
            details.OrderTotal             = new BasicAmountType();
            details.OrderTotal.Value       = OrderTotal.ToString("N", new CultureInfo("en-us"));
            details.OrderTotal.currencyID  = PaypalHelper.GetPaypalCurrency(CurrencyManager.PrimaryStoreCurrency);
            details.ReturnURL = ReturnURL;
            details.CancelURL = CancelURL;
            SetExpressCheckoutResponseType response = service2.SetExpressCheckout(req);
            string error;

            if (PaypalHelper.CheckSuccess(response, out error))
            {
                return(GetPaypalUrl(response.Token));
            }
            throw new NopException(error);
        }
        /// <summary>
        /// Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice"/> to be paid</param>
        /// <param name="payment">The <see cref="IPayment"/> record</param>
        /// <param name="args"></param>
        /// <returns>The <see cref="IPaymentResult"/></returns>
        public IPaymentResult ProcessPayment(IInvoice invoice, IPayment payment, ProcessorArgumentCollection args)
        {
            var setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
            {
                ReturnURL      = String.Format("{0}/App_Plugins/Merchello.PayPal/PayPalExpressCheckout.html?InvoiceKey={1}&PaymentKey={2}&PaymentMethodKey={3}", GetWebsiteUrl(), invoice.Key, payment.Key, payment.PaymentMethodKey),
                CancelURL      = "http://localhost/cancel",
                PaymentDetails = new List <PaymentDetailsType> {
                    GetPaymentDetails(invoice)
                }
            };


            var setExpressCheckout        = new SetExpressCheckoutReq();
            var setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);

            setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;
            var config = new Dictionary <string, string>
            {
                { "mode", "sandbox" },
                { "account1.apiUsername", _settings.ApiUsername },
                { "account1.apiPassword", _settings.ApiPassword },
                { "account1.apiSignature", _settings.ApiSignature }
            };
            var service = new PayPalAPIInterfaceServiceService(config);
            var responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);

            // If this were using a service we might want to store some of the transaction data in the ExtendedData for record
            payment.ExtendedData.SetValue("RedirectUrl", "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + responseSetExpressCheckoutResponseType.Token);

            return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, false));
        }
        protected void btnPay_Click(object sender, EventArgs e)
        {
            if (radPaypal.Checked)
            {
                PayPalAPIAAInterfaceClient paypalAAInt = new PayPalAPIAAInterfaceClient();
                string hosting = ConfigurationManager.AppSettings["HostingPrefix"];

                CustomSecurityHeaderType type = new CustomSecurityHeaderType();
                type.Credentials = new UserIdPasswordType()
                {
                    Username = ConfigurationManager.AppSettings["PP_APIUsername"],
                    Password = ConfigurationManager.AppSettings["PP_APIPassword"],
                    Signature = ConfigurationManager.AppSettings["PP_APISignature"]
                };

                SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
                sdt.NoShipping = "1";
                PaymentDetailsType pdt = new PaymentDetailsType()
                {
                    OrderDescription = "Payment Details Sushant",
                    OrderTotal = new BasicAmountType()
                    {
                        currencyID = CurrencyCodeType.USD,
                        Value = "100.00"
                    }
                };

                sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
                sdt.CancelURL = hosting + "Default.aspx";
                sdt.ReturnURL = hosting + "ExpressCheckoutSuccess.aspx";

                SetExpressCheckoutReq req = new SetExpressCheckoutReq()
                {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                    {
                        SetExpressCheckoutRequestDetails = sdt,
                        Version = "60.0"
                    }
                };

                var resp = paypalAAInt.SetExpressCheckout(ref type, req);
                if (resp.Errors != null && resp.Errors.Length > 0)
                {
                    // errors occured
                    throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
                        resp.Errors[0].LongMessage);
                }

                Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
                    ConfigurationManager.AppSettings["PayPalSubmitUrl"], resp.Token));
            }
        }
        protected void btnPay_Click(object sender, EventArgs e)
        {
            if (radPaypal.Checked)
            {
                PayPalAPIAAInterfaceClient paypalAAInt = new PayPalAPIAAInterfaceClient();
                string hosting = ConfigurationManager.AppSettings["HostingPrefix"];

                CustomSecurityHeaderType type = new CustomSecurityHeaderType();
                type.Credentials = new UserIdPasswordType()
                {
                    Username  = ConfigurationManager.AppSettings["PP_APIUsername"],
                    Password  = ConfigurationManager.AppSettings["PP_APIPassword"],
                    Signature = ConfigurationManager.AppSettings["PP_APISignature"]
                };

                SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
                sdt.NoShipping = "1";
                PaymentDetailsType pdt = new PaymentDetailsType()
                {
                    OrderDescription = "Payment Details Sushant",
                    OrderTotal       = new BasicAmountType()
                    {
                        currencyID = CurrencyCodeType.USD,
                        Value      = "100.00"
                    }
                };

                sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
                sdt.CancelURL      = hosting + "Default.aspx";
                sdt.ReturnURL      = hosting + "ExpressCheckoutSuccess.aspx";

                SetExpressCheckoutReq req = new SetExpressCheckoutReq()
                {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                    {
                        SetExpressCheckoutRequestDetails = sdt,
                        Version = "60.0"
                    }
                };

                var resp = paypalAAInt.SetExpressCheckout(ref type, req);
                if (resp.Errors != null && resp.Errors.Length > 0)
                {
                    // errors occured
                    throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
                                        resp.Errors[0].LongMessage);
                }

                Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
                                                ConfigurationManager.AppSettings["PayPalSubmitUrl"], resp.Token));
            }
        }
        private SetExpressCheckoutReq CreatePaypalRequest(CustomerOrder order, Store store, PaymentIn payment)
        {
            var retVal = new SetExpressCheckoutReq();

            var request = new SetExpressCheckoutRequestType();

            var ecDetails = new SetExpressCheckoutRequestDetailsType
            {
                CallbackTimeout = "3",
                ReturnURL       = string.Format("{0}/{1}?cancel=false&orderId={2}", store.Url, PaypalPaymentRedirectRelativePath, order.Id),
                CancelURL       = string.Format("{0}/{1}?cancel=true&orderId={2}", store.Url, PaypalPaymentRedirectRelativePath, order.Id)
            };

            if (PaypalPaymentModeStoreSetting.Equals("BankCard"))
            {
                ecDetails.SolutionType = SolutionTypeType.SOLE;
                ecDetails.LandingPage  = LandingPageType.BILLING;
            }
            else
            {
                ecDetails.SolutionType = SolutionTypeType.MARK;
                ecDetails.LandingPage  = LandingPageType.LOGIN;
            }

            var currency = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), order.Currency.ToString());

            var billingAddress = order.Addresses.FirstOrDefault(s => s.AddressType == VirtoCommerce.Domain.Order.Model.AddressType.Billing);

            if (billingAddress != null)
            {
                ecDetails.BuyerEmail = billingAddress.Email;
            }
            else
            {
                billingAddress = order.Addresses.FirstOrDefault();
            }

            if (billingAddress != null && !string.IsNullOrEmpty(billingAddress.Email))
            {
                ecDetails.BuyerEmail = billingAddress.Email;
            }

            ecDetails.PaymentDetails.Add(GetPaypalPaymentDetail(currency, PaymentActionCodeType.SALE, payment));

            request.SetExpressCheckoutRequestDetails = ecDetails;

            retVal.SetExpressCheckoutRequest = request;

            return(retVal);
        }
Example #10
0
        public string SetExpressCheckout(string billToEmail, decimal dTotal, string returnUrl, string cancelUrl, bool useAddressOverride, Address shippingAddress)
        {
            PayPalSvc.SetExpressCheckoutReq setRequest = new SetExpressCheckoutReq();
            PayPalSvc.SetExpressCheckoutRequestDetailsType setDetails = new SetExpressCheckoutRequestDetailsType();
            setRequest.SetExpressCheckoutRequest         = new SetExpressCheckoutRequestType();
            setRequest.SetExpressCheckoutRequest.Version = PayPalServiceUtility.PayPalAPIVersionNumber;

            if (useAddressOverride)
            {
                setDetails.AddressOverride = "1";
                //Required Stuff
                setDetails.Address                  = new AddressType();
                setDetails.Address.Name             = shippingAddress.FirstName + " " + shippingAddress.LastName;
                setDetails.Address.Street1          = shippingAddress.Address1;
                setDetails.Address.CityName         = shippingAddress.City;
                setDetails.Address.PostalCode       = shippingAddress.Zip;
                setDetails.Address.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), shippingAddress.Country);
                setDetails.Address.CountrySpecified = true;
                //Not Required
                setDetails.Address.Street2         = shippingAddress.Address2;
                setDetails.Address.StateOrProvince = shippingAddress.StateOrRegion;
            }

            setDetails.BuyerEmail = billToEmail;
            Currency currency = new Currency();

            setDetails.OrderTotal = GetBasicAmount(decimal.Round(dTotal, currency.CurrencyDecimals));
            setDetails.ReturnURL  = returnUrl;
            setDetails.CancelURL  = cancelUrl;

            setRequest.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails = setDetails;
            PayPalSvc.SetExpressCheckoutResponseType setResponse = service2.SetExpressCheckout(setRequest);

            string errors = this.CheckErrors(setResponse);
            string sOut   = "";

            if (errors == string.Empty)
            {
                sOut = setResponse.Token;
            }
            else
            {
                sOut = errors;
            }
            return(sOut);
        }
        public SetExpressCheckoutRequestDetailsType GetSetExpressCheckoutRequestDetails(IList <ShoppingCartItem> cart)
        {
            var setExpressCheckoutRequestDetailsType =
                new SetExpressCheckoutRequestDetailsType
            {
                ReturnURL          = _payPalUrlService.GetReturnURL(),
                CancelURL          = _payPalUrlService.GetCancelURL(),
                ReqConfirmShipping = _payPalShippingService.GetRequireConfirmedShippingAddress(cart),
                NoShipping         = _payPalShippingService.GetNoShipping(cart),
                LocaleCode         = _payPalExpressCheckoutPaymentSettings.LocaleCode,
                cppheaderimage     = _payPalExpressCheckoutPaymentSettings.LogoImageURL,
                cppcartbordercolor = _payPalExpressCheckoutPaymentSettings.CartBorderColor,
                PaymentDetails     = _payPalOrderService.GetPaymentDetails(cart),
                BuyerEmail         = _payPalOrderService.GetBuyerEmail(),
                MaxAmount          = _payPalOrderService.GetMaxAmount(cart)
            };

            return(setExpressCheckoutRequestDetailsType);
        }
Example #12
0
        public SetExpressCheckoutReq GetSetExpressCheckoutRequest(CartModel cart)
        {
            List <ShippingOptionType> flatRateShippingOptions =
                cart.PotentiallyAvailableShippingMethods.OrderBy(x => x.GetShippingTotal(cart))
                .Select(x => new ShippingOptionType
            {
                ShippingOptionAmount    = x.GetShippingTotal(cart).GetAmountType(),
                ShippingOptionName      = x.DisplayName,
                ShippingOptionIsDefault = cart.ShippingMethod == x ? "true" : "false",
            }).ToList();

            if (flatRateShippingOptions.Any() && flatRateShippingOptions.All(type => type.ShippingOptionIsDefault != "true"))
            {
                flatRateShippingOptions[0].ShippingOptionIsDefault = "true";
            }
            var setExpressCheckoutRequestDetailsType = new SetExpressCheckoutRequestDetailsType
            {
                ReturnURL               = _payPalUrlService.GetReturnURL(),
                CancelURL               = _payPalUrlService.GetCancelURL(),
                ReqConfirmShipping      = _payPalShippingService.GetRequireConfirmedShippingAddress(),
                NoShipping              = _payPalShippingService.GetNoShipping(cart),
                LocaleCode              = _payPalExpressCheckoutSettings.LocaleCode,
                cppHeaderImage          = _payPalExpressCheckoutSettings.LogoImageURL,
                cppCartBorderColor      = _payPalExpressCheckoutSettings.CartBorderColor,
                PaymentDetails          = _payPalOrderService.GetPaymentDetails(cart),
                BuyerEmail              = _payPalOrderService.GetBuyerEmail(cart),
                MaxAmount               = _payPalOrderService.GetMaxAmount(cart),
                InvoiceID               = cart.CartGuid.ToString(),
                Custom                  = cart.CartGuid.ToString(),
                CallbackURL             = _payPalUrlService.GetCallbackUrl(),
                CallbackTimeout         = "6",
                FlatRateShippingOptions = flatRateShippingOptions,
            };
            var setExpressCheckoutRequestType = new SetExpressCheckoutRequestType
            {
                SetExpressCheckoutRequestDetails = setExpressCheckoutRequestDetailsType,
            };

            return(new SetExpressCheckoutReq {
                SetExpressCheckoutRequest = setExpressCheckoutRequestType
            });
        }
Example #13
0
        private void PopulateSetCheckoutRequestObject(SetExpressCheckoutRequestType request)
        {
            var requestedDetails = new SetExpressCheckoutRequestDetailsType();

            requestedDetails.SolutionType    = SolutionTypeType.SOLE;
            requestedDetails.NoShipping      = "1";
            requestedDetails.BuyerEmail      = Checkout.BillingInfo.Email;
            requestedDetails.AddressOverride = "0";
            requestedDetails.BillingAddress  = new AddressType
            {
                Name            = Checkout.BillingInfo.FirstName + " " + Checkout.BillingInfo.SurName,
                Street1         = Checkout.BillingInfo.FirmName + " " + Checkout.BillingInfo.BuildingName + " " + Checkout.BillingInfo.StreetName,
                CityName        = Checkout.BillingInfo.City,
                StateOrProvince = Checkout.BillingInfo.County,
                PostalCode      = Checkout.BillingInfo.PostCode
            };
            requestedDetails.BrandName = "Bluecoat Software";
            PopulatePaymentDetails(requestedDetails);
            requestedDetails.ReturnURL = CheckoutReturnUrl; requestedDetails.CancelURL = CancelUrl; request.SetExpressCheckoutRequestDetails = requestedDetails;
        }
        public SetExpressCheckoutRequestDetailsType GetSetExpressCheckoutRequestDetails(IList <ShoppingCartItem> cart)
        {
            var noShippingCart = cart.Any(item => _productService.GetProductById(item.ProductId)?.IsDownload != true);

            var setExpressCheckoutRequestDetailsType =
                new SetExpressCheckoutRequestDetailsType
            {
                ReturnURL          = _payPalUrlService.GetReturnURL(),
                CancelURL          = _payPalUrlService.GetCancelURL(),
                ReqConfirmShipping = noShippingCart || !_payPalExpressCheckoutPaymentSettings.RequireConfirmedShippingAddress ? "0" : "1",
                NoShipping         = noShippingCart ? "2" : "1",
                LocaleCode         = _payPalExpressCheckoutPaymentSettings.LocaleCode,
                cppheaderimage     = _payPalExpressCheckoutPaymentSettings.LogoImageURL,
                cppcartbordercolor = _payPalExpressCheckoutPaymentSettings.CartBorderColor,
                PaymentDetails     = _payPalOrderService.GetPaymentDetails(cart),
                BuyerEmail         = _payPalOrderService.GetBuyerEmail(),
                MaxAmount          = _payPalOrderService.GetMaxAmount(cart)
            };

            return(setExpressCheckoutRequestDetailsType);
        }
        public SetExpressCheckoutResponseType SetExpressCheckout(PayPalProcessPaymentRequest processPaymentRequest,
                                                                 IList <Core.Domain.Orders.OrganizedShoppingCartItem> cart)
        {
            var result       = new SetExpressCheckoutResponseType();
            var currentStore = CommonServices.StoreContext.CurrentStore;

            var req = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    Version = PayPalHelper.GetApiVersion(),
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                }
            };

            var details = new SetExpressCheckoutRequestDetailsType
            {
                PaymentAction          = PayPalHelper.GetPaymentAction(Settings),
                PaymentActionSpecified = true,
                CancelURL = CommonServices.WebHelper.GetStoreLocation(currentStore.SslEnabled) + "cart",
                ReturnURL = CommonServices.WebHelper.GetStoreLocation(currentStore.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalExpress/GetDetails",
                //CallbackURL = _webHelper.GetStoreLocation(currentStore.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalExpress/ShippingOptions?CustomerID=" + _workContext.CurrentCustomer.Id.ToString(),
                //CallbackTimeout = _payPalExpressPaymentSettings.CallbackTimeout.ToString()
                ReqConfirmShipping = Settings.ConfirmedShipment.ToString(),
                NoShipping         = Settings.NoShipmentAddress.ToString()
            };

            // populate cart
            decimal itemTotal = decimal.Zero;
            var     cartItems = new List <PaymentDetailsItemType>();

            foreach (OrganizedShoppingCartItem item in cart)
            {
                decimal shoppingCartUnitPriceWithDiscountBase = _priceCalculationService.GetUnitPrice(item, true);
                decimal shoppingCartUnitPriceWithDiscount     = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartUnitPriceWithDiscountBase, CommonServices.WorkContext.WorkingCurrency);
                decimal priceIncludingTier = shoppingCartUnitPriceWithDiscount;
                cartItems.Add(new PaymentDetailsItemType()
                {
                    Name     = item.Item.Product.Name,
                    Number   = item.Item.Product.Sku,
                    Quantity = item.Item.Quantity.ToString(),
                    Amount   = new BasicAmountType() // this is the per item cost
                    {
                        currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)),
                        Value      = (priceIncludingTier).ToString("N", new CultureInfo("en-us"))
                    }
                });
                itemTotal += (item.Item.Quantity * priceIncludingTier);
            }
            ;

            decimal shippingTotal = decimal.Zero;

            if (cart.RequiresShipping())
            {
                decimal?shoppingCartShippingBase = OrderTotalCalculationService.GetShoppingCartShippingTotal(cart);
                if (shoppingCartShippingBase.HasValue && shoppingCartShippingBase > 0)
                {
                    shippingTotal = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartShippingBase.Value, CommonServices.WorkContext.WorkingCurrency);
                }
                else
                {
                    shippingTotal = Settings.DefaultShippingPrice;
                }
            }

            //This is the default if the Shipping Callback fails
            //var shippingOptions = new List<ShippingOptionType>();
            //shippingOptions.Add(new ShippingOptionType()
            //{
            //    ShippingOptionIsDefault = "true",
            //    ShippingOptionName = "Standard Shipping",
            //    ShippingOptionAmount = new BasicAmountType()
            //    {
            //        Value = shippingTotal.ToString(), //This is the default value used for shipping if the Instant Update API returns an error or does not answer within the callback time
            //        currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
            //    }
            //});
            //details.FlatRateShippingOptions = shippingOptions.ToArray();
            //details.TotalType = TotalType.EstimatedTotal;

            // get total tax
            SortedDictionary <decimal, decimal> taxRates = null;
            decimal shoppingCartTaxBase = OrderTotalCalculationService.GetTaxTotal(cart, out taxRates);
            decimal shoppingCartTax     = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartTaxBase, CommonServices.WorkContext.WorkingCurrency);
            decimal discount            = -processPaymentRequest.Discount;


            // Add discounts to PayPal order
            if (discount != 0)
            {
                cartItems.Add(new PaymentDetailsItemType()
                {
                    Name     = "Threadrock Discount",
                    Quantity = "1",
                    Amount   = new BasicAmountType() // this is the total discount
                    {
                        currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)),
                        Value      = discount.ToString("N", new CultureInfo("en-us"))
                    }
                });

                itemTotal += discount;
            }

            // get customer
            int customerId = Convert.ToInt32(CommonServices.WorkContext.CurrentCustomer.Id.ToString());
            var customer   = _customerService.GetCustomerById(customerId);

            if (!cart.IsRecurring())
            {
                //we don't apply gift cards for recurring products
                var giftCards = _giftCardService.GetActiveGiftCardsAppliedByCustomer(customer);
                if (giftCards != null)
                {
                    foreach (var gc in giftCards)
                    {
                        if (itemTotal > decimal.Zero)
                        {
                            decimal remainingAmount = gc.GetGiftCardRemainingAmount();
                            decimal amountCanBeUsed = decimal.Zero;
                            if (itemTotal > remainingAmount)
                            {
                                amountCanBeUsed = remainingAmount;
                            }
                            else
                            {
                                amountCanBeUsed = itemTotal - .01M;
                            }

                            decimal amountToSubtract = -amountCanBeUsed;

                            cartItems.Add(new PaymentDetailsItemType()
                            {
                                Name     = "Giftcard Applied",
                                Quantity = "1",
                                Amount   = new BasicAmountType()
                                {
                                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)),
                                    Value      = amountToSubtract.ToString("N", new CultureInfo("en-us"))
                                }
                            });

                            //reduce subtotal
                            itemTotal += amountToSubtract;
                        }
                    }
                }
            }

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                ItemTotal = new BasicAmountType
                {
                    Value      = Math.Round(itemTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                ShippingTotal = new BasicAmountType
                {
                    Value      = Math.Round(shippingTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                TaxTotal = new BasicAmountType
                {
                    Value      = Math.Round(shoppingCartTax, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(itemTotal + shoppingCartTax + shippingTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                Custom             = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource       = SmartStoreVersion.CurrentFullVersion,
                PaymentAction      = PayPalHelper.GetPaymentAction(Settings),
                PaymentDetailsItem = cartItems.ToArray()
            };

            details.PaymentDetails = new[] { paymentDetails };
            //details.MaxAmount = new BasicAmountType()  // this is the per item cost
            //{
            //    currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)),
            //    Value = (decimal.Parse(paymentDetails.OrderTotal.Value) + 30).ToString()
            //};

            details.ShippingMethodSpecified = true;

            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails.Custom = processPaymentRequest.OrderGuid.ToString();
            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails        = details;

            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(Settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(Settings);
                result = service.SetExpressCheckout(req);
            }

            _httpContext.GetCheckoutState().CustomProperties.Add("PayPalExpressButtonUsed", true);

            return(result);
        }
Example #16
0
        private void PopulateSetExpressCheckoutRequestObject(SetExpressCheckoutRequestType request, User user, Product product, string referrer, int quantity, string billingAgreementText = "")
        {
            const string zero       = "0.00";
            var          orderTotal = 0.0;
            var          itemTotal  = 0.0;

            // Each payment can include requestDetails about multiple items
            // This example shows just one payment item
            if (quantity < 1)
            {
                throw new Exception("Insufficient quantity");
            }
            var itemDetails = new PaymentDetailsItemType {
                Name     = product.Name,
                Amount   = new BasicAmountType(MSKatushaCurrencyCode, product.Amount),
                Quantity = quantity,
                //ItemCategory = ItemCategoryType.PHYSICAL,
                Tax         = new BasicAmountType(MSKatushaCurrencyCode, product.Tax),
                Description = product.Description,
            };

            itemTotal += (Double.Parse(itemDetails.Amount.value) * quantity);

            orderTotal += Double.Parse(itemDetails.Tax.value);
            orderTotal += itemTotal;

            var paymentDetails = new PaymentDetailsType {
                ShippingTotal    = new BasicAmountType(MSKatushaCurrencyCode, zero),
                OrderDescription = MSKatushaorderDescription,
                PaymentAction    = PaymentActionCodeType.SALE,
                ItemTotal        = new BasicAmountType(MSKatushaCurrencyCode, itemTotal.ToString(CultureInfo.InvariantCulture)),
                Custom           = product.FriendlyName + "|" + (referrer ?? ""),
            };

            orderTotal += Double.Parse(paymentDetails.ShippingTotal.value);
            paymentDetails.OrderTotal = new BasicAmountType(MSKatushaCurrencyCode, orderTotal.ToString(CultureInfo.InvariantCulture));
            paymentDetails.PaymentDetailsItem.Add(itemDetails);


            var ecDetails = new SetExpressCheckoutRequestDetailsType {
                ReturnURL       = _settings.ReturnUrl,
                CancelURL       = _settings.CancelUrl,
                BuyerEmail      = user.Email,
                AddressOverride = "0",
                NoShipping      = "1",
                SolutionType    = SolutionTypeType.SOLE,
                BuyerDetails    = new BuyerDetailsType {
                    BuyerId = user.Guid.ToString(), BuyerRegistrationDate = user.CreationDate.ToString("s"), BuyerUserName = user.UserName
                },
                cppHeaderImage = MSKatushaImageUrl,
                BrandName      = MSKatushaBrandName
                                 //PageStyle = pageStyle.Value,
                                 //cppHeaderBorderColor = cppheaderbordercolor.Value,
                                 //cppHeaderBackColor = cppheaderbackcolor.Value,
                                 //cppPayflowColor = cpppayflowcolor.Value,
            };

            ecDetails.PaymentDetails.Add(paymentDetails);

            if (!String.IsNullOrWhiteSpace(billingAgreementText))
            {
                var baType = new BillingAgreementDetailsType(BillingCodeType.MERCHANTINITIATEDBILLINGSINGLEAGREEMENT)
                {
                    BillingAgreementDescription = billingAgreementText
                };
                ecDetails.BillingAgreementDetails.Add(baType);
            }
            request.SetExpressCheckoutRequestDetails = ecDetails;

            /*
             *          //if (insuranceTotal.Value != "" && !double.Parse(insuranceTotal.Value).Equals(0.0)) {
             *          //    paymentDetails.InsuranceTotal = new BasicAmountType(MSKatushaCurrencyCode, zero);
             *          //    paymentDetails.InsuranceOptionOffered = "true";
             *          //    orderTotal += Double.Parse(insuranceTotal.Value);
             *          //}
             *          //if (handlingTotal.Value != "") {
             *          //    paymentDetails.HandlingTotal = new BasicAmountType(MSKatushaCurrencyCode, handlingTotal.Value);
             *          //    orderTotal += Double.Parse(handlingTotal.Value);
             *          //}
             *          //if (taxTotal.Value != "") {
             *          //    paymentDetails.TaxTotal = new BasicAmountType(MSKatushaCurrencyCode, taxTotal.Value);
             *          //    orderTotal += Double.Parse(taxTotal.Value);
             *          //}
             *          //if (shippingName.Value != "" && shippingStreet1.Value != ""
             *          //    && shippingCity.Value != "" && shippingState.Value != ""
             *          //    && shippingCountry.Value != "" && shippingPostalCode.Value != "") {
             *          //    AddressType shipAddress = new AddressType();
             *          //    shipAddress.Name = shippingName.Value;
             *          //    shipAddress.Street1 = shippingStreet1.Value;
             *          //    shipAddress.Street2 = shippingStreet2.Value;
             *          //    shipAddress.CityName = shippingCity.Value;
             *          //    shipAddress.StateOrProvince = shippingState.Value;
             *          //    shipAddress.Country = (CountryCodeType)
             *          //        Enum.Parse(typeof(CountryCodeType), shippingCountry.Value);
             *          //    shipAddress.PostalCode = shippingPostalCode.Value;
             *          //    ecDetails.PaymentDetails[0].ShipToAddress = shipAddress;
             *          //}
             * */
        }
    // # SetExpressCheckout API Operation
    // The SetExpressCheckout API operation initiates an Express Checkout transaction.
    public SetExpressCheckoutResponseType SetExpressCheckoutAPIOperation()
    {
        // Create the SetExpressCheckoutResponseType object
        SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType();

        try
        {
            // # SetExpressCheckoutReq
            SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();

            // URL to which the buyer's browser is returned after choosing to pay
            // with PayPal. For digital goods, you must add JavaScript to this page
            // to close the in-context experience.
            // `Note:
            // PayPal recommends that the value be the final review page on which
            // the buyer confirms the order and payment or billing agreement.`
            setExpressCheckoutRequestDetails.ReturnURL = "http://localhost/return";

            // URL to which the buyer is returned if the buyer does not approve the
            // use of PayPal to pay you. For digital goods, you must add JavaScript
            // to this page to close the in-context experience.
            // `Note:
            // PayPal recommends that the value be the original page on which the
            // buyer chose to pay with PayPal or establish a billing agreement.`
            setExpressCheckoutRequestDetails.CancelURL = "http://localhost/cancel";

            // # Payment Information
            // list of information about the payment
            List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

            // information about the first payment
            PaymentDetailsType paymentDetails1 = new PaymentDetailsType();

            // Total cost of the transaction to the buyer. If shipping cost and tax
            // charges are known, include them in this value. If not, this value
            // should be the current sub-total of the order.
            //
            // If the transaction includes one or more one-time purchases, this field must be equal to
            // the sum of the purchases. Set this field to 0 if the transaction does
            // not include a one-time purchase such as when you set up a billing
            // agreement for a recurring payment that is not immediately charged.
            // When the field is set to 0, purchase-specific fields are ignored.
            //
            // * `Currency Code` - You must set the currencyID attribute to one of the
            // 3-character currency codes for any of the supported PayPal
            // currencies.
            // * `Amount`
            BasicAmountType orderTotal1 = new BasicAmountType(CurrencyCodeType.USD, "2.00");
            paymentDetails1.OrderTotal = orderTotal1;

            // How you want to obtain payment. When implementing parallel payments,
            // this field is required and must be set to `Order`. When implementing
            // digital goods, this field is required and must be set to `Sale`. If the
            // transaction does not include a one-time purchase, this field is
            // ignored. It is one of the following values:
            //
            // * `Sale` - This is a final sale for which you are requesting payment
            // (default).
            // * `Authorization` - This payment is a basic authorization subject to
            // settlement with PayPal Authorization and Capture.
            // * `Order` - This payment is an order authorization subject to
            // settlement with PayPal Authorization and Capture.
            // `Note:
            // You cannot set this field to Sale in SetExpressCheckout request and
            // then change the value to Authorization or Order in the
            // DoExpressCheckoutPayment request. If you set the field to
            // Authorization or Order in SetExpressCheckout, you may set the field
            // to Sale.`
            paymentDetails1.PaymentAction = PaymentActionCodeType.ORDER;

            // Unique identifier for the merchant. For parallel payments, this field
            // is required and must contain the Payer Id or the email address of the
            // merchant.
            SellerDetailsType sellerDetails1 = new SellerDetailsType();
            sellerDetails1.PayPalAccountID = "*****@*****.**";
            paymentDetails1.SellerDetails  = sellerDetails1;

            // A unique identifier of the specific payment request, which is
            // required for parallel payments.
            paymentDetails1.PaymentRequestID = "PaymentRequest1";

            // `Address` to which the order is shipped, which takes mandatory params:
            //
            // * `Street Name`
            // * `City`
            // * `State`
            // * `Country`
            // * `Postal Code`
            AddressType shipToAddress1 = new AddressType();
            shipToAddress1.Street1         = "Ape Way";
            shipToAddress1.CityName        = "Austin";
            shipToAddress1.StateOrProvince = "TX";
            shipToAddress1.Country         = CountryCodeType.US;
            shipToAddress1.PostalCode      = "78750";

            paymentDetails1.ShipToAddress = shipToAddress1;

            // IPN URL
            // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed
            // * The transaction related IPN variables will be received on the call back URL specified in the request
            // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"
            // * PayPal would continuously resend IPN if a wrong IPN is sent
            paymentDetails1.NotifyURL = "http://IPNhost";

            // information about the second payment
            PaymentDetailsType paymentDetails2 = new PaymentDetailsType();
            // Total cost of the transaction to the buyer. If shipping cost and tax
            // charges are known, include them in this value. If not, this value
            // should be the current sub-total of the order.
            //
            // If the transaction includes one or more one-time purchases, this field must be equal to
            // the sum of the purchases. Set this field to 0 if the transaction does
            // not include a one-time purchase such as when you set up a billing
            // agreement for a recurring payment that is not immediately charged.
            // When the field is set to 0, purchase-specific fields are ignored.
            //
            // * `Currency Code` - You must set the currencyID attribute to one of the
            // 3-character currency codes for any of the supported PayPal
            // currencies.
            // * `Amount`
            BasicAmountType orderTotal2 = new BasicAmountType(CurrencyCodeType.USD, "4.00");
            paymentDetails2.OrderTotal = orderTotal2;

            // How you want to obtain payment. When implementing parallel payments,
            // this field is required and must be set to `Order`. When implementing
            // digital goods, this field is required and must be set to `Sale`. If the
            // transaction does not include a one-time purchase, this field is
            // ignored. It is one of the following values:
            //
            // * `Sale` - This is a final sale for which you are requesting payment
            // (default).
            // * `Authorization` - This payment is a basic authorization subject to
            // settlement with PayPal Authorization and Capture.
            // * `Order` - This payment is an order authorization subject to
            // settlement with PayPal Authorization and Capture.
            // `Note:
            // You cannot set this field to Sale in SetExpressCheckout request and
            // then change the value to Authorization or Order in the
            // DoExpressCheckoutPayment request. If you set the field to
            // Authorization or Order in SetExpressCheckout, you may set the field
            // to Sale.`
            paymentDetails2.PaymentAction = PaymentActionCodeType.ORDER;

            // Unique identifier for the merchant. For parallel payments, this field
            // is required and must contain the Payer Id or the email address of the
            // merchant.
            SellerDetailsType sellerDetails2 = new SellerDetailsType();
            sellerDetails2.PayPalAccountID = "*****@*****.**";
            paymentDetails2.SellerDetails  = sellerDetails2;

            // A unique identifier of the specific payment request, which is
            // required for parallel payments.
            paymentDetails2.PaymentRequestID = "PaymentRequest2";

            // IPN URL
            // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed
            // * The transaction related IPN variables will be received on the call back URL specified in the request
            // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"
            // * PayPal would continuously resend IPN if a wrong IPN is sent
            paymentDetails2.NotifyURL = "http://IPNhost";

            // `Address` to which the order is shipped, which takes mandatory params:
            //
            // * `Street Name`
            // * `City`
            // * `State`
            // * `Country`
            // * `Postal Code`
            AddressType shipToAddress2 = new AddressType();
            shipToAddress2.Street1         = "Ape Way";
            shipToAddress2.CityName        = "Austin";
            shipToAddress2.StateOrProvince = "TX";
            shipToAddress2.Country         = CountryCodeType.US;
            shipToAddress2.PostalCode      = "78750";
            paymentDetails2.ShipToAddress  = shipToAddress2;

            paymentDetailsList.Add(paymentDetails1);
            paymentDetailsList.Add(paymentDetails2);

            setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList;

            SetExpressCheckoutReq         setExpressCheckout        = new SetExpressCheckoutReq();
            SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);

            setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;

            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

            // # API call
            // Invoke the SetExpressCheckout method in service wrapper object
            responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);

            if (responseSetExpressCheckoutResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "SetExpressCheckout API Operation - ";
                acknowledgement += responseSetExpressCheckoutResponseType.Ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseSetExpressCheckoutResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // # Redirecting to PayPal for authorization
                    // Once you get the "Success" response, needs to authorise the
                    // transaction by making buyer to login into PayPal. For that,
                    // need to construct redirect url using EC token from response.
                    // For example,
                    // `redirectURL="https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="+setExpressCheckoutResponse.Token;`

                    // Express Checkout Token
                    logger.Info("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
                    Console.WriteLine("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseSetExpressCheckoutResponseType.Errors;
                    foreach (ErrorType error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.LongMessage);
                        Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                    }
                }
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return(responseSetExpressCheckoutResponseType);
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="PayPalExpressCheckoutRequestDetailsOverride"/> class.
 /// </summary>
 /// <param name="invoice">
 /// The invoice.
 /// </param>
 /// <param name="payment">
 /// The payment.
 /// </param>
 /// <param name="ecDetails">
 /// The express checkout details.
 /// </param>
 public PayPalExpressCheckoutRequestDetailsOverride(IInvoice invoice, IPayment payment, SetExpressCheckoutRequestDetailsType ecDetails)
 {
     this.Invoice = invoice;
     this.Payment = payment;
     this.ExpressCheckoutDetails = ecDetails;
 }
        /// <summary>
        /// Performs the setup for an express checkout.
        /// </summary>
        /// <param name="invoice">
        /// The <see cref="IInvoice"/>.
        /// </param>
        /// <param name="payment">
        /// The <see cref="IPayment"/>
        /// </param>
        /// <param name="returnUrl">
        /// The return URL.
        /// </param>
        /// <param name="cancelUrl">
        /// The cancel URL.
        /// </param>
        /// <returns>
        /// The <see cref="ExpressCheckoutResponse"/>.
        /// </returns>
        protected virtual PayPalExpressTransactionRecord SetExpressCheckout(IInvoice invoice, IPayment payment, string returnUrl, string cancelUrl)
        {
            var record = new PayPalExpressTransactionRecord
                             {
                                 Success = true,
                                 Data = { Authorized = false, CurrencyCode = invoice.CurrencyCode }
                             };

            var factory = new PayPalPaymentDetailsTypeFactory(new PayPalFactorySettings { WebsiteUrl = _websiteUrl });
            var paymentDetailsType = factory.Build(invoice, PaymentActionCodeType.ORDER);

            // The API requires this be in a list
            var paymentDetailsList = new List<PaymentDetailsType>() { paymentDetailsType };

            // ExpressCheckout details
            //// We do not want the customer to be able to reset their shipping address at PayPal
            //// due to the fact that it could affect shipping charges and in some cases tax rates.
            //// This is the AddressOverride = "0" - NOT WORKING!
            var ecDetails = new SetExpressCheckoutRequestDetailsType()
                    {
                        ReturnURL = returnUrl,
                        CancelURL = cancelUrl,
                        PaymentDetails = paymentDetailsList,
                        AddressOverride = "0"
                    };

            // Trigger the event to allow for overriding ecDetails
            var ecdOverride = new PayPalExpressCheckoutRequestDetailsOverride(invoice, payment, ecDetails);
            SettingCheckoutRequestDetails.RaiseEvent(new ObjectEventArgs<PayPalExpressCheckoutRequestDetailsOverride>(ecdOverride), this);

            // The ExpressCheckoutRequest
            var request = new SetExpressCheckoutRequestType
                    {
                        Version = Version,
                        SetExpressCheckoutRequestDetails = ecdOverride.ExpressCheckoutDetails
                    };

            // Crete the wrapper for Express Checkout
            var wrapper = new SetExpressCheckoutReq
                              {
                                  SetExpressCheckoutRequest = request
                              };

            try
            {
                var service = GetPayPalService();
                var response = service.SetExpressCheckout(wrapper);
                record.SetExpressCheckout = _responseFactory.Build(response, response.Token);
                record.Data.Token = response.Token;
                record.SetExpressCheckout.RedirectUrl = GetRedirectUrl(response.Token);
            }
            catch (Exception ex)
            {
                record.Success = false;
                record.SetExpressCheckout = _responseFactory.Build(ex);
            }

            return record;
        }
        /// <summary>
        /// Performs the setup for an express checkout.
        /// </summary>
        /// <param name="invoice">
        /// The <see cref="IInvoice"/>.
        /// </param>
        /// <param name="payment">
        /// The <see cref="IPayment"/>
        /// </param>
        /// <param name="returnUrl">
        /// The return URL.
        /// </param>
        /// <param name="cancelUrl">
        /// The cancel URL.
        /// </param>
        /// <returns>
        /// The <see cref="ExpressCheckoutResponse"/>.
        /// </returns>
        protected virtual PayPalExpressTransactionRecord SetExpressCheckout(IInvoice invoice, IPayment payment, string returnUrl, string cancelUrl)
        {
            var record = new PayPalExpressTransactionRecord
            {
                Success = true,
                Data    = { Authorized = false, CurrencyCode = invoice.CurrencyCode }
            };

            var factory = new PayPalPaymentDetailsTypeFactory(new PayPalFactorySettings {
                WebsiteUrl = _websiteUrl
            });
            var paymentDetailsType = factory.Build(invoice, PaymentActionCodeType.ORDER);

            // The API requires this be in a list
            var paymentDetailsList = new List <PaymentDetailsType>()
            {
                paymentDetailsType
            };

            // ExpressCheckout details
            var ecDetails = new SetExpressCheckoutRequestDetailsType()
            {
                ReturnURL       = returnUrl,
                CancelURL       = cancelUrl,
                PaymentDetails  = paymentDetailsList,
                AddressOverride = "1"
            };

            // Trigger the event to allow for overriding ecDetails
            var ecdOverride = new PayPalExpressCheckoutRequestDetailsOverride(invoice, payment, ecDetails);

            SettingCheckoutRequestDetails.RaiseEvent(new ObjectEventArgs <PayPalExpressCheckoutRequestDetailsOverride>(ecdOverride), this);

            // The ExpressCheckoutRequest
            var request = new SetExpressCheckoutRequestType
            {
                Version = Version,
                SetExpressCheckoutRequestDetails = ecdOverride.ExpressCheckoutDetails
            };

            // Crete the wrapper for Express Checkout
            var wrapper = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = request
            };

            try
            {
                var service  = GetPayPalService();
                var response = service.SetExpressCheckout(wrapper);

                record.SetExpressCheckout = _responseFactory.Build(response, response.Token);
                if (record.SetExpressCheckout.Success())
                {
                    record.Data.Token = response.Token;
                    record.SetExpressCheckout.RedirectUrl = GetRedirectUrl(response.Token);
                }
                else
                {
                    foreach (var et in record.SetExpressCheckout.ErrorTypes)
                    {
                        var code = et.ErrorCode;
                        var sm   = et.ShortMessage;
                        var lm   = et.LongMessage;
                        MultiLogHelper.Warn <PayPalExpressCheckoutService>(string.Format("{0} {1} {2}", code, lm, sm));
                    }

                    record.Success = false;
                }
            }
            catch (Exception ex)
            {
                record.Success            = false;
                record.SetExpressCheckout = _responseFactory.Build(ex);
            }

            return(record);
        }
        public ExpressCheckoutResult SetExpressCheckout()
        {
            HttpContext context = HttpContext.Current;
            User        user    = Token.Instance.User;
            Basket      basket  = user.Basket;

            //MAKE SURE BASKET IS PROPERLY PACKAGED FOR CHECKOUT
            basket.Package();

            //GET EXISTING SESSION IF IT IS PRESENT
            ExpressCheckoutSession existingSession = ExpressCheckoutSession.Current;

            if (existingSession != null)
            {
                WebTrace.Write("Existing session token: " + existingSession.Token);
            }

            //CREATE THE EXPRESS CHECKOUT REQUEST OBJECT
            SetExpressCheckoutRequestType expressCheckoutRequest = new SetExpressCheckoutRequestType();

            expressCheckoutRequest.SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            if (existingSession != null)
            {
                expressCheckoutRequest.SetExpressCheckoutRequestDetails.Token = existingSession.Token;
            }
            expressCheckoutRequest.Version = "1.0";

            //GET THE CURRENCY FOR THE TRANSACTION
            string           baseCurrencyCode = Token.Instance.Store.BaseCurrency.ISOCode;
            CurrencyCodeType baseCurrency     = PayPalProvider.GetPayPalCurrencyType(baseCurrencyCode);
            //BUILD THE REQUEST DETAILS
            SetExpressCheckoutRequestDetailsType expressCheckoutDetails = expressCheckoutRequest.SetExpressCheckoutRequestDetails;
            LSDecimal basketTotal = basket.Items.TotalPrice();

            WebTrace.Write("Basket Total: " + basketTotal.ToString());
            expressCheckoutDetails.OrderTotal            = new BasicAmountType();
            expressCheckoutDetails.OrderTotal.currencyID = baseCurrency;
            expressCheckoutDetails.OrderTotal.Value      = string.Format("{0:##,##0.00}", basketTotal);
            expressCheckoutDetails.MaxAmount             = new BasicAmountType();
            expressCheckoutDetails.MaxAmount.currencyID  = baseCurrency;
            expressCheckoutDetails.MaxAmount.Value       = string.Format("{0:##,##0.00}", basketTotal + 50);

            //SET THE URLS
            string storeUrl = GetStoreUrl();

            expressCheckoutDetails.ReturnURL = storeUrl + "/PayPalExpressCheckout.aspx?Action=GET";
            expressCheckoutDetails.CancelURL = storeUrl + "/PayPalExpressCheckout.aspx?Action=CANCEL";

            //SET THE CUSTOM VALUE TO THE USER ID FOR MATCHING DURING GET
            expressCheckoutDetails.Custom = "UID" + basket.UserId.ToString();

            //SET THE CUSTOMER ADDRESS
            Address     billingAddress = user.PrimaryAddress;
            AddressType address        = new AddressType();

            address.Name       = billingAddress.FirstName + " " + billingAddress.LastName;
            address.Street1    = billingAddress.Address1;
            address.Street2    = billingAddress.Address2;
            address.CityName   = billingAddress.City;
            address.PostalCode = billingAddress.PostalCode;
            if (billingAddress.Country != null)
            {
                address.Country = PayPalProvider.GetPayPalCountry(billingAddress.CountryCode);
            }
            else
            {
                address.Country = CountryCodeType.US;
            }
            address.CountrySpecified          = true;
            expressCheckoutDetails.BuyerEmail = billingAddress.Email;
            expressCheckoutDetails.Address    = address;

            //SET THE PAYMENT ACTION
            expressCheckoutDetails.PaymentAction          = this.UseAuthCapture ? PaymentActionCodeType.Sale : PaymentActionCodeType.Authorization;
            expressCheckoutDetails.PaymentActionSpecified = true;

            //EXECUTE REQUEST
            SetExpressCheckoutResponseType expressCheckoutResponse;

            context.Trace.Write("DO SOAP CALL");
            expressCheckoutResponse = (SetExpressCheckoutResponseType)SoapCall("SetExpressCheckout", expressCheckoutRequest);
            context.Trace.Write("CHECK SOAP RESULT");
            if (expressCheckoutResponse == null)
            {
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "NORESP";
                customError.ShortMessage = "No Response From Server";
                customError.LongMessage  = "The PayPal service is unavailable at this time.";
                customErrorList[0]       = customError;
                return(new ExpressCheckoutResult(0, string.Empty, customErrorList));
            }

            //IF ERRORS ARE IN RESPONSE, RETURN THEM AND EXIT PROCESS
            if (expressCheckoutResponse.Errors != null)
            {
                return(new ExpressCheckoutResult(0, string.Empty, expressCheckoutResponse.Errors));
            }

            //NO ERRORS FOUND, PUT PAYPAL DETAILS INTO SESSION
            context.Trace.Write("Store PayPal Token In Session");
            ExpressCheckoutSession newSession = new ExpressCheckoutSession();

            newSession.Token           = expressCheckoutResponse.Token;
            newSession.TokenExpiration = DateTime.UtcNow.AddHours(3);
            newSession.Save();

            context.Trace.Write("Saved PayPal Token:" + newSession.Token);
            context.Trace.Write("Token Expiration:" + newSession.TokenExpiration.ToLongDateString());

            //RETURN TO CALLER INCLUDING REDIRECTION URL
            string redirectUrl = "https://www" + (this.UseSandbox ? ".sandbox" : string.Empty) + ".paypal.com/webscr?cmd=_express-checkout&token=" + expressCheckoutResponse.Token;

            return(new ExpressCheckoutResult(0, redirectUrl, null));
        }
Example #22
0
        protected void btnPPCont_Click(object sender, EventArgs e)
        {
            try
            {
                var Surcharge   = Math.Round((Convert.ToDouble(amount.Value) * 3) / 100, 2);
                var orderAmount = (Convert.ToDouble(amount.Value) + Surcharge).ToString();

                Dictionary <string, string> PPPayment = new Dictionary <string, string>();
                PPPayment.Add("AccNum", accountNum.Value);
                // PPPayment.Add("Amount", amount.Value);

                PPPayment.Add("Amount", orderAmount);

                Session["PPPaymentDetails"] = PPPayment;
                CustomSecurityHeaderType _credentials = new CustomSecurityHeaderType
                {
                    Credentials = new UserIdPasswordType()
                    {
                        Username  = System.Configuration.ConfigurationManager.AppSettings["UserName"].ToString(),
                        Password  = System.Configuration.ConfigurationManager.AppSettings["Password"].ToString(),
                        Signature = System.Configuration.ConfigurationManager.AppSettings["Signature"].ToString(),
                    }
                };


                var expressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
                // expressCheckoutRequestDetails.ReturnURL = "http://payment.trumans.blendev.com/PayPalPayment.aspx";
                //expressCheckoutRequestDetails.CancelURL = "http://payment.trumans.blendev.com/PayPalCancel.aspx";
                expressCheckoutRequestDetails.CancelURL  = System.Configuration.ConfigurationManager.AppSettings["CancelURL"].ToString();
                expressCheckoutRequestDetails.ReturnURL  = System.Configuration.ConfigurationManager.AppSettings["SuccessURL"].ToString();
                expressCheckoutRequestDetails.NoShipping = "1";
                var paymentDetailsArray = new PaymentDetailsType[1];
                paymentDetailsArray[0] = new PaymentDetailsType
                {
                    PaymentAction = PaymentActionCodeType.Sale,
                    OrderTotal    = new BasicAmountType
                    {
                        currencyID = CurrencyCodeType.AUD,
                        Value      = orderAmount.ToString(),
                    }
                };

                BasicAmountType OTotal = new BasicAmountType();
                OTotal.Value      = orderAmount.ToString();
                OTotal.currencyID = CurrencyCodeType.AUD;
                expressCheckoutRequestDetails.OrderTotal = OTotal;

                var ExpressCheck = new SetExpressCheckoutRequestType
                {
                    SetExpressCheckoutRequestDetails = expressCheckoutRequestDetails,
                    Version = "98",
                };

                SetExpressCheckoutReq obj = new SetExpressCheckoutReq();
                obj.SetExpressCheckoutRequest = ExpressCheck;

                PayPalAPI.PayPalAPIAAInterfaceClient objPayPalAPI = new PayPalAPIAAInterfaceClient();

                var setExpressCheckoutResponse = objPayPalAPI.SetExpressCheckout(ref _credentials, obj);
                if (setExpressCheckoutResponse.Ack == AckCodeType.Success)
                {
                    Response.Redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + setExpressCheckoutResponse.Token, false);
                    Session["Token"] = setExpressCheckoutResponse.Token;
                }
                else
                {
                    StreamWriter File2 = File.AppendText(HttpContext.Current.Server.MapPath("~/Logs/file.txt"));
                    File2.WriteLine("Error : " + setExpressCheckoutResponse.Errors[0].LongMessage);
                    File2.Close();


                    string script = "<script type=\"text/javascript\">alert('Unexpected Error Occured , Please try Later!!');</script>";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
                }
            }
            catch (Exception ex)
            {
                StreamWriter File2 = File.AppendText(HttpContext.Current.Server.MapPath("~/Logs/file.txt"));
                File2.WriteLine("Error : " + ex.Message);
                File2.Close();


                string script = "<script type=\"text/javascript\">alert('Unexpected Error Occured , Please try Later!!');</script>";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
            }
        }
Example #23
0
        private SetExpressCheckoutRequestType populateRequestObject(FinancialGateway financialGateway, PaymentInfo paymentInfo, List <GatewayAccountItem> selectedAccounts)
        {
            SetExpressCheckoutRequestType        request   = new SetExpressCheckoutRequestType();
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();
            String host      = GlobalAttributesCache.Value("PublicApplicationRoot");
            int    lastSlash = host.LastIndexOf('/');

            host = (lastSlash > -1) ? host.Substring(0, lastSlash) : host;
            if (financialGateway.GetAttributeValue("ReturnPage") != string.Empty)
            {
                PageReference pageReference = new PageReference(financialGateway.GetAttributeValue("ReturnPage"));
                ecDetails.ReturnURL = host + pageReference.BuildUrl();
            }
            if (financialGateway.GetAttributeValue("CancelPage") != string.Empty)
            {
                PageReference pageReference = new PageReference(financialGateway.GetAttributeValue("CancelPage"));
                ecDetails.CancelURL = host + pageReference.BuildUrl();
            }

            /*
             * // (Optional) Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages.
             * if (buyerEmail.Value != string.Empty)
             * {
             *
             * }*/
            ecDetails.BuyerEmail = paymentInfo.Email;

            /* Populate payment requestDetails.
             * SetExpressCheckout allows parallel payments of upto 10 payments.
             * This samples shows just one payment.
             */
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            ecDetails.PaymentDetails.Add(paymentDetails);
            // (Required) Total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. Set this field to 0 if the transaction does not include a one-time purchase such as when you set up a billing agreement for a recurring payment that is not immediately charged. When the field is set to 0, purchase-specific fields are ignored.
            double orderTotal = 0.0;
            // Sum of cost of all items in this order. For digital goods, this field is required.
            double           itemTotal = Convert.ToDouble(paymentInfo.Amount);
            CurrencyCodeType currency  = CurrencyCodeType.USD;

            //(Optional) Description of items the buyer is purchasing.
            paymentDetails.OrderDescription = "Contribution";

            // We do a authorization then complete the sale in the "Charge" phase
            paymentDetails.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            foreach (GatewayAccountItem item in selectedAccounts)
            {
                if (item.Amount > 0)
                {
                    PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();

                    itemDetails.Name        = item.Name;
                    itemDetails.Amount      = new BasicAmountType(currency, item.Amount.ToString());
                    itemDetails.Quantity    = 1;
                    itemDetails.Description = item.PublicName;
                    itemDetails.Number      = item.Id.ToString();
                    paymentDetails.PaymentDetailsItem.Add(itemDetails);
                }
            }

            orderTotal += itemTotal;
            paymentDetails.ItemTotal  = new BasicAmountType(currency, itemTotal.ToString());
            paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString());

            //(Optional) Your URL for receiving Instant Payment Notification (IPN)
            //about this transaction. If you do not specify this value in the request,
            //the notification URL from your Merchant Profile is used, if one exists.
            //Important:
            //The notify URL applies only to DoExpressCheckoutPayment.
            //This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
            //Character length and limitations: 2,048 single-byte alphanumeric characters
            paymentDetails.NotifyURL = "";
            // ipnNotificationUrl.Value.Trim();

            //(Optional) Locale of pages displayed by PayPal during Express Checkout.

            /*if (localeCode.SelectedIndex != 0)
             * {
             *  ecDetails.LocaleCode = localeCode.SelectedValue;
             * }
             *
             * // (Optional) Name of the Custom Payment Page Style for payment pages associated with this button or link. It corresponds to the HTML variable page_style for customizing payment pages. It is the same name as the Page Style Name you chose to add or edit the page style in your PayPal Account profile.
             * if (pageStyle.Value != string.Empty)
             * {
             *  ecDetails.PageStyle = pageStyle.Value;
             * }*/
            //(Optional) URL for the image you want to appear at the top left of the payment page. The image has a maximum size of 750 pixels wide by 90 pixels high. PayPal recommends that you provide an image that is stored on a secure (https) server. If you do not specify an image, the business name displays.
            if (financialGateway.GetAttributeValue("PayPalLogoImage") != string.Empty)
            {
                ecDetails.cppHeaderImage = financialGateway.GetAttributeValue("PayPalLogoImage");
            }

            /*// (Optional) Sets the border color around the header of the payment page. The border is a 2-pixel perimeter around the header space, which is 750 pixels wide by 90 pixels high. By default, the color is black.
             * if (cppheaderbordercolor.Value != string.Empty)
             * {
             *  ecDetails.cppHeaderBorderColor = cppheaderbordercolor.Value;
             * }
             * // (Optional) Sets the background color for the header of the payment page. By default, the color is white.
             * if (cppheaderbackcolor.Value != string.Empty)
             * {
             *  ecDetails.cppHeaderBackColor = cppheaderbackcolor.Value;
             * }
             * // (Optional) Sets the background color for the payment page. By default, the color is white.
             * if (cpppayflowcolor.Value != string.Empty)
             * {
             *  ecDetails.cppPayflowColor = cpppayflowcolor.Value;
             * }
             * // (Optional) A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.
             */
            if (financialGateway.GetAttributeValue("PayPalBrandName") != string.Empty)
            {
                ecDetails.BrandName = financialGateway.GetAttributeValue("PayPalBrandName");
            }

            request.SetExpressCheckoutRequestDetails = ecDetails;

            return(request);
        }
Example #24
0
        public static string StartEC(ShoppingCart cart, bool boolBypassOrderReview, IDictionary <string, string> checkoutOptions)
        {
            var payPalRefund   = new PayPalAPISoapBinding();
            var payPalBinding  = new PayPalAPIAASoapBinding();
            var redirectUrl    = new StringBuilder();
            var ecOrderTotal   = new BasicAmountType();
            var request        = new SetExpressCheckoutReq();
            var requestType    = new SetExpressCheckoutRequestType();
            var requestDetails = new SetExpressCheckoutRequestDetailsType();
            var response       = new SetExpressCheckoutResponseType();
            var result         = string.Empty;
            var urlHelper      = DependencyResolver.Current.GetService <UrlHelper>();

            //Express checkout
            GetPaypalRequirements(out payPalRefund, out payPalBinding);

            ecOrderTotal.Value = Localization.CurrencyStringForGatewayWithoutExchangeRate(cart.Total(true));

            if (cart.HasRecurringComponents() && AppLogic.AppConfigBool("Recurring.UseGatewayInternalBilling"))
            {
                //Have to send extra details on the SetExpressCheckoutReq or the token will be invalid for creating a recurring profile later
                var recurringAgreement     = new BillingAgreementDetailsType();
                var recurringAgreementList = new List <BillingAgreementDetailsType>();

                recurringAgreement.BillingType = BillingCodeType.RecurringPayments;
                recurringAgreement.BillingAgreementDescription = "Recurring order created on " + System.DateTime.Now.ToShortDateString() + " from " + AppLogic.AppConfig("StoreName");
                recurringAgreementList.Add(recurringAgreement);
                requestDetails.BillingAgreementDetails = recurringAgreementList.ToArray();
            }

            request.SetExpressCheckoutRequest            = requestType;
            requestType.SetExpressCheckoutRequestDetails = requestDetails;

            ecOrderTotal.currencyID   = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
            requestDetails.OrderTotal = ecOrderTotal;

            if (AppLogic.AppConfigBool("PayPal.RequireConfirmedAddress"))
            {
                requestDetails.ReqConfirmShipping = "1";
            }
            else
            {
                requestDetails.ReqConfirmShipping = "0";
            }

            requestDetails.ReturnURL = string.Format("{0}{1}",
                                                     AppLogic.GetStoreHTTPLocation(
                                                         useSsl: true,
                                                         includeScriptLocation: true,
                                                         noVirtualNoSlash: true),
                                                     urlHelper.Action(
                                                         actionName: ActionNames.PayPalExpressReturn,
                                                         controllerName: ControllerNames.PayPalExpress));
            if (boolBypassOrderReview)
            {
                requestDetails.ReturnURL = string.Format("{0}?BypassOrderReview=true", requestDetails.ReturnURL);
            }

            requestDetails.CancelURL = string.Format("{0}{1}",
                                                     AppLogic.GetStoreHTTPLocation(
                                                         useSsl: true,
                                                         includeScriptLocation: true,
                                                         noVirtualNoSlash: true),
                                                     urlHelper.Action(
                                                         actionName: ActionNames.Index,
                                                         controllerName: ControllerNames.Checkout));
            requestDetails.LocaleCode    = AppLogic.AppConfig("PayPal.DefaultLocaleCode");
            requestDetails.PaymentAction = PaymentActionCodeType.Authorization;

            if (AppLogic.TransactionModeIsAuthCapture() || AppLogic.AppConfigBool("PayPal.ForceCapture") || PayPalController.GetAppropriateExpressType() == ExpressAPIType.PayPalAcceleratedBording)
            {
                requestDetails.PaymentAction = PaymentActionCodeType.Sale;
            }

            requestDetails.SolutionType           = SolutionTypeType.Sole;
            requestDetails.PaymentActionSpecified = true;
            requestType.Version = API_VER;

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.PageStyle")))
            {
                requestDetails.PageStyle = AppLogic.AppConfig("PayPal.Express.PageStyle").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderImage")))
            {
                requestDetails.cppheaderimage = AppLogic.AppConfig("PayPal.Express.HeaderImage").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderBackColor")))
            {
                requestDetails.cppheaderbackcolor = AppLogic.AppConfig("PayPal.Express.HeaderBackColor").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderBorderColor")))
            {
                requestDetails.cppheaderbordercolor = AppLogic.AppConfig("PayPal.Express.HeaderBorderColor").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.PayFlowColor")))
            {
                requestDetails.cpppayflowcolor = AppLogic.AppConfig("PayPal.Express.PayFlowColor").Trim();
            }

            if (checkoutOptions != null && checkoutOptions.ContainsKey("UserSelectedFundingSource") && checkoutOptions["UserSelectedFundingSource"] == "BML")
            {
                var fundingSourceDetails = new FundingSourceDetailsType();

                fundingSourceDetails.AllowPushFunding                   = "0";
                fundingSourceDetails.UserSelectedFundingSource          = UserSelectedFundingSourceType.BML;
                fundingSourceDetails.UserSelectedFundingSourceSpecified = true;
                requestDetails.FundingSourceDetails = fundingSourceDetails;
            }

            try
            {
                response = payPalBinding.SetExpressCheckout(request);

                if (response.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    if (response.Errors != null)
                    {
                        bool first = true;
                        for (int ix = 0; ix < response.Errors.Length; ix++)
                        {
                            if (!first)
                            {
                                result += ", ";
                            }
                            result += "Error: [" + response.Errors[ix].ErrorCode + "] " + response.Errors[ix].LongMessage;
                            first   = false;
                        }
                    }
                }
            }
            catch (Exception)
            {
                result = "Failed to start PayPal Express Checkout! Please try another payment method.";
            }

            if (result == AppLogic.ro_OK)
            {
                var useIntegratedCheckout = AppLogic.AppConfigBool("PayPal.Express.UseIntegratedCheckout");

                if (AppLogic.AppConfigBool("UseLiveTransactions") == true)
                {
                    redirectUrl.Append(useIntegratedCheckout
                                                ? AppLogic.AppConfig("PayPal.Express.IntegratedCheckout.LiveURL")
                                                : AppLogic.AppConfig("PayPal.Express.LiveURL"));
                }
                else
                {
                    redirectUrl.Append(useIntegratedCheckout
                                                ? AppLogic.AppConfig("PayPal.Express.IntegratedCheckout.SandboxURL")
                                                : AppLogic.AppConfig("PayPal.Express.SandboxURL"));
                }

                redirectUrl.Append(useIntegratedCheckout
                                        ? "?token="
                                        : "?cmd=_express-checkout&token=");

                redirectUrl.Append(response.Token);

                if (boolBypassOrderReview)
                {
                    redirectUrl.Append("&useraction=commit");
                }

                // Set active payment method to PayPalExpress
                DB.ExecuteSQL(string.Format("UPDATE Address SET PaymentMethodLastUsed={0} WHERE AddressID={1}",
                                            DB.SQuote(AppLogic.ro_PMPayPalExpress),
                                            cart.ThisCustomer.PrimaryBillingAddressID));

                SetECFaultRedirect(cart.ThisCustomer, redirectUrl.ToString());
            }
            else
            {
                var error = new ErrorMessage(HttpUtility.HtmlEncode(result));
                redirectUrl.Append(urlHelper.BuildCheckoutLink(error.MessageId));
            }

            return(redirectUrl.ToString());
        }
Example #25
0
        /// <summary>
        /// Processes the Authorize and AuthorizeAndCapture transactions
        /// </summary>
        /// <param name="invoice">The <see cref="IInvoice"/> to be paid</param>
        /// <param name="payment">The <see cref="IPayment"/> record</param>
        /// <param name="args"></param>
        /// <returns>The <see cref="IPaymentResult"/></returns>
        public IPaymentResult InitializePayment(IInvoice invoice, IPayment payment, ProcessorArgumentCollection args)
        {
            var setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();

            Func <string, string> adjustUrl = (url) => {
                if (!url.StartsWith("http"))
                {
                    url = GetWebsiteUrl() + (url[0] == '/' ? "" : "/") + url;
                }
                url = url.Replace("{invoiceKey}", invoice.Key.ToString(), StringComparison.InvariantCultureIgnoreCase);
                url = url.Replace("{paymentKey}", payment.Key.ToString(), StringComparison.InvariantCultureIgnoreCase);
                url = url.Replace("{paymentMethodKey}", payment.PaymentMethodKey.ToString(), StringComparison.InvariantCultureIgnoreCase);
                return(url);
            };

            // Save ReturnUrl and CancelUrl in ExtendedData.
            // They will be usefull in PayPalApiController.

            var returnUrl = args.GetReturnUrl();

            if (returnUrl.IsEmpty())
            {
                returnUrl = _settings.ReturnUrl;
            }
            if (returnUrl.IsEmpty())
            {
                returnUrl = "/";
            }
            returnUrl = adjustUrl(returnUrl);
            payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.ReturnUrl, returnUrl);

            var cancelUrl = args.GetCancelUrl();

            if (cancelUrl.IsEmpty())
            {
                cancelUrl = _settings.CancelUrl;
            }
            if (cancelUrl.IsEmpty())
            {
                cancelUrl = "/";
            }
            cancelUrl = adjustUrl(cancelUrl);
            payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.CancelUrl, cancelUrl);

            // Set ReturnUrl and CancelUrl of PayPal request to PayPalApiController.
            setExpressCheckoutRequestDetails.ReturnURL = adjustUrl("/umbraco/MerchelloPayPal/PayPalApi/SuccessPayment?InvoiceKey={invoiceKey}&PaymentKey={paymentKey}");
            setExpressCheckoutRequestDetails.CancelURL = adjustUrl("/umbraco/MerchelloPayPal/PayPalApi/AbortPayment?InvoiceKey={invoiceKey}&PaymentKey={paymentKey}");

            //setExpressCheckoutRequestDetails.OrderDescription = "#" + invoice.InvoiceNumber;
            setExpressCheckoutRequestDetails.PaymentDetails = new List <PaymentDetailsType> {
                CreatePayPalPaymentDetails(invoice, args)
            };

            var setExpressCheckout = new SetExpressCheckoutReq()
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails)
            };

            try {
                var response = GetPayPalService().SetExpressCheckout(setExpressCheckout);
                if (response.Ack != AckCodeType.SUCCESS && response.Ack != AckCodeType.SUCCESSWITHWARNING)
                {
                    return(new PaymentResult(Attempt <IPayment> .Fail(payment, CreateErrorResult(response.Errors)), invoice, false));
                }

                var redirectUrl = string.Format("https://www.{0}paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={1}", (_settings.LiveMode ? "" : "sandbox."), response.Token);
                payment.ExtendedData.SetValue("RedirectUrl", redirectUrl);
                return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, true));
            } catch (Exception ex) {
                return(new PaymentResult(Attempt <IPayment> .Fail(payment, ex), invoice, true));
            }
        }
Example #26
0
        private void populateRequestObject(SetExpressCheckoutRequestType request)
        {
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();

            if (returnUrl.Value != "")
            {
                ecDetails.ReturnURL = returnUrl.Value;
            }
            if (cancelUrl.Value != "")
            {
                ecDetails.CancelURL = cancelUrl.Value;
            }
            if (buyerEmail.Value != "")
            {
                ecDetails.BuyerEmail = buyerEmail.Value;
            }

            //Fix for release
            //NOTE: Setting this field overrides the setting you specified in your Merchant Account Profile
            if (reqConfirmShipping.SelectedIndex != 0)
            {
                ecDetails.ReqConfirmShipping = reqConfirmShipping.SelectedValue;
            }

            if (addressoverride.SelectedIndex != 0)
            {
                ecDetails.AddressOverride = addressoverride.SelectedValue;
            }

            if (noShipping.SelectedIndex != 0)
            {
                ecDetails.NoShipping = noShipping.SelectedValue;
            }
            if (solutionType.SelectedIndex != 0)
            {
                ecDetails.SolutionType = (SolutionTypeType)
                                         Enum.Parse(typeof(SolutionTypeType), solutionType.SelectedValue);
            }

            /* Populate payment requestDetails.
             * SetExpressCheckout allows parallel payments of upto 10 payments.
             * This samples shows just one payment.
             */
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            ecDetails.PaymentDetails.Add(paymentDetails);
            double           orderTotal = 0.0;
            double           itemTotal  = 0.0;
            CurrencyCodeType currency   = (CurrencyCodeType)
                                          Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);

            if (shippingTotal.Value != "")
            {
                paymentDetails.ShippingTotal = new BasicAmountType(currency, shippingTotal.Value);
                orderTotal += Double.Parse(shippingTotal.Value);
            }
            if (insuranceTotal.Value != "" && !double.Parse(insuranceTotal.Value).Equals(0.0))
            {
                paymentDetails.InsuranceTotal         = new BasicAmountType(currency, insuranceTotal.Value);
                paymentDetails.InsuranceOptionOffered = "true";
                orderTotal += Double.Parse(insuranceTotal.Value);
            }
            if (handlingTotal.Value != "")
            {
                paymentDetails.HandlingTotal = new BasicAmountType(currency, handlingTotal.Value);
                orderTotal += Double.Parse(handlingTotal.Value);
            }
            if (taxTotal.Value != "")
            {
                paymentDetails.TaxTotal = new BasicAmountType(currency, taxTotal.Value);
                orderTotal += Double.Parse(taxTotal.Value);
            }
            if (orderDescription.Value != "")
            {
                paymentDetails.OrderDescription = orderDescription.Value;
            }
            paymentDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

            if (shippingName.Value != "" && shippingStreet1.Value != "" &&
                shippingCity.Value != "" && shippingState.Value != "" &&
                shippingCountry.Value != "" && shippingPostalCode.Value != "")
            {
                AddressType shipAddress = new AddressType();
                shipAddress.Name            = shippingName.Value;
                shipAddress.Street1         = shippingStreet1.Value;
                shipAddress.Street2         = shippingStreet2.Value;
                shipAddress.CityName        = shippingCity.Value;
                shipAddress.StateOrProvince = shippingState.Value;
                shipAddress.Country         = (CountryCodeType)
                                              Enum.Parse(typeof(CountryCodeType), shippingCountry.Value);
                shipAddress.PostalCode = shippingPostalCode.Value;

                //Fix for release
                shipAddress.Phone = shippingPhone.Value;

                ecDetails.PaymentDetails[0].ShipToAddress = shipAddress;
            }

            // Each payment can include requestDetails about multiple items
            // This example shows just one payment item
            if (itemName.Value != null && itemAmount.Value != null && itemQuantity.Value != null)
            {
                PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();
                itemDetails.Name         = itemName.Value;
                itemDetails.Amount       = new BasicAmountType(currency, itemAmount.Value);
                itemDetails.Quantity     = Int32.Parse(itemQuantity.Value);
                itemDetails.ItemCategory = (ItemCategoryType)
                                           Enum.Parse(typeof(ItemCategoryType), itemCategory.SelectedValue);
                itemTotal += Double.Parse(itemDetails.Amount.value) * itemDetails.Quantity.Value;
                if (salesTax.Value != "")
                {
                    itemDetails.Tax = new BasicAmountType(currency, salesTax.Value);
                    orderTotal     += Double.Parse(salesTax.Value);
                }
                if (itemDescription.Value != "")
                {
                    itemDetails.Description = itemDescription.Value;
                }
                paymentDetails.PaymentDetailsItem.Add(itemDetails);
            }

            orderTotal += itemTotal;
            paymentDetails.ItemTotal  = new BasicAmountType(currency, itemTotal.ToString());
            paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString());

            // Set Billing agreement (for Reference transactions & Recurring payments)
            if (billingAgreementText.Value != "")
            {
                BillingCodeType billingCodeType = (BillingCodeType)
                                                  Enum.Parse(typeof(BillingCodeType), billingType.SelectedValue);
                BillingAgreementDetailsType baType = new BillingAgreementDetailsType(billingCodeType);
                baType.BillingAgreementDescription = billingAgreementText.Value;
                ecDetails.BillingAgreementDetails.Add(baType);
            }

            //Fix for release
            if (localeCode.SelectedIndex != 0)
            {
                ecDetails.LocaleCode = localeCode.SelectedValue;
            }

            // Set styling attributes for PayPal page
            if (pageStyle.Value != "")
            {
                ecDetails.PageStyle = pageStyle.Value;
            }
            if (cppheaderimage.Value != "")
            {
                ecDetails.cppHeaderImage = cppheaderimage.Value;
            }
            if (cppheaderbordercolor.Value != "")
            {
                ecDetails.cppHeaderBorderColor = cppheaderbordercolor.Value;
            }
            if (cppheaderbackcolor.Value != "")
            {
                ecDetails.cppHeaderBackColor = cppheaderbackcolor.Value;
            }
            if (cpppayflowcolor.Value != "")
            {
                ecDetails.cppPayflowColor = cpppayflowcolor.Value;
            }
            if (brandName.Value != "")
            {
                ecDetails.BrandName = brandName.Value;
            }

            request.SetExpressCheckoutRequestDetails = ecDetails;
        }
Example #27
0
        public SetExpressCheckoutResponseType SetExpressCheckout(PayPalProcessPaymentRequest processPaymentRequest, IList <OrganizedShoppingCartItem> cart)
        {
            var result         = new SetExpressCheckoutResponseType();
            var store          = Services.StoreService.GetStoreById(processPaymentRequest.StoreId);
            var customer       = Services.WorkContext.CurrentCustomer;
            var settings       = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);
            var payPalCurrency = GetApiCurrency(store.PrimaryStoreCurrency);
            var excludingTax   = (Services.WorkContext.GetTaxDisplayTypeFor(customer, store.Id) == TaxDisplayType.ExcludingTax);

            var req = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    Version = ApiVersion,
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                }
            };

            var details = new SetExpressCheckoutRequestDetailsType
            {
                PaymentAction          = GetPaymentAction(settings),
                PaymentActionSpecified = true,
                CancelURL = Services.WebHelper.GetStoreLocation(store.SslEnabled) + "cart",
                ReturnURL = Services.WebHelper.GetStoreLocation(store.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalExpress/GetDetails",
                //CallbackURL = _webHelper.GetStoreLocation(currentStore.SslEnabled) + "Plugins/SmartStore.PayPal/PayPalExpress/ShippingOptions?CustomerID=" + _workContext.CurrentCustomer.Id.ToString(),
                //CallbackTimeout = _payPalExpressPaymentSettings.CallbackTimeout.ToString()
                ReqConfirmShipping = settings.ConfirmedShipment.ToString(),
                NoShipping         = settings.NoShipmentAddress.ToString()
            };

            // populate cart
            var taxRate          = decimal.Zero;
            var unitPriceTaxRate = decimal.Zero;
            var itemTotal        = decimal.Zero;
            var cartItems        = new List <PaymentDetailsItemType>();

            foreach (var item in cart)
            {
                var product   = item.Item.Product;
                var unitPrice = _priceCalculationService.GetUnitPrice(item, true);
                var shoppingCartUnitPriceWithDiscount = excludingTax
                    ? _taxService.GetProductPrice(product, unitPrice, false, customer, out taxRate)
                    : _taxService.GetProductPrice(product, unitPrice, true, customer, out unitPriceTaxRate);

                cartItems.Add(new PaymentDetailsItemType
                {
                    Name     = product.Name,
                    Number   = product.Sku,
                    Quantity = item.Item.Quantity.ToString(),
                    // this is the per item cost
                    Amount = new BasicAmountType
                    {
                        currencyID = payPalCurrency,
                        Value      = shoppingCartUnitPriceWithDiscount.FormatInvariant()
                    }
                });

                itemTotal += (item.Item.Quantity * shoppingCartUnitPriceWithDiscount);
            }
            ;

            // additional handling fee
            var additionalHandlingFee = GetAdditionalHandlingFee(cart);

            cartItems.Add(new PaymentDetailsItemType
            {
                Name     = T("Plugins.Payments.PayPal.PaymentMethodFee").Text,
                Quantity = "1",
                Amount   = new BasicAmountType()
                {
                    currencyID = payPalCurrency,
                    Value      = additionalHandlingFee.FormatInvariant()
                }
            });

            itemTotal += GetAdditionalHandlingFee(cart);

            //shipping
            var shippingTotal = decimal.Zero;

            if (cart.RequiresShipping())
            {
                decimal?shoppingCartShippingBase = OrderTotalCalculationService.GetShoppingCartShippingTotal(cart);
                if (shoppingCartShippingBase.HasValue && shoppingCartShippingBase > 0)
                {
                    shippingTotal = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartShippingBase.Value, Services.WorkContext.WorkingCurrency);
                }
                else
                {
                    shippingTotal = settings.DefaultShippingPrice;
                }
            }

            //This is the default if the Shipping Callback fails
            //var shippingOptions = new List<ShippingOptionType>();
            //shippingOptions.Add(new ShippingOptionType()
            //{
            //    ShippingOptionIsDefault = "true",
            //    ShippingOptionName = "Standard Shipping",
            //    ShippingOptionAmount = new BasicAmountType()
            //    {
            //        Value = shippingTotal.ToString(), //This is the default value used for shipping if the Instant Update API returns an error or does not answer within the callback time
            //        currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
            //    }
            //});
            //details.FlatRateShippingOptions = shippingOptions.ToArray();
            //details.TotalType = TotalType.EstimatedTotal;

            // get total tax
            //SortedDictionary<decimal, decimal> taxRates = null;
            //decimal shoppingCartTaxBase = OrderTotalCalculationService.GetTaxTotal(cart, out taxRates);
            //decimal shoppingCartTax = _currencyService.ConvertFromPrimaryStoreCurrency(shoppingCartTaxBase, CommonServices.WorkContext.WorkingCurrency);

            // discount
            var discount = -processPaymentRequest.Discount;

            if (discount != 0)
            {
                cartItems.Add(new PaymentDetailsItemType
                {
                    Name     = T("Plugins.Payments.PayPal.ThreadrockDiscount").Text,
                    Quantity = "1",
                    Amount   = new BasicAmountType // this is the total discount
                    {
                        currencyID = payPalCurrency,
                        Value      = discount.FormatInvariant()
                    }
                });

                itemTotal += discount;
            }

            if (!cart.IsRecurring())
            {
                //we don't apply gift cards for recurring products
                var giftCards = _giftCardService.GetActiveGiftCardsAppliedByCustomer(customer, Services.StoreContext.CurrentStore.Id);
                if (giftCards != null)
                {
                    foreach (var gc in giftCards)
                    {
                        if (itemTotal > decimal.Zero)
                        {
                            decimal remainingAmount = gc.GetGiftCardRemainingAmount();
                            decimal amountCanBeUsed = decimal.Zero;
                            if (itemTotal > remainingAmount)
                            {
                                amountCanBeUsed = remainingAmount;
                            }
                            else
                            {
                                amountCanBeUsed = itemTotal - .01M;
                            }

                            decimal amountToSubtract = -amountCanBeUsed;

                            cartItems.Add(new PaymentDetailsItemType
                            {
                                Name     = T("Plugins.Payments.PayPal.GiftcardApplied").Text,
                                Quantity = "1",
                                Amount   = new BasicAmountType
                                {
                                    currencyID = payPalCurrency,
                                    Value      = amountToSubtract.FormatInvariant()
                                }
                            });

                            //reduce subtotal
                            itemTotal += amountToSubtract;
                        }
                    }
                }
            }

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                ItemTotal = new BasicAmountType
                {
                    Value      = Math.Round(itemTotal, 2).FormatInvariant(),
                    currencyID = payPalCurrency
                },
                ShippingTotal = new BasicAmountType
                {
                    Value      = Math.Round(shippingTotal, 2).FormatInvariant(),
                    currencyID = payPalCurrency
                },
                //TaxTotal = new BasicAmountType
                //{
                //    Value = Math.Round(shoppingCartTax, 2).ToString("N", new CultureInfo("en-us")),
                //    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                //},
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(itemTotal + shippingTotal, 2).FormatInvariant(),
                    currencyID = payPalCurrency
                },
                Custom             = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource       = SmartStoreVersion.CurrentFullVersion,
                PaymentAction      = GetPaymentAction(settings),
                PaymentDetailsItem = cartItems.ToArray()
            };

            details.PaymentDetails = new[] { paymentDetails };

            details.ShippingMethodSpecified = true;

            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails.Custom = processPaymentRequest.OrderGuid.ToString();
            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails        = details;

            using (var service = GetApiAaService(settings))
            {
                result = service.SetExpressCheckout(req);
            }

            var checkoutState = _httpContext.GetCheckoutState();

            if (checkoutState.CustomProperties.ContainsKey("PayPalExpressButtonUsed"))
            {
                checkoutState.CustomProperties["PayPalExpressButtonUsed"] = true;
            }
            else
            {
                checkoutState.CustomProperties.Add("PayPalExpressButtonUsed", true);
            }

            return(result);
        }
Example #28
0
        private ActionResult Processing_PayPal(int claim, PaymentMode payment)
        {
            if (payment == null)
            {
                throw new System.ArgumentNullException("payment");
            }
            PaymentBeforeProcessingResult beforePaymentResult = BookingProvider.BeforePaymentProcessing(UrlLanguage.CurrentLanguage, payment.paymentparam);

            if (beforePaymentResult == null)
            {
                throw new System.Exception("cannot get payment details");
            }
            if (!beforePaymentResult.success)
            {
                throw new System.Exception("payment details fail");
            }
            System.Collections.Generic.List <PaymentDetailsType> paymentDetails = new System.Collections.Generic.List <PaymentDetailsType>();
            PaymentDetailsType paymentDetail = new PaymentDetailsType();

            paymentDetail.AllowedPaymentMethod = new AllowedPaymentMethodType?(AllowedPaymentMethodType.ANYFUNDINGSOURCE);
            CurrencyCodeType       currency    = (CurrencyCodeType)EnumUtils.GetValue(payment.payrest.currency, typeof(CurrencyCodeType));
            PaymentDetailsItemType paymentItem = new PaymentDetailsItemType();

            paymentItem.Name                 = string.Format(PaymentStrings.ResourceManager.Get("PaymentForOrderFormat"), claim);
            paymentItem.Amount               = new BasicAmountType(new CurrencyCodeType?(currency), payment.payrest.total.ToString("#.00", System.Globalization.NumberFormatInfo.InvariantInfo));
            paymentItem.Quantity             = new int?(1);
            paymentItem.ItemCategory         = new ItemCategoryType?(ItemCategoryType.PHYSICAL);
            paymentItem.Description          = string.Format("Booking #{0}", claim);
            paymentDetail.PaymentDetailsItem = new System.Collections.Generic.List <PaymentDetailsItemType>
            {
                paymentItem
            };
            paymentDetail.PaymentAction = new PaymentActionCodeType?(PaymentActionCodeType.SALE);
            paymentDetail.OrderTotal    = new BasicAmountType(paymentItem.Amount.currencyID, paymentItem.Amount.value);
            paymentDetails.Add(paymentDetail);
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();

            ecDetails.ReturnURL = new Uri(base.Request.BaseServerAddress(), base.Url.Action("processingresult", new
            {
                id      = "paypal",
                success = true
            })).ToString();
            ecDetails.CancelURL = new Uri(base.Request.BaseServerAddress(), base.Url.Action("processingresult", new
            {
                id      = "paypal",
                success = false
            })).ToString();
            ecDetails.NoShipping     = "1";
            ecDetails.AllowNote      = "0";
            ecDetails.SolutionType   = new SolutionTypeType?(SolutionTypeType.SOLE);
            ecDetails.SurveyEnable   = "0";
            ecDetails.PaymentDetails = paymentDetails;
            ecDetails.InvoiceID      = beforePaymentResult.invoiceNumber;
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();

            request.Version = "104.0";
            request.SetExpressCheckoutRequestDetails = ecDetails;
            SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq();

            wrapper.SetExpressCheckoutRequest = request;
            System.Collections.Generic.Dictionary <string, string> config = PaymentController.PayPal_CreateConfig();
            PayPalAPIInterfaceServiceService service       = new PayPalAPIInterfaceServiceService(config);
            SetExpressCheckoutResponseType   setECResponse = service.SetExpressCheckout(wrapper);

            System.Collections.Generic.KeyValuePair <string, string> sandboxConfig = config.FirstOrDefault((System.Collections.Generic.KeyValuePair <string, string> m) => m.Key == "mode");
            string sandboxServer = (sandboxConfig.Key != null && sandboxConfig.Value == "sandbox") ? ".sandbox" : "";

            return(base.View("PaymentSystems\\PayPal", new ProcessingContext
            {
                Reservation = BookingProvider.GetReservationState(UrlLanguage.CurrentLanguage, claim),
                PaymentMode = payment,
                BeforePaymentResult = beforePaymentResult,
                RedirectUrl = string.Format("https://www{0}.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={1}", sandboxServer, base.Server.UrlEncode(setECResponse.Token))
            }));

            //  return new RedirectResult(string.Format("https://www{0}.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={1}", sandboxServer, base.Server.UrlEncode(setECResponse.Token)));
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext CurrContext = HttpContext.Current;

        // Create the SetExpressCheckoutResponseType object
        SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType();

        try
        {
            // Check if the EC methos is shorcut or mark
            string ecMethod = "";
            if (Request.QueryString["ExpressCheckoutMethod"] != null)
            {
                ecMethod = Request.QueryString["ExpressCheckoutMethod"];
            }
            else if ((string)(Session["ExpressCheckoutMethod"]) != null)
            {
                ecMethod = (string)(Session["ExpressCheckoutMethod"]);
            }
            string item_name     = "";
            string item_id       = "";
            string item_desc     = "";
            string item_quantity = "";
            string item_amount   = "";
            //string tax_amount = "";
            //string shipping_amount = "";
            //string handling_amount = "";
            //string shipping_discount_amount = "";
            //string insurance_amount = "";
            string total_amount  = "";
            string currency_code = "";
            string payment_type  = "";
            string roundedtotal  = "";
            string roundeditmamt = "";

            // From Marck EC Page
            //string shipping_rate = "";
            string first_name  = "";
            string last_name   = "";
            string street1     = "";
            string street2     = "";
            string city        = "";
            string state       = "";
            string postal_code = "";
            string country     = "";
            string phone       = "";
            //Double new_total_rate = 0.00;
            AddressType shipToAddress = new AddressType();
            if (ecMethod != null && ecMethod == "ShorcutExpressCheckout")
            {
                // Get parameters from index page (shorcut express checkout)
                item_name     = Request.Form["item_name"];
                item_id       = Request.Form["item_id"];
                item_desc     = Request.Form["item_desc"];
                item_quantity = Request.Form["item_quantity"];
                item_amount   = Request.Form["item_amount"];

                total_amount            = Request.Form["total_amount"];
                currency_code           = Request.Form["currency_code_type"];
                payment_type            = Request.Form["payment_type"];
                Session["Total_Amount"] = total_amount;

                roundeditmamt = (Math.Round(double.Parse(item_amount), 2)).ToString();
                roundedtotal  = (Math.Round(double.Parse(total_amount), 2)).ToString();
            }
            else if (ecMethod != null && ecMethod == "MarkExpressCheckout")
            {
                // Get parameters from mark ec page
                //shipping_rate = Request.Form["shipping_method"].ToString();

                item_name     = Request.Form["item_name"];
                item_id       = Request.Form["item_id"];
                item_desc     = Request.Form["item_desc"];
                item_quantity = Request.Form["item_quantity"];
                item_amount   = Request.Form["item_amount"];
                //tax_amount = Request.Form["tax_amount"];
                //shipping_amount = Request.Form["shipping_amount"];
                //handling_amount = Request.Form["handling_amount"];
                //shipping_discount_amount = Request.Form["shipping_discount_amount"];
                //insurance_amount = Request.Form["insurance_amount"];
                total_amount  = Request.Form["total_amount"];
                currency_code = Request.Form["currency_code"];
                payment_type  = Request.Form["payment_type"];

                first_name  = Request.Form["FIRST_NAME"];
                last_name   = Request.Form["LAST_NAME"];
                street1     = Request.Form["STREET_1"];
                street2     = Request.Form["STREET_2"];
                city        = Request.Form["CITY"];
                state       = Request.Form["STATE"];
                postal_code = Request.Form["POSTAL_CODE"];
                country     = Request.Form["COUNTRY"];
                phone       = Request.Form["PHONE"];

                roundeditmamt = (Math.Round(double.Parse(item_amount), 2)).ToString();
                roundedtotal  = (Math.Round(double.Parse(total_amount), 2)).ToString();

                // Set the details of new shipping address
                //shipToAddress.Name = first_name + " " + last_name;
                //shipToAddress.Street1 = street1;
                //if (!street2.Equals(""))
                //{
                //    shipToAddress.Street2 = street2;
                //}
                //shipToAddress.CityName = city;
                //shipToAddress.StateOrProvince = state;
                //string countrycode = country;
                //CountryCodeType countryCodeType = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), countrycode, true);
                //shipToAddress.Country = countryCodeType;
                //shipToAddress.PostalCode = postal_code;
                //if (!phone.Equals(""))
                //{
                //    shipToAddress.Phone = phone;
                //}

                //Double total_rate = Convert.ToDouble(total_amount);
                //Double old_shipping_rate = Convert.ToDouble(shipping_amount);
                //Double new_shipping_rate = Convert.ToDouble(shipping_rate);

                // Calculate new order total based on shipping method selected
                //new_total_rate = total_rate - old_shipping_rate + new_shipping_rate;
                //Session["Total_Amount"] = new_total_rate.ToString();
                //total_amount = new_total_rate.ToString();
                //shipping_amount = new_shipping_rate.ToString();
            }

            Session["SellerEmail"] = SellerEmail;
            CurrencyCodeType currencyCode_Type = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currency_code, true);
            Session["currency_code_type"] = currencyCode_Type;
            PaymentActionCodeType payment_ActionCode_Type = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), payment_type, true);
            Session["payment_action_type"] = payment_ActionCode_Type;
            // SetExpressCheckoutRequestDetailsType object
            SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            // (Required) URL to which the buyer's browser is returned after choosing to pay with PayPal.
            setExpressCheckoutRequestDetails.ReturnURL = ReturnUrl;
            //(Required) URL to which the buyer is returned if the buyer does not approve the use of PayPal to pay you
            setExpressCheckoutRequestDetails.CancelURL = CancelUrl;
            // A URL to your logo image. Use a valid graphics format, such as .gif, .jpg, or .png
            setExpressCheckoutRequestDetails.cppLogoImage = LogoUrl;
            // To display the border in your principal identifying color, set the "cppCartBorderColor" parameter to the 6-digit hexadecimal value of that color
            // setExpressCheckoutRequestDetails.cppCartBorderColor = "0000CD";

            //Item details
            PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();
            itemDetails.Name        = item_name;
            itemDetails.Amount      = new BasicAmountType(currencyCode_Type, roundeditmamt);
            itemDetails.Quantity    = Convert.ToInt32(item_quantity);
            itemDetails.Description = item_desc;
            itemDetails.Number      = item_id;

            //Add more items if necessary by using the class 'PaymentDetailsItemType'

            // Payment Information
            List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

            PaymentDetailsType paymentDetails = new PaymentDetailsType();
            paymentDetails.PaymentAction = payment_ActionCode_Type;
            paymentDetails.ItemTotal     = new BasicAmountType(currencyCode_Type, roundeditmamt);//item amount
            //paymentDetails.TaxTotal = new BasicAmountType(currencyCode_Type, tax_amount); //tax amount;
            //paymentDetails.ShippingTotal = new BasicAmountType(currencyCode_Type, shipping_amount); //shipping amount
            //paymentDetails.HandlingTotal = new BasicAmountType(currencyCode_Type, handling_amount); //handling amount
            //paymentDetails.ShippingDiscount = new BasicAmountType(currencyCode_Type, shipping_discount_amount); //shipping discount
            //paymentDetails.InsuranceTotal = new BasicAmountType(currencyCode_Type, insurance_amount); //insurance amount
            paymentDetails.OrderTotal = new BasicAmountType(currencyCode_Type, roundedtotal); // order total amount

            paymentDetails.PaymentDetailsItem.Add(itemDetails);

            // Unique identifier for the merchant.
            SellerDetailsType sellerDetails = new SellerDetailsType();
            sellerDetails.PayPalAccountID = SellerEmail;
            paymentDetails.SellerDetails  = sellerDetails;

            if (ecMethod != null && ecMethod == "MarkExpressCheckout")
            {
                paymentDetails.ShipToAddress = shipToAddress;
            }
            paymentDetailsList.Add(paymentDetails);
            setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList;

            // Collect Shipping details if MARK express checkout

            SetExpressCheckoutReq         setExpressCheckout        = new SetExpressCheckoutReq();
            SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);
            setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;

            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

            // API call
            // Invoke the SetExpressCheckout method in service wrapper object
            responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);

            if (responseSetExpressCheckoutResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "SetExpressCheckout API Operation - ";
                acknowledgement += responseSetExpressCheckoutResponseType.Ack.ToString();
                //logger.Debug(acknowledgement + "\n");
                System.Diagnostics.Debug.WriteLine(acknowledgement + "\n");
                // # Success values
                if (responseSetExpressCheckoutResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // # Redirecting to PayPal for authorization
                    // Once you get the "Success" response, needs to authorise the
                    // transaction by making buyer to login into PayPal. For that,
                    // need to construct redirect url using EC token from response.
                    // Express Checkout Token
                    string EcToken = responseSetExpressCheckoutResponseType.Token;
                    //logger.Info("Express Checkout Token : " + EcToken + "\n");
                    System.Diagnostics.Debug.WriteLine("Express Checkout Token : " + EcToken + "\n");
                    // Store the express checkout token in session to be used in GetExpressCheckoutDetails & DoExpressCheckout API operations
                    Session["EcToken"] = EcToken;
                    Response.Redirect(RedirectUrl + HttpUtility.UrlEncode(EcToken), false);
                    Context.ApplicationInstance.CompleteRequest();
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseSetExpressCheckoutResponseType.Errors;
                    string           errorMessage  = "";
                    foreach (ErrorType error in errorMessages)
                    {
                        //logger.Debug("API Error Message : " + error.LongMessage);
                        System.Diagnostics.Debug.WriteLine("API Error Message : " + error.LongMessage + "\n");
                        errorMessage = errorMessage + error.LongMessage;
                    }
                    //Redirect to error page in case of any API errors
                    CurrContext.Items.Add("APIErrorMessage", errorMessage);
                    Server.Transfer("~/Response.aspx");
                }
            }
        }
        catch (System.Exception ex)
        {
            // Log the exception message
            //logger.Debug("Error Message : " + ex.Message);
            System.Diagnostics.Debug.WriteLine("Error Message : " + ex.Message);
        }
    }
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var paymentResponse = new ProcessPaymentResult();
            var req             = new SetExpressCheckoutReq();

            req.SetExpressCheckoutRequest = new SetExpressCheckoutRequestType {
                Version = Settings.Version
            };
            var details = new SetExpressCheckoutRequestDetailsType();

            req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails = details;

            var currencyCode = (CurrencyCodeType)Utils.GetEnumValueByName(typeof(CurrencyCodeType), processPaymentRequest.CurrencyCode);
            var oPayDetail   = new PaymentDetailsType();

            oPayDetail.OrderTotal            = new BasicAmountType();
            oPayDetail.OrderTotal.Value      = (processPaymentRequest.OrderTotal).ToString("N", new CultureInfo("en-gb"));
            oPayDetail.OrderTotal.currencyID = currencyCode;

            oPayDetail.ShippingMethod = ShippingServiceCodeType.ShippingMethodStandard;

            oPayDetail.ItemTotal                = new BasicAmountType();
            oPayDetail.ItemTotal.Value          = (processPaymentRequest.OrderTotal - processPaymentRequest.Order.ShippingCharge.Raw.WithTax).ToString("N", new CultureInfo("en-gb"));
            oPayDetail.ItemTotal.currencyID     = currencyCode;
            oPayDetail.ShippingMethodSpecified  = true;
            oPayDetail.ShippingTotal            = new BasicAmountType();
            oPayDetail.ShippingTotal.Value      = processPaymentRequest.Order.ShippingCharge.Raw.WithTax.ToString("N", new CultureInfo("en-gb"));
            oPayDetail.ShippingTotal.currencyID = currencyCode;
            oPayDetail.OrderDescription         = "Order Total:" + processPaymentRequest.OrderTotal.ToString();
            oPayDetail.PaymentActionSpecified   = true;
            oPayDetail.PaymentAction            = PaymentActionCodeType.Authorization;


            oPayDetail.InvoiceID = processPaymentRequest.OrderId;

            var oItems = new List <PaymentDetailsItemType>();
            int i      = 1;

            foreach (var itm in processPaymentRequest.Order.Items)
            {
                var oItem = new PaymentDetailsItemType {
                    Number = i.ToString(CultureInfo.InvariantCulture)
                };
                oItem.Name        = itm.StockCode;
                oItem.Description = itm.Name;
                oItem.Amount      = new BasicAmountType();
                decimal itmPrice = itm.Price.Raw.WithTax;
                oItem.Amount.Value      = itmPrice.ToString("N", new CultureInfo("en-gb"));
                oItem.Amount.currencyID = currencyCode;
                oItem.Quantity          = itm.Qty.ToString(CultureInfo.InvariantCulture);
                i = i + 1;
                oItems.Add(oItem);
            }
            if (processPaymentRequest.Order.Discount.Raw.WithTax > 0)
            {
                var odiscountItem = new PaymentDetailsItemType {
                    Number = i.ToString(CultureInfo.InvariantCulture)
                };
                odiscountItem.Name        = "Discount";
                odiscountItem.Description = "Discount";
                odiscountItem.Amount      = new BasicAmountType();
                decimal itmPrice = -processPaymentRequest.Order.Discount.Raw.WithTax;
                odiscountItem.Amount.Value      = itmPrice.ToString("N", new CultureInfo("en-GB"));
                odiscountItem.Amount.currencyID = currencyCode;
                odiscountItem.Quantity          = (1).ToString(CultureInfo.InvariantCulture);
                oItems.Add(odiscountItem);
            }
            if (processPaymentRequest.Order.GrandTotal.Raw.WithTax > processPaymentRequest.OrderTotal)
            {
                var odiscountItem = new PaymentDetailsItemType {
                    Number = i.ToString(CultureInfo.InvariantCulture)
                };
                odiscountItem.Name        = "Paid By Other Source";
                odiscountItem.Description = "Other Source";
                odiscountItem.Amount      = new BasicAmountType();
                decimal itmPrice = -(processPaymentRequest.Order.GrandTotal.Raw.WithTax - processPaymentRequest.OrderTotal);
                odiscountItem.Amount.Value      = itmPrice.ToString("N", new CultureInfo("en-GB"));
                odiscountItem.Amount.currencyID = currencyCode;
                odiscountItem.Quantity          = (1).ToString(CultureInfo.InvariantCulture);
                oItems.Add(odiscountItem);
            }

            oPayDetail.PaymentDetailsItem = oItems.ToArray();

            PaymentDetailsType[] oPayDetails = { oPayDetail };

            details.PaymentDetails = oPayDetails;

            details.ReturnURL = Settings.NotificationUrl + "?oid=" + processPaymentRequest.OrderId + "&payid=" + processPaymentRequest.PaymentId;
            details.CancelURL = Settings.CancelUrl + "/" + processPaymentRequest.BasketId;
            System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            var credentials = PaypalSecurityHeader();
            SetExpressCheckoutResponseType response = _paypalService2.SetExpressCheckout(ref credentials, req);

            if (response.Ack == AckCodeType.Success)
            {
                paymentResponse.AuthorizationTransactionUrl = GetPaypalUrl(response.Token);
                paymentResponse.UseAuthUrlToRedirect        = true;
            }
            else
            {
                foreach (var er in response.Errors)
                {
                    paymentResponse.AddError(er.ErrorCode + " : " + er.ShortMessage);
                }
            }
            return(paymentResponse);
        }
Example #31
0
        public string GenerateOrder(List <ItemPayPal> items)
        {
            // Create request object
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();

            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();



            /* Populate payment requestDetails.
             * SetExpressCheckout allows parallel payments of upto 10 payments.
             * This samples shows just one payment.
             */
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            ecDetails.PaymentDetails.Add(paymentDetails);
            // (Required) Total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. Set this field to 0 if the transaction does not include a one-time purchase such as when you set up a billing agreement for a recurring payment that is not immediately charged. When the field is set to 0, purchase-specific fields are ignored.
            double orderTotal = 0.0;
            // Sum of cost of all items in this order. For digital goods, this field is required.
            double           itemTotal = 0.0;
            CurrencyCodeType currency  = CurrencyCodeType.MXN;


            //(Optional) Description of items the buyer is purchasing.
            // Note:
            // The value you specify is available only if the transaction includes a purchase.
            // This field is ignored if you set up a billing agreement for a recurring payment
            // that is not immediately charged.
            // Character length and limitations: 127 single-byte alphanumeric characters

            paymentDetails.OrderDescription = "";

            // How you want to obtain payment. When implementing parallel payments,
            // this field is required and must be set to Order.
            // When implementing digital goods, this field is required and must be set to Sale.
            // If the transaction does not include a one-time purchase, this field is ignored.
            // It is one of the following values:
            //   Sale – This is a final sale for which you are requesting payment (default).
            //   Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            //   Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture.
            paymentDetails.PaymentAction = PaymentActionCodeType.SALE;

            paymentDetails.ButtonSource = "PTSH";

            foreach (ItemPayPal item in items)
            {
                PaymentDetailsItemType details = new PaymentDetailsItemType()
                {
                    Name     = item.Name,
                    Amount   = new BasicAmountType(currency, ((decimal)item.Price).ToString()),
                    Quantity = item.Quantity
                };

                // Indicates whether an item is digital or physical. For digital goods, this field is required and must be set to Digital. It is one of the following values:
                //   1.Digital
                //   2.Physical
                //  This field is available since version 65.1.
                //itemDetails.ItemCategory = ItemCategoryType.DIGITAL;

                itemTotal += Convert.ToDouble(details.Amount.value) * details.Quantity.Value;

                //(Optional) Item description.
                // Character length and limitations: 127 single-byte characters
                // This field is introduced in version 53.0.

                details.Description = item.Description;

                paymentDetails.PaymentDetailsItem.Add(details);
            }

            orderTotal += itemTotal;
            paymentDetails.ItemTotal  = new BasicAmountType(currency, itemTotal.ToString());
            paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString());
            paymentDetails.Custom     = "9998";
            paymentDetails.InvoiceID  = null;

            ecDetails.ReturnURL          = AppSettings.PayPalCallbackOk;
            ecDetails.CancelURL          = AppSettings.PayPalCallbackFail;
            ecDetails.NoShipping         = "1";
            ecDetails.AllowNote          = "0";
            ecDetails.cppCartBorderColor = "0b5ba1";

            // (Optional) URL for the image you want to appear at the top left of the payment page. The image has a maximum size of 750 pixels wide by 90 pixels high. PayPal recommends that you provide an image that is stored on a secure (https) server. If you do not specify an image, the business name displays.
            ecDetails.cppHeaderImage = "";

            request.SetExpressCheckoutRequestDetails = ecDetails;

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////


            // Invoke the API
            SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq();

            wrapper.SetExpressCheckoutRequest = request;

            System.Net.ServicePointManager.Expect100Continue = false;

            // Configuration map containing signature credentials and other required configuration.
            // For a full list of configuration parameters refer in wiki page
            // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]

            // Create the PayPalAPIInterfaceServiceService service object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(_payPalConfiguration);

            //wrapper.SetExpressCheckoutRequest.Version = "84.0";
            // # API call
            // Invoke the SetExpressCheckout method in service wrapper object
            SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper);

            // Check for API return status

            if (setECResponse.Ack.Equals(AckCodeType.FAILURE) || (setECResponse.Errors != null && setECResponse.Errors.Any()))
            {
                return(string.Empty);
            }
            return(setECResponse.Token);
        }
Example #32
0
        public static PayPalResponceModel Pay(string email, CartViewModel cart, string expressCheckoutSuccessUrl, string paymentFailureUrl)
        {
            Dictionary <string, string>      config  = PayPal.Api.ConfigManager.Instance.GetProperties();
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config);

            SetExpressCheckoutRequestType        setExpressCheckoutReqType = new SetExpressCheckoutRequestType();
            SetExpressCheckoutRequestDetailsType details    = new SetExpressCheckoutRequestDetailsType();
            List <PaymentDetailsType>            payDetails = new List <PaymentDetailsType>();
            PaymentDetailsType paydtl = new PaymentDetailsType();

            paydtl.PaymentAction = PaymentActionCodeType.ORDER;

            BasicAmountType shippingTotal = new BasicAmountType();

            shippingTotal.value      = cart.ShippingCost.ToString();
            shippingTotal.currencyID = CurrencyCodeType.USD;

            decimal itemsTotal = 0.0M;

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

            foreach (var cartItem in cart.Items)
            {
                PaymentDetailsItemType item = new PaymentDetailsItemType();
                BasicAmountType        amt  = new BasicAmountType();
                amt.currencyID = CurrencyCodeType.USD;

                amt.value     = "50";
                item.Quantity = cartItem.Count;
                itemsTotal   += 50 * cartItem.Count;

                item.Name   = string.Format("{0} {1} Shirt", cartItem.Project.ShirtColor, cartItem.Project.SizeString);
                item.Amount = amt;

                lineItems.Add(item);
            }

            decimal orderTotal = itemsTotal + cart.ShippingCost;

            paydtl.OrderTotal         = new BasicAmountType(CurrencyCodeType.USD, Convert.ToString(orderTotal));
            paydtl.PaymentDetailsItem = lineItems;

            paydtl.ShippingTotal      = shippingTotal;
            paydtl.PaymentDetailsItem = lineItems;
            payDetails.Add(paydtl);

            details.BuyerEmail     = email;
            details.PaymentDetails = payDetails;
            details.ReturnURL      = expressCheckoutSuccessUrl;
            details.CancelURL      = paymentFailureUrl;

            setExpressCheckoutReqType.SetExpressCheckoutRequestDetails = details;
            SetExpressCheckoutReq expressCheckoutReq = new SetExpressCheckoutReq();

            expressCheckoutReq.SetExpressCheckoutRequest = setExpressCheckoutReqType;
            SetExpressCheckoutResponseType response = null;

            try
            {
                response = service.SetExpressCheckout(expressCheckoutReq);
            }
            catch (Exception ex)
            {
                return(new PayPalResponceModel
                {
                    Success = false,
                    ErrorMessage = ex.Message
                });
            }

            if (!response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.Ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                var redirectUrl = string.Format("{0}_express-checkout&token={1}", config["paypalResultUrl"], response.Token);
                return(new PayPalResponceModel
                {
                    Success = true,
                    RedirectUrl = redirectUrl
                });
            }

            return(new PayPalResponceModel
            {
                Success = false,
                ErrorMessage = string.Join(". ", response.Errors.Select(x => x.LongMessage).ToList())
            });
        }
Example #33
0
        public virtual async Task <PaymentRequestResult> RequestForPaymentUrl(string callbackUrl, TblInvoices invoice)
        {
            var settings = await _settingService.LoadSettingAsync <PayPalSettingsModel>();

            var currentCurrency = DependencyResolver.Current.GetService <IWorkContext>().CurrentCurrency;
            var amount          = invoice.ComputeInvoiceTotalAmount();


            var currencyCode = CurrencyCodeType.USD;

            if (currentCurrency.IsoCode.ToLower().Trim() == "eur")
            {
                currencyCode = CurrencyCodeType.EUR;
            }
            var buyerEmail  = "";
            var paymentDesc = string.Format(_localizationService.GetResource("Plugin.PaymentMethod.PayPal.InvoiceNumber"), invoice.Id.ToString("N").ToUpper());

            if (invoice.User != null)
            {
                buyerEmail = invoice.User.Email;
            }

            if (string.IsNullOrWhiteSpace(settings.APIUserName) ||
                string.IsNullOrWhiteSpace(settings.APIPassword) ||
                string.IsNullOrWhiteSpace(settings.APISignature))
            {
                return(new PaymentRequestResult()
                {
                    ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.InvalidConfig")
                });
            }

            var result = new PaymentRequestResult();
            await Task.Run(() =>
            {
                try
                {
                    var ecDetails = new SetExpressCheckoutRequestDetailsType()
                    {
                        ReturnURL          = AppendQueryStringToUrl(callbackUrl, "Status", "OK"),
                        CancelURL          = AppendQueryStringToUrl(callbackUrl, "Status", "NOK"),
                        LocaleCode         = "US",
                        BuyerEmail         = buyerEmail,
                        InvoiceID          = invoice.Id.ToString(),
                        OrderDescription   = paymentDesc,
                        ShippingMethod     = ShippingServiceCodeType.DOWNLOAD,
                        PaymentAction      = PaymentActionCodeType.SALE,
                        OrderTotal         = new BasicAmountType(currencyCode, amount.ToString()),
                        NoShipping         = "1", //PayPal does not display shipping address fields and removes shipping information from the transaction.
                        ReqConfirmShipping = "0", //do not require the buyer's shipping address be a confirmed address.
                        AddressOverride    = "0", //The PayPal pages should not display the shipping address.
                        cppHeaderImage     = settings.PayPalHeaderImageUrl,
                        BrandName          = settings.PayPalBrandName,
                    };

                    var request = new SetExpressCheckoutRequestType(ecDetails);
                    var wrapper = new SetExpressCheckoutReq {
                        SetExpressCheckoutRequest = request
                    };
                    var service = new PayPalAPIInterfaceServiceService(GetPayPalConfig());
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    var setEcResponse = service.SetExpressCheckout(wrapper);

                    if (setEcResponse.Ack == AckCodeType.SUCCESS)
                    {
                        result.RedirectUrl = settings.PaymentPageUrl + "_express-checkout&token=" +
                                             setEcResponse.Token;
                        result.Token     = setEcResponse.Token;
                        result.IsSuccess = true;
                    }
                    else
                    {
                        foreach (var error in setEcResponse.Errors)
                        {
                            result.ErrorMessage +=
                                $"[{error.SeverityCode}] {error.ErrorCode} : {error.LongMessage} </br>";
                        }
                    }
                }
                catch
                {
                    result.ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.ServiceUnavailable");
                }
            });

            return(result);
        }
        /// <summary>
        /// Performs the setup for an express checkout.
        /// </summary>
        /// <param name="invoice">
        /// The <see cref="IInvoice"/>.
        /// </param>
        /// <param name="payment">
        /// The <see cref="IPayment"/>
        /// </param>
        /// <param name="returnUrl">
        /// The return URL.
        /// </param>
        /// <param name="cancelUrl">
        /// The cancel URL.
        /// </param>
        /// <returns>
        /// The <see cref="ExpressCheckoutResponse"/>.
        /// </returns>
        protected virtual PayPalExpressTransactionRecord SetExpressCheckout(IInvoice invoice, IPayment payment, string returnUrl, string cancelUrl)
        {
            var record = new PayPalExpressTransactionRecord
                             {
                                 Success = true,
                                 Data = { Authorized = false, CurrencyCode = invoice.CurrencyCode }
                             };

            var factory = new PayPalPaymentDetailsTypeFactory(new PayPalFactorySettings { WebsiteUrl = _websiteUrl });
            var paymentDetailsType = factory.Build(invoice, PaymentActionCodeType.ORDER);

            // The API requires this be in a list
            var paymentDetailsList = new List<PaymentDetailsType>() { paymentDetailsType };

            // ExpressCheckout details
            var ecDetails = new SetExpressCheckoutRequestDetailsType()
                    {
                        ReturnURL = returnUrl,
                        CancelURL = cancelUrl,
                        PaymentDetails = paymentDetailsList,
                        AddressOverride = "0"
                    };

            // Trigger the event to allow for overriding ecDetails
            var ecdOverride = new PayPalExpressCheckoutRequestDetailsOverride(invoice, payment, ecDetails);
            SettingCheckoutRequestDetails.RaiseEvent(new ObjectEventArgs<PayPalExpressCheckoutRequestDetailsOverride>(ecdOverride), this);

            // The ExpressCheckoutRequest
            var request = new SetExpressCheckoutRequestType
                    {
                        Version = Version,
                        SetExpressCheckoutRequestDetails = ecdOverride.ExpressCheckoutDetails
                    };

            // Crete the wrapper for Express Checkout
            var wrapper = new SetExpressCheckoutReq
                              {
                                  SetExpressCheckoutRequest = request
                              };

            try
            {
                var service = GetPayPalService();
                var response = service.SetExpressCheckout(wrapper);

                record.SetExpressCheckout = _responseFactory.Build(response, response.Token);
                if (record.SetExpressCheckout.Success())
                {
                    record.Data.Token = response.Token;
                    record.SetExpressCheckout.RedirectUrl = GetRedirectUrl(response.Token);
                }
                else
                {
                    foreach (var et in record.SetExpressCheckout.ErrorTypes)
                    {
                        var code = et.ErrorCode;
                        var sm = et.ShortMessage;
                        var lm = et.LongMessage;
                        MultiLogHelper.Warn<PayPalExpressCheckoutService>(string.Format("{0} {1} {2}", code, lm, sm));
                    }

                    record.Success = false;
                }
            }
            catch (Exception ex)
            {
                record.Success = false;
                record.SetExpressCheckout = _responseFactory.Build(ex);
            }

            return record;
        }