Example #1
0
 public PaymentDto(Payment payment)
 {
     _PaymentID = payment.ID;
     _BookingID = payment.BookingID;
     _PaymentTypeId = payment.PaymentTypeId;
     _ResponseMessage = payment.ResponseMessage;
 }
        public ActionResult SubmitPayment(int id, double hours)
        {
            if (Request.HttpMethod == "POST")
            {
              Appointment app = svc.getAppointmentById(id);
              Payment p = new Payment();
              p.doctor = app.doctor;
              p.type = "appointment";
              p.hours = hours;
              p.pay_rate = 10;
              p.for_text = app.patient;
              p.pay_date = DateTime.Now;

              PaymentProviderService paysvc = new PaymentProviderService();
              paysvc.makePayment(p);

              Bill b = new Bill();
              b.patient = app.patient;
              b.bill_total = p.pay_rate * p.hours;
              b.for_text = "appointment: " + p.doctor;
              b.bill_date = DateTime.Now;

              BillingProviderService billsvc = new BillingProviderService();
              billsvc.addBill(b);

              svc.cancelAppointment(id, false);
            }
            return RedirectToAction("Index");
        }
Example #3
0
        // <summary>
        /// 确认提交方法
        /// </summary>
        public void button_ok()
        {
            if (this.TxtDiscount.Text != null)
            {
                string price_fixed = double.Parse(this.TxtDiscount.Text).ToString("0.00");
                Member mb = new Member();
                mb = (Member)this.Owner;
                mb.KeyPreview = true;
                mb.panelChildren.Controls.Remove(this);
                mb.panelInfor.Visible = true;
                mb.lbTitle.Text = "支付信息";

                if (PassValue.payments.Count != 0 && PassValue.payments.Where(payment => payment.method == "other").FirstOrDefault() != null)
                {
                    mb.lbReceiveActual.Text = (mb.Price_Recive + double.Parse(price_fixed) - double.Parse(PassValue.payments.Where(payment => payment.method == "other").FirstOrDefault().amount)).ToString("0.00");
                    PassValue.payments.Remove(PassValue.payments.Where(payment => payment.method == "other").FirstOrDefault());
                }
                else
                {
                    mb.lbReceiveActual.Text = (mb.Price_Recive + double.Parse(price_fixed)).ToString("0.00");
                }

                //银联卡支付
                Payment pm = new Payment();
                pm.amount = double.Parse(this.TxtDiscount.Text).ToString("0.00");
                pm.method = "other";
                Reasons rs = new Reasons();
                rs.description = this.lbReasons.Text;
                rs.id = reasonid[0];
                pm.reason = rs;
                PassValue.payments.Add(pm);
                mb.panelChildren.Visible = true;
                Form_Esc();
            }
        }
Example #4
0
        // <summary>
        /// 确认提交方法
        /// </summary>
        public void button_ok()
        {
            if (!string.IsNullOrEmpty(this.TxtDiscount.Text))
            {
                string price_fixed = double.Parse(this.TxtDiscount.Text).ToString("0.00");
                Member mb = new Member();
                mb = (Member)this.Owner;
                mb.KeyPreview = true;
                mb.panelChildren.Controls.Remove(this);
                mb.panelInfor.Visible = true;
                mb.lbTitle.Text = "支付信息";
                if (PassValue.payments.Count != 0 && PassValue.payments.Where(payment => payment.method == "cash").FirstOrDefault() != null)
                {
                    mb.lbReceiveActual.Text = (mb.Price_Recive - double.Parse(PassValue.payments.Where(payment => payment.method == "cash").FirstOrDefault().amount) + double.Parse(price_fixed)).ToString("0.00");
                    PassValue.payments.Remove(PassValue.payments.Where(payment => payment.method == "cash").FirstOrDefault());
                }
                //现金支付
                Payment pm = new Payment();
                if (double.Parse(this.TxtDiscount.Text) <= double.Parse(this.lbReceiveShould.Text))
                {
                    pm.amount = this.TxtDiscount.Text;
                }
                else
                {
                    pm.amount = this.lbReceiveShould.Text;
                }
                pm.method = "cash";
                PassValue.payments.Add(pm);

                mb.lbReceiveActual.Text = (mb.Price_Recive + double.Parse(pm.amount)).ToString("0.00");
                mb.panelChildren.Visible = true;
                Form_Esc();
            }
        }
Example #5
0
        public void PaymentCreate()
        {
            var liqpayConnId = "111000064";
            var payment = new Payment
            {
                Amount = 13,
                Currency = "RUB",
                Connection = liqpayConnId,
            };
            payment.Params["description"] = "yo, liqpay";
            Assert.AreEqual(0, payment.AmountPaid);
            Assert.AreEqual(0, payment.AmountRefunded);
            Assert.False(payment.Paid);
            Assert.False(payment.Refunded);
            Assert.False(payment.Cancelled);
            Assert.True(string.IsNullOrEmpty(payment.Id));
            payment.Save();
            Assert.False(string.IsNullOrEmpty(payment.Id));

            var payment2 = Payment.Get(payment.Id);
            Assert.AreEqual(13, payment2.Amount);
            Assert.AreEqual("RUB", payment2.Currency);
            Assert.AreEqual(liqpayConnId, payment2.Connection);
            Assert.AreEqual("yo, liqpay", payment2.Params["description"].ToString());
            Assert.That(payment2.Created, Is.EqualTo(DateTime.UtcNow).Within(5).Minutes);
            Assert.That(payment2.Modified, Is.EqualTo(DateTime.UtcNow).Within(5).Minutes);
            Assert.True(payment2.PaymentUrl.Contains("unipag"));
            Assert.AreEqual(payment.ToString(), payment2.ToString());
        }
        public void UpdatePaymentTest()
        {
            Payment rec = new Payment { ClientId = ClientId, Amount = 0.01, Type = "Check" };

            PaymentIdentity id = Service.Create(new PaymentRequest { Payment = rec });

            try
            {
                rec = Service.Get(id).Payment;
                Assert.AreEqual(ClientId, rec.ClientId);

                Service.Update(
                    new PaymentUpdateRequest
                        {
                            Payment =
                                new PaymentUpdate(rec)
                                    {
                                        Notes = "Nunit update test",
                                    }
                        });

                Payment fetched = Service.Get(id).Payment;
                Assert.AreEqual(ClientId, rec.ClientId);
                Assert.AreEqual("Nunit update test", fetched.Notes);
            }
            finally
            {
                Service.Delete(id);
            }
        }
Example #7
0
        static void Main()
        {
            var payment1 = new Payment { AmountToPay = 25.0m, CardNumber = "1234123412341234" };
            var payment2 = new Payment { AmountToPay = 5.0m, CardNumber = "1234123412341234" };
            var payment3 = new Payment { AmountToPay = 2.0m, CardNumber = "1234123412341234" };
            var payment4 = new Payment { AmountToPay = 17.0m, CardNumber = "1234123412341234" };
            var payment5 = new Payment { AmountToPay = 300.0m, CardNumber = "1234123412341234" };
            var payment6 = new Payment { AmountToPay = 350.0m, CardNumber = "1234123412341234" };
            var payment7 = new Payment { AmountToPay = 295.0m, CardNumber = "1234123412341234" };
            var payment8 = new Payment { AmountToPay = 5625.0m, CardNumber = "1234123412341234" };
            var payment9 = new Payment { AmountToPay = 5.0m, CardNumber = "1234123412341234" };
            var payment10 = new Payment { AmountToPay = 12.0m, CardNumber = "1234123412341234" };

            CreateConnection();

            SendMessage(payment1);
            SendMessage(payment2);
            SendMessage(payment3);
            SendMessage(payment4);
            SendMessage(payment5);
            SendMessage(payment6);
            SendMessage(payment7);
            SendMessage(payment8);
            SendMessage(payment9);
            SendMessage(payment10);

            Console.ReadLine();
        }
