Exemplo n.º 1
0
        public override void PreRedirect(FinancialGateway financialGateway, PaymentInfo paymentInfo, List <GatewayAccountItem> selectedAccounts, out string errorMessage)
        {
            // Create request object
            SetExpressCheckoutRequestType request = populateRequestObject(financialGateway, paymentInfo, selectedAccounts);

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

            wrapper.SetExpressCheckoutRequest = request;


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

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

            // Check for API return status
            String url = financialGateway.GetAttributeValue("PayPalURL")
                         + "_express-checkout&token=" + setECResponse.Token;

            mRedirectUrl = url;
            errorMessage = string.Empty;
            return;
        }
        /// <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));
        }
Exemplo n.º 3
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();

            populateRequestObject(request);

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

            wrapper.SetExpressCheckoutRequest = request;

            // 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]
            Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig();

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

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

            // Check for API return status
            HttpContext CurrContext = HttpContext.Current;

            CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails);
            setKeyResponseObjects(service, setECResponse);
        }
Exemplo n.º 4
0
        // GET: PayPal
        public ActionResult PayPalCreateRequest(string orderId)
        {
            var config  = ConfigManager.Instance.GetProperties();
            var service = new PayPalAPIInterfaceServiceService(config);

            var setExpressCheckoutRequestType = new SetExpressCheckoutRequestType
            {
                SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                {
                    OrderTotal = new BasicAmountType(CurrencyCodeType.USD, "20"),
                    CancelURL  = GlobalSettings.PayPalSettings.PayPalCancelUrl,
                    ReturnURL  = GlobalSettings.PayPalSettings.PayPalReturnUrl + "/?orderId=" + orderId,
                }
            };

            var request = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = setExpressCheckoutRequestType
            };

            var response = service.SetExpressCheckout(request);

            if (!response.Ack.ToString().Trim().ToUpper().Equals(AckCodeType.FAILURE.ToString()) && !response.Ack.ToString().Trim().ToUpper().Equals(AckCodeType.FAILUREWITHWARNING.ToString()))
            {
                var redirectUrl = GlobalSettings.PayPalSettings.PayPalRedirectUrl + "_express-checkout&token=" + response.Token;
                return(Redirect(redirectUrl));
            }

            return(ErrorTransaction());
        }
Exemplo n.º 5
0
        public ActionResult BuyProduct(int?productId)
        {
            if (!productId.HasValue)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            Order order = PayPalHelper.CreateOrder(productId.Value);

            if (order == null)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            string domain    = PayPalHelper.GetDomainName(Request);
            var    returnURL = domain + "/Payment/PaymentDetails";
            var    cancelURL = domain + "/Payment/PaypalCancel";
            SetExpressCheckoutReq          request     = PayPalHelper.GetSetExpressCheckoutReq(order, returnURL, cancelURL);
            CustomSecurityHeaderType       credentials = PayPalHelper.GetPayPalCredentials();
            PayPalAPIAAInterfaceClient     client      = new PayPalAPIAAInterfaceClient();
            SetExpressCheckoutResponseType response    = client.SetExpressCheckout(ref credentials, request);

            if (response.Errors != null && response.Errors.Length > 0)
            {
                throw new Exception("Exception occured when calling PayPal: " + response.Errors[0].LongMessage);
            }
            string redirectUrl = string.Format("{0}?cmd=_express-checkout&token={1}", PayPalHelper.GetPaypalRequestUrl(), response.Token);

            return(Redirect(redirectUrl));
        }
Exemplo n.º 6
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);
        }
        /// <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);
        }
Exemplo n.º 8
0
        public ShoppingCartPayment Pay(ShoppingCartPayment orderDetails)
        {
            if (string.IsNullOrEmpty(orderDetails.authToken))
            {
                return(orderDetails);
            }
            if (!CheckUserBuyer(orderDetails.authToken))
            {
                return(orderDetails);
            }
            if (orderDetails.amount <= 0.01)
            {
                return(orderDetails);
            }
            PayPalAPIAAInterfaceClient pp          = CreatePaypalConnection();
            CustomSecurityHeaderType   credentials = CreateHeaderCredentials(orderDetails.username,
                                                                             orderDetails.password, orderDetails.signature);
            SetExpressCheckoutReq request = CreateExpressCheckoutRequest(orderDetails.amount);

            try
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                var response = pp.SetExpressCheckout(ref credentials, request);
                if (response.Ack == AckCodeType.Success)
                {
                    orderDetails.successfulPayment = true;
                    return(orderDetails);
                }
            }
            catch (Exception ex) { }
            orderDetails.successfulPayment = false;
            return(orderDetails);
        }
