Example #1
0
        /// <summary>
        /// Handles refund
        /// </summary>
        /// <param name="request">RefundPaymentRequest</param>
        /// <returns>RefundPaymentResult</returns>
        public override RefundPaymentResult Refund(RefundPaymentRequest request)
        {
            var    result        = new RefundPaymentResult();
            string transactionId = request.Order.CaptureTransactionId;

            var req = new RefundTransactionReq();

            req.RefundTransactionRequest = new RefundTransactionRequestType();
            //NOTE: Specify amount in partial refund
            req.RefundTransactionRequest.RefundType          = RefundType.Full;
            req.RefundTransactionRequest.RefundTypeSpecified = true;
            req.RefundTransactionRequest.Version             = PayPalHelper.GetApiVersion();
            req.RefundTransactionRequest.TransactionID       = transactionId;

            using (var service = new PayPalAPISoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(Settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(Settings);
                RefundTransactionResponseType response = service.RefundTransaction(req);

                string error   = string.Empty;
                bool   Success = PayPalHelper.CheckSuccess(_helper, response, out error);
                if (Success)
                {
                    result.NewPaymentStatus = PaymentStatus.Refunded;
                    //cancelPaymentResult.RefundTransactionID = response.RefundTransactionID;
                }
                else
                {
                    result.AddError(error);
                }
            }

            return(result);
        }
Example #2
0
    protected void btnContinue_Click(object sender, EventArgs e)
    {
        //set the order username and IP
        order.UserIP   = Request.UserHostAddress;
        order.UserName = Utility.GetUserName();

        //set the billToAddress to something
        order.BillToAddress   = "Paid for at PayPal";
        order.ShippingAddress = AddressEntry1.SelectedAddress;
        order.ShipToAddress   = AddressEntry1.SelectedAddress.ToHtmlString();

        string companyOrderIdentifier = ConfigurationManager.AppSettings["companyOrderIdentifier"];
        string orderNumber            = companyOrderIdentifier + "-STD-" + Utility.GetRandomString();

        order.OrderNumber = orderNumber;
        order.OrderDate   = DateTime.Now;

        order.Save(Utility.GetUserName());

        //if successful, send along the new orderID to PayPal
        string sUrl = PayPalHelper.GetUploadCartUrl(order);

        sUrl += "&custom=" + order.OrderGUID.ToString();

        Response.Redirect(sUrl, false);
    }
Example #3
0
        public ActionResult PaypalIpn()
        {
            var content = Request.BinaryRead(Request.ContentLength);
            var message = Encoding.ASCII.GetString(content);

            var helper = new PayPalHelper();

            var lines   = helper.SplitIpnMessage(message);
            var payment = helper.ParsePaymentLines(lines);
            var txnId   = !String.IsNullOrEmpty(payment.TxnId) ? payment.TxnId : "IPN " + KeyUtils.GetCurrentTimeKey();

            var logRowKey = helper.WriteLog(PayPalLogEntity.NotificationKind.IPN, txnId, message);

            var response = helper.VerifyIPN(message, txnId);

            helper.WriteLog(PayPalLogEntity.NotificationKind.IPNResponse, txnId, response);

            if (response == "VERIFIED")
            {
                if (helper.PostIncomingPayPalPayment(payment, logRowKey))
                {
                    //helper.PurchaseOnIncomingPayPalPayment(payment);
                }
            }

            return(new HttpStatusCodeResult(HttpStatusCode.NoContent));
        }
        /// <summary>
        /// Cancels a recurring payment
        /// </summary>
        /// <param name="cancelPaymentRequest">Request</param>
        /// <returns>Result</returns>
        public override CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest request)
        {
            var result   = new CancelRecurringPaymentResult();
            var order    = request.Order;
            var settings = CommonServices.Settings.LoadSetting <TSetting>(order.StoreId);

            var req = new ManageRecurringPaymentsProfileStatusReq();

            req.ManageRecurringPaymentsProfileStatusRequest         = new ManageRecurringPaymentsProfileStatusRequestType();
            req.ManageRecurringPaymentsProfileStatusRequest.Version = PayPalHelper.GetApiVersion();
            var details = new ManageRecurringPaymentsProfileStatusRequestDetailsType();

            req.ManageRecurringPaymentsProfileStatusRequest.ManageRecurringPaymentsProfileStatusRequestDetails = details;

            details.Action = StatusChangeActionType.Cancel;
            //Recurring payments profile ID returned in the CreateRecurringPaymentsProfile response
            details.ProfileID = order.SubscriptionTransactionId;

            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                var response = service.ManageRecurringPaymentsProfileStatus(req);

                string error = "";
                if (!PayPalHelper.CheckSuccess(_helper, response, out error))
                {
                    result.AddError(error);
                }
            }

            return(result);
        }
