コード例 #1
0
        public IActionResult Pay()
        {
            PayPalConfig payPalConfig = PayPalService.GetPayPalConfig();

            ViewBag.payPalConfig = payPalConfig;
            return(View());
        }
コード例 #2
0
        public IActionResult ShoppingCart()
        {
            List <OfferedLabourerService> serviceList = new List <OfferedLabourerService>();

            //Check if we're logged in.
            bool loggedIn = SessionController.returnLoggedIn(this.HttpContext);

            if (!loggedIn)
            {
                //Not logged in, get products from cookies
                List <string> keyList = Request.Cookies.Keys.Where(k => k.StartsWith("SC")).ToList();
                serviceList = Utility.CookieController.fetchItemsInCookies(keyList);
            }

            else
            {
                //Logged in, get products from database
                List <Object> offeredServiceIds = MollShopContext.GetShoppingCartItems((int)HttpContext.Session.GetInt32("UserId"));
                serviceList = new List <OfferedLabourerService>();

                foreach (Object id in offeredServiceIds)
                {
                    serviceList.Add(ElasticSearch.Queries.EsOLSQuery <object> .findByOfferedServiceId((int)id));
                }
            }


            PayPalConfig payPalConfig = PayPalService.getPayPalConfig();

            ViewBag.payPayConfig = payPalConfig;

            return(View(serviceList));
        }
コード例 #3
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);
        }
コード例 #4
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"));
        }
コード例 #5
0
        public IActionResult Index()
        {
            var cart = SessionHelper.GetObjectFromJson <List <ItemViewModel> >(HttpContext.Session, "cart");

            if (cart != null)
            {
                ViewBag.cart  = cart;
                ViewBag.total = cart.Sum(i => i.Product.UnitPrice * i.Quantity);
            }

            PayPalConfig payPalConfig = PayPalService.GetPayPalConfig();

            ViewBag.PayPalConfig = payPalConfig;

            return(View());
        }
コード例 #6
0
        public IActionResult PaymentMethod(string fld_email, string fld_firstname, string fld_lastname, string fld_address, string fld_zipcode)
        {
            //The variables received from this form will be used to create the confirmation email later on
            HttpContext.Session.SetString("FORM", fld_firstname + ";" + fld_lastname + ";" + fld_address + ";" + fld_zipcode + ";" + fld_email);


            //This view will show the users their options for paying
            //In reality, the user would be able to choose between IDEAL, PayPal, etc. However, we only have PayPal

            List <OfferedLabourerService> olsList = ParseOrdersToOLS();

            PayPalConfig payPalConfig = PayPalService.getPayPalConfig();

            ViewBag.payPayConfig = payPalConfig;


            return(View(olsList));
        }
コード例 #7
0
        public IActionResult Index()
        {
            string pay_status = HttpContext.Session.GetString("PayStatus");

            if (pay_status == "paid" || HttpContext.Session.GetInt32("OrderId") == null)
            {
                return(RedirectToAction("Index", "Home"));
            }


            int orderid = (int)HttpContext.Session.GetInt32("OrderId");
            List <OrderDetail> orderdetails = _context.OrderDetails.Where(o => o.Order_Id == orderid).ToList();

            List <Product> products = new List <Product>();

            foreach (var detail in orderdetails)
            {
                Product pro = _context.Products.Where(o => o.Id == detail.Product_Id).FirstOrDefault();
                products.Add(pro);
            }

            CheckoutIndexViewModel vm = new CheckoutIndexViewModel()
            {
                OrderDetails  = orderdetails,
                Products      = products,
                ProductTypes  = _context.ProductTypes.ToList(),
                productBrands = _context.ProductBrands.ToList()
            };

            int sum = 0;

            foreach (var detail in vm.OrderDetails)
            {
                sum += detail.PriceTotal;
            }
            HttpContext.Session.SetString("TongTien", sum.ToString());

            PayPalConfig payPalConfig = PayPalService.GetPayPalConfig();

            ViewBag.payPalConfig = payPalConfig;

            return(View(vm));
        }
コード例 #8
0
        public IActionResult Index()
        {
            CartItem a = new CartItem();
            //test luôn đúng
            List <HangHoaViewModel> s = new List <HangHoaViewModel>()
            {
                new HangHoaViewModel {
                    Id = 1, Name = "Gi do", Price = 10000, Quantity = 3
                }, new HangHoaViewModel {
                    Id = 2, Name = "Gi do 2", Price = 6000, Quantity = 3
                }
            };

            ViewBag.products = s;
            PayPalConfig payPalConfig = PayPalService.getPayPalConfig();

            ViewBag.payPalConfig = payPalConfig;
            return(View(Carts));
        }
コード例 #9
0
        public ActionResult Index()
        {
            if (Models.SessionExtensions.Get <List <Item> >(HttpContext.Session, "cart") == null)
            {
                return(View("error"));
            }
            else
            {
                var cart = Models.SessionExtensions.Get <List <Item> >(HttpContext.Session, "cart");


                ViewBag.cart  = cart;
                ViewBag.total = cart.Sum(item => item.Price * item.Quantity);
            }
            PayPalConfig payPalConfig = PayPalService.GetPayPalConfig();

            ViewBag.payPalConfig = payPalConfig;
            return(View());
        }