Exemplo n.º 9
0
        protected string GetPaypalTransactionToken(decimal price, string returnUrl, string cancelUrl)
        {
            var client      = new PayPalAPIAAInterfaceClient();
            var credentials = GetPaypalCredentials();
            var request     = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    Version = "89.0",
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
                    {
                        PaymentAction = PaymentActionCodeType.Sale,
                        OrderTotal    = new BasicAmountType {
                            Value = price.ToString(), currencyID = CurrencyCodeType.USD
                        },
                        PaymentActionSpecified = true,
                        ReturnURL = returnUrl,
                        CancelURL = cancelUrl
                    }
                }
            };

            var response = client.SetExpressCheckout(ref credentials, request);

            if (response.Ack == AckCodeType.Failure)
            {
                throw new InvalidOperationException("Paypal returned the following error: " + response.Errors.FirstOrDefault().LongMessage);
            }

            return(response.Token);
        }
Exemplo n.º 10
0
        /**
         *
         */
        public SetExpressCheckoutResponseType SetExpressCheckout(SetExpressCheckoutReq SetExpressCheckoutReq, string apiUsername)
        {
            setStandardParams(SetExpressCheckoutReq.SetExpressCheckoutRequest);
            string resp = call("SetExpressCheckout", SetExpressCheckoutReq.toXMLString(), apiUsername);

            return(new SetExpressCheckoutResponseType(resp));
        }
        /**
         * AUTO_GENERATED
         */
        public SetExpressCheckoutResponseType SetExpressCheckout(SetExpressCheckoutReq setExpressCheckoutReq, string apiUserName)
        {
            setStandardParams(setExpressCheckoutReq.SetExpressCheckoutRequest);
            string      response    = Call("SetExpressCheckout", setExpressCheckoutReq.ToXMLString(), apiUserName);
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(response);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='SetExpressCheckoutResponse']");

            return(new SetExpressCheckoutResponseType(xmlNode));
        }
Exemplo n.º 12
0
        public string SetExpressCheckout(User user, Product product, string referrer = "", int quantity = 1, string billingAgreementText = "")
        {
            var request = new SetExpressCheckoutRequestType();

            PopulateSetExpressCheckoutRequestObject(request, user, product, referrer, quantity, billingAgreementText);
            var wrapper = new SetExpressCheckoutReq {
                SetExpressCheckoutRequest = request
            };
            var setEcResponse = _payPalApiService.SetExpressCheckout(wrapper, GetApiUserName());

            return(setEcResponse.Token);
        }
Exemplo n.º 13
0
        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));
            }
        }
Exemplo n.º 14
0
        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));
            }
        }
Exemplo n.º 15
0
        public async Task <string> SetExpressCheckoutAsync(SetExpressCheckoutReq request, bool recordarDatos = false)
        {
            PayPalAPIAAInterfaceClient client = new PayPalAPIAAInterfaceClient();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var response = await client.SetExpressCheckoutAsync(GetAuthorizationRequest(), request);

            if (response.SetExpressCheckoutResponse1.Ack == AckCodeType.Success)
            {
                return(string.Format(PAYPALURLCHECKOUT, response.SetExpressCheckoutResponse1.Token));
            }
            throw new ResponseException("Not correct");
        }