Example #5
0
        public override CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
        {
            var result   = new DoCaptureResponseType();
            var settings = CommonServices.Settings.LoadSetting <PayPalExpressPaymentSettings>(capturePaymentRequest.Order.StoreId);

            // build the request
            var req = new DoCaptureReq
            {
                DoCaptureRequest = new DoCaptureRequestType()
            };

            //execute request
            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                result = service.DoCapture(req);
            }

            var capturePaymentResult = new CapturePaymentResult();

            if (result.Ack == AckCodeType.Success)
            {
                capturePaymentResult.CaptureTransactionId     = result.DoCaptureResponseDetails.PaymentInfo.TransactionID;
                capturePaymentResult.CaptureTransactionResult = "Success";
            }
            else
            {
                capturePaymentResult.CaptureTransactionResult = "Error";
                capturePaymentResult.Errors.Add(result.Errors.FirstOrDefault().LongMessage);
            }

            return(capturePaymentResult);
        }
Example #6
0
        public static CommerceQuote CreateQuote(PayPalHelper payPal, bool aggregateData, bool itemizedData, Entity website, IShoppingCart cart, IPortalContext portal)
        {
            var args = new Dictionary <string, string>();

            if (aggregateData)
            {
                args.Add("item_name", "Aggregated Items");
                args.Add("amount", cart.GetCartTotal().ToString("#.00"));
            }
            // Paypal Item Data for itemized data.
            else if (itemizedData)
            {
                var cartItems = cart.GetCartItems().Select(sci => sci.Entity);

                var counter = 0;

                foreach (var item in cartItems)
                {
                    counter++;

                    args.Add(string.Format("item_name_{0}", counter), item.GetAttributeValue <string>("adx_name"));
                    args.Add(string.Format("amount_{0}", counter), item.GetAttributeValue <Money>("adx_quotedprice") == null ? "0.00" : item.GetAttributeValue <Money>("adx_quotedprice").Value.ToString("#.00"));
                    args.Add(string.Format("quantity_{0}", counter), item.GetAttributeValue <int?>("adx_quantity").GetValueOrDefault(0).ToString(CultureInfo.InvariantCulture));
                    //add arguments for shipping/handling cost?
                    args.Add(string.Format("item_number_{0}", counter), item.GetAttributeValue <Guid>("adx_shoppingcartitemid").ToString());
                }

                // If we are calculating the tax, this is done and added as an arg.
            }

            // If a quote was created, pass in the quote ID.
            args.Add("invoice", cart.Id.ToString());

            return(new CommerceQuote(args, portal, "PayPal"));
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var doPayment = DoExpressCheckoutPayment(processPaymentRequest);
            var result    = new ProcessPaymentResult();

            if (doPayment.Ack == AckCodeType.Success)
            {
                if (PayPalHelper.GetPaymentAction(Settings) == PaymentActionCodeType.Authorization)
                {
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
                result.AuthorizationTransactionId = processPaymentRequest.PaypalToken;
                result.CaptureTransactionId       = doPayment.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault().TransactionID;
                result.CaptureTransactionResult   = doPayment.Ack.ToString();
            }
            else
            {
                result.NewPaymentStatus = PaymentStatus.Pending;
            }

            return(result);
        }
Example #8
0
        public ActionResult PaymentDetails(string token)
        {
            if (token.IsNullOrWhiteSpace())
            {
                return(RedirectToAction("PayPalCancel"));
            }
            GetExpressCheckoutDetailsReq          req         = PayPalHelper.GetGetExpressCheckoutDetailsReq(token);
            CustomSecurityHeaderType              credentials = PayPalHelper.GetPayPalCredentials();
            PayPalAPIAAInterfaceClient            client      = new PayPalAPIAAInterfaceClient();
            GetExpressCheckoutDetailsResponseType response    = client.GetExpressCheckoutDetails(ref credentials, req);

            if (response.Errors != null && response.Errors.Length > 0)
            {
                throw new Exception("Exception occured when calling PayPal: " + response.Errors[0].LongMessage);
            }
            GetExpressCheckoutDetailsResponseDetailsType respDetails = response.GetExpressCheckoutDetailsResponseDetails;
            Order order = PayPalHelper.UpdateOrderAfterAuthentication(respDetails.Custom, respDetails.PayerInfo.PayerID);
            var   model = new PaymentModel
            {
                Order     = order,
                BuyerName = respDetails.PayerInfo.PayerName.FirstName + respDetails.PayerInfo.PayerName.LastName
            };

            Session["CheckoutDetails"] = response;
            return(View("PaymentDetails", model));
        }
Example #9
0
        // GET: /account/paypal-payment
        public ActionResult PaypalPayment(string tx = null)
        {
            PayPalPaymentResult result = PayPalPaymentResult.Canceled;

            var helper = new PayPalHelper();

            var txnId = !String.IsNullOrEmpty(tx)
                        // tx in PDT from Sandbox is upper-case on automatic return and lower-case on manual return. A PDT request returns error 4002 if given a low-case tx.
                ? tx.ToUpper()
                : "PDT " + KeyUtils.GetCurrentTimeKey();

            helper.WriteLog(PayPalLogEntity.NotificationKind.PDT, txnId, Request.Url.Query);

            if (!String.IsNullOrEmpty(tx))
            {
                // Query PayPal.
                var response = helper.RequestPaymentDetails(txnId);

                var logRowKey = helper.WriteLog(PayPalLogEntity.NotificationKind.DetailsRequest, txnId, response);

                // Parse the response
                var lines   = helper.SplitPdtMessage(response);
                var payment = helper.ParsePaymentLines(lines);

                // Write the payment to the database.
                if (helper.PostIncomingPayPalPayment(payment, logRowKey))
                {
                    result = PayPalPaymentResult.Success;
                }
            }

            return(RedirectToAction("Transactions", new { PayPalPaymentResult = result }));
        }
Example #10
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));
        }