Example #8
0
        public static IList<Payment> GetPayments()
        {
            IList<Payment> paymentList = new List<Payment>();

            using (ManagementEntity context = new ManagementEntity())
            {
                try
                {
                    var queryPayments = from p in context.Payments select p;

                    foreach (var item in queryPayments)
                    {
                        Payment payment = new Payment();
                        payment.ID = item.Id;
                        payment.TicketID = item.TicketId;
                        payment.OrderID = item.OrderId;
                        payment.CustomerID = item.CustomerId;
                        payment.PaymentStatus = (e_PaymentStatus)item.Type;
                        payment.Amount = item.Amount;
                        payment.Date = (int)item.Date.ToBinary();
                        payment.Destination = item.Destination;

                        paymentList.Add(payment);
                    }
                }
                catch (InvalidOperationException ex)
                {
                    throw ex;
                }
            }

            return paymentList;
        }
Example #9
0
        public static void CreatePayment(Payment newPayment)
        {
            using (ManagementEntity context = new ManagementEntity())
            {
                try
                {
                    Models.Management.Payment payment = new Models.Management.Payment
                    {
                        TicketId = newPayment.TicketID,
                        OrderId = newPayment.OrderID,
                        Type = (int)e_PaymentStatus.NotPaid,//default is not paid
                        Amount = newPayment.Amount,
                        Date = DateTime.UtcNow,
                        Destination = newPayment.Destination
                    };

                    context.Payments.AddObject(payment);
                    context.SaveChanges();

                }
                catch (InvalidOperationException ex)
                {
                    throw ex;
                }
            }
        }
