Ejemplo n.º 1
0
        /// <summary>
        /// Create payment
        /// </summary>
        /// <returns></returns>
        ///
        private PayPal.Api.Payment CreatePayment(PayPal.Api.APIContext apiContext, string redirectUrl, string tenSp, int?price)
        {
            var itemList = new PayPal.Api.ItemList()
            {
                items = new List <PayPal.Api.Item>()
            };
            //Các giá trị bao gồm danh sách sản phẩm, thông tin đơn hàng
            //Sẽ được thay đổi bằng hành vi thao tác mua hàng trên website
            var items = new PayPal.Api.Item()
            {
                //Thông tin đơn hàng
                name     = tenSp,
                currency = "USD",
                price    = String.Format("{0:0.00}", price / 23000),
                quantity = "1",
                sku      = "sku"
            };

            itemList.items.Add(items);
            var subtotal = float.Parse(items.price) * float.Parse(items.quantity);
            //Hình thức thanh toán qua paypal
            var payer = new PayPal.Api.Payer()
            {
                payment_method = "paypal"
            };
            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new PayPal.Api.RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };
            //các thông tin trong đơn hàng
            var details = new PayPal.Api.Details()
            {
                tax      = "1",
                shipping = "1",
                subtotal = subtotal.ToString()
            };
            var total = subtotal + float.Parse(details.tax) + float.Parse(details.shipping);
            //Đơn vị tiền tệ và tổng đơn hàng cần thanh toán
            var amount = new PayPal.Api.Amount()
            {
                currency = "USD",
                total    = total.ToString(), // Total must be equal to sum of shipping, tax and subtotal.
                details  = details
            };
            var transactionList = new List <PayPal.Api.Transaction>();

            //Tất cả thông tin thanh toán cần đưa vào transaction
            transactionList.Add(new PayPal.Api.Transaction()
            {
                description    = "Transaction description.",
                invoice_number = Guid.NewGuid().ToString(),
                amount         = amount,
                item_list      = itemList
            });
            this.payment = new PayPal.Api.Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };
            return(this.payment.Create(apiContext));
        }