Example #11
0
        public async Task <IActionResult> PaymentSuccessAsync(string paymentId, string payerId)
        {
            int    TerminId      = (int)TempData["TerminId"];
            int    BrojKarata    = (int)TempData["BrojKarata"];
            int    TipSjedistaId = (int)TempData["TipSjedistaId"];
            double Cijena        = (double)TempData["CijenaKarte"];

            TempData.Remove("TerminId");
            TempData.Remove("BrojKarata");
            TempData.Remove("TipSjedistaId");
            TempData.Remove("CijenaKarte");
            if (await PayPalHelper.ExecutePayment(paymentId, payerId))
            {
                _context.Narudzba.Add(new Data.Models.Narudzba
                {
                    TerminId      = TerminId,
                    TipSjedistaId = TipSjedistaId,
                    CijenaKarte   = (float)Cijena,
                    Kolicina      = BrojKarata,
                    KupacId       = _context.Kupac.First(w => w.Username == HttpContext.User.Identity.Name).Id,
                });

                _context.SaveChanges();
                return(Redirect("~/MojProfil"));
            }

            else
            {
                return(Content("Doslo je do greske!"));
            }
        }
Example #12
0
        public async Task <IActionResult> PaymentAsync(CheckoutVM model)
        {
            if (model.BrojKarata > (_context.DvoranaTipSjedista.First(w => w.TipSjedistaId == model.TipSjedistaId && w.DvoranaId == _context.Termin.First(q => q.Id == model.TerminId).DvoranaId).BrojSjedista
                                    - _context.Narudzba.Where(w => w.TerminId == model.TerminId && w.TipSjedistaId == model.TipSjedistaId).Sum(a => (int?)a.Kolicina) ?? 0))
            {
                return(Redirect("~/Termini/Checkout/" + model.TerminId.ToString()));
            }

            Data.Models.Termin      termin      = _context.Termin.Include("Predstava").First(w => w.Id == model.TerminId);
            Data.Models.TipSjedista tipSjedista = _context.TipSjedista.First(w => w.Id == model.TipSjedistaId);

            string Naziv  = termin.Predstava.Naziv + " " + termin.DatumVrijeme.ToString("dd.MM.yyyy HH:mm") + " " + tipSjedista.Naziv;
            double Cijena = (termin.BaznaCijenaKarte * tipSjedista.CijenaKarteMultiplier) - (termin.BaznaCijenaKarte * tipSjedista.CijenaKarteMultiplier * _context.Kupac.Where(w => w.Username == HttpContext.User.Identity.Name).Select(s => s.TipKorisnika.CijenaKartePopust).First());

            TempData["TerminId"]      = model.TerminId;
            TempData["BrojKarata"]    = model.BrojKarata;
            TempData["TipSjedistaId"] = model.TipSjedistaId;
            TempData["CijenaKarte"]   = Cijena;

            string SucessUrl = "http://" + Request.Host.ToString() + "/Termini/Checkout/PaymentSuccess";
            string CancelUrl = "http://" + Request.Host.ToString();

            string link = await PayPalHelper.GeneratePayment(Naziv, (float)Cijena / 2, model.BrojKarata, SucessUrl, CancelUrl);

            return(Redirect(link));
        }
Example #13
0
        public ActionResult Donate()
        {
            var model = new PaymentModel();

            //model.CallbackUrl = PayPalHelper.GetDomainName(Request) + "/Payment/PayPalCallback";
            model.ReturnSuccessUrl = PayPalHelper.GetDomainName(Request) + "/Payment/PayPalSuccess";
            return(View(model));
        }
Example #14
0
        public ActionResult Donate(int?amount)
        {
            if (!amount.HasValue)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            string returnSuccessUrl = PayPalHelper.GetDomainName(Request) + "/Payment/PayPalSuccess";
            string redirectUrl      = string.Format("{0}?cmd=_donations&business={1}&item_name={2}&amount={3}&return={4}", PayPalHelper.GetPaypalRequestUrl(), ConfigurationManager.AppSettings["PayPalAccount"], "Save red crayfishes in Belarus", amount.Value, returnSuccessUrl);

            return(Redirect(redirectUrl));
        }