Exemplo n.º 16
0
        public PaypalResponse SetExpressCheckout(string userpackageID, string email, string orderDescription, string billingAgreementText,
                                                 string LogoURL, string brandName, double itemTotalAmount, string PlanName, double planAmount, string planDescription)
        {
            // Create request object
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();

            PopulateRequestObject(request, email, orderDescription, billingAgreementText, LogoURL, brandName, itemTotalAmount, PlanName, planAmount, planDescription);

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

            wrapper.SetExpressCheckoutRequest = request;

            // 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]
            Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig();

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


            string fileName      = DateTime.Now.ToString("Request_" + userpackageID + "_" + "yyyy-MM-dd-HH-mm", CultureInfo.InvariantCulture) + ".txt";
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string path          = "~/App_Data/";

            path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
            path = path + fileName;

            string reqString = string.Empty;

            reqString = JsonConvert.SerializeObject(wrapper);
            string text = "Paypal request: " + DateTime.Now.ToString();

            text += Environment.NewLine + Environment.NewLine + "request string: " + reqString;
            System.IO.File.WriteAllText(Path.Combine(baseDirectory, path), text);

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

            string responseString = string.Empty;

            responseString = JsonConvert.SerializeObject(setECResponse);

            PaypalResponse responsePaypal = new PaypalResponse();

            responsePaypal = ProcessResponse(setECResponse);
            return(responsePaypal);
        }
        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);
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            SetExpressCheckoutReq req = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    Version = "74.0",
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
                    {
                        OrderTotal = new BasicAmountType
                        {
                            Value      = "10.00",
                            currencyID = CurrencyCodeType.EUR
                        },
                        ReturnURL = "http://www.google.com",
                        CancelURL = "http://www.google.com"
                    }
                }
            };
            CustomSecurityHeaderType cred = new CustomSecurityHeaderType
            {
                Credentials = new UserIdPasswordType
                {
                    Username  = "******",
                    Password  = "******",
                    Signature = "AFcWxV21C7fd0v3bYYYRCpSSRl31AhzL0GoBgvn-TKnJd6oSO-B8Lqz6",
                    AppId     = "APP-80W284485P519543T"
                }
            };

            PayPalAPIAAInterfaceClient pp = new PayPalAPIAAInterfaceClient();

            pp.Endpoint.Address = new System.ServiceModel.EndpointAddress("https://api-3t.sandbox.paypal.com/nvp");
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                var resp = pp.SetExpressCheckout(ref cred, req);
                Console.Out.WriteLine(resp.CorrelationID);
                Console.Out.WriteLine(resp.Ack.ToString());
                foreach (ErrorType msg in resp.Errors)
                {
                    Console.Out.WriteLine(msg.LongMessage);
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
        }
Exemplo n.º 19
0
 public static string SetExpressCheckout(string email, double total, string returnUrl, string cancelUrl, bool allowGuestCheckout, bool showCreditCardAndAddress)
 {
     System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
     using (var client = new PayPalAPIAAInterfaceClient(new BasicHttpsBinding(), new EndpointAddress(EndpointUrl)))
     {
         var credentials = new CustomSecurityHeaderType()
         {
             Credentials = new UserIdPasswordType()
             {
                 Username  = APIUserName,
                 Password  = APIPassword,
                 Signature = APISignature
             }
         };
         SetExpressCheckoutReq req = new SetExpressCheckoutReq()
         {
             SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
             {
                 Version = "121.0",
                 SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                 {
                     BuyerEmail = email,
                     OrderTotal = new BasicAmountType()
                     {
                         currencyID = CurrencyCodeType.USD,
                         Value      = total.ToString()
                     },
                     ReturnURL             = returnUrl,
                     CancelURL             = cancelUrl,
                     SolutionType          = allowGuestCheckout ? SolutionTypeType.Sole : SolutionTypeType.Mark,
                     SolutionTypeSpecified = allowGuestCheckout,
                     LandingPage           = LandingPageType.Billing,
                     LandingPageSpecified  = showCreditCardAndAddress
                 }
             }
         };
         var    resp   = client.SetExpressCheckout(ref credentials, req);
         string errors = CheckErrors(resp);
         if (errors == String.Empty)
         {
             return(resp.Token);
         }
         else
         {
             return(errors);
         }
     }
 }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
