/// <summary>
        /// Changes the express checkout operation
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="request"></param>
        public static void SetupExpressCheckoutUrls(this Controller controller, PayPalSetExpressCheckoutOperation request, string confirmAction, string cancelAction, object values = null)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var context = controller.Request.RequestContext;

            if (context.HttpContext.Request.Url == null)
            {
                throw new Exception("Request Url must not be null");
            }

            // Setting return and cancel URLs.
            var url = new UrlHelper(context);

            string urlBase = context.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority);

            if (request.ReturnURL == null)
            {
                request.ReturnURL = urlBase + url.Action(confirmAction, values);
            }

            if (request.CancelURL == null)
            {
                request.CancelURL = urlBase + url.Action(cancelAction, values);
            }
        }
Ejemplo n.º 2
0
        public override PayPalSetExpressCheckoutResult SetExpressCheckout(PayPalSetExpressCheckoutOperation operation)
        {
            var operationToUse = operation;

            SetupCredential(operation, ref operationToUse);

            SetupDefaultCurrencyCode(operation, ref operationToUse);

            // If LocaleCode is undefined then load it from the configuration file.
            if (operationToUse.LocaleCode != LocaleCode.Undefined)
            {
                if (operationToUse != operation)
                {
                    operationToUse = operation.Clone();
                }

                var        locale = this.configurations.LocalCode;
                LocaleCode outValue;
                if (Enum.TryParse(locale, out outValue))
                {
                    operationToUse.LocaleCode = outValue;
                }
            }

            // Calling the API.
            return(base.SetExpressCheckout(operationToUse));
        }
Ejemplo n.º 3
0
        public virtual PayPalSetExpressCheckoutResult SetExpressCheckout(PayPalSetExpressCheckoutOperation operation)
        {
            // reference:
            // https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECGettingStarted
            // https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_testing_SBWPTesting
            // https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_testing_SBTestTools

            // sample code:
            // http://stackoverflow.com/questions/8452563/paypal-api-request-with-mvc3
            // https://www.paypal-brasil.com.br/x/tutoriais/integracao-avancada-com-express-checkout-em-c/
            // https://github.com/paypalxbrasil/ExpressCheckoutAdvancedFeatures/blob/master/ExpressCheckoutAdvancedFeatures/Controllers/HomeController.cs

            return(ApiCall <PayPalSetExpressCheckoutApiResult>(operation));
        }