Example #15
0
        private void HandlePaypalPayment(decimal total)
        {
            var payPal = new PayPalHelper(Portal);

            var currencyCode = Html.Setting("Ecommerce/Paypal/CurrencyCode");

            // Paypal Item Data for aggregateddata
            var aggregateData   = Html.BooleanSetting("Ecommerce/Paypal/aggregateData").GetValueOrDefault(false);
            var itemizedData    = Html.BooleanSetting("Ecommerce/Paypal/itemizedData").GetValueOrDefault(true);
            var addressOverride = Html.BooleanSetting("Ecommerce/Paypal/AddressOverride").GetValueOrDefault(true);

            HandlePayPalRedirection(payPal, total, payPal.PayPalAccountEmail, currencyCode, itemizedData, aggregateData, addressOverride);
        }
Example #16
0
        public async Task <IActionResult> UpgradeCheckout()
        {
            TipKorisnika IduciTipKorisnika = _context.Kupac.Where(w => w.Username == HttpContext.User.Identity.Name)
                                             .Select(s => s.TipKorisnika.IduciTipKorisnika).First();

            string Naziv  = IduciTipKorisnika.Naziv;
            double Cijena = IduciTipKorisnika.Cijena;

            string SucessUrl = "http://" + Request.Host + "/MojProfil/UpgradeSuccess";
            string CancelUrl = "http://" + Request.Host + "/MojProfil";

            return(Redirect(await PayPalHelper.GeneratePayment(Naziv, (float)Cijena, 1, SucessUrl, CancelUrl)));
        }
Example #17
0
        public ActionResult PaymentInfo()
        {
            var model = new PayPalExpressPaymentInfoModel();

            model.CurrentPageIsBasket = PayPalHelper.CurrentPageIsBasket(this.ControllerContext.ParentActionViewContext.RequestContext.RouteData);

            if (model.CurrentPageIsBasket)
            {
                var culture   = _services.WorkContext.WorkingLanguage.LanguageCulture;
                var buttonUrl = "https://www.paypalobjects.com/{0}/i/btn/btn_xpressCheckout.gif".FormatWith(culture.Replace("-", "_"));
                model.SubmitButtonImageUrl = PayPalHelper.CheckIfButtonExists(buttonUrl);
            }

            return(PartialView(model));
        }
Example #18
0
        public async Task <IActionResult> UpgradeSuccess(string paymentId, string payerId)
        {
            if (!await PayPalHelper.ExecutePayment(paymentId, payerId))
            {
                return(Content("Doslo je do greske!"));
            }

            Kupac        Kupac             = _context.Kupac.First(w => w.Username == HttpContext.User.Identity.Name);
            TipKorisnika IduciTipKorisnika = _context.TipKorisnika.Where(w => w.Id == Kupac.TipKorisnikaId)
                                             .Select(s => s.IduciTipKorisnika).First();

            Kupac.TipKorisnika = IduciTipKorisnika;
            _context.SaveChanges();

            return(Redirect("~/MojProfil"));
        }
Example #19
0
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new DoExpressCheckoutPaymentResponseType();
            var settings = CommonServices.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                Custom       = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource = SmartStoreVersion.CurrentFullVersion
            };

            // build the request
            var req = new DoExpressCheckoutPaymentReq
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                {
                    Version = PayPalHelper.GetApiVersion(),
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token                  = processPaymentRequest.PaypalToken,
                        PayerID                = processPaymentRequest.PaypalPayerId,
                        PaymentAction          = PayPalHelper.GetPaymentAction(settings),
                        PaymentActionSpecified = true,
                        PaymentDetails         = new PaymentDetailsType[]
                        {
                            paymentDetails
                        }
                    }
                }
            };

            //execute request
            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                result = service.DoExpressCheckoutPayment(req);
            }
            return(result);
        }
        public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetails(string token)
        {
            var result = new GetExpressCheckoutDetailsResponseType();

            using (var service = new PayPalAPIAASoapBinding())
            {
                var req = new GetExpressCheckoutDetailsReq();
                req.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType
                {
                    Token   = token,
                    Version = PayPalHelper.GetApiVersion()
                };

                service.Url = PayPalHelper.GetPaypalServiceUrl(Settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(Settings);
                result = service.GetExpressCheckoutDetails(req);
            }
            return(result);
        }
        /// <summary>
        /// Voids a payment
        /// </summary>
        /// <param name="voidPaymentRequest">Request</param>
        /// <returns>Result</returns>
        public override VoidPaymentResult Void(VoidPaymentRequest request)
        {
            var result = new VoidPaymentResult()
            {
                NewPaymentStatus = request.Order.PaymentStatus
            };

            string transactionId = request.Order.AuthorizationTransactionId;
            var    settings      = CommonServices.Settings.LoadSetting <TSetting>(request.Order.StoreId);

            if (String.IsNullOrEmpty(transactionId))
            {
                transactionId = request.Order.CaptureTransactionId;
            }

            var req = new DoVoidReq();

            req.DoVoidRequest                 = new DoVoidRequestType();
            req.DoVoidRequest.Version         = PayPalHelper.GetApiVersion();
            req.DoVoidRequest.AuthorizationID = transactionId;


            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                DoVoidResponseType response = service.DoVoid(req);

                string error   = "";
                bool   success = PayPalHelper.CheckSuccess(_helper, response, out error);
                if (success)
                {
                    result.NewPaymentStatus = PaymentStatus.Voided;
                    //result.VoidTransactionID = response.RefundTransactionID;
                }
                else
                {
                    result.AddError(error);
                }
            }
            return(result);
        }