Example #10
0
        public static void Main()
        {            
            var payment1 = new Payment { AmountToPay = 25.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment2 = new Payment { AmountToPay = 5.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment3 = new Payment { AmountToPay = 2.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment4 = new Payment { AmountToPay = 17.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment5 = new Payment { AmountToPay = 300.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment6 = new Payment { AmountToPay = 350.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment7 = new Payment { AmountToPay = 295.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment8 = new Payment { AmountToPay = 5625.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment9 = new Payment { AmountToPay = 5.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
            var payment10 = new Payment { AmountToPay = 12.0m, CardNumber = "1234123412341234", Name = "Mr S Haunts" };
                        
            CreateQueue();            
                        
            SendMessage(payment1);
            SendMessage(payment2);
            SendMessage(payment3);
            SendMessage(payment4);
            SendMessage(payment5);
            SendMessage(payment6);
            SendMessage(payment7);
            SendMessage(payment8);
            SendMessage(payment9);
            SendMessage(payment10);
                                 
            Recieve();

            Console.ReadLine();
        }
Example #11
0
        static void Main(string[] args)
        {
            Payment customer1FirstPayment = new Payment("Laptop Lenovo", 1234.50m);
            Payment customer1SecondPayment = new Payment("Laptop HP", 2345.55m);
            List<Payment> customer1ListPayment= new List<Payment>() { customer1FirstPayment, customer1SecondPayment };
            Payment customer2FirstPayment = new Payment("Laptop Dell", 1234.50m);
            List<Payment> customer2ListPayment = new List<Payment>() { customer1FirstPayment, customer1SecondPayment };

            Payment custome2SecondPayment = new Payment("Laptop Asus", 2345.55m);
            Customer customer1 = new Customer("Ivancho", "Kurtev", "Ivanov", "8767890987", "sdfdfsdf sdf sf as", "+3598 8777 7819", "*****@*****.**", customer2ListPayment, CustomerType.Regular);

            Customer customer3 = new Customer("Ivelina", "Hristov", "Nikolova", "8767890987", "sdfdfsdf sdf sf as", "+3598 8777 7819", "*****@*****.**", customer2ListPayment, CustomerType.Regular);
            Customer customer2 = new Customer("Ivancho", "Kurtev", "Ivanov", "8767890987", "sdfdfsdf sdf sf as", "+3598 8777 7819", "*****@*****.**", customer2ListPayment, CustomerType.Regular);

            Console.WriteLine("customer2 == customer1 - {0}",customer2 == customer1);
            Console.WriteLine("customer2 != customer1 - {0}", customer2 != customer1);
            Console.WriteLine("customer2.Equals(customer1) - {0}\n", customer2.Equals(customer1));

            Console.WriteLine("customer2 == customer3 - {0}", customer2 == customer3);
            Console.WriteLine("customer2 != customer3 - {0}", customer2 != customer3);
            Console.WriteLine("customer2.Equals(customer3) - {0}\n", customer2.Equals(customer3));
            var customer4 = (Customer)customer2.Clone();
            customer4.FirstName = "Petko";

            Console.WriteLine(customer2);
            Console.WriteLine("--------------------------------------------------------------------------");
            Console.WriteLine(customer4);
            Console.WriteLine(customer1.CompareTo(customer4));
        }
Example #12
0
 ///<summary>Inserts one Payment into the database.  Returns the new priKey.</summary>
 internal static long Insert(Payment payment)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         payment.PayNum=DbHelper.GetNextOracleKey("payment","PayNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(payment,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     payment.PayNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(payment,false);
     }
 }
    public object Clone()
    {
        Payment payment = new Payment();
        payment.ProductName = this.ProductName;
        payment.Price = this.Price;

        return payment;
    }
 public void a_AddValid()
 {
     var response = client.AddPayment(entity);
     WasSuccessfulTest(response);
     Assert.True(response.Data.id > 0);
     Assert.True(response.Data.data_saved.id == response.Data.id);
     entity = response.Data.data_saved;
 }
Example #15
0
 public Order(Guid _UserId, Dictionary<Guid, int> _Items, Payment _PayMethod, Delivery _Delivery)
     : base(_UserId)
 {
     PayMethod = _PayMethod;
     Delivery = _Delivery;
     Status = 0;
     SetTime = DateTime.Now;
     Items = _Items;
 }
        protected override void ProcessPayment(Payment payment)
        {
            var command = InitCommand(new AddPaymentNoteLineItemCommand());
            command.Amount = payment.Amount;
            command.PaymentModeId = 0; //Always zero (copied from existing app)
            command.LineItemSequenceNo = Commands.Count + 1;

            Commands.Add(command);
        }
Example #17
0
    public void notifyTest()
    {
        // Enable this if you do not want to use Annotations
        // service.registerNotifierListener();

        Payment payment = new Payment();
        payment.Status=ETransactionStatus.CANCELLED;

        proxy.Write(payment);
    }
Example #18
0
    public void pollingTest()
    {
        // Enable this if you do not want to use Annotations
        // service.registerPollingListener();

        Payment payment = new Payment();
        payment.Status=ETransactionStatus.AUDITED;

        proxy.Write(payment);
    }
Example #19
0
        private void btnSure_Click(object sender, EventArgs e)
        {
            if (this.cboPayment.SelectedIndex < 0)
            {
                MessageBox.Show("請先選擇收費模組!");
                return;
            }

            if (this.cboSemester.Text == "")
            {
                MessageBox.Show("請先選擇學期別!");
                return;
            }

            if (this.txtPayment.Text == "")
            {
                MessageBox.Show("請先填入收費名稱!");
                return;
            }

            //讀取系統中所有的收費模組(日期設定)。
            List<Payment> pays = Payment.GetAll();
            if (pays.Count > 0)
            {
                foreach (Payment pay in pays)
                    if (pay.SchoolYear == this.intSchoolYear.Value && pay.Semester == (this.cboSemester.Text == "上學期" ? 1 : 2))
                    {
                        if (this.txtPayment.Text == pay.Name)
                        {
                            MessageBox.Show("此學期此收費名稱已存在!");
                            return;
                        }
                    }
            }

            //新增收費,這個收費是每次收費都要新增一個,例如:第一季車費、第二季車費....。
            Payment BusPayment = new Payment(txtPayment.Text, intSchoolYear.Value, cboSemester.Text == "上學期" ? 1 : 2);

            //設定收費的預設繳款到期日,如果在計算收費時沒有額外指定,就會使用這裡的設定。
            //DefaultExpiration 是關鍵字,程式會抓這個 Key,所以是固定不變的。
            //demoPayment.Extensions.Add(DateTime.Parse(((Payment)cboPayment.SelectedItem).Extensions["DefaultExpiration"]));
            BusPayment.Extensions.Add("DefaultExpiration", dtDueDate.Value.ToShortDateString());

            //BarcodeConfiguration 屬性是 Payment 的「條碼計算設定」,所以是一定要指定的
            //在畫面上就是「銀行設定」裡面的項目,可以透過 BarcodeConfiguration 類別列出與取得
            //使用者在銀行設定裡的所有設定項目,通常可能設計成讓使用者可以選擇要用那個設定。
            //demoPayment.BarcodeConfiguration = GetBarcodeConfiguration();
            //demoPayment.BarcodeConfiguration = ((BarcodeConfiguration)cboPayment.SelectedItem).BarcodeConfiguration;
            BusPayment.BarcodeConfiguration = cboPayment.SelectedItem as BarcodeConfiguration;

            //將此收費新增到資料庫中,回傳的 Payment 物件會包含新增後的 UID。
            BusPayment = Payment.Insert(BusPayment);

            this.Close();
        }
Example #20
0
    /// <summary>
    /// Constructs a Purchase object which contains information about a specific purchase.
    /// 
    /// Contains public member ToUpload which constructs the string appropriate to send to 
    /// the webpage to display.
    /// </summary>
    /// <param name="payment">the Payment object for this purchase</param>
    /// <param name="contact">the Contact object for this purchase</param>
    public Purchase(Payment payment, Contact contact)
    {
        this.Payment = payment;
        this.Contact = contact;

        CompanyName = Contact.Name;
        Date = Payment.Date;
        Amount = Payment.Amount;
        Address = getAddressString();
        ContactName = Contact.Name;
    }
        public PaymentListVM CreatePaymentListVM(Payment item)
        {
            return new PaymentListVM
            {
                Id = item.Id,

                Amount = item.Amount,
                PaymentType = item.PaymentType,
                PaymentDate = item.PaymentDate,
            };
        }
Example #22
0
    protected void btnOrder_Click(object sender, EventArgs e)
    {
        // validate payment info
        if (ValidatePayment())
        {
            // get the cart
            CartsComponent cComp = new CartsComponent();
            Cart c = cComp.GetCartByUserName(Request.Cookies["userName"].Value);

            // get the user
            UsersComponent users = new UsersComponent();
            BLL.User u = users.GetUserByName(Request.Cookies["userName"].Value);

            // get the catalog
            CatalogComponent catalog = new CatalogComponent();
            Item it = catalog.GetItemById(c.CatalogId);

            // create a payment
            PaymentsComponent pmts = new PaymentsComponent();
            Payment pmt = new Payment();
            pmt.CardholderName = txtName.Text;
            pmt.CardNumber = txtNumber.Text;
            pmt.CardType = ddlType.SelectedValue;
            // make expiration date
            int month = Convert.ToInt32(ddlMonth.SelectedValue);
            int year = Convert.ToInt32(ddlYear.SelectedValue);
            int day = DateTime.DaysInMonth(year, month);
            DateTime dt = Convert.ToDateTime(month + "-" + day + "-" + year);
            pmt.CardExpiration = dt;
            // save the payment
            int pmtId = pmts.InsertPayment(pmt);

            // create the order
            OrdersComponent orders = new OrdersComponent();
            Order o = new Order();
            o.CatalogId = c.CatalogId;
            o.ClientId = u.ClientId;
            o.Details = c.Details;
            o.PaymentId = pmtId;
            o.Price = it.Price;
            o.OrderDate = DateTime.Now;
            // save the order
            int orderId = orders.InsertOrder(o);

            // delete the cart
            cComp.DeleteCart(c);

            // display results to user
            lblOrderNum.Text = Convert.ToString(orderId);
            pnlCC.Visible = false;
            pnlSuccess.Visible = true;
            pnlTopLabels.Visible = false;
        }
    }
Example #23
0
        private IEnumerable<Payment> GetDummyPayments()
        {
            List<Payment> payments = new List<Payment> ();
            for (int n = 0; n < 2; n++) {
                var payment = new Payment (Profile.Current, Profile.Current, 200f, "DKK", DateTime.Now);
                payment.Expenses.AddRange (GetDummyExpenses (ExpenseStatus.Paid));
                payments.Add (payment);
            }

            return payments;
        }
Example #24
0
        public ActionResult RedirectFromPayPal(FormCollection collection)
        {
            Payment payment = new Payment();

            payment.Address_City = Request.Form["Address_City"].ToString();
            payment.Address_Country = Request.Form["Address_Country"].ToString();
            payment.Address_Country_Code = Request.Form["Address_Country_Code"].ToString();

            if (!string.IsNullOrEmpty(Request.Form["Contact_Phone"]))
            {
                payment.Contact_Phone = Request.Form["Contact_Phone"].ToString();
            }
            else
            {
                payment.Contact_Phone = string.Empty;
            }

            if (!string.IsNullOrEmpty(Request.Form["First_Name"]))
            {
                payment.First_Name = Request.Form["First_Name"].ToString();
            }
            else
            {
                payment.First_Name = string.Empty;
            }

            if (!string.IsNullOrEmpty(Request.Form["Last_Name"]))
            {
                payment.Last_Name = Request.Form["Last_Name"].ToString();
            }
            else
            {
                payment.Last_Name = string.Empty;
            }

            if (!string.IsNullOrEmpty(Request.Form["Payer_Business_Name"]))
            {
                payment.Payer_Business_Name = Request.Form["Payer_Business_Name"].ToString();
            }
            else
            {
                payment.Payer_Business_Name = string.Empty;
            }

            payment.Payer_Email = Request.Form["Payer_Email"].ToString();
            payment.Payer_Id = Request.Form["Payer_Id"].ToString();
            payment.Payment_Status = Request.Form["Payment_Status"].ToString();
            payment.Tax = Convert.ToDecimal(Request.Form["Tax"].ToString());
            payment.Mc_Gross = Convert.ToDecimal(Request.Form["Mc_Gross"]);
            payment.Txn_Id = Request.Form["Txn_Id"].ToString();

            return View(payment);
        }
Example #25
0
 protected Order CreateEmptyOrder(PwintyApi api, Payment paymentOption = Payment.InvoiceMe, string countryCode = "GB")
 {
     var result = api.Order.Create(new CreateOrderRequest()
     {
         countryCode = countryCode,
         payment = paymentOption,
         qualityLevel = QualityLevel.PRO
     });
     Assert.IsTrue(result.id > 0);
     Assert.AreEqual(result.countryCode, countryCode);
     return result;
 }
        protected override void ProcessPayment(Payment payment)
        {
            var command = InitCommand(new AddReceiptLineItemCommand());
            command.Value = payment.Amount;
            command.PaymentTypeId = (int) PaymentNoteType.Availabe;
            command.LineItemId = Guid.NewGuid();
            command.LineItemType = 2; //;
            command.Description = payment.PaymentReference;
            command.LineItemSequenceNo = Commands.Count + 1;

            Commands.Add(command);
        }
        /// <inheritdoc/>
        public override bool ProcessPayment(Payment payment, ref string message)
        {
            var creditCardPayment = (CreditCardPayment)payment;

            if (!creditCardPayment.CreditCardNumber.EndsWith("4"))
            {
                message = "Invalid credit card number.";
                return false;
            }

            return true;
        }
        /// <summary>
        /// Cancels the payment reservation
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="paymentArgs">The payment args.</param>
        /// <param name="reservationTicket">The reservation ticket.</param>
        public void CancelReservation([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs, [NotNull] ReservationTicket reservationTicket)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
              Assert.ArgumentNotNull(paymentArgs, "paymentArgs");
              Assert.ArgumentNotNull(reservationTicket, "reservationTicket");

              ITransactionData transactionDataProvider = Context.Entity.Resolve<ITransactionData>();

              Payment payment = new Payment();
              int pbsResponse = 0;
              bool deleteResult = payment.delete(int.Parse(paymentSystem.Username), long.Parse(reservationTicket.TransactionNumber), string.Empty, paymentSystem.Password, ref pbsResponse);
              transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, deleteResult ? PaymentConstants.CancelSuccess : string.Format("pbsResponse={0}", pbsResponse));
        }
Example #29
0
        /// <summary>
        ///获取某个指定还款档期的还款信息
        /// </summary>
        /// <param name="paymentNumber">指定要计算的还款档期序号</param>
        /// <param name="rate">利率</param>
        /// <param name="paymentCount">还款总期数</param>
        /// <param name="totalAmount">贷款总费用</param>
        /// <param name="dueDate">还款在每期的开始还是结尾时间,缺省为每期的结尾时间(大部分商业都是用结尾时间)</param>
        /// <returns>每期还款的额度</returns>
        /// <remarks>参数rate和参数paymentCount是呼应的。即如果paymentCount按照月计数,那么rate就必须指定为月利率;
        ///    如果paymentCount按照年计数,那么rate就必须指定为年利率。</remarks>
        public static Payment GetPayment(double rate, double totalAmount, int paymentCount, int paymentNumber, DueDate dueDate = DueDate.EndOfPeriod)
        {
            double amount = -Financial.Pmt(rate, paymentCount, totalAmount, 0, dueDate);
            double principal = -Financial.PPmt(rate, paymentNumber, paymentCount, totalAmount, 0, dueDate);
            double interest = amount - principal;

            Payment payment = new Payment();
            payment.Number = paymentNumber;
            payment.Interest = interest;
            payment.Principal = principal;

            return payment;
        }
Example #30
0
        /// <summary>
        ///获取某个指定还款档期的还款信息
        /// </summary>
        /// <param name="paymentNumber">指定要计算的还款档期序号</param>
        /// <param name="rate">利率</param>
        /// <param name="paymentCount">还款总期数</param>
        /// <param name="totalAmount">贷款总费用</param>
        /// <param name="dueDate">还款在每期的开始还是结尾时间,缺省为每期的结尾时间(大部分商业都是用结尾时间)</param>
        /// <returns>每期还款的额度</returns>
        /// <remarks>参数rate和参数paymentCount是呼应的。即如果paymentCount按照月计数,那么rate就必须指定为月利率;
        ///    如果paymentCount按照年计数,那么rate就必须指定为年利率。</remarks>
        public static Payment GetPayment(double rate, double totalAmount, int paymentCount, int paymentNumber, DueDate dueDate = DueDate.EndOfPeriod)
        {
            double principal = totalAmount / paymentCount;
            double remainAmountPercent = 1 - ((double)paymentNumber - 1) / (double)paymentCount;
            double interest = totalAmount * remainAmountPercent * rate;

            Payment payment = new Payment();
            payment.Number = paymentNumber;
            payment.Interest = interest;
            payment.Principal = principal;

            return payment;
        }
        public static void GetPaymentById()
        {
            Payment payment = Helper.TestGetPaymentById();

            Assert.AreNotSame(null, payment);
        }
 public IActionResult Post([FromBody] Payment item)
 {
     _repository.Add(item);
     return(Ok("New Payment Added.."));
 }
        public Payment GetPayment(int id)
        {
            Payment payment = GetasyncPayment(id).Result;

            return(payment);
        }
Example #34
0
 public bool  addPaymentDetails(Payment payment)
 {
     return(true);
 }
Example #35
0
 public Order(Payment payment, Shipment shipment)
 {
     Payment  = payment;
     Shipment = shipment;
 }
Example #36
0
 private static void AssertPaymentFields(string dateString, string merchantName, decimal fee, Payment payment)
 {
     Assert.Equal(Convert.ToDateTime(dateString), payment.Date);
     Assert.Equal(merchantName, payment.MerchantName);
     Assert.Equal(fee, payment.Amount);
 }
 private String serialize(Payment payment)
 {
     return(JsonConvert.SerializeObject(payment, Formatting.Indented));
 }
Example #38
0
        public async Task <string> PayRoom(OrderRequestModel model)
        {
            try
            {
                if (model.ReservationId == null)
                {
                    throw new Exception("operation is impossible without Id");
                }
                var userId = _headerService.GetUserId();
                if (userId == null)
                {
                    throw new Exception("operation is impossible without Id");
                }
                var verify = new VerificationReservationId()
                {
                    ReservationId = model.ReservationId.ToString(),
                    UserId        = userId.ToString()
                };

                var reservation = await _publisher.VerifyReservationId(verify);

                var receiveReservation = JsonConvert.DeserializeObject <ReceiveReservation>(reservation);


                var amountPaid = receiveReservation.AmountPaid.ToString();


                var pay = new PaymentModel()
                {
                    AmountPaid = amountPaid, UserId = userId.ToString()
                };

                var message = await _publisher.PayRoom(pay);

                var userSearchError = "User was not found";
                var errMes          = "Sorry, but it appears your account has insufficient funds";


                if (message == userSearchError)
                {
                    throw new Exception(message);
                }

                if (message == errMes)
                {
                    throw new Exception(message);
                }

                var dateOfPayment = DateTime.UtcNow;
                var newOrder      = new Order()
                {
                    Id               = Guid.NewGuid(),
                    UserId           = userId,
                    RoomId           = receiveReservation.RoomId,
                    ReservStartDate  = receiveReservation.ReservStartDate,
                    ReservFinishDate = receiveReservation.ReservFinishedDate,
                    DateOfPayment    = dateOfPayment,
                    AmountPaid       = receiveReservation.AmountPaid,
                };

                await _orderRepository.AddOrderAsync(newOrder);

                var payment = new Payment()
                {
                    ReservationId = model.ReservationId.ToString()
                };

                await _publisher.PublishPayment(payment);

                return(message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "faild orderService");
                throw;
            }
        }
Example #39
0
 public async Task <IActionResult> PostPayment([FromBody] Payment payment)
 {
     payments.Add(payment);
     return(Ok());
 }
Example #40
0
 public IResult Update(Payment payment)
 {
     _paymentDal.Update(payment);
     return(new SuccessResult());
 }
Example #41
0
        public static List <ChangeRecord> FromDTO(this Member member, IEnumerable <PaymentDTO> list, string userName)
        {
            var changes = new List <ChangeRecord>();

            if (list != null && list.Count() > 0)
            {
                var existingPayments = member.Payments.Where(x => list.Select(l => l.Id).Contains(x.Id));
                var deletedPayments  = member.Payments.Where(x => !list.Select(l => l.Id).Contains(x.Id));
                var newPayments      = list.Where(x => !member.Payments.Select(p => p.Id).Contains(x.Id));
                foreach (var item in deletedPayments)
                {
                    member.Payments.Remove(item);
                    changes.Add(new ChangeRecord
                    {
                        Time        = DateTimeOffset.Now,
                        By          = userName,
                        Description = $"payment received on {item.ReceivedDate.Format()}, amount {item.AmountReceived.Format()} deleted"
                    });
                }
                foreach (var item in newPayments)
                {
                    var np = new Payment
                    {
                        Member = member,
                        //DueDate = item.DueDate,
                        //AmountDue = item.AmountDue,
                        SubscriptionYear = item.SubscriptionYear,
                        ReceivedDate     = item.ReceivedDate,
                        AmountReceived   = item.AmountReceived,
                        Type             = item.Type,
                        IsPaid           = item.IsPaid,
                    };
                    foreach (var n in item.Notes)
                    {
                        var pn = new PaymentNote
                        {
                            Note = new Note {
                                CreatedOn = n.CreatedOn.StripTimeAndZone()
                            }
                        };
                        n.NoteLines.ToList().ForEach(x => pn.Note.NoteLines.Add(new NoteLine {
                            Index = x.Index, Line = x.Line
                        }));
                        np.PaymentNotes.Add(pn);
                    }
                    member.Payments.Add(np);
                    changes.Add(new ChangeRecord
                    {
                        Time = DateTimeOffset.Now,
                        By   = userName,
                        RecordForNewMember = true,
                        Description        = $"new payment added: Amount Received £{item.AmountReceived.Format()} for {item.SubscriptionYear}, received on {item.ReceivedDate.Format()}"
                    });
                }
                foreach (var item in existingPayments)
                {
                    var dto = list.Single(x => x.Id == item.Id);
                    changes.AddRange(item.FromDTO(dto, userName));
                }
            }
            return(changes);
        }
Example #42
0
 public IResult Delete(Payment payment)
 {
     _paymentDal.Delete(payment);
     return(new SuccessResult());
 }
Example #43
0
 //[SecuredOperation("payment.add")]
 public IResult Add(Payment payment)
 {
     _paymentDal.Add(payment);
     return(new SuccessResult(Messages.PaymentSuccessful));
 }
Example #44
0
 public bool TransactionAlreadyImported(Payment payment)
 {
     return(ContributionWithPayment(payment).Any());
 }
Example #45
0
        protected void DoListPaymentByTeacher(string teacherID, string searchStr, bool isNewSearch)
        {
            DBManager db;

            db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD, Config.DB_CHAR_ENC);
            db.Connect();

            listTeacher = Teacher.LoadListFromDB(db, " WHERE is_active=1 ORDER BY firstname ");

            if (teacherID == null)
            {
                return;
            }


            // get Page
            int pg = 1;

            if ((!isNewSearch) && (Request["pg"] != null))
            {
                pg = Int32.Parse(Request["pg"]);
            }

            string[,] bgclass = new string[, ] {
                { "class=\"spec\"", "class=\"td1\"", "class=\"td1_grey\"", "class=\"td1_red\"" }, { "class=\"specalt\"", "class=\"alt\"", "class=\"td1_grey\"", "class=\"td1_red\"" }
            };
            string grey = "class=\"thspec_grey\"";
            string red  = "class=\"thspec_red\"";

            listPayment = new List <Payment>();

            AppUser user = (AppUser)Session[SessionVar.USER];

            filterPayment = Request["filter_payment"];
            if (filterPayment == null)
            {
                filterPayment = "0";                        // by default
            }
            string whereSQL = " pm.course_id=c.course_id AND c.teacher_id=t.teacher_id AND c.room_id = r.room_id ";

            // only admin can view all payment
            if (!user.IsAdmin())
            {
                whereSQL = whereSQL + " AND r.branch_id=" + user._branchID;
            }
            // filter only payable courses
            if (filterPayment.Equals("0"))
            {
                whereSQL = whereSQL + " AND sum_max_payable<>sum_paid_cost ";
            }

            int numRec = db.QueryCount("SELECT Count(*) FROM payment pm, course c, teacher t, room r WHERE " + whereSQL);

            OdbcDataReader reader = db.Query("SELECT pm.course_id as course_id ,c.bts_course_id as bts_course_id ,c.course_name as course_name, t.paid_group_id as paid_group_id"
                                             + ", pm.sum_all_cost as sum_all_cost, pm.sum_max_payable as sum_max_payable, pm.sum_paid_cost as sum_paid_cost "
                                             + "FROM payment pm, course c, teacher t, room r WHERE "
                                             + whereSQL + " LIMIT " + Config.TBRECORD_PER_PAGE + " OFFSET " + (((pg - 1) * Config.TBRECORD_PER_PAGE)));
            int i = 0;

            while (reader.Read())
            {
                Payment payment = Payment.CreateForm(reader);

                string chbname = "course" + payment._courseID;

                int sumPayable = payment._sumMaxPayable - payment._sumPaidCost;
                int n          = 1;
                if (sumPayable == 0)
                {
                    n = 2;
                }
                else if (sumPayable < 0)
                {
                    n = 3;
                }

                string bgcolor = (sumPayable == 0) ? grey : red;

                outBuf.Append("<tr>");
                outBuf.Append("<th scope=\"row\" abbr=\"Model\" " + (sumPayable > 0 ? bgclass[i % 2, 0] : bgcolor) + ">" + payment._btsCourseID + "</th>");
                outBuf.Append("<td " + bgclass[i % 2, n] + " align=center ><input type=\"checkbox\" name=\"" + chbname + "\" id=\"" + chbname + "\" />" + "</td>");
                outBuf.Append("<td " + bgclass[i % 2, n] + "  ><a href=\"CourseManage.aspx?actPage=view&targetID=" + payment._courseID + "\" >" + payment._courseName + "</a></td>");
                outBuf.Append("<td " + bgclass[i % 2, n] + " align=center >" + PaidGroup.GetPaidGroupID(payment._paidGroupID) + "</td>");
                outBuf.Append("<td " + bgclass[i % 2, n] + " align=center ><b>" + StringUtil.Int2StrComma(payment._sumAllCost) + "</b></td>");
                outBuf.Append("<td " + bgclass[i % 2, n] + " align=center ><b><font color=blue>" + StringUtil.Int2StrComma(payment._sumMaxPayable) + "</font></b></td>");
                outBuf.Append("<td " + bgclass[i % 2, n] + " align=center ><b><font color=red>" + StringUtil.Int2StrComma(payment._sumPaidCost) + "</font></b></td>");
                outBuf.Append("<td " + bgclass[i % 2, n] + " align=center ><b><font color=green>" + StringUtil.Int2StrComma(sumPayable) + "</font></b></td>");

                /*                outBuf.Append("<td " + bgclass[i % 2, n] + "  align=center>"
                 + payment._lastPaidDate.ToString("dd/MM/yyyy HH:mm", ci) +  "&nbsp</td>");
                 */
                outBuf.Append("<td " + bgclass[i % 2, n] + "  align=center>&nbsp");
                outBuf.Append("<a href=\"javascript:setVal('actPage','view');setVal('targetID','" + payment._courseID + "');doSubmit()\"><img src=\"img/sys/view.gif\" border=0 alt=\"View detail\"></a>&nbsp");
                //                outBuf.Append("<a href=\"javascript:if (confirm('Delete this payment?')) { setVal('actPage','delete');setVal('targetID','" + payment._paymentID + "');doSubmit(); }\"><img src=\"img/sys/delete.gif\" border=0 alt=\"Delete\"></a>&nbsp");

                outBuf.Append("</td>");
                outBuf.Append("</tr>\n");

                i++;
            }
            db.Close();

            // calculate max page
            int maxpg = numRec / Config.TBRECORD_PER_PAGE;

            if (maxpg < 1)
            {
                maxpg = 1;
            }
            else if (numRec % Config.TBRECORD_PER_PAGE > 0)
            {
                maxpg++;
            }
            // Generate Page Navi HTML
            outBuf2.Append("<b>Page</b>  ");
            for (i = 1; i <= maxpg; i++)
            {
                if (i == pg)
                {
                    outBuf2.Append("<b>" + i + "</b> ");
                }
                else
                {
                    outBuf2.Append(String.Format("<a href=\"PaymentManage.aspx?pg={0}&filter_payment={1}&qsearch={1}\">{0}</a> ", i.ToString(), filterPayment, searchStr));
                }
            }

            //  <a href="#">1</a> <b>2</b> <a href="#">3</a> <a href="#">4</a>
        }
 public bool DeletePaymentRecord(Payment payment)
 {
     _db.Payments.Remove(payment);
     return(Save());
 }
Example #47
0
        protected void DoViewPayment(string courseID)
        {
            DBManager db = new MySQLDBManager(Config.DB_SERVER, Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD, Config.DB_CHAR_ENC);

            db.Connect();

            thePayment = new Payment();
            thePayment.LoadFromDB(db, " course_id=" + courseID);
            thePayment.LoadHistory(db);
            thePayment.LoadCourse(db);
            Course c = thePayment._course;

            c.LoadTeacher(db);
            c.LoadPaidGroup(db);
            // preload all branches
            Dictionary <int, Branch> branches = Branch.LoadListFromDBAsMap(db, "");


            PaidGroup pg = new PaidGroup();

            pg.LoadFromDB(db, " paid_group_id=" + c._paidGroupID);
            // Load teachers in this group
            listTeacher = pg.LoadMemberTeachers(db);

            // Generate HTML content
            TextReader reader          = new StreamReader(Config.PATH_APP_ROOT + "\\template\\payment_view.htm");
            String     templateContent = reader.ReadToEnd();

            reader.Close();

            // Construct Teacher List
            StringBuilder teachTxt = new StringBuilder();

            for (int i = 0; i < listTeacher.Length; i++)
            {
                string link = "TeacherManage.aspx?actPage=edit&targetID=" + listTeacher[i]._teacherID;
                teachTxt.Append("<a href=\"" + link + "\" >" + listTeacher[i]._firstname + " " + listTeacher[i]._surname + "</a><br>");
            }

            // Construct RaitInfo List
            StringBuilder rinfoTxt = new StringBuilder();

            for (int i = 0; i < pg._rateInfo.Length; i++)
            {
                rinfoTxt.Append("มากกว่า " + StringUtil.Int2StrComma(pg._rateInfo[i]._bound) + " บาท ได้รับ " + pg._rateInfo[i]._percent + " %<br>");
            }

            // Construct Paid history
            StringBuilder phTxt = new StringBuilder();

            foreach (PaymentHistory ph in thePayment._historyList)
            {
                ph.LoadReceiver(db);
                ph.LoadUser(db);
                Branch b    = branches[ph._branchID];
                string link = "TeacherManage.aspx?actPage=edit&targetID=" + ph._receiverTeacherID;
                phTxt.AppendLine("<tr><td align=center>" + PaymentHistory.GetPaymentHistoryID(ph._paymentID) + "</td>");
                phTxt.AppendLine("<td align=center>" + StringUtil.ConvertYearToEng(ph._paidDate, "yyyy/MM/dd HH:mm:ss") + "</td>");
                phTxt.AppendLine("<td align=center>" + StringUtil.Int2StrComma(ph._paidCost) + "</td>");
                phTxt.AppendLine("<td align=center><a href=\"" + link + "\" >" + ph._receiverTeacher._firstname + " " + ph._receiverTeacher._surname + "</a></td>");
                phTxt.AppendLine("<td align=center>" + ph._user._firstname + " " + ph._user._surname + "</td>");
                phTxt.AppendLine("<td align=center>" + b._branchName + "</td>");
                phTxt.AppendLine("<td align=center><a href=\"javascript:doInitPrint(" + ph._paymentID + ")\"><img src=\"" + Config.URL_PIC_SYS + "/view.gif\" border=0></a> </td>");
            }

            String htmlContent =
                String.Format(templateContent
                              , c._courseName
                              , "<a href=\"TeacherManage.aspx?actPage=edit&targetID=" + c._teacherID + "\" >" + c._teacher._firstname + " " + c._teacher._surname + "</a>"
                              , PaidGroup.GetPaidGroupID(c._paidGroupID) + " " + c._paidGroup._name
                              , teachTxt.ToString()
                              , rinfoTxt.ToString()
                              , StringUtil.Int2StrComma(thePayment._sumAllCost)
                              , StringUtil.Int2StrComma(thePayment._sumMaxPayable)
                              , StringUtil.Int2StrComma(thePayment._sumPaidCost)
                              , StringUtil.Int2StrComma(thePayment._sumMaxPayable - thePayment._sumPaidCost)
                              , phTxt.ToString()
                              );

            outBuf.Append(htmlContent);

            db.Close();
        }
        // ##Create
        // Sample showing to create a Payment using
        // CreditCard as a FundingInstrument
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;

            // ###Items
            // Items within a transaction.
            Item item = new Item();

            item.name     = "Item Name";
            item.currency = "USD";
            item.price    = "1";
            item.quantity = "5";
            item.sku      = "sku";

            List <Item> itms = new List <Item>();

            itms.Add(item);
            ItemList itemList = new ItemList();

            itemList.items = itms;

            // ###Address
            // Base Address object used as shipping or billing
            // address in a payment.
            Address billingAddress = new Address();

            billingAddress.city         = "Johnstown";
            billingAddress.country_code = "US";
            billingAddress.line1        = "52 N Main ST";
            billingAddress.postal_code  = "43210";
            billingAddress.state        = "OH";

            // ###CreditCard
            // A resource representing a credit card that can be
            // used to fund a payment.
            CreditCard crdtCard = new CreditCard();

            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2            = 874;
            crdtCard.expire_month    = 11;
            crdtCard.expire_year     = 2018;
            crdtCard.first_name      = "Joe";
            crdtCard.last_name       = "Shopper";
            crdtCard.number          = "4417119669820331";
            crdtCard.type            = "visa";

            // ###Details
            // Let's you specify details of a payment amount.
            Details details = new Details();

            details.shipping = "1";
            details.subtotal = "5";
            details.tax      = "1";

            // ###Amount
            // Let's you specify a payment amount.
            Amount amnt = new Amount();

            amnt.currency = "USD";
            // Total must be equal to sum of shipping, tax and subtotal.
            amnt.total   = "7";
            amnt.details = details;

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it.
            Transaction tran = new Transaction();

            tran.amount      = amnt;
            tran.description = "This is the payment transaction description.";
            tran.item_list   = itemList;

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            List <Transaction> transactions = new List <Transaction>();

            transactions.Add(tran);

            // ###FundingInstrument
            // A resource representing a Payer's funding instrument.
            // For direct credit card payments, set the CreditCard
            // field on this object.
            FundingInstrument fundInstrument = new FundingInstrument();

            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of
            // FundingInstrument; add the created `FundingInstrument`
            // to a List
            List <FundingInstrument> fundingInstrumentList = new List <FundingInstrument>();

            fundingInstrumentList.Add(fundInstrument);

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Use the List of `FundingInstrument` and the Payment Method
            // as `credit_card`
            Payer payr = new Payer();

            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method      = "credit_card";

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale` or `authorize`
            Payment pymnt = new Payment();

            pymnt.intent       = "sale";
            pymnt.payer        = payr;
            pymnt.transactions = transactions;

            try
            {
                // ### Api Context
                // Pass in a `APIContext` object to authenticate
                // the call and to send a unique request id
                // (that ensures idempotency). The SDK generates
                // a request id if you do not pass one explicitly.
                // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext..
                APIContext apiContext = Configuration.GetAPIContext();

                // Create a payment using a valid APIContext
                Payment createdPayment = pymnt.Create(apiContext);
                CurrContext.Items.Add("ResponseJson", JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

            CurrContext.Items.Add("RequestJson", JObject.Parse(pymnt.ConvertToJson()).ToString(Formatting.Indented));

            Server.Transfer("~/Response.aspx");
        }
 public bool UpdatePaymentRecord(Payment paymment)
 {
     _db.Payments.Update(paymment);
     return(Save());
 }
Example #50
0
 // method to read the column values in the database (through the referenced reader) and assign it to the correct properties of the referenced Payment object
 // allows for easier editing of column names if needed, used only for methods with select statments regarding Payment
 private static void readAPayment(ref Payment pay, ref SqlDataReader reader)
 {
     pay.PaymentID    = reader["paymentID"].ToString();
     pay.StripeRefNum = reader["stripeRefNum"].ToString();
 }
Example #51
0
        // GET: Orders/Create
        public ActionResult Create(int id)
        {
            // Populate an OrderNumber (if one doesn't exist) for the Customer session
            if (Session["OrderNumber"] == null)
            {
                Session["OrderNumber"] = GenerateOrderNumber();
            }
            // Populate TableNumber
            if (Session["TableNumber"] == null)
            {
                Session["TableNumber"] = GenerateTableNumber();
            }
            // Default Quantity
            var Quantity = 1;

            // Variables
            var OrderNumber = Int32.Parse(Session["OrderNumber"].ToString());

            ViewBag.OrderNumber = Session["OrderNumber"];
            ViewBag.TableNumber = Session["TableNumber"];
            ViewBag.OrderDate   = DateTime.Now;

            // Preselected Product
            ViewBag.ProductId = new SelectList(db.Products, "ProductId", "ProductName", id);

            // Get Customer Id to Preselct
            var customerId = db.Customers.Where(x => x.CustomerEmail == User.Identity.Name).Select(x => x.CustomerId).First();

            ViewBag.CustomerId = new SelectList(db.Customers, "CustomerId", "CustomerEmail", customerId);

            // Create the Order
            var order = new Order();

            order.CustomerId    = customerId;
            order.OrderDate     = DateTime.Now;
            order.OrderNumber   = Int32.Parse(Session["OrderNumber"].ToString());
            order.OrderQuantity = Quantity;
            order.ProductId     = id;
            order.TableNumber   = Int32.Parse(Session["TableNumber"].ToString());
            db.Orders.Add(order);
            db.SaveChanges();

            // Create the Payment (Invoice)
            // If payment already doesn't exist, create new, else update the same record with new total
            var paymentexist = db.Payments.Where(x => x.OrderNumber == OrderNumber).FirstOrDefault();

            if (paymentexist == null)
            {
                var payment = new Payment();
                payment.OrderNumber = OrderNumber;

                // Calculate the Total
                decimal total = 0;
                var     query = db.Orders.Join(db.Products, ord => ord.ProductId, prod => prod.ProductId, (ord, prod) => new { Order = ord, Product = prod }).Where(x => x.Order.OrderNumber == OrderNumber).ToList();
                foreach (var val in query)
                {
                    // Get price from product db
                    total += val.Product.ProductPrice;
                }
                payment.Total       = total;
                payment.PaymentDate = DateTime.Now;

                var db2 = new RestaurantContext();
                db2.Payments.Add(payment);
                db2.SaveChanges();
            }
            else
            {
                var payment = db.Payments.Where(x => x.OrderNumber == OrderNumber).First();

                // Calculate the Total
                decimal total = 0;
                var     query = db.Orders.Join(db.Products, ord => ord.ProductId, prod => prod.ProductId, (ord, prod) => new { Order = ord, Product = prod }).Where(x => x.Order.OrderNumber == OrderNumber).ToList();
                foreach (var val in query)
                {
                    // Get price from product db
                    total += val.Product.ProductPrice;
                }
                payment.Total       = total;
                payment.PaymentDate = DateTime.Now;

                var db2 = new RestaurantContext();
                db2.Entry(payment).State = EntityState.Modified;
                db2.SaveChanges();
            }

            return(RedirectToAction("Index", "Orders"));
        }
Example #52
0
 public override bool ProcessPayment(Payment payment, ref string message)
 {
     OrderGroup = payment.Parent.Parent;
     _orderForm = payment.Parent;
     return(ProcessPayment(payment, ref message));
 }
Example #53
0
        private async Task <Dictionary <string, string> > RequestWeChatPayRefundAsync(Payment payment, PaymentRecord paymentRecord, WeChatPayRefundEto eventData, string outRefundNo)
        {
            var refundAmount = eventData.Refunds.Sum(model => model.RefundAmount);

            var result = await _serviceProviderPayService.RefundAsync(
                appId : payment.GetProperty <string>("appid"),
                mchId : payment.PayeeAccount,
                subAppId : null,
                subMchId : null,
                transactionId : paymentRecord.TransactionId,
                outTradeNo : payment.Id.ToString("N"),
                outRefundNo : outRefundNo,
                totalFee : paymentRecord.TotalFee,
                refundFee : _weChatPayFeeConverter.ConvertToWeChatPayFee(refundAmount),
                refundFeeType : null,
                refundDesc : eventData.DisplayReason,
                refundAccount : null,
                notifyUrl : null
                );

            var dict = new Dictionary <string, string>(result.SelectSingleNode("xml").ToDictionary() ?? throw new NullReferenceException());

            if (dict.GetOrDefault("return_code") != "SUCCESS")
            {
                throw new RefundFailedException(dict.GetOrDefault("return_code"), dict.GetOrDefault("return_msg"));
            }

            await CreateWeChatPayRefundRecordEntitiesAsync(payment, dict);

            return(dict);
        }
        protected void btnPurchase_Click(object sender, EventArgs e)
        {
            // Code adapted from https://stackoverflow.com/a/8185231
            var    AdDarbukaPrice    = ProductFormVw.FindControl("ProductPriceLabel") as Label;
            var    ProductPriceLabel = AdDarbukaPrice.Text;
            var    AdDarbukaName     = ProductFormVw.FindControl("ProductNameLabel") as Label;
            string ProductNameLabel  = AdDarbukaName.Text;


            decimal postagePackagingCost = 3.95m;
            decimal productPrice         = decimal.Parse(ProductPriceLabel);
            int     quantityProduct      = int.Parse(ddlQuantity.SelectedValue);
            decimal subTotal             = (quantityProduct * productPrice);
            decimal total = subTotal + postagePackagingCost;

            var clientId     = "ATQaU4q8O7_JJFYS6ky9VJXe4LnPeAj9d6x7kTBqWjfROo0-yf8O5iCxp9wTIc04JXjcqK2FaPsRE_Pl";
            var clientSecret = "EH9hlRKiqI-__hWkNl0sYGHMkhw7tx4sHeUglveQ3tiUseGb5NbU-yKbEmEx4QGt7LeYiMkSlk5K_5fp";

            var sdkConfig = new Dictionary <string, string>
            {
                { "mode", "sandbox" },
                { "clientId", "clientId" },
                { "clientSecret", "clientSecret" }
            };

            var accessToken = new OAuthTokenCredential(clientId, clientSecret, sdkConfig).GetAccessToken();
            var apiContext  = new APIContext(accessToken);

            apiContext.Config = sdkConfig;


            var productItem = new Item();

            productItem.name     = ProductNameLabel;
            productItem.currency = "USD";
            productItem.price    = ProductPriceLabel.ToString();
            productItem.quantity = quantityProduct.ToString();

            var transactionDetails = new Details();

            transactionDetails.tax      = "0";
            transactionDetails.shipping = postagePackagingCost.ToString();
            transactionDetails.subtotal = subTotal.ToString("0.00");

            var transactionAmount = new Amount();

            transactionAmount.currency = "USD";
            transactionAmount.total    = total.ToString("0.00");
            transactionAmount.details  = transactionDetails;

            var transaction = new Transaction();

            transaction.description    = "Your order of";
            transaction.invoice_number = Guid.NewGuid().ToString();
            transaction.amount         = transactionAmount;
            transaction.item_list      = new ItemList
            {
                items = new List <Item> {
                    productItem
                }
            };

            var payer = new Payer();

            payer.payment_method = "paypal";

            var redirectUrls = new RedirectUrls();

            redirectUrls.cancel_url = "http://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath + "/Default.aspx";
            redirectUrls.return_url = "http://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath + "/CompletePurchase.aspx";


            var payment = Payment.Create(apiContext, new Payment
            {
                intent       = "sale",
                payer        = payer,
                transactions = new List <Transaction> {
                    transaction
                },
                redirect_urls = redirectUrls
            });

            Session["paymentId"] = payment.id;

            foreach (var link in payment.links)
            {
                if (link.rel.ToLower().Trim().Equals("approval_url"))
                {
                    Response.Redirect(link.href);
                }
            }

            Response.Redirect("~/ShoppingCart/ProductDescriptionUser.aspx");
        }
Example #55
0
 public override ActionResult AddPayment(Payment payment)
 {
     throw new NotImplementedException();
 }
Example #56
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            //var payer = new Payer() { payment_method = "paypal" };

            //var guid = Convert.ToString((new Random()).Next(100000));
            //var redirUrls = new RedirectUrls()
            //{
            //    cancel_url = "http://localhost:44320/cancel",
            //    return_url = "http://localhost:44320/process"
            //};

            //var itemList = new ItemList()
            //{
            //    items = new List<Item>()
            //     {
            //       new Item()
            //       {
            //         name = "Item Name",
            //         currency = "USD",
            //         price = "15",
            //         quantity = "5",
            //         sku = "sku"
            //       }
            //     }
            //};

            //var details = new Details()
            //{
            //    tax = "15",
            //    shipping = "10",
            //    subtotal = "75"
            //};

            //var amount = new Amount()
            //{
            //    currency = "USD",
            //    total = "100.00",
            //    details = details
            //};

            //var transactionList = new List<Transaction>();

            //transactionList.Add(new Transaction()
            //{
            //    description = "Transaction description.",
            //    invoice_number = Convert.ToString((new Random()).Next(100000)),
            //    amount = amount,
            //    item_list = itemList
            //});

            //var payment = new Payment()
            //{
            //    intent = "sale",
            //    payer = payer,
            //    redirect_urls = redirUrls,
            //    transactions = transactionList
            //};


            // ### Api Context
            // Pass in a `APIContext` object to authenticate
            // the call and to send a unique request id
            // (that ensures idempotency). The SDK generates
            // a request id if you do not pass one explicitly.
            // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext.
            var apiContext = PaypalConfiguration.GetAPIContext();

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

            if (string.IsNullOrEmpty(payerId))
            {
                // ###Items
                // Items within a transaction.
                var itemList = new ItemList()
                {
                    items = new List <Item>()
                    {
                        new Item()
                        {
                            name     = "Item Name",
                            currency = "USD",
                            price    = "15",
                            quantity = "5",
                            sku      = "sku"
                        }
                    }
                };

                // ###Payer
                // A resource representing a Payer that funds a payment
                // Payment Method
                // as `paypal`
                var payer = new Payer()
                {
                    payment_method = "paypal"
                };

                // ###Redirect URLS
                // These URLs will determine how the user is redirected from PayPal once they have either approved or canceled the payment.
                var baseURI     = Request.Url.Scheme + "://" + Request.Url.Authority + "/Events/testing1.aspx?";
                var guid        = Convert.ToString((new Random()).Next(100000));
                var redirectUrl = baseURI + "guid=" + guid;
                var redirUrls   = new RedirectUrls()
                {
                    cancel_url = redirectUrl + "&cancel=true",
                    return_url = redirectUrl
                };

                // ###Details
                // Let's you specify details of a payment amount.
                var details = new Details()
                {
                    tax      = "15",
                    shipping = "10",
                    subtotal = "75"
                };

                // ###Amount
                // Let's you specify a payment amount.
                var amount = new Amount()
                {
                    currency = "USD",
                    total    = "100.00", // Total must be equal to sum of shipping, tax and subtotal.
                    details  = details
                };

                // ###Transaction
                // A transaction defines the contract of a
                // payment - what is the payment for and who
                // is fulfilling it.
                var transactionList = new List <Transaction>();

                // The Payment creation API requires a list of
                // Transaction; add the created `Transaction`
                // to a List
                transactionList.Add(new Transaction()
                {
                    description    = "Transaction description.",
                    invoice_number = Common.GetRandomInvoiceNumber(),
                    amount         = amount,
                    item_list      = itemList
                });

                // ###Payment
                // A Payment Resource; create one using
                // the above types and intent as `sale` or `authorize`
                var payment = new Payment()
                {
                    intent        = "sale",
                    payer         = payer,
                    transactions  = transactionList,
                    redirect_urls = redirUrls
                };

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

                // Using the `links` provided by the `createdPayment` object, we can give the user the option to redirect to PayPal to approve the payment.
                var links = createdPayment.links.GetEnumerator();
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        Response.Redirect(link.href);
                    }
                }
                Session.Add(guid, createdPayment.id);
            }
            else
            {
                var guid = Request.Params["guid"];


                // Using the information from the redirect, setup the payment to execute.
                var paymentId        = Session[guid] as string;
                var paymentExecution = new PaymentExecution()
                {
                    payer_id = payerId
                };
                var payment = new Payment()
                {
                    id = paymentId
                };


                // Execute the payment.
                var executedPayment = payment.Execute(apiContext, paymentExecution);


                // For more information, please visit [PayPal Developer REST API Reference](https://developer.paypal.com/docs/api/).
            }
        }
Example #57
0
 public IDataResult<Payment> Get(Payment payment)
 {
     return new SuccessDataResult<Payment>(_paymentDal.Get(x => x.Id == payment.Id));
 }
        public static void CapturePayment()
        {
            Payment payment = Helper.TestCapturePayment();

            Assert.AreNotSame(null, payment);
        }
 public void UpdatePayment(Payment payment)
 {
     throw new NotImplementedException();
 }
        public ReservationOperationResult ReservationsOperation(ReservationsOperationParam param)
        {
            ReservationOperationResult result = new ReservationOperationResult();

            using (var trans = Session.BeginSaveTransaction())
            {
                var     dbEmployee    = Session.Load <Profile>(SecurityInfo.SessionData.Profile.GlobalId);
                var     dbReservation = param.ReservationId.HasValue ? Session.QueryOver <ScheduleEntryReservation>().Fetch(x => x.ScheduleEntry).Eager.Where(x => x.GlobalId == param.ReservationId).SingleOrDefault() : null;
                var     dbEntry       = param.EntryId.HasValue ? Session.Get <ScheduleEntryBase>(param.EntryId) : dbReservation.ScheduleEntry;
                Payment zakup         = null;
                if (param.OperationType == ReservationsOperationType.StatusDone)
                {
                    setStatus(dbEntry, ScheduleEntryState.Done);
                }
                else if (param.OperationType == ReservationsOperationType.StatusCancelled)
                {
                    setStatus(dbEntry, ScheduleEntryState.Cancelled);
                }
                else if (param.OperationType == ReservationsOperationType.MakeGroup)
                {
                    makeGroupReservation(param, dbEntry, dbEmployee);
                }
                else
                {
                    var dbCustomer = param.CustomerId.HasValue ? Session.Get <Customer>(param.CustomerId) : dbReservation.Customer;

                    if (dbCustomer.Profile != dbEmployee || (dbEntry.Profile != dbEmployee))
                    {
                        throw new CrossProfileOperationException("Customer or ScheduleEntry belongs to another user");
                    }

                    if (param.OperationType == ReservationsOperationType.Absent)
                    {
                        dbReservation.LeaveDateTime = dbReservation.EnterDateTime = null;
                    }
                    else if (param.OperationType == ReservationsOperationType.Presnet)
                    {
                        if (dbEntry.State != ScheduleEntryState.Done)
                        {
                            throw new InvalidOperationException("Absent can be only set for entries with Done status");
                        }
                        dbReservation.EnterDateTime = dbEntry.StartTime;
                        dbReservation.LeaveDateTime = dbEntry.EndTime;
                    }
                    else if (param.OperationType == ReservationsOperationType.Make)
                    {
                        //get existing reservation for this customer (except virtual customers)
                        if (!dbCustomer.IsVirtual)
                        {
                            dbReservation =
                                dbEntry.Reservations.SingleOrDefault(
                                    x => x.Customer == dbCustomer && x.LeaveDateTime == null);
                        }
                        dbReservation = makeReservation(dbEmployee, dbEntry, dbCustomer, dbReservation);
                        zakup         = calculatePayement(dbReservation, false);
                    }
                    else if (param.OperationType == ReservationsOperationType.Undo)
                    {
                        undoReservation(dbReservation, dbEntry);
                    }
                    Session.SaveOrUpdate(dbReservation);
                }

                Session.SaveOrUpdate(dbEntry);
                trans.Commit();
                result.Reservation   = Mapper.Map <ScheduleEntryReservation, ScheduleEntryReservationDTO>(dbReservation);
                result.ScheduleEntry = dbEntry.Map <ScheduleEntryBaseDTO>();
                result.Payment       = Mapper.Map <Payment, PaymentDTO>(zakup);
                //return result;
            }
            return(result);
        }