コード例 #1
0
ファイル: PaypalController.cs プロジェクト: Pro20/TestGit
        //Paypal payment
        public ActionResult PaymentWithPaypal(List <string> data)
        {
            OrderId = DateTime.Now.ToString("ddmmyyyyhhmmss");

            //getting the apiContext as earlier
            APIContext apiContext = PaymentConfiguration.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.Scheme + "://" + Request.Url.Authority +
                                     "/Paypal/PaymentWithPayPal?";

                    //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(apiContext, baseURI + "guid=" + guid);
                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid, data);

                    //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(Json(new { data = paypalRedirectUrl }, JsonRequestBehavior.AllowGet));
                }
                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 orderid         = Request.Params["OrionOrderId"];
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(RedirectToAction("FailureView", "Paypal", new { area = "Shopping" }));
                    }

                    var    payment      = Payment.Get(apiContext, Session[guid].ToString());
                    string city         = payment.transactions[0].item_list.shipping_address.city;
                    string postalcode   = payment.transactions[0].item_list.shipping_address.postal_code;
                    string countryCode  = payment.transactions[0].item_list.shipping_address.country_code;
                    string recipentName = payment.transactions[0].item_list.shipping_address.recipient_name;
                    string state        = payment.transactions[0].item_list.shipping_address.state;
                    string street       = payment.transactions[0].item_list.shipping_address.line1;

                    StringBuilder sb = new StringBuilder();
                    sb.Append("Recipient name: ");
                    sb.Append(recipentName);
                    sb.Append(Environment.NewLine);
                    sb.Append("Address: ");
                    sb.Append(street);
                    sb.Append(Environment.NewLine);
                    sb.Append("City: ");
                    sb.Append(city);
                    sb.Append(Environment.NewLine);
                    sb.Append("State: ");
                    sb.Append(state);
                    sb.Append(Environment.NewLine);
                    sb.Append("Postal code: ");
                    sb.Append(postalcode);
                    sb.Append(Environment.NewLine);
                    sb.Append("Country code: ");
                    sb.Append(countryCode);
                    sb.Append(Environment.NewLine);
                    string ShippingAddress = sb.ToString();

                    //update order after recievining parameters from paypal
                    db_AirborneEntities OEM = new db_AirborneEntities();
                    var updatePayment       = OEM.Order_Payments.Where(x => x.OrderID != null && x.OrderID == orderid).FirstOrDefault();
                    if (updatePayment != null)
                    {
                        TempData["Status"]            = updatePayment.OrderID;
                        updatePayment.ShippingAddress = ShippingAddress;
                        updatePayment.RecipientName   = recipentName ?? "";
                        updatePayment.Street          = street ?? "";
                        updatePayment.City            = city ?? "";
                        updatePayment.State           = state ?? "";
                        updatePayment.PostalCode      = postalcode ?? "";
                        updatePayment.CountryCode     = countryCode ?? "";

                        updatePayment.Status              = "1";
                        updatePayment.ModifiedDate        = DateTime.UtcNow;
                        updatePayment.PaypalTransactionID = Convert.ToString(Session[guid]);
                        OEM.SaveChanges();
                    }

                    var emailStatus = HtmlHelpersUtility.SendOrderEmail(updatePayment.OrderID, updatePayment.Email);
                }
            }
            catch (Exception ex)
            {
                log4net.ILog logger = log4net.LogManager.GetLogger("Errorlog");
                logger.Error("Error" + ex.Message);
                //Logger.log("Error" + ex.Message);
                return(RedirectToAction("FailureView", "Paypal", new { area = "Shopping" }));
            }
            return(RedirectToAction("SuccessView", "Paypal", new { area = "Shopping" }));
        }
コード例 #2
0
        //public static Customer temp;
        ////// GET: Paypal



        //tạm tắt
        public ActionResult PaymentWithPaypal(CustomerModel user)
        {
            //getting the apiContext as earlier
            //CustomerModel temp = new CustomerModel();
            //if (user.shipName != null)
            //{
            //    temp.shipName = user.shipName;
            //    temp.Phone = user.Phone;
            //    temp.Email = user.Email;
            //    temp.Address = user.Address;
            //    temp.DistrictID = user.DistrictID;
            //    temp.ProvinceID = user.ProvinceID;
            //    temp.PrecinctID = user.PrecinctID;
            //    CommonConstants.CustomerTemp = temp;
            //}
            APIContext apiContext = PaymentConfiguration.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.Scheme + "://" + Request.Url.Authority
                                     +
                                     "/Payment/PaymentWithPayPal?";
                    //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(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(View("FailureView"));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log("Error" + ex.Message);
                return(View("FailureView"));
            }

            //Khoi tao hoa don
            var order = new KetnoiCSDL.EF.Order();

            //Kiểm tra xem khách hàng có đăng nhập hay không
            var user_temp = (BunyStore.Common.UserLogin)Session[BunyStore.Common.CommonConstants.USER_SESSION];

            if (user_temp != null)
            {
                //Nếu có đăng nhập thì gán vào UserID
                order.CustomerID = user_temp.UserID;
            }

            // tiến hành tạo bill
            order.CreatedDate  = DateTime.Now;
            order.ShipAddress  = Common.CommonConstants.CustomerTemp.Address;
            order.ShipMobile   = Common.CommonConstants.CustomerTemp.Phone;
            order.ShipName     = Common.CommonConstants.CustomerTemp.shipName;
            order.ShipEmail    = Common.CommonConstants.CustomerTemp.Email;
            order.ShipPrecinct = Common.CommonConstants.CustomerTemp.PrecinctID;
            order.ShipProvince = Common.CommonConstants.CustomerTemp.ProvinceID;
            order.ShipDistrict = Common.CommonConstants.CustomerTemp.DistrictID;
            order.Status       = "Chờ xử lý";
            order.PaymentForms = "Paypal";
            try
            {
                var id = new OrderDao().Insert(order);

                var     cart      = (List <CartItem>)Session[CartSession];
                var     detailDao = new KetnoiCSDL.DAO.OrderDetailDao();
                decimal total     = 0;
                foreach (var item in cart)
                {
                    // Tạo mới hóa đơn vào database
                    var orderDetail = new OrderDetail();
                    orderDetail.ProductID = item.Product.ID;
                    orderDetail.OrderID   = id;
                    orderDetail.Price     = item.Product.Price;
                    orderDetail.Quantity  = item.Quantity;
                    detailDao.Insert(orderDetail);


                    //cập nhật số lượng bán
                    Product Update_product = db.Products.Where(p => p.ID == item.Product.ID).FirstOrDefault();

                    // chắc chắn rằng không rỗng
                    if (Update_product != null)
                    {
                        //vì trong database set mặc định là null nên không thể cộng được mà phải thêm 1 phần if để kiểm tra null hay có giá trị
                        if (Update_product.BoughtCount == null)
                        {
                            Update_product.BoughtCount = int.Parse(item.Quantity.ToString());
                        }
                        else
                        {
                            Update_product.BoughtCount += item.Quantity;
                        }
                        db.Products.AddOrUpdate(Update_product);
                        db.SaveChanges();
                        var a = Update_product.BoughtCount;
                    }
                    //db.SaveChanges();
                    Session[CartSession] = null;
                }
                Common.CommonConstants.CustomerTemp = null;
            }
            catch (Exception ex)
            {
                //ghi log
                return(Redirect("/loi-thanh-toan"));
            }

            return(RedirectToAction("Success", "Cart"));
        }