Example #22
0
        public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetails(string token)
        {
            var result   = new GetExpressCheckoutDetailsResponseType();
            var settings = CommonServices.Settings.LoadSetting <PayPalExpressPaymentSettings>(CommonServices.StoreContext.CurrentStore.Id);

            using (var service = new PayPalAPIAASoapBinding())
            {
                var req = new GetExpressCheckoutDetailsReq();
                req.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType
                {
                    Token   = token,
                    Version = PayPalHelper.GetApiVersion()
                };

                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                result = service.GetExpressCheckoutDetails(req);
            }
            return(result);
        }
Example #23
0
        /// <summary>
        /// Verifies IPN
        /// </summary>
        /// <param name="formString">Form string</param>
        /// <param name="values">Values</param>
        /// <returns>Result</returns>
        public bool VerifyIPN(string formString, out Dictionary <string, string> values)
        {
            // settings: multistore context not possible here. we need the custom value to determine what store it is.
            var settings = _commonServices.Settings.LoadSetting <PayPalStandardPaymentSettings>();

            var req = (HttpWebRequest)WebRequest.Create(PayPalHelper.GetPaypalUrl(settings));

            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.UserAgent   = HttpContext.Current.Request.UserAgent;

            string formContent = string.Format("{0}&cmd=_notify-validate", formString);

            req.ContentLength = formContent.Length;

            using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
            {
                sw.Write(formContent);
            }

            string response = null;

            using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
            {
                response = HttpUtility.UrlDecode(sr.ReadToEnd());
            }
            bool success = response.Trim().Equals("VERIFIED", StringComparison.OrdinalIgnoreCase);

            values = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            foreach (string l in formString.Split('&'))
            {
                string line     = HttpUtility.UrlDecode(l).Trim();
                int    equalPox = line.IndexOf('=');
                if (equalPox >= 0)
                {
                    values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
                }
            }

            return(success);
        }
Example #24
0
        /// <summary>
        /// Gets PDT details
        /// </summary>
        /// <param name="tx">TX</param>
        /// <param name="values">Values</param>
        /// <param name="response">Response</param>
        /// <returns>Result</returns>
        public bool GetPDTDetails(string tx, PayPalStandardPaymentSettings settings, out Dictionary <string, string> values, out string response)
        {
            var req = (HttpWebRequest)WebRequest.Create(PayPalHelper.GetPaypalUrl(settings));

            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";

            string formContent = string.Format("cmd=_notify-synch&at={0}&tx={1}", settings.PdtToken, tx);

            req.ContentLength = formContent.Length;

            using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
                sw.Write(formContent);

            response = null;
            using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
                response = HttpUtility.UrlDecode(sr.ReadToEnd());

            values = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            bool firstLine = true, success = false;

            foreach (string l in response.Split('\n'))
            {
                string line = l.Trim();
                if (firstLine)
                {
                    success   = line.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase);
                    firstLine = false;
                }
                else
                {
                    int equalPox = line.IndexOf('=');
                    if (equalPox >= 0)
                    {
                        values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
                    }
                }
            }

            return(success);
        }
        /// <summary>
        /// Captures payment
        /// </summary>
        /// <param name="capturePaymentRequest">Capture payment request</param>
        /// <returns>Capture payment result</returns>
        public override CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
        {
            var result = new CapturePaymentResult()
            {
                NewPaymentStatus = capturePaymentRequest.Order.PaymentStatus
            };

            var    settings        = CommonServices.Settings.LoadSetting <TSetting>(capturePaymentRequest.Order.StoreId);
            string authorizationId = capturePaymentRequest.Order.AuthorizationTransactionId;

            var req = new DoCaptureReq();

            req.DoCaptureRequest                   = new DoCaptureRequestType();
            req.DoCaptureRequest.Version           = PayPalHelper.GetApiVersion();
            req.DoCaptureRequest.AuthorizationID   = authorizationId;
            req.DoCaptureRequest.Amount            = new BasicAmountType();
            req.DoCaptureRequest.Amount.Value      = Math.Round(capturePaymentRequest.Order.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            req.DoCaptureRequest.Amount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), Helper.CurrencyCode, true);
            req.DoCaptureRequest.CompleteType      = CompleteCodeType.Complete;

            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                DoCaptureResponseType response = service.DoCapture(req);

                string error   = "";
                bool   success = PayPalHelper.CheckSuccess(_helper, response, out error);
                if (success)
                {
                    result.NewPaymentStatus         = PaymentStatus.Paid;
                    result.CaptureTransactionId     = response.DoCaptureResponseDetails.PaymentInfo.TransactionID;
                    result.CaptureTransactionResult = response.Ack.ToString();
                }
                else
                {
                    result.AddError(error);
                }
            }
            return(result);
        }
