Example #1
0
        public static Agreement CreateBillingAgreement(string planId, ShippingAddress shippingAddress,
                                                       string name, string description, DateTime startDate)
        {
            // PayPal Authentication tokens
            var apiContext = PayPalConfig.GetAPIContext();

            var agreement = new Agreement()
            {
                name        = name,
                description = description,
                start_date  = startDate.ToString("yyyy-MM-ddTHH:mm:ss") + "Z",
                payer       = new Payer()
                {
                    payment_method = "paypal",
                },
                plan = new Plan()
                {
                    id = planId
                },
                shipping_address = shippingAddress
            };

            var createdAgreement = agreement.Create(apiContext);

            return(createdAgreement);
        }
Example #2
0
        // GET: Payment
        public ActionResult PaymentWithPayPal(string Cancel = null)
        {
            if (Session["usr"] == null)
            {
                return(RedirectToAction("Login", "Account"));
            }

            APIContext apiContext = PayPalConfig.GetAPIContext();

            try
            {
                string PayerId = Request.Params["PayerId"];
                if (string.IsNullOrEmpty(PayerId))
                {
                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority
                                     + "/Payment/PaymentWithPayPal?";

                    var guid = Convert.ToString((new Random()).Next(100000));

                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);

                    var    links             = createdPayment.links.GetEnumerator();
                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links link = links.Current;
                        if (link.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = link.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    var guid           = Request.Params["guid"];
                    var executePayment = ExecutePayment(apiContext, PayerId, Session[guid] as string);

                    if (executePayment.state.ToLower() != "approved")
                    {
                        ViewBag.ErrorMessage = executePayment.failure_reason;
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception x)
            {
                ViewBag.ErrorMessage = x.Message;
                return(View("FailureView"));
            }
            RegistrarVenta();
            return(View("SuccessView"));
        }
Example #3
0
        /// <summary>
        ///
        /// UPDATE:
        ///     UpdateBillingPlan(
        ///        planId: "P-5FY40070P6526045UHFWUVEI",
        ///        path: "/",
        ///        value: new Plan { description = "new description" }
        ///        );
        /// DELETE:
        ///     UpdateBillingPlan(
        ///         planId: "P-5FY40070P6526045UHFWUVEI",
        ///         path: "/",
        ///         value: new Plan { state = "INACTIVE" });
        /// </summary>
        /// <param name="planId"></param>
        /// <param name="path"></param>
        /// <param name="value"></param>
        public static void UpdateBillingPlan(string planId, string path, object value)
        {
            // PayPal Authentication tokens
            var apiContext = PayPalConfig.GetAPIContext();

            // Retrieve Plan
            var plan = Plan.Get(apiContext, planId);

            // Activate the plan
            var patchRequest = new PatchRequest()
            {
                new Patch()
                {
                    op    = "replace",
                    path  = path,
                    value = value
                }
            };

            plan.Update(apiContext, patchRequest);
        }
Example #4
0
        public ActionResult PaymentWithCreditCard(string CreditCardId = "")
        {
            var pvm = PaypalViewModel.GetSamplePayment("*****@*****.**");

            var apiContext = PayPalConfig.GetAPIContext();

            // A transaction defines the contract of a payment.
            var transaction = new Transaction()
            {
                amount = new Amount()
                {
                    currency = pvm.Transaction.Amount.Currency,
                    total    = pvm.Transaction.Amount.Total,
                    details  = new Details()
                    {
                        shipping = pvm.Transaction.Amount.Detail.Shipping,
                        subtotal = pvm.Transaction.Amount.Detail.Subtotal,
                        tax      = pvm.Transaction.Amount.Detail.Tax
                    }
                },
                description = pvm.Transaction.Description,
                item_list   = new ItemList()
                {
                    items = pvm.Transaction.ItemList.Select(s => new Item
                    {
                        name     = s.Name,
                        currency = s.Currency,
                        price    = s.Price,
                        quantity = s.Quantity,
                        sku      = s.Sku
                    }).ToList(),
                    shipping_address = new ShippingAddress
                    {
                        city           = pvm.Transaction.ShippingAddress.City,
                        country_code   = pvm.Transaction.ShippingAddress.CountryCodeDomain,
                        line1          = pvm.Transaction.ShippingAddress.AddressLine,
                        postal_code    = pvm.Transaction.ShippingAddress.PostalCode,
                        state          = pvm.Transaction.ShippingAddress.State,
                        recipient_name = pvm.Transaction.ShippingAddress.RecipientName
                    }
                },
                invoice_number = String.IsNullOrEmpty(pvm.Transaction.InvoiceNumber) ? GetRandomInvoiceNumber() : pvm.Transaction.InvoiceNumber
            };

            // A resource representing a Payer that funds a payment.
            var payer = new Payer()
            {
                payment_method = "credit_card",
                payer_info     = new PayerInfo
                {
                    email = pvm.Payer.PayerInfo.Email
                }
            };

            if (String.IsNullOrEmpty(CreditCardId))
            {
                payer.funding_instruments = new List <FundingInstrument>()
                {
                    new FundingInstrument()
                    {
                        credit_card = new CreditCard()
                        {
                            billing_address = new Address()
                            {
                                city         = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.City,
                                country_code = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.CountryCodeDomain,
                                line1        = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.AddressLine,
                                postal_code  = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.PostalCode,
                                state        = pvm.Payer.FundingInstrument.CreditCard.BillingAddress.State
                            },
                            cvv2         = pvm.Payer.FundingInstrument.CreditCard.Cvv2,
                            expire_month = pvm.Payer.FundingInstrument.CreditCard.ExpireMonth,
                            expire_year  = pvm.Payer.FundingInstrument.CreditCard.ExpireYear,
                            first_name   = pvm.Payer.FundingInstrument.CreditCard.FirstName,
                            last_name    = pvm.Payer.FundingInstrument.CreditCard.LastName,
                            number       = pvm.Payer.FundingInstrument.CreditCard.CcNumber,
                            type         = pvm.Payer.FundingInstrument.CreditCard.CcType
                        }
                    }
                };

                CreditCardId = PaypalVault.StoreCreditCardInPaypal(pvm.Payer.FundingInstrument.CreditCard);
            }
            else
            {
                //Here, we are assigning the User's Credit Card ID which we saved in Database
                payer.funding_instruments = new List <FundingInstrument>()
                {
                    new FundingInstrument()
                    {
                        credit_card_token = new CreditCardToken
                        {
                            credit_card_id = CreditCardId
                        }
                    }
                };
            }


            // A Payment resource; create one using the above types and intent as `sale` or `authorize`
            var payment = new PayPal.Api.Payment()
            {
                intent       = "sale",
                payer        = payer,
                transactions = new List <Transaction>()
                {
                    transaction
                }
            };

            // ^ Ignore workflow code segment
            #region Track Workflow
            //this.flow.AddNewRequest("Create credit card payment", payment);
            #endregion

            // Create a payment using a valid APIContext
            var createdPayment = payment.Create(apiContext);

            // ^ Ignore workflow code segment
            #region Track Workflow
            //this.flow.RecordResponse(createdPayment);
            #endregion

            if (createdPayment.state.ToLower() != "approved")
            {
                //return View("FailureView");
                return(Content("Failed"));
            }

            return(Content("Success Id: " + CreditCardId));

            // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
        }
Example #5
0
        public ActionResult PaymentWithPaypal(PaypalViewModel pvm)
        {
            pvm = PaypalViewModel.GetSamplePayment();

            //getting the apiContext as earlier
            APIContext apiContext = PayPalConfig.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist
                    //it is returned by the create function call of the payment class

                    // Creating a payment
                    // baseURL is the url on which paypal sendsback the data.
                    // So we have provided URL of this controller only
                    //
                    string baseURI = Request.Url.GetLeftPart(UriPartial.Authority)  // Request.Url.Scheme + "://" + Request.Url.Authority
                                     + "/" + Url.Action("PaymentWithPayPal", "Paypal", new { area = "OrderFramework" }) + "?";

                    //guid we are generating for storing the paymentID received in session
                    //after calling the create function and it is used in the payment execution

                    var guid = Convert.ToString((new Random()).Next(100000));

                    //CreatePayment function gives us the payment approval url
                    //on which payer is redirected for paypal account payment

                    var createdPayment = this.CreatePayment(pvm, apiContext, baseURI + "guid=" + guid);

                    //get links returned from paypal in response to Create function call

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment

                    var guid = Request.Params["guid"];

                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(Content("Failed"));
                    }
                }
            }
            catch (Exception ex)
            {
                //Logger.log("Error" + ex.Message);
                //return View("FailureView");
                return(Content("Failed"));
            }

            //return View("SuccessView");
            return(Content("Success"));
        }
        public ActionResult AddressAndPayment(OrderViewModel orderViewModel)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Months = PayPalHelper.Months;

                ViewBag.Years = PayPalHelper.Years;

                ViewBag.CreditCardTypes = PayPalHelper.CreditCardTypes;

                ViewBag.Countries = PayPalHelper.Countries;

                return(View(orderViewModel));
            }

            try
            {
                //create the order to store information in our database
                var     cart       = ShoppingCart.GetCart(this.HttpContext);
                Order   order      = new Order();
                decimal orderTotal = 0;
                order.Username     = User.Identity.Name;
                order.OrderDate    = DateTime.Now;
                order.OrderDetails = new List <OrderDetail>();

                var cartProducts = cart.GetCartProducts();
                // Iterate over the products in the cart,
                // adding the order details for each
                foreach (var product in cartProducts)
                {
                    var orderDetail = new OrderDetail
                    {
                        ProductId = product.ProductId,
                        OrderId   = order.OrderId,
                        UnitPrice = product.Product.Price,
                        Quantity  = product.Count
                    };
                    // Set the order total of the shopping cart
                    orderTotal += (product.Count * product.Product.Price);
                    order.OrderDetails.Add(orderDetail);
                }
                // Set the order's total to the orderTotal count
                order.Total = orderTotal;

                //add everything to the DB
                dbContext.Orders.Add(order);
                dbContext.OrderDetails.AddRange(order.OrderDetails);

                //proccess to paypal
                List <PayPal.Api.Item> items = new List <PayPal.Api.Item>();
                foreach (OrderDetail orderDetail in order.OrderDetails)
                {
                    PayPal.Api.Item item = new PayPal.Api.Item();
                    item.name     = dbContext.Products.Single(p => p.ProductId == orderDetail.ProductId).Name;
                    item.currency = "USD";
                    item.price    = orderDetail.UnitPrice.ToString();
                    item.quantity = orderDetail.Quantity.ToString();
                    item.sku      = orderDetail.ProductId.ToString();

                    items.Add(item);
                }
                PayPal.Api.ItemList itemList = new PayPal.Api.ItemList();
                itemList.items = items;

                PayPal.Api.Address address = new PayPal.Api.Address();
                address.city         = orderViewModel.City;
                address.country_code = orderViewModel.Country;
                address.line1        = orderViewModel.Address;
                address.postal_code  = orderViewModel.PostalCode.ToString();
                address.state        = orderViewModel.State;

                PayPal.Api.CreditCard creditCard = new PayPal.Api.CreditCard();
                creditCard.billing_address = address;
                creditCard.cvv2            = orderViewModel.CSC.ToString();
                creditCard.expire_month    = Int32.Parse(orderViewModel.ExpirationMonth);
                creditCard.expire_year     = Int32.Parse(orderViewModel.ExpirationYear);
                creditCard.first_name      = orderViewModel.FirstName;
                creditCard.last_name       = orderViewModel.LastName;
                creditCard.number          = orderViewModel.CreditCardNumber;
                creditCard.type            = orderViewModel.CcType;

                PayPal.Api.Details details = new PayPal.Api.Details();
                details.shipping = "1";
                details.subtotal = order.Total.ToString();
                details.tax      = "1";

                PayPal.Api.Amount amount = new PayPal.Api.Amount();
                amount.currency = "USD";
                amount.total    = (order.Total + 2).ToString();
                amount.details  = details;

                PayPal.Api.Transaction transaction = new PayPal.Api.Transaction();
                transaction.amount         = amount;
                transaction.description    = "Description goes here";
                transaction.item_list      = itemList;
                transaction.invoice_number = order.OrderId.ToString();

                List <PayPal.Api.Transaction> transactionList = new List <PayPal.Api.Transaction>();
                transactionList.Add(transaction);

                PayPal.Api.FundingInstrument fundInstrument = new PayPal.Api.FundingInstrument();
                fundInstrument.credit_card = creditCard;

                List <PayPal.Api.FundingInstrument> fundingList = new List <PayPal.Api.FundingInstrument>();
                fundingList.Add(fundInstrument);

                PayPal.Api.Payer payer = new PayPal.Api.Payer();
                payer.funding_instruments = fundingList;
                payer.payment_method      = "credit_card";

                PayPal.Api.Payment payment = new PayPal.Api.Payment();
                payment.intent       = "sale";
                payment.payer        = payer;
                payment.transactions = transactionList;

                try
                {
                    //getting context from the paypal
                    //basically we are sending the clientID and clientSecret key in this function
                    //to the get the context from the paypal API to make the payment
                    //for which we have created the object above.

                    //Basically, apiContext object has a accesstoken which is sent by the paypal
                    //to authenticate the payment to facilitator account.
                    //An access token could be an alphanumeric string

                    PayPal.Api.APIContext apiContext = PayPalConfig.GetAPIContext();

                    //Create is a Payment class function which actually sends the payment details
                    //to the paypal API for the payment. The function is passed with the ApiContext
                    //which we received above.

                    PayPal.Api.Payment createdPayment = payment.Create(apiContext);

                    //if the createdPayment.state is "approved" it means the payment was successful else not

                    if (createdPayment.state.ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
                catch (PayPal.PayPalException ex)
                {
                    //Logger.Log("Error: " + ex.Message);
                    return(View("FailureView"));
                }


                cart.EmptyCart();
                return(RedirectToAction("Complete", new { id = order.OrderId }));
            }
            catch (Exception ex)
            {
                //Invalid - redisplay with errors
                //return View(order);
            }
            return(View());
        }