コード例 #10
0
        public static Token GetToken(PayPalConfig cnf, List <Item> items, bool isSandbox = false)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append(!isSandbox ? "https://api-3t.paypal.com/nvp?" : "https://api-3t.sandbox.paypal.com/nvp?");
            PayPalRequest request = new PayPalRequest
            {
                METHOD    = "SetExpressCheckout",
                VERSION   = !isSandbox ? "109.0" : "104.0",
                USER      = cnf.User,
                PWD       = cnf.Password,
                SIGNATURE = cnf.Signature,
                Items     = new Dictionary <string, object>()
            };
            int num = 0;

            foreach (Item item in items)
            {
                request.Items.Add("L_PAYMENTREQUEST_0_NAME" + num, item.Name);
                request.Items.Add("L_PAYMENTREQUEST_0_NUMBER" + num, num);
                request.Items.Add("L_PAYMENTREQUEST_0_QTY" + num, item.Quantity);
                request.Items.Add("L_PAYMENTREQUEST_0_AMT" + num, item.TotalAmount);
                num++;
            }
            request.PAYMENTREQUEST_0_AMT          = items.Sum <Item>(x => x.TotalAmount);
            request.PAYMENTREQUEST_0_CURRENCYCODE = "USD";
            request.RETURNURL = cnf.ReturnUrl + "?guid=" + cnf.guid;
            request.CANCELURL = cnf.CancelUrl + "?guid=" + cnf.guid;
            request.PAYMENTREQUEST_0_PAYMENTACTION = "Sale";
            request.SOLUTIONTYPE = "Sole";
            request.LANDINGPAGE  = "Billing";
            request.BRANDNAME    = cnf.CompanyName;
            builder.Append(QuerystringSerializer.Serialize(request));
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            WebResponse  response = WebRequest.Create(builder.ToString()).GetResponse();
            StreamReader reader1  = new StreamReader(response.GetResponseStream());
            string       s        = reader1.ReadToEnd();

            reader1.Close();
            response.Close();
            return(QuerystringSerializer.Deserialize <Token>(HttpContext.Current.Server.UrlDecode(s), "", false));
        }
コード例 #11
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);
        }
コード例 #12
0
        public static void _PayPal(BuyingVM buynow)
        {
            PayPalConfig config = PayPalConfig.GetConfiguration(HttpContext.Current.Server.MapPath("~/paypalconfig/paypal.config"));

            config.guid = buynow.GuId;
            List <PaymentLibrary.PayPal.Item> items = new List <PaymentLibrary.PayPal.Item>();

            //foreach (OrderSummary orderSummary in buynow.OrderSummary)
            //{
            //    //if price is not set or null then do not add to order summary
            //    if (orderSummary.Price == null)
            //        continue;

            //    PaymentLibrary.PayPal.Item itm = new PaymentLibrary.PayPal.Item();
            //    itm.Name = orderSummary.ReportTitle.ZSubstring(0, 20);
            //    itm.Quantity = orderSummary.Quantity;
            //    itm.Price = orderSummary.Price;
            //    items.Add(itm);
            //}

            items.Add(new Item
            {
                Name     = buynow.ReportTitle.Length > 20 ? buynow.ReportTitle.Substring(0, 20) : buynow.ReportTitle,
                Quantity = 1,
                Price    = buynow.Price
            });

            // PaymentLibrary.PayPal.Token tkn = PaymentLibrary.PayPal.PayPal.GetToken(config, items, true);
            PaymentLibrary.PayPal.Token tkn = GetToken(config, items, true);

            if (!string.IsNullOrEmpty(tkn.L_ERRORCODE0))
            {
                log4net.LogManager.GetLogger("Error").Error("Error at SaveBuynowDetails. PayPal \nErrorCode - " + tkn.L_ERRORCODE0 + "\nError Message - " + tkn.L_SHORTMESSAGE0 + "\n" + tkn.L_LONGMESSAGE0 + "\nFull Data - " + Newtonsoft.Json.JsonConvert.SerializeObject(buynow));
                //return new Utility.Message { MessageText = tkn.L_LONGMESSAGE0 };
            }

            PaymentLibrary.PayPal.PayPal.RedirectUser(tkn);

            // return new Utility.Message { MessageText = "Payment Initiated" };
        }
コード例 #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson(x =>
                                                        x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Payments", Version = "v1"
                });
            });

            // Add JWT token functionality
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime         = true,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidIssuer      = Configuration["JWT:Issuer"],
                    ValidAudience    = Configuration["JWT:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Key"]))
                };
            });

            // Set JWT to be default Authenticator
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "Bearer";
            });
            var payPalConfig = new PayPalConfig();

            Configuration.GetSection("PayPalConfig").Bind(payPalConfig);
            services.AddSingleton(payPalConfig);
            //services.AddSingleton<PayPalClient>();
        }
コード例 #14
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"));
        }
コード例 #15
0
        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());
        }