Example #26
0
        public ActionResult PaymentConfirmation(int?orderId)
        {
            if (!orderId.HasValue)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            var response = Session["CheckoutDetails"] as GetExpressCheckoutDetailsResponseType;

            if (response == null)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            DoExpressCheckoutPaymentReq          payReq      = PayPalHelper.GetDoExpressCheckoutPaymentReq(response);
            CustomSecurityHeaderType             credentials = PayPalHelper.GetPayPalCredentials();
            PayPalAPIAAInterfaceClient           client      = new PayPalAPIAAInterfaceClient();
            DoExpressCheckoutPaymentResponseType doResponse  = client.DoExpressCheckoutPayment(ref credentials, payReq);

            if (doResponse.Errors != null && doResponse.Errors.Length > 0)
            {
                throw new Exception("Exception occured when calling PayPal: " + doResponse.Errors[0].LongMessage);
            }
            PayPalHelper.UpdateOrderAfterConfirmation(orderId.Value);
            return(RedirectToAction("PayPalSuccess"));
        }
 public PaymentPayPalAdvancedController(
     IWorkContext workContext,
     IStoreService storeService,
     ISettingService settingService,
     IPaymentService paymentService,
     IOrderService orderService,
     IOrderProcessingService orderProcessingService,
     ILocalizationService localizationService,
     IStoreContext storeContext,
     IOrderTotalCalculationService orderTotalCalculationService,
     ICurrencyService _currencyService,
     IPriceFormatter priceFormatter,
     ITaxService taxService,
     PayPalAdvancedPaymentSettings payPalAdvancedPaymentSettings,
     TaxSettings taxSettings,
     RewardPointsSettings rewardPointsSettings,
     ILicenseService licenseService,
     IEncryptionService encryptionService,
     PayPalHelper payPalHelper,
     ILogger logger)
 {
     this._workContext = workContext;
     this._storeService = storeService;
     this._settingService = settingService;
     this._paymentService = paymentService;
     this._orderService = orderService;
     this._orderProcessingService = orderProcessingService;
     this._localizationService = localizationService;
     this._storeContext = storeContext;
     this._orderTotalCalculationService = orderTotalCalculationService;
     this._currencyService = _currencyService;
     this._priceFormatter = priceFormatter;
     this._taxService = taxService;
     this._payPalAdvancedPaymentSettings = payPalAdvancedPaymentSettings;
     this._taxSettings = taxSettings;
     this._rewardPointsSettings = rewardPointsSettings;
     this._licenseService = licenseService;
     this._encryptionService = encryptionService;
     this._payPalHelper = payPalHelper;
     this._logger = logger;
 }
Example #28
0
        /// <returns>A task that represents the asynchronous operation</returns>
        public async Task <IActionResult> IPNHandler()
        {
            await using var stream = new MemoryStream();
            await Request.Body.CopyToAsync(stream);

            var strRequest = Encoding.ASCII.GetString(stream.ToArray());

            if (await _paymentPluginManager.LoadPluginBySystemNameAsync("Payments.PayPalStandard") is not PayPalStandardPaymentProcessor processor || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("PayPal Standard module cannot be loaded");
            }

            var(result, values) = await processor.VerifyIpnAsync(strRequest);

            if (!result)
            {
                await _logger.ErrorAsync("PayPal IPN failed.", new NopException(strRequest));

                //nothing should be rendered to visitor
                return(Ok());
            }

            var mcGross = decimal.Zero;

            try
            {
                mcGross = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
            }
            catch
            {
                // ignored
            }

            values.TryGetValue("payment_status", out var paymentStatus);
            values.TryGetValue("pending_reason", out var pendingReason);
            values.TryGetValue("txn_id", out var txnId);
            values.TryGetValue("txn_type", out var txnType);
            values.TryGetValue("rp_invoice_id", out var rpInvoiceId);

            var sb = new StringBuilder();

            sb.AppendLine("PayPal IPN:");
            foreach (var kvp in values)
            {
                sb.AppendLine(kvp.Key + ": " + kvp.Value);
            }

            var newPaymentStatus = PayPalHelper.GetPaymentStatus(paymentStatus, pendingReason);

            sb.AppendLine("New payment status: " + newPaymentStatus);

            var ipnInfo = sb.ToString();

            switch (txnType)
            {
            case "recurring_payment":
                await ProcessRecurringPaymentAsync(rpInvoiceId, newPaymentStatus, txnId, ipnInfo);

                break;

            case "recurring_payment_failed":
                if (Guid.TryParse(rpInvoiceId, out var orderGuid))
                {
                    var order = await _orderService.GetOrderByGuidAsync(orderGuid);

                    if (order != null)
                    {
                        var recurringPayment = (await _orderService.SearchRecurringPaymentsAsync(initialOrderId: order.Id))
                                               .FirstOrDefault();
                        //failed payment
                        if (recurringPayment != null)
                        {
                            await _orderProcessingService.ProcessNextRecurringPaymentAsync(recurringPayment,
                                                                                           new ProcessPaymentResult
                            {
                                Errors = new[] { txnType },
                                RecurringPaymentFailed = true
                            });
                        }
                    }
                }

                break;

            default:
                values.TryGetValue("custom", out var orderNumber);
                await ProcessPaymentAsync(orderNumber, ipnInfo, newPaymentStatus, mcGross, txnId);

                break;
            }

            //nothing should be rendered to visitor
            return(Ok());
        }