Ejemplo n.º 2
0
        public ActionResult SaveOrder(FormCollection fc)
        {
            if (IsCardNumberValid(NormalizeCardNumber(fc["cardNumber"])))
            {
                bool res = false;
                switch (GetCardType(fc["cardNumber"]))
                {
                case (CardType.Amex):
                    fc["cardType"] = "amex";
                    res            = true;
                    break;

                case (CardType.Discover):
                    fc["cardType"] = "discover";
                    res            = true;
                    break;

                case (CardType.MasterCard):
                    fc["cardType"] = "mastercard";
                    res            = true;
                    break;

                case (CardType.VISA):
                    fc["cardType"] = "visa";
                    res            = true;
                    break;

                default:
                    res = false;
                    break;
                }



                if (res)
                {
                    List <Item> cart    = (List <Item>)Session["cart"];
                    Invoice     invoice = new Invoice();
                    invoice.CustomerName    = fc["customerName"];
                    invoice.CustomerAddress = fc["customerAddress"];
                    invoice.Name            = "New Invoice";

                    PayPal.Api.Item        paitem;
                    List <Item>            lstItem  = (List <Item>)Session["cart"];
                    List <PayPal.Api.Item> itms     = new List <PayPal.Api.Item>();
                    PayPal.Api.ItemList    itemList = new PayPal.Api.ItemList();
                    decimal totalPrice = 0;
                    foreach (var item in lstItem)
                    {
                        paitem          = new PayPal.Api.Item();
                        paitem.name     = item.pr.ProductName;
                        paitem.currency = "USD";
                        paitem.price    = item.pr.Price.ToString();// "5";
                        paitem.quantity = "1";
                        paitem.sku      = "sku";

                        if (item.Quantity > 0)
                        {
                            for (int i = 0; i < Convert.ToInt16(item.Quantity); i++)
                            {
                                itms.Add(paitem);
                            }
                            itemList.items = new List <PayPal.Api.Item>();
                            foreach (var itm in itms)
                            {
                                itemList.items.Add(itm);
                            }

                            totalPrice = totalPrice + item.pr.Price * item.Quantity;
                        }
                    }
                    //Now make a List of Item and add the above item to it
                    //you can create as many items as you want and add to this list


                    //Address for the payment
                    PayPal.Api.Address billingAddress = new PayPal.Api.Address();
                    billingAddress.city         = "NewYork";
                    billingAddress.country_code = "US";
                    billingAddress.line1        = "23rd street kew gardens";
                    billingAddress.postal_code  = "43210";
                    billingAddress.state        = "NY";


                    //Now Create an object of credit card and add above details to it
                    //Please replace your credit card details over here which you got from paypal
                    PayPal.Api.CreditCard crdtCard = new PayPal.Api.CreditCard();
                    crdtCard.billing_address = billingAddress;
                    crdtCard.cvv2            = fc["CVV"];                       //card cvv2 number
                    crdtCard.expire_month    = Convert.ToInt32(fc["expMonth"]); //card expire date
                    crdtCard.expire_year     = Convert.ToInt32(fc["expYear"]);  //card expire year
                    crdtCard.first_name      = fc["nameOnCardFirstName"];
                    crdtCard.last_name       = fc["nameOnCardLastName"];

                    crdtCard.number = fc["cardNumber"]; //enter your credit card number here
                    crdtCard.type   = fc["cardType"];   //credit card type here paypal allows 4 types

                    // Specify details of your payment amount.
                    PayPal.Api.Details details = new PayPal.Api.Details();
                    details.shipping = (1 * Convert.ToInt32(0)).ToString();
                    details.subtotal = totalPrice.ToString();
                    details.tax      = (1 * Convert.ToInt32(0)).ToString();

                    // Specify your total payment amount and assign the details object
                    PayPal.Api.Amount amnt = new PayPal.Api.Amount();
                    amnt.currency = "USD";
                    // Total = shipping tax + subtotal.
                    amnt.total   = (Convert.ToInt32(totalPrice) + Convert.ToInt32(details.shipping) + Convert.ToInt32(details.tax)).ToString();
                    amnt.details = details;

                    // Now make a transaction object and assign the Amount object
                    Random random = new Random();
                    PayPal.Api.Transaction tran = new PayPal.Api.Transaction();
                    tran.amount         = amnt;
                    tran.description    = "Description about the payment amount.";
                    tran.item_list      = itemList;
                    tran.invoice_number = random.Next().ToString();

                    // Now, we have to make a list of transaction and add the transactions object
                    // to this list. You can create one or more object as per your requirements

                    List <PayPal.Api.Transaction> transactions = new List <PayPal.Api.Transaction>();
                    transactions.Add(tran);

                    // Now we need to specify the FundingInstrument of the Payer
                    // for credit card payments, set the CreditCard which we made above

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

                    // The Payment creation API requires a list of FundingIntrument

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

                    // Now create Payer object and assign the fundinginstrument list to the object
                    PayPal.Api.Payer payr = new PayPal.Api.Payer();
                    payr.funding_instruments = fundingInstrumentList;
                    payr.payment_method      = "credit_card";

                    // finally create the payment object and assign the payer object & transaction list to it
                    PayPal.Api.Payment pymnt = new PayPal.Api.Payment();
                    pymnt.intent       = "sale";
                    pymnt.payer        = payr;
                    pymnt.transactions = transactions;

                    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 = PayPalIntegration.Models.Configuration.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 = pymnt.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)
                    {
                        ViewBag.Error = "Error: " + ex.Message;
                        return(View("FailureView"));
                    }
                    return(View("Thanks"));
                }
                else
                {
                    ViewBag.Error = "Please provide valid card";
                    return(View("FailureView"));
                }
            }
            else
            {
                ViewBag.Error = "Please provide valid credit card number";
                return(View("FailureView"));
            }
        }
        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());
        }