0
        public string SetExpressCheckout(PayPalDGModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            _model.AssertRequiredParameters();
            _model = model;

            var paymentDetails = new PaymentDetailsType();

            AddProductsToDetails(paymentDetails);

            paymentDetails.PaymentAction = PaymentActionCodeType.SALE;
            paymentDetails.ItemTotal     = new BasicAmountType(_model.CurrencyCodeType, _model.GetItemTotalAmount().ToString());
            paymentDetails.OrderTotal    = new BasicAmountType(_model.CurrencyCodeType, _model.GetOrderTotalAmount().ToString());
            paymentDetails.TaxTotal      = new BasicAmountType(_model.CurrencyCodeType, _model.TaxTotalAmount.ToString());

            var ecDetails = CheckoutRequestDetails();

            ecDetails.PaymentDetails.Add(paymentDetails);

            if (_model.SupportCreditCardPayment)
            {
                ecDetails.SolutionType = SolutionTypeType.SOLE;
            }

            var request = new SetExpressCheckoutRequestType {
                SetExpressCheckoutRequestDetails = ecDetails
            };
            var checkoutReq = new SetExpressCheckoutReq {
                SetExpressCheckoutRequest = request
            };

            var service       = new PayPalAPIInterfaceServiceService();
            var setECResponse = service.SetExpressCheckout(checkoutReq);

            var ack = setECResponse.Ack.HasValue ? setECResponse.Ack.Value : AckCodeType.FAILURE;

            AssertCheckoutResponse(ack, setECResponse.Errors);

            return(setECResponse.Token);
        }
Exemplo n.º 22
0
        public void SetQuickCheckOut()
        {
            var request = new SetExpressCheckoutRequestType();

            PopulateSetCheckoutRequestObject(request);
            var wrapper = new SetExpressCheckoutReq();

            wrapper.SetExpressCheckoutRequest = request;
            var service  = new PayPalAPIInterfaceServiceService();
            var response = service.SetExpressCheckout(wrapper);

            if (response.Ack.Equals(AckCodeType.FAILURE) || (response.Errors != null && response.Errors.Count > 0))
            {
                throw new InvalidOperationException(string.Join("\n", response.Errors.Select(x => x.LongMessage)));
            }
            var paypalRedirectUrl = string.Format(ConfigurationManager.AppSettings["PayPalRedirectUrl"] + "_express-checkout&token={0}", response.Token);

            WebResponse.Redirect(paypalRedirectUrl);
        }
Exemplo n.º 23
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();

            populateRequestObject(request);

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

            wrapper.SetExpressCheckoutRequest = request;
            PayPalAPIInterfaceServiceService service       = new PayPalAPIInterfaceServiceService();
            SetExpressCheckoutResponseType   setECResponse = service.SetExpressCheckout(wrapper);

            // Check for API return status
            HttpContext CurrContext = HttpContext.Current;

            CurrContext.Items.Add("paymentDetails", request.SetExpressCheckoutRequestDetails.PaymentDetails);
            setKeyResponseObjects(service, setECResponse);
        }
        public string SetExpressCheckOut()
        {
            var req = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
                    {
                        ReturnURL      = @"https://www.paypal.com/checkoutnow/error",
                        CancelURL      = @"https://www.paypal.com/checkoutnow/error",
                        PaymentDetails = new[]
                        {
                            new PaymentDetailsType
                            {
                                OrderTotal = new BasicAmountType {
                                    currencyID = CurrencyCodeType.USD, Value = "100"
                                },
                                PaymentAction = PaymentActionCodeType.Order
                            }
                        },
                        SolutionType = SolutionTypeType.Mark
                    },
                    Version = "100"
                }
            };

            var factory = new ChannelFactory <PayPalAPIAAInterface>(new BasicHttpBinding(BasicHttpSecurityMode.Transport), new EndpointAddress("https://api-aa.sandbox.paypal.com/2.0/"));
            var proxy   = factory.CreateChannel();
            var resp    = proxy.SetExpressCheckoutAsync(new SetExpressCheckoutRequest
            {
                RequesterCredentials  = GetHeaderCredentials(),
                SetExpressCheckoutReq = req
            }).Result;

            factory.Close();

            return(resp?.SetExpressCheckoutResponse1?.Token ?? "");
        }
        /// <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);
        }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
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));
            }
        }
Exemplo n.º 28
0
        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);
        }
Exemplo n.º 29
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);
            }
        }