Example #29
0
        public ActionResult IPNHandler()
        {
            Debug.WriteLine("PayPal Direct IPN: {0}".FormatWith(Request.ContentLength));

            byte[] param      = Request.BinaryRead(Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            Dictionary <string, string> values;

            var provider  = _paymentService.LoadPaymentMethodBySystemName("Payments.PayPalDirect", true);
            var processor = provider != null ? provider.Value as PayPalDirectProvider : null;

            if (processor == null)
            {
                throw new SmartException(_helper.GetResource("NoModuleLoading"));
            }

            if (processor.VerifyIPN(strRequest, out values))
            {
                #region values
                decimal total = decimal.Zero;
                try
                {
                    total = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch { }

                string payer_status = string.Empty;
                values.TryGetValue("payer_status", out payer_status);
                string payment_status = string.Empty;
                values.TryGetValue("payment_status", out payment_status);
                string pending_reason = string.Empty;
                values.TryGetValue("pending_reason", out pending_reason);
                string mc_currency = string.Empty;
                values.TryGetValue("mc_currency", out mc_currency);
                string txn_id = string.Empty;
                values.TryGetValue("txn_id", out txn_id);
                string txn_type = string.Empty;
                values.TryGetValue("txn_type", out txn_type);
                string rp_invoice_id = string.Empty;
                values.TryGetValue("rp_invoice_id", out rp_invoice_id);
                string payment_type = string.Empty;
                values.TryGetValue("payment_type", out payment_type);
                string payer_id = string.Empty;
                values.TryGetValue("payer_id", out payer_id);
                string receiver_id = string.Empty;
                values.TryGetValue("receiver_id", out receiver_id);
                string invoice = string.Empty;
                values.TryGetValue("invoice", out invoice);
                string payment_fee = string.Empty;
                values.TryGetValue("payment_fee", out payment_fee);

                #endregion

                var sb = new StringBuilder();
                sb.AppendLine("PayPal IPN:");
                foreach (KeyValuePair <string, string> kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                var newPaymentStatus = PayPalHelper.GetPaymentStatus(payment_status, pending_reason);
                sb.AppendLine("{0}: {1}".FormatWith(_helper.GetResource("NewPaymentStatus"), newPaymentStatus));

                switch (txn_type)
                {
                case "recurring_payment_profile_created":
                    //do nothing here
                    break;

                case "recurring_payment":
                    #region Recurring payment
                {
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(rp_invoice_id);
                    }
                    catch
                    {
                    }

                    var initialOrder = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (initialOrder != null)
                    {
                        var recurringPayments = _orderService.SearchRecurringPayments(0, 0, initialOrder.Id, null);
                        foreach (var rp in recurringPayments)
                        {
                            switch (newPaymentStatus)
                            {
                            case PaymentStatus.Authorized:
                            case PaymentStatus.Paid:
                            {
                                var recurringPaymentHistory = rp.RecurringPaymentHistory;
                                if (recurringPaymentHistory.Count == 0)
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory()
                                    {
                                        RecurringPaymentId = rp.Id,
                                        OrderId            = initialOrder.Id,
                                        CreatedOnUtc       = DateTime.UtcNow
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                else
                                {
                                    //next payments
                                    _orderProcessingService.ProcessNextRecurringPayment(rp);
                                }
                            }
                            break;
                            }
                        }

                        //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                        Logger.Information(_helper.GetResource("IpnLogInfo"), new SmartException(sb.ToString()));
                    }
                    else
                    {
                        Logger.Error(_helper.GetResource("IpnOrderNotFound"), new SmartException(sb.ToString()));
                    }
                }
                    #endregion
                    break;

                default:
                    #region Standard payment
                {
                    string orderNumber = string.Empty;
                    values.TryGetValue("custom", out orderNumber);
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch
                    {
                    }

                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        //order note
                        order.HasNewPaymentNotification = true;

                        order.OrderNotes.Add(new OrderNote
                            {
                                Note = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                        _orderService.UpdateOrder(order);

                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Pending:
                        {
                        }
                        break;

                        case PaymentStatus.Authorized:
                        {
                            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                            {
                                _orderProcessingService.MarkAsAuthorized(order);
                            }
                        }
                        break;

                        case PaymentStatus.Paid:
                        {
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                        break;

                        case PaymentStatus.Refunded:
                        {
                            if (_orderProcessingService.CanRefundOffline(order))
                            {
                                _orderProcessingService.RefundOffline(order);
                            }
                        }
                        break;

                        case PaymentStatus.Voided:
                        {
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                        }
                        break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        Logger.Error(_helper.GetResource("IpnOrderNotFound"), new SmartException(sb.ToString()));
                    }
                }
                    #endregion
                    break;
                }
            }
            else
            {
                Logger.Error(_helper.GetResource("IpnFailed"), new SmartException(strRequest));
            }

            //nothing should be rendered to visitor
            return(Content(""));
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            var settings = CommonServices.Settings.LoadSetting <PayPalDirectPaymentSettings>(processPaymentRequest.StoreId);

            var req = new CreateRecurringPaymentsProfileReq();

            req.CreateRecurringPaymentsProfileRequest         = new CreateRecurringPaymentsProfileRequestType();
            req.CreateRecurringPaymentsProfileRequest.Version = PayPalHelper.GetApiVersion();
            var details = new CreateRecurringPaymentsProfileRequestDetailsType();

            req.CreateRecurringPaymentsProfileRequest.CreateRecurringPaymentsProfileRequestDetails = details;

            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType    = PayPalHelper.GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2      = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry  = PayPalHelper.GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;

            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = PayPalHelper.GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;

            //start date
            details.RecurringPaymentsProfileDetails = new RecurringPaymentsProfileDetailsType();
            details.RecurringPaymentsProfileDetails.BillingStartDate = DateTime.UtcNow;
            details.RecurringPaymentsProfileDetails.ProfileReference = processPaymentRequest.OrderGuid.ToString();

            //schedule
            details.ScheduleDetails                                 = new ScheduleDetailsType();
            details.ScheduleDetails.Description                     = Helper.GetResource("RecurringPayment");
            details.ScheduleDetails.PaymentPeriod                   = new BillingPeriodDetailsType();
            details.ScheduleDetails.PaymentPeriod.Amount            = new BasicAmountType();
            details.ScheduleDetails.PaymentPeriod.Amount.Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.ScheduleDetails.PaymentPeriod.Amount.currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            details.ScheduleDetails.PaymentPeriod.BillingFrequency  = processPaymentRequest.RecurringCycleLength;
            switch (processPaymentRequest.RecurringCyclePeriod)
            {
            case RecurringProductCyclePeriod.Days:
                details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Day;
                break;

            case RecurringProductCyclePeriod.Weeks:
                details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Week;
                break;

            case RecurringProductCyclePeriod.Months:
                details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Month;
                break;

            case RecurringProductCyclePeriod.Years:
                details.ScheduleDetails.PaymentPeriod.BillingPeriod = BillingPeriodType.Year;
                break;

            default:
                throw new SmartException(Helper.GetResource("NotSupportedPeriod"));
            }
            details.ScheduleDetails.PaymentPeriod.TotalBillingCycles          = processPaymentRequest.RecurringTotalCycles;
            details.ScheduleDetails.PaymentPeriod.TotalBillingCyclesSpecified = true;

            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                CreateRecurringPaymentsProfileResponseType response = service.CreateRecurringPaymentsProfile(req);

                string error   = "";
                bool   success = PayPalHelper.CheckSuccess(Helper, response, out error);
                if (success)
                {
                    result.NewPaymentStatus = PaymentStatus.Pending;
                    if (response.CreateRecurringPaymentsProfileResponseDetails != null)
                    {
                        result.SubscriptionTransactionId = response.CreateRecurringPaymentsProfileResponseDetails.ProfileID;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }

            return(result);
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            var settings = CommonServices.Settings.LoadSetting <PayPalDirectPaymentSettings>(processPaymentRequest.StoreId);

            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = PayPalHelper.GetApiVersion();

            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = CommonServices.WebHelper.GetCurrentIpAddress();

            if (details.IPAddress.IsEmpty())
            {
                details.IPAddress = "127.0.0.1";
            }

            if (settings.TransactMode == TransactMode.Authorize)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }

            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType    = PayPalHelper.GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2      = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry  = PayPalHelper.GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = PayPalHelper.GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = SmartStoreVersion.CurrentFullVersion;
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name                 = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1              = customer.ShippingAddress.Address1;
                    shippingAddress.CityName             = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified     = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                DoDirectPaymentResponseType response = service.DoDirectPayment(req);

                string error   = "";
                bool   success = PayPalHelper.CheckSuccess(Helper, response, out error);
                if (success)
                {
                    result.AvsResult = response.AVSCode;
                    result.AuthorizationTransactionCode = response.CVV2Code;
                    if (settings.TransactMode == TransactMode.Authorize)
                    {
                        result.AuthorizationTransactionId     = response.TransactionID;
                        result.AuthorizationTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Authorized;
                    }
                    else
                    {
                        result.CaptureTransactionId     = response.TransactionID;
                        result.CaptureTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Paid;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }
            return(result);
        }