コード例 #16
0
        public static bool PayPalProcess(PaymentLibrary.PayPal.PayPalResponse paypalResponse)
        {
            ExcellentMarketResearchEntities db = new ExcellentMarketResearchEntities();

            if (paypalResponse != null && (!string.IsNullOrEmpty(paypalResponse.PAYERID) || !string.IsNullOrEmpty(paypalResponse.guid)))
            {
                BuyingInfo b = new BuyingInfo();

                if (string.IsNullOrEmpty(paypalResponse.PAYERID))
                {
                    log4net.LogManager.GetLogger("Error").Error("PayerID not found OR Response is null OR guid is not found.\nData - " + Newtonsoft.Json.JsonConvert.SerializeObject(paypalResponse));
                }

                //TODO: Get buyer from table using guid

                var buyer = GetBuyerByGuId(paypalResponse.guid);

                //bool IsBuyerExist= buyer.Count(x=>x.GuId==paypalResponse.guid)>0?true:false;
                bool IsBuyerExist = buyer != null ? true : false;

                //TODO: Check buyer if exist or not
                if (IsBuyerExist == null)
                {
                    // log4net.logmanager.getlogger("error").error("buyer not found.\ndata - " + newtonsoft.json.jsonconvert.serializeobject(paypalresponse));
                    return(false);
                }


                ValidResponse vResponse = PaymentLibrary.PayPal.PayPal.IsPaymentValid(paypalResponse,
                                                                                      PayPalConfig.GetConfiguration(HttpContext.Current.Server.MapPath("/paypalconfig/paypal.config"), false), false);

                if (vResponse.IsValid)
                {
                    //TODO: update status of payment transaction to success

                    var updatestatus = db.BuyingInfoes.Where(x => x.GuId == paypalResponse.guid).FirstOrDefault();
                    b.PaymentTransaction            = true;
                    updatestatus.PaymentTransaction = b.PaymentTransaction;
                    db.Entry(updatestatus).State    = EntityState.Modified;
                    db.SaveChanges();
                    return(true);
                }
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                Stream     s = new MemoryStream();
                TextWriter t = new StreamWriter(s);

                serializer.Serialize(t, paypalResponse);
                TextReader r = new StreamReader(s);

                //TODO: Save error to db

                //_saveStatus(, 'f', vResponse.Reason + "|ErrorCode - " + vResponse.ErrorCode + "|PaypalResponse - " + r.ReadToEnd());

                var saveError = db.BuyingInfoes.Where(x => x.GuId == paypalResponse.guid).FirstOrDefault();
                b.PaymentTransaction         = false;
                saveError.PaymentTransaction = b.PaymentTransaction;
                saveError.ErrorReason        = vResponse.Reason;
                saveError.ErrorCode          = vResponse.ErrorCode;
                db.Entry(saveError).State    = EntityState.Modified;
                db.SaveChanges();

                return(false);
            }
            return(false);
        }
コード例 #17
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/).
        }
コード例 #18
0
        public async Task <IActionResult> Index()
        {
            List <CartItemViewModel> cartItem = new List <CartItemViewModel>();
            double sum = 0;

            if (HttpContext.Session.GetString("IdTaiKhoan") == null)
            {
                ViewBag.Hau = 1;
                if (HttpContext.Session.GetInt32("IdCart") != null)
                {
                    cartItem = await(from d in _context.AnoCartDetails
                                     join c in _context.AnoCarts
                                     on d.Cart_Id equals c.Id
                                     join p in _context.Products
                                     on d.Product_Id equals p.Id
                                     where c.Id == HttpContext.Session.GetInt32("IdCart")
                                     select new CartItemViewModel
                    {
                        Id         = d.Id,
                        Name       = p.Name,
                        Quantity   = d.Quantity,
                        Price      = d.PriceSingle,
                        TotalPrice = d.PriceTotal
                    }).ToListAsync();
                }
                foreach (var item in cartItem)
                {
                    sum += item.TotalPrice;
                }
            }
            else
            {
                cartItem = await(from d in _context.CartDetails
                                 join c in _context.Carts
                                 on d.Cart_Id equals c.Id
                                 join p in _context.Products
                                 on d.Product_Id equals p.Id
                                 where c.User_Id == HttpContext.Session.GetInt32("IdTaiKhoan")
                                 select new CartItemViewModel
                {
                    Id         = d.Id,
                    Name       = p.Name,
                    Quantity   = d.Quantity,
                    Price      = d.PriceSingle,
                    TotalPrice = d.PriceTotal
                }).ToListAsync();
                foreach (var item in cartItem)
                {
                    sum += item.TotalPrice;
                }
            }

            CartViewModel vm = new CartViewModel()
            {
                ProductTypes       = _context.ProductTypes.ToList(),
                CartItemViewModels = cartItem
            };

            HttpContext.Session.SetString("TongTien", sum.ToString());
            string Ten    = HttpContext.Session.GetString("TenTaiKhoan");
            string DiaChi = HttpContext.Session.GetString("diachi");

            ViewBag.ten    = Ten;
            ViewBag.diachi = DiaChi;
            PayPalConfig payPalConfig = PayPalService.GetPayPalConfig();

            ViewBag.payPalConfig = payPalConfig;
            return(View(vm));
        }