Exemplo n.º 30
0
 /// <remarks/>
 public void SetExpressCheckoutAsync(SetExpressCheckoutReq SetExpressCheckoutReq, object userState) {
     if ((this.SetExpressCheckoutOperationCompleted == null)) {
         this.SetExpressCheckoutOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetExpressCheckoutOperationCompleted);
     }
     this.InvokeAsync("SetExpressCheckout", new object[] {
                 SetExpressCheckoutReq}, this.SetExpressCheckoutOperationCompleted, userState);
 }
Exemplo n.º 31
0
 /// <remarks/>
 public void SetExpressCheckoutAsync(SetExpressCheckoutReq SetExpressCheckoutReq) {
     this.SetExpressCheckoutAsync(SetExpressCheckoutReq, null);
 }
Exemplo n.º 32
0
        private async Task <ActionResult> DoMakePayment(GNInvoice invoice, double paymentAmount, string cancelURL, RedirectToRouteResult errorRedirectAction)
        {
            SetExpressCheckoutResponseType ecResponse = null;

            try
            {
                CurrencyCodeType currencyUSD = (CurrencyCodeType)EnumUtils.GetValue("USD", typeof(CurrencyCodeType));

                //define payment details
                List <PaymentDetailsType> paymentDetails = new List <PaymentDetailsType>()
                {
                    new PaymentDetailsType
                    {
                        PaymentDetailsItem = new List <PaymentDetailsItemType>()
                        {
                            new PaymentDetailsItemType
                            {
                                Name         = invoice.Name,
                                Amount       = new BasicAmountType(currencyUSD, Math.Round(paymentAmount, 2) + ""),
                                Quantity     = 1,
                                ItemCategory = (ItemCategoryType)EnumUtils.GetValue("Physical", typeof(ItemCategoryType))
                            }
                        },
                        PaymentAction = (PaymentActionCodeType)EnumUtils.GetValue("Sale", typeof(PaymentActionCodeType)),
                        OrderTotal    = new BasicAmountType(currencyUSD, (Math.Round(paymentAmount, 2) * 1) + "")
                    }
                };

                //define checkout request details
                SetExpressCheckoutReq expressCheckoutRequest = new SetExpressCheckoutReq()
                {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                    {
                        Version = "104.0",
                        SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                        {
                            ReturnURL      = Url.Action("PaymentSuccess", "PayPal", new { invoiceId = invoice.Id }, protocol: GetURLScheme()),
                            CancelURL      = cancelURL,
                            PaymentDetails = paymentDetails
                        }
                    }
                };

                //define sdk configuration
                Dictionary <string, string> sdkConfig = new Dictionary <string, string>();
                sdkConfig.Add("mode", ConfigurationManager.AppSettings["paypal.mode"]);
                sdkConfig.Add("account1.apiUsername", ConfigurationManager.AppSettings["paypal.apiUsername"]);
                sdkConfig.Add("account1.apiPassword", ConfigurationManager.AppSettings["paypal.apiPassword"]);
                sdkConfig.Add("account1.apiSignature", ConfigurationManager.AppSettings["paypal.apiSignature"]);

                //instantiate PayPal API service and send Express Checkout Request
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(sdkConfig);
                ecResponse = service.SetExpressCheckout(expressCheckoutRequest);
            }
            catch (Exception e)
            {
                LogUtil.Error(logger, "Error sending PayPal payment!!", e);
            }

            if (ecResponse != null &&
                ecResponse.Ack.HasValue &&
                ecResponse.Ack.Value.ToString() != "FAILURE" &&
                ecResponse.Errors.Count == 0)
            {
                //redirect to PayPal
                if (ConfigurationManager.AppSettings["paypal.mode"] == "live")
                {
                    string paypalURL = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ecResponse.Token;
                    return(RedirectPermanent(paypalURL));
                }
                else
                {
                    string paypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + ecResponse.Token;
                    return(RedirectPermanent(paypalURL));
                }
            }
            else
            {
                errorRedirectAction.RouteValues["error"] = string.Join(",", ecResponse.Errors.Select(e => e.LongMessage).ToArray());
                return(errorRedirectAction);
            }
        }
Exemplo n.º 33
0
        /// <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;
        }
Exemplo n.º 34
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;
        }