Ejemplo n.º 4
0
        public ActionResult PayPalCheckout()
        {
            var operation = new PayPalSetExpressCheckoutOperation();

            FillOperationDetails(operation, true);

            // Validating the request object.
            var validationResults = new List <ValidationResult>();

            Validator.TryValidateObject(
                operation,
                new ValidationContext(operation, null, null),
                validationResults,
                validateAllProperties: true);

            var opResult = this.SetExpressCheckout(operation, "PayPalConfirm", "PayPalCancel");

            return(this.RedirectToCheckout(opResult));
        }
        public ActionResult PayPalCheckout()
        {
            var operation = new PayPalSetExpressCheckoutOperation();

            FillOperationDetails(operation, null, null, null);

            // Validating the request object.
            // TODO: handle the invalid object if it has errors.
            var validationResults = new List <System.ComponentModel.DataAnnotations.ValidationResult>();

            System.ComponentModel.DataAnnotations.Validator.TryValidateObject(
                operation,
                new System.ComponentModel.DataAnnotations.ValidationContext(operation, null, null),
                validationResults,
                validateAllProperties: true);

            var opResult = this.SetExpressCheckout(operation, "PayPalConfirm", "PayPalCancel");

            return(this.RedirectToCheckout(opResult));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Tests whether it is possible or not to have multiple payments when there are digital goods.
        /// </summary>
        /// <remarks>
        /// This test will test all possibilities of
        /// setting new payments/items collections,
        /// setting/adding a specific payments/items collection items,
        /// and setting values,
        /// in any order of execution.
        /// </remarks>
        private static void DigitalGoodsTest()
        {
            string msg = "{0} - {1}";

            Action <int[], int, int> test = (int[] arrange5in5, int paymentChooser, int itemChooser) =>
            {
                // Creating objects.
                PayPalSetExpressCheckoutOperation ecop = new PayPalSetExpressCheckoutOperation
                {
                    PaymentRequests = new PayPalList <PayPalPaymentRequest>
                    {
                        new PayPalPaymentRequest {
                            Items = new PayPalList <PayPalPaymentRequestItem> {
                                new PayPalPaymentRequestItem(), new PayPalPaymentRequestItem()
                            }
                        },
                        new PayPalPaymentRequest {
                            Items = new PayPalList <PayPalPaymentRequestItem> {
                                new PayPalPaymentRequestItem(), new PayPalPaymentRequestItem()
                            }
                        },
                    }
                };

                PayPalList <PayPalPaymentRequest> listPayments = new PayPalList <PayPalPaymentRequest> {
                    new PayPalPaymentRequest {
                        Items = new PayPalList <PayPalPaymentRequestItem> {
                            new PayPalPaymentRequestItem(), new PayPalPaymentRequestItem()
                        }
                    },
                    new PayPalPaymentRequest {
                        Items = new PayPalList <PayPalPaymentRequestItem> {
                            new PayPalPaymentRequestItem(), new PayPalPaymentRequestItem()
                        }
                    }
                };

                PayPalPaymentRequest payment = new PayPalPaymentRequest {
                    Items = new PayPalList <PayPalPaymentRequestItem> {
                        new PayPalPaymentRequestItem(), new PayPalPaymentRequestItem()
                    }
                };

                PayPalList <PayPalPaymentRequestItem> listItems = new PayPalList <PayPalPaymentRequestItem> {
                    new PayPalPaymentRequestItem(), new PayPalPaymentRequestItem()
                };

                PayPalPaymentRequestItem item = new PayPalPaymentRequestItem();

                // Creating delegates.
                Action listPaymentsSet = () => ecop.PaymentRequests = listPayments;

                Action paymentSet = () => listPayments[0] = payment;
                Action paymentAdd = () => listPayments.Add(payment);

                Action listItemsSet = () => payment.Items = listItems;

                Action itemAdd = () => listItems.Add(item);
                Action itemSet = () => listItems[0] = item;

                Action digitalSet = () => item.Category = ItemCategory.Digital;

                // Selecting delegates.
                Action paymentAction = (new[] { paymentSet, paymentAdd })[paymentChooser];
                Action itemAction    = (new[] { itemSet, itemAdd })[itemChooser];

                Action[] all = (new[] { listPaymentsSet, paymentAction, listItemsSet, itemAction, digitalSet });

                Action[] sequence = (new[] { all[arrange5in5[0]], all[arrange5in5[1]], all[arrange5in5[2]], all[arrange5in5[3]], all[arrange5in5[4]] });

                // Executing test.
                bool      ok = true;
                Exception ex = null;
                try
                {
                    foreach (var action in sequence)
                    {
                        action();
                    }

                    ok = false;
                }
                catch (Exception ex1)
                {
                    ex = ex1;
                }
                finally
                {
                    Console.WriteLine(msg, ok ? "SUCCESS" : "FAILED", ex != null ? ex.Message : null);
                }
            };

            // arrangements of 5 elements in 5 slots.
            int index        = 0;
            var arranges5in5 = new int[5 * 4 * 3 * 2 * 1][];

            for (int itA = 0; itA < 5; itA++)
            {
                for (int itB = 0; itB < 4; itB++)
                {
                    for (int itC = 0; itC < 3; itC++)
                    {
                        for (int itD = 0; itD < 2; itD++)
                        {
                            for (int itE = 0; itE < 1; itE++)
                            {
                                List <int> list = new List <int>(new[] { 0, 1, 2, 3, 4 });
                                arranges5in5[index++] = new[] {
                                    list.Slice(itA),
                                    list.Slice(itB),
                                    list.Slice(itC),
                                    list.Slice(itD),
                                    list.Slice(itE),
                                };
                            }
                        }
                    }
                }
            }

            // Trying every variation: (5*4*3*2) * 2 * 2 = 480 alternatives.
            foreach (var arrg in arranges5in5)
            {
                for (int it1 = 0; it1 < 2; it1++)
                {
                    for (int it2 = 0; it2 < 2; it2++)
                    {
                        test(arrg, it1, it2);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        private static PayPalSetExpressCheckoutOperation BuildExpressCheckoutOperation1()
        {
            PayPalSetExpressCheckoutOperation ecop = new PayPalSetExpressCheckoutOperation
            {
                Credential = new PayPalSignatureCredential
                {
                    ApiPassword  = "******",
                    ApiSignature = "ApiSignature",
                    ApiUserName  = "******",
                },

                ReturnURL = "http://mydomain/returnUrl",
                CancelURL = "http://mydomain/cancelUrl",

                LocaleCode = LocaleCode.Undefined,

                SurveyChoice = new List <string>
                {
                    "Item 1",
                    "Item 2",
                    "Item 3",
                },
                PaymentRequests = new PayPalList <PayPalPaymentRequest>
                {
                    new PayPalPaymentRequest
                    {
                        Action      = PaymentActionCode.Sale,
                        ItemAmount  = 180.00m,
                        Description = "Cerebello - Pacote premium",
                        Items       = new PayPalList <PayPalPaymentRequestItem>
                        {
                            new PayPalPaymentRequestItem
                            {
                                Amount      = 170.00m,
                                Description = "Cerebello - Plano premium",
                                Quantity    = 1,
                                Category    = ItemCategory.Digital,
                            },
                            new PayPalPaymentRequestItem
                            {
                                Amount      = 50.00m,
                                Description = "Cerebello - Envio de Sms",
                                Quantity    = 1,
                                Category    = ItemCategory.Digital,
                            },
                            new PayPalPaymentRequestItem
                            {
                                Amount      = 40.00m,
                                Description = "Cerebello - Suporte via chat",
                                Quantity    = 1,
                                Category    = ItemCategory.Digital,
                            },
                            new PayPalPaymentRequestItem
                            {
                                Amount      = -60.00m,
                                Description = "Cupom de desconto (CEB-0A9B8C13EA9D)",
                                Quantity    = 1,
                                Category    = ItemCategory.Digital,
                            },
                            new PayPalPaymentRequestItem
                            {
                                Description = "Manual de instruções",
                                Quantity    = 1,
                                Category    = ItemCategory.Physical,
                            },
                        }
                    },
                }
            };

            return(ecop);
        }
Ejemplo n.º 8
0
        public static void Main(string[] args)
        {
            NameValueCollection nvc0 = new NameValueCollection();

            nvc0["xpto"] = "abc1";
            nvc0.Add("xpto", "abc2");
            nvc0.Add("xpto", "");

            nvc0.Add("cde", null);
            var cde  = nvc0["cde"];
            var cde2 = nvc0.GetValues("cde");

            var xpto  = nvc0["xpto"];
            var xpto2 = nvc0.GetValues("xpto");


            Console.SetBufferSize(170, 500);
            Console.SetWindowSize(170, 80);

            DigitalGoodsTest();

            Console.ReadKey();

            Console.Clear();

            PayPalSetExpressCheckoutOperation ecop0 = BuildExpressCheckoutOperation1();
            var nvc1 = ecop0.ToNameValueCollection();

            foreach (var key in nvc1.AllKeys)
            {
                var value = nvc1[key];

                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write(key);
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.Write(" = ");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(@"""");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write(value);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(@"""");
                Console.WriteLine();
            }

            Console.SetWindowPosition(0, 0);

            Console.ReadKey();

            Console.Clear();

            var ecop2 = nvc1.LoadToPayPalModelType <PayPalSetExpressCheckoutOperation>();

            var nvc2 = ecop2.ToNameValueCollection();

            foreach (var key in nvc2.AllKeys)
            {
                var value = nvc2[key];

                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write(key);
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.Write(" = ");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(@"""");
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write(value);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(@"""");
                Console.WriteLine();
            }

            Console.ReadKey();

            var value2 = EnumHelper.GetAttributeOfType <StringValueAttribute, TestEnum>("Text1");
        }
        /// <summary>
        /// Set express checkout
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        public static PayPalSetExpressCheckoutResult SetExpressCheckout(this Controller controller, PayPalSetExpressCheckoutOperation operation, [AspMvcAction] string confirmAction, [AspMvcAction] string cancelAction, object routeData = null)
        {
            if (controller == null)
            {
                throw new ArgumentNullException("controller");
            }

            if (operation == null)
            {
                throw new ArgumentNullException("request");
            }

            var operationToUse = operation;

            if (string.IsNullOrWhiteSpace(operationToUse.CancelURL) || string.IsNullOrWhiteSpace(operationToUse.ReturnURL))
            {
                // Need to clone to avoid side effect on passed object.
                if (operationToUse == operation)
                {
                    operationToUse = operation.Clone();
                }

                SetupExpressCheckoutUrls(controller, operationToUse, confirmAction, cancelAction, routeData);
            }

            // Calling the PayPal API, and returning the result.
            var settings = DependencyResolver.Current.GetService <IPayPalApiSettings>();
            var api      = new PayPalApiConfigurable(settings ?? new PayPalApiSettingsFromConfigurationManager());
            var response = api.SetExpressCheckout(operationToUse);

            return(response);
        }
        public ActionResult SetAccountPaymentInfo(ChangeContractViewModel viewModel)
        {
            var mainContract = dbPractice.AccountContract;

            string planId;
            Bus.ContractToPlan.TryGetValue(dbPractice.AccountContract.SYS_ContractType.UrlIdentifier, out planId);

            // because each plan has a different set of features,
            // this is going to be used by the view, to define the partial page that will be shown
            this.ViewBag.CurrentContractName = mainContract.SYS_ContractType.UrlIdentifier;

            if (!viewModel.AcceptedByUser)
            {
                this.ModelState.AddModelError(
                    () => viewModel.AcceptedByUser, "A caixa de checagem de aceitação do contrato precisa ser marcada para concluir o processo.");
            }

            if (mainContract.IsPartialBillingInfo)
            {
                if (planId == "ProfessionalPlan")
                {
                    // calculating values to see if the submited values are correct
                    var unitPrice = Bus.Pro.DOCTOR_PRICE;
                    Func<double, double, double> integ = (x, n) => Math.Pow(n, x) / Math.Log(n);
                    Func<double, double, double> integ0to = (x, n) => (integ(x, n) - integ(0, n));
                    Func<double, double> priceFactor = x => x * (1.0 - 0.1 * integ0to((x - 1) / 3.0, 0.75));
                    Func<double, double> price = (extraDoctors) => Math.Round(priceFactor(extraDoctors) * unitPrice * 100) / 100;

                    var dicValues = new Dictionary<string, decimal>(StringComparer.InvariantCultureIgnoreCase)
                        {
                            { "MONTH", Bus.Pro.PRICE_MONTH },
                            { "3-MONTHS", Bus.Pro.PRICE_QUARTER },
                            { "6-MONTHS", Bus.Pro.PRICE_SEMESTER },
                            { "12-MONTHS", Bus.Pro.PRICE_YEAR },
                        };

                    var dicDiscount = new Dictionary<string, decimal>(StringComparer.InvariantCultureIgnoreCase)
                        {
                            { "MONTH", 0 },
                            { "3-MONTHS", Bus.Pro. DISCOUNT_QUARTER },
                            { "6-MONTHS", Bus.Pro. DISCOUNT_SEMESTER },
                            { "12-MONTHS", Bus.Pro.DISCOUNT_YEAR },
                        };

                    var periodSizesDic = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase)
                        {
                            { "MONTH", 1 },
                            { "3-MONTHS", 3 },
                            { "6-MONTHS", 6 },
                            { "12-MONTHS", 12 },
                        };

                    var dicount = 1m - dicDiscount[viewModel.PaymentModelName] / 100m;
                    var accountValue = dicValues[viewModel.PaymentModelName];
                    var doctorsValueWithoutDiscount = (decimal)Math.Round(price(viewModel.DoctorCount - 1))
                        * periodSizesDic[viewModel.PaymentModelName];

                    var finalValue = accountValue + doctorsValueWithoutDiscount * dicount;

                    var finalValueWithoutDiscount =
                        Bus.Pro.PRICE_MONTH * periodSizesDic[viewModel.PaymentModelName]
                        + doctorsValueWithoutDiscount;

                    // tolerance of R$ 0.10 in the final value... maybe the browser could not make the calculations correctly,
                    // but we must use that value, since it is the value that the user saw
                    if (Math.Abs(finalValue - viewModel.FinalValue) >= 0.10m)
                    {
                        this.ModelState.AddModelError(
                            () => viewModel.FinalValue,
                            "Seu browser apresentou um defeito no cálculo do valor final. Não foi possível processar sua requisição de upgrade.");
                    }

                    viewModel.ContractUrlId = planId;
                    viewModel.CurrentDoctorsCount = dbPractice.Users.Count(x => x.DoctorId != null);

                    if (this.ModelState.IsValid)
                    {
                        //// sending e-mail to [email protected]
                        //// to remember us to send the payment request
                        //var emailViewModel = new InternalUpgradeEmailViewModel(this.DbUser, viewModel);
                        //var toAddress = new MailAddress("*****@*****.**", this.DbUser.Person.FullName);
                        //var mailMessage = this.CreateEmailMessagePartial("InternalUpgradeEmail", toAddress, emailViewModel);
                        //this.SendEmailAsync(mailMessage).ContinueWith(t =>
                        //{
                        //    // observing exception so that it is not raised
                        //    var ex = t.Exception;

                        //    // todo: should do something when e-mail is not sent
                        //    // 1) use a schedule table to save a serialized e-mail, and then send it later
                        //    // 2) log a warning message somewhere stating that this e-mail was not sent
                        //    // send e-mail again is not an option, SendEmailAsync already tries a lot of times
                        //});

                        // changing the partial contract, to match the new billing settings
                        // Note: the contract will still be partial, and only when the user pays
                        //     the partial flag will be removed and the StartDate will be defined.
                        mainContract.CustomText = viewModel.WholeUserAgreement;
                        mainContract.DoctorsLimit = viewModel.DoctorCount;

                        mainContract.BillingAmount = finalValueWithoutDiscount;
                        mainContract.BillingDiscountAmount = finalValueWithoutDiscount - viewModel.FinalValue;
                        mainContract.BillingDueDay = viewModel.InvoceDueDayOfMonth;
                        mainContract.BillingPeriodCount = null;
                        mainContract.BillingPeriodSize = periodSizesDic[viewModel.PaymentModelName];
                        mainContract.BillingPeriodType = "M";
                        mainContract.BillingPaymentMethod = "PayPal Invoice";

                        this.db.SaveChanges();

                        // Creating the first billing
                        var utcNow = this.GetUtcNow();
                        var localNow = PracticeController.ConvertToLocalDateTime(dbPractice, utcNow);

                        Billing billing = null;
                        var idSet = string.Format(
                            "CEREB.{1}{2}.{0}",
                            localNow.Year,
                            mainContract.BillingPeriodSize,
                            mainContract.BillingPeriodType);

                        billing = db.Billings.SingleOrDefault(b => b.PracticeId == dbPractice.Id
                            && b.MainAccountContractId == dbPractice.ActiveAccountContractId
                            && b.ReferenceDate == null);

                        if (billing == null)
                        {
                            billing = new Billing
                            {
                                PracticeId = dbPractice.Id,
                                AfterDueMonthlyTax = 1.00m, // 1%
                                AfterDueTax = 2.00m, // 2%
                                IssuanceDate = utcNow,
                                MainAmount = (decimal)mainContract.BillingAmount,
                                MainDiscount = (decimal)mainContract.BillingDiscountAmount,
                                DueDate = PracticeController.ConvertToUtcDateTime(dbPractice, localNow.AddDays(10)),
                                IdentitySetName = idSet,
                                IdentitySetNumber = db.Billings.Count(b => b.PracticeId == dbPractice.Id && b.IdentitySetName == idSet) + 1,
                                ReferenceDate = PracticeController.ConvertToUtcDateTime(dbPractice, null),
                                ReferenceDateEnd = PracticeController.ConvertToUtcDateTime(dbPractice, null),
                                MainAccountContractId = dbPractice.ActiveAccountContractId.Value,
                            };

                            db.Billings.AddObject(billing);
                        }

                        this.db.SaveChanges();

                        // Using PayPal API to start an Express Checkout operation, and then redirecting user to PayPal.
                        var operation = new PayPalSetExpressCheckoutOperation();
                        ConfigAccountController.FillOperationDetails(operation, dbPractice, mainContract, billing);
                        var practice = this.dbPractice.UrlIdentifier;
                        operation.PaymentRequests[0].NotifyUrl = UseExternalIpIfDebug(this.Url.ActionAbsolute("PayPalNotification", new { practice }));
                        var opResult = this.SetExpressCheckout(operation, "PayPalConfirm", "PayPalCancel", new { practice });

                        if (opResult.Errors != null && opResult.Errors.Any())
                            return new StatusCodeResult(HttpStatusCode.InternalServerError, opResult.Errors[0].LongMessage);

                        return this.RedirectToCheckout(opResult);
                    }

                    return this.View(viewModel);
                }
            }

            return this.HttpNotFound();
        }
Ejemplo n.º 11
0
        public ActionResult PayPalCheckout()
        {
            var operation = new PayPalSetExpressCheckoutOperation();
            FillOperationDetails(operation, null, null, null);

            // Validating the request object.
            // TODO: handle the invalid object if it has errors.
            var validationResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
            System.ComponentModel.DataAnnotations.Validator.TryValidateObject(
                operation,
                new System.ComponentModel.DataAnnotations.ValidationContext(operation, null, null),
                validationResults,
                validateAllProperties: true);

            var opResult = this.SetExpressCheckout(operation, "PayPalConfirm", "PayPalCancel");

            return this.RedirectToCheckout(opResult);
        }