public CreditCard(CVV cvv, string name, string cardNumber, ExpiryDate expiryDate)
 {
     this.Id         = Guid.NewGuid();
     this.CVV        = cvv;
     this.Name       = name;
     this.CardNumber = cardNumber;
     this.ExpiryDate = expiryDate;
     this.Type       = PaymentType.CreditCard;
 }
Beispiel #2
0
        public CardTransaction OnlinePayment(decimal amount, string destinationName, string destinationAccount, string cvv)
        {
            if (!CVV.Equals(cvv))
            {
                throw new CVVMismatchException(CVV, cvv);
            }

            var transaction     = BankAccount.CreatePayment(amount, destinationName, destinationAccount, "Online Payment");
            var cardTransaction = CardTransaction.Create(transaction, CardTransactionType.Online);

            cardTransactions.Add(cardTransaction);
            return(cardTransaction);
        }
 public PaymentEntityMasked ToPaymentEntityMasked()
 {
     return(new PaymentEntityMasked()
     {
         Id = Id,
         PaymentStatus = PaymentStatus,
         CardNumber = CardNumber.Mask(0, 12),
         ExpiryYear = ExpiryYear.ToStringMask(0, 4),
         ExpiryMonth = ExpiryMonth.ToString("D2").Mask(0, 2),
         Amount = Amount,
         CurrencyCode = CurrencyCode,
         CVV = CVV.ToStringMask(0, 3)
     });
 }
Beispiel #4
0
        private bool validateCVV()
        {
            if (string.IsNullOrEmpty(this.CVV))
            {
                return(false);
            }
            String cvcValue = CVV.Trim();

            bool validLength = ((this.CardScheme == null && cvcValue.Length >= 3 && cvcValue.Length <= 4) ||
                                (CardScheme == CreditCardType.Amex && cvcValue.Length == 4) || (CardScheme != CreditCardType.Amex && cvcValue
                                                                                                .Length == 3));

            return(validLength);
        }
        private void ValidateAddCard(ErrorBucket errors)
        {
            if (string.IsNullOrEmpty(Bank))
                errors.AddError(res.GetString("RequiredBank"));

            if (string.IsNullOrEmpty(CardNo))
                errors.AddError(res.GetString("RequiredCardNo"));

            if (string.IsNullOrEmpty(Expiry))
                errors.AddError(res.GetString("RequiredExpiry"));

            if (string.IsNullOrEmpty(CVV.ToString()))
                errors.AddError(res.GetString("RequiredCVV"));

        }
        private void CardHolderName_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            char c = Convert.ToChar(e.Text);

            if (Char.IsControl(c))
            {
                CVV.Focus();
                return;
            }
            if (Char.IsLetter(c) || Char.IsSurrogate(c))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
Beispiel #7
0
 public void FillingBillingInformation(BookingForm bookingForm)
 {
     SelectTitle.SelectByValue(bookingForm.Title);
     NameInput.SendKeys(bookingForm.Name);
     SurName.SendKeys(bookingForm.Surname);
     Email.SendKeys(bookingForm.Email);
     Phone.SendKeys(bookingForm.Phone);
     Birthday.SendKeys(bookingForm.Birthday.ToString());
     PassportNumber.SendKeys(bookingForm.PassportNumber);
     ExpirationDate.SendKeys(bookingForm.ExpirationDate);
     NationalityAnchor.Click();
     _wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath(BookingCompletionPageConstants.NationalityItemSelectPath)));
     NationalityItemSelect.Click();
     SelectCardType.SelectByValue(bookingForm.CardType);
     CardNumber.SendKeys(bookingForm.CardNumber);
     CardExpiryYear.SelectByValue(bookingForm.CardExpiryYear);
     CVV.SendKeys(bookingForm.CVV);
 }
Beispiel #8
0
        async void Continuar_Clicked(object sender, EventArgs e)
        {
            if (Settings.session_MetodoPago.Equals("tarjeta"))
            {
                if (String.IsNullOrEmpty(Nombre.Text))
                {
                    await DisplayAlert("", "Por favor, indique el nombre que aparece en su tarjeta", "Aceptar");

                    Nombre.Focus();
                    return;
                }

                if (String.IsNullOrEmpty(Numero.Text))
                {
                    await DisplayAlert("", "Por favor, indique el número de su tarjeta", "Aceptar");

                    Numero.Focus();
                    return;
                }
                else if (!IsValidNumber(Regex.Replace(Numero.Text.Trim(), @"\s+", "")))
                {
                    await DisplayAlert("Número inválido", "Verifique el número de su tarjeta", "Aceptar");

                    Numero.Focus();
                    return;
                }
                if (String.IsNullOrEmpty(Vencimiento.Text))
                {
                    await DisplayAlert("", "Por favor, indique la fecha de expiración de su tarjeta", "Aceptar");

                    Vencimiento.Focus();
                    return;
                }
                else if (!IsValidExpiration(Regex.Replace(Vencimiento.Text.Trim(), @"\s+", "")))
                {
                    await DisplayAlert("Fecha inválida", "Verifique la fecha de expiración de su tarjeta", "Aceptar");

                    Vencimiento.Focus();
                    return;
                }
                if (String.IsNullOrEmpty(CVV.Text))
                {
                    await DisplayAlert("", "Por favor, indique el código CVV de su tarjeta", "Aceptar");

                    CVV.Focus();
                    return;
                }
                else if (CVV.Text.Trim().Length < 3)
                {
                    await DisplayAlert("Código CVV inválido", "Verifique el código CVV de su tarjeta", "Aceptar");

                    CVV.Focus();
                    return;
                }
            }
            else
            {
            }
            PopupPage pagar = new Pagar();
            //pagar.bac
            await Navigation.PushPopupAsync(pagar);
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            CGX_NET pGeo = null;
            CDB     hDB  = null;
            CVV     hVV  = null;
            CVM     hVM  = null;
            CVA     hVA  = null;

            Int32 iChan, iLine; // database symbols

            int          iVA, iL, iLines, iS;
            double       dValue;
            DoubleVector dData;


            // --- Usage ---
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: chanadd database channel value");
                return;
            }

            try
            {
                // --- Initialize ---
                pGeo = new CGX_NET("CHANADD", "V1", 2047, null, 0);
                if (pGeo == null)
                {
                    Console.WriteLine("Unable to start Geosoft session");
                    return;
                }

                // ---
                // Open a database.
                // Note that all databases created by normal Geosoft users will have
                // user name "SUPER" with password "".  Third-party or custom applications
                // may create databases that require a user-name and password, in which
                // case you require these values to open the database.
                // ---
                hDB = CDB.Open(args[0], "SUPER", "");

                // --- Get the channel handle ---
                iChan = hDB.FindSymb(args[1], CoreConstant.DB_SYMB_CHAN);
                if (iChan == CoreConstant.NULLSYMB)
                {
                    Console.WriteLine(args[1] + " channel not found in database " + args[0]);
                    return;
                }

                // --- Lock channel for read-writer ---
                hDB.LockSymb(iChan, CoreConstant.DB_LOCK_READWRITE, CoreConstant.DB_WAIT_NONE);

                // --- do we need a VV or a VA? ---
                iVA = hDB.iGetColVA(iChan); // number of elements in a VA, 1 if its a VV
                if (iVA == 1)
                {
                    // --- Create a VV to hold data array ---
                    hVV = CVV.CreateExt(CoreConstant.GS_DOUBLE, 0);
                }
                else
                {
                    // --- its a VA channel ---
                    hVA = CVA.CreateExt(CoreConstant.GS_DOUBLE, 0, iVA);
                }

                // --- Get a real VM to hold the data in memory ---
                hVM = CVM.Create(CoreConstant.GS_REAL, 0);

                // -- Get Value to add to data ---
                dValue = Convert.ToDouble(args[2]);

                // --- Count selected lines ---
                iLines = hDB.iCountSelLines();

                // --- Go through all selected lines ---
                iL    = 0;
                iLine = hDB.FirstSelLine();

                do
                {
                    // --- Break if line is not a valid line ---
                    if (hDB.iIsLineValid(iLine) == 0)
                    {
                        break;
                    }

                    // --- Update progress ---
                    Console.WriteLine("Chanadd " + (iL + 1) + " of " + iLines + " Complete");

                    // --- Read Data ---
                    if (iVA == 1)
                    {
                        // --- get VV data ---
                        hDB.GetChanVV(iLine, iChan, hVV);
                    }
                    else
                    {
                        // --- get VA data ---
                        hDB.GetChanVA(iLine, iChan, hVA);

                        // ---
                        // Get the VV to the VA data.  This VV contains all VA data
                        // by element, then by row.  The VV is owned by the VA, so you
                        // cannot destroy the VA or the VV will become invalid.
                        // ---

                        hVV = hVA.GetFullVV();
                    }

                    // ---
                    // Get data VM from the VV.  This will re-size the VM to
                    // hold all the data in the VV.
                    // ---

                    CVV.CopyVVtoVM(hVM, hVV);

                    // --- now get a pointer to the data ---

                    iS = hVV.iLength();

                    dData = CGX_NET.GetDoubleVM(hVM, iS);

                    //-----------------------------------------------------------------------
                    //                             MAIN MATH CODE
                    //-----------------------------------------------------------------------

                    for (int i = 0; i < iS; i++)
                    {
                        dData[i] += dValue;
                    }

                    // --- Put the VM data back in the VV ---
                    hVV.CopyVMtoVV(hVM);

                    // --- Write data back to the database ---
                    if (iVA == 1)
                    {
                        hDB.PutChanVV(iLine, iChan, hVV);
                    }
                    else
                    {
                        // ---
                        // Since the VA owned the VV, changing the VV data is the same as
                        // changing toe VA data.  All I need to do is write the VA data.
                        // ---
                        hDB.PutChanVA(iLine, iChan, hVA);
                    }

                    // --- Advance to Next Line ---
                    iLine = hDB.NextSelLine(iLine);
                    iL++;
                }while (true);

                Console.WriteLine("ChanAdd Complete");


                // --- Cleanup ---

                hDB.UnLockSymb(iChan);

                // ---
                // Destroy any handles that were created.  This is not really necessary since
                // destroying a pGeo handle will destroy all classes.  However, we considere it
                // good practice to destroy your own instances since it ensures you are
                // thinking about what instances you have created.  You really do not want to
                // keep class instances longer than you need them since they consume system
                // resources that could be better used by other parts of your application.
                // ---

                if (hVM != null)
                {
                    hVM.Dispose();
                }

                // --- be careful not to try to destroy a VV owned by a VA ---

                if (hVV != null && (iVA != 1))
                {
                    hVV.Dispose();
                }

                if (hVA != null)
                {
                    hVA.Dispose();
                }

                hDB.Dispose();
            }
            catch (CERROR e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
            finally
            {
                if (pGeo != null)
                {
                    pGeo.Dispose();
                }
            }
        }
        public static void Thread1(object sock)
        {
            string sendMessage, receiveMessage;
            Common c      = new Common();
            Socket socket = (Socket)sock;
            //nhận message từ gateway
            string issuerPrivateKey = File.ReadAllText("d:/file/IssuerPrivateKey.xml");

            receiveMessage = c.receive(socket);
            string[] splitAuthReq = receiveMessage.Split('-');
            ForwardAuthorizationRequest forwardAuthorization = new ForwardAuthorizationRequest(splitAuthReq[0], splitAuthReq[1], splitAuthReq[2], splitAuthReq[3]);

            Console.WriteLine("verify gateway forward authorization: " + forwardAuthorization.verify(issuerPrivateKey));
            string PI = forwardAuthorization.getPI(issuerPrivateKey);
            string cardNumber, CVV, dateValid, transID;
            long   tien;

            string[] splitPI = PI.Split(':');
            transID    = splitPI[0];
            cardNumber = splitPI[3];
            CVV        = splitPI[4];
            dateValid  = splitPI[5];
            tien       = Convert.ToInt64(splitPI[6]);
            //connect SQL server
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

            builder.DataSource     = "localhost";
            builder.UserID         = "sa";
            builder.Password       = "******";
            builder.InitialCatalog = "Bank";
            bool flag = false;

            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                connection.Open();

                string        sql;
                StringBuilder sb = new StringBuilder();
                sql = "SELECT CardNumber, CVV, DateValid FROM Issuer;";
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    string a;
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            a = reader.GetString(2);
                            if (cardNumber.Equals(reader.GetString(0)) == true && CVV.Equals(reader.GetString(1)) == true && dateValid.Equals(reader.GetString(2)) == true)
                            {
                                flag = true;
                            }
                        }
                    }
                }
                //Console.WriteLine("kq sql server: " + flag);
                //ghi PI vào log Isuuer

                sb.Clear();
                sb.Append("INSERT LogIssuer (TransID, CardNumber, Money, Paid) ");
                sb.Append("VALUES (@trans, @cardid, @money, @paid);");
                sql = sb.ToString();
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@trans", transID);
                    command.Parameters.AddWithValue("@cardid", cardNumber);
                    command.Parameters.AddWithValue("@money", tien);
                    command.Parameters.AddWithValue("@paid", 0);
                    int rowsAffected = command.ExecuteNonQuery();
                    Console.WriteLine(rowsAffected + " row(s) inserted");
                }
                connection.Close();
            }
            //gửi forward response
            X509Certificate2             issuerCertificate     = new X509Certificate2("d:/file/issuer.crt", "123456");
            string                       issuerCert            = c.ByteArrayToString(issuerCertificate.GetRawCertData());
            ForwardAuthorizationResponse authorizationResponse = new ForwardAuthorizationResponse(transID, splitPI[1], 1, "ok", issuerPrivateKey, issuerCert);

            c.send(authorizationResponse.ToMessage(), socket);
            //nhận capture request từ gateway
            receiveMessage = c.receive(socket);
            string[]         splitCapture     = receiveMessage.Split('-');
            string           keyCapture       = c.DecryptionRSA(issuerPrivateKey, splitCapture[2]);
            string           captureRequest   = c.DecryptDES(splitCapture[1], keyCapture);//transid:RRPID:merchantcard:merchantCVV:merchantDatevalid:tien
            X509Certificate2 certificate2     = new X509Certificate2(c.StringToByteArray(splitCapture[3]));
            string           gatewayPublicKey = certificate2.GetRSAPublicKey().ToXmlString(false);

            Console.WriteLine("verify capture request: " + c.Verify(gatewayPublicKey, splitCapture[0], captureRequest));
            string merchantCardNumber, merchantCVV, merchantDateValid;

            string[] splitCaptureRequest = captureRequest.Split(':');
            transID = splitCaptureRequest[0];
            string RRPID = splitCaptureRequest[1];

            merchantCardNumber = splitCaptureRequest[2];
            merchantCVV        = splitCaptureRequest[3];
            merchantDateValid  = splitCaptureRequest[4];
            tien = Convert.ToInt64(splitCaptureRequest[5]);
            //nhập dữ liệu thanh toán vào sql server
            using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
            {
                connection.Open();
                string        sql;
                StringBuilder sb = new StringBuilder();
                sb.Clear();
                sb.Append("UPDATE LogIssuer SET Paid = @paid WHERE TransID = @id");
                sql = sb.ToString();
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@id", transID);
                    command.Parameters.AddWithValue("@paid", 1);
                    int rowsAffected = command.ExecuteNonQuery();
                }
                string customerCardNumber = "";
                sql = "SELECT TransID, CardNumber FROM LogIssuer;";
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    string a;
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            a = reader.GetString(1);
                            if (transID.Equals(reader.GetString(0)) == true)
                            {
                                customerCardNumber = reader.GetString(1);
                            }
                        }
                    }
                }
                long tienBanDau = 0;
                sql = "SELECT CardNumber, UsedMoney FROM Issuer;";
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    string a;
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            if (cardNumber.Equals(reader.GetString(0)) == true)
                            {
                                tienBanDau = reader.GetInt64(1);
                            }
                        }
                    }
                }
                sb.Clear();
                sb.Append("UPDATE Issuer SET UsedMoney = @tien WHERE CardNumber = @id");
                sql = sb.ToString();
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@tien", tien + tienBanDau);
                    command.Parameters.AddWithValue("@id", customerCardNumber);
                    int rowsAffected = command.ExecuteNonQuery();
                }
                connection.Close();
            }
            //send message to acquirer
            string message = transID + ":" + merchantCardNumber + ":" + merchantCVV + ":" + merchantDateValid + ":" + tien;

            sendMessage = message + "-" + c.Sign(issuerPrivateKey, message) + "-" + issuerCert;
            IPEndPoint iep    = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1237);
            Socket     client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            client.Connect(iep);
            c.send(sendMessage, client);
            //nhận message từ acquirer
            receiveMessage = c.receive(client);
            string[]         splitAcquirer       = receiveMessage.Split('-');
            X509Certificate2 acquirerCertificate = new X509Certificate2(c.StringToByteArray(splitAcquirer[2]));
            string           acquirerPublicKey   = acquirerCertificate.GetRSAPublicKey().ToXmlString(false);

            Console.WriteLine("verify message from acquirer: " + c.Verify(acquirerPublicKey, splitAcquirer[1], splitAcquirer[0]));
            string[] splitAcquirerMessage = splitAcquirer[0].Split(':');
            if (splitAcquirerMessage[1].CompareTo("1") == 0)
            {
                //gửi capture response tới gateway
                message = splitAcquirerMessage[0] + ":" + RRPID + ":" + splitAcquirerMessage[1] + ":" + splitAcquirerMessage[2];
                c.send(message + "-" + c.Sign(issuerPrivateKey, message) + "-" + issuerCert, socket);
            }
            else
            {
            }
            Console.Read();
        }
Beispiel #11
0
 /// <summary>
 /// Cria uma instância de Cielo.Holder definindo os dados do cartão.
 /// </summary>
 /// <param name="number">Número do cartão</param>
 /// <param name="expirationYear">Ano de expiração do cartão</param>
 /// <param name="expirationMonth">Mês de expiração do cartão</param>
 /// <param name="cvv">CVV do cartão</param>
 /// <param name="indicator">Indicador do CVV do cartão; ; veja Cielo.Holder.CVV</param>
 public Holder(String number, String expirationYear, String expirationMonth, String cvv, CVV indicator)
     : this(number, expirationYear, expirationMonth, cvv)
 {
     this.indicator = indicator;
 }
Beispiel #12
0
        public static void processPayment(List <float> allTotals)
        {
            Console.WriteLine("Please enter your payment method,choose from cash/credit/check ");
            Console.WriteLine("For cash enter 1");
            Console.WriteLine("For check enter 2");
            Console.WriteLine("For credit enter 3");

            //for check verification-printing the ending message
            bool checkverify = true;
            //for credit card verification-printing card rejected
            int cardCount = 0;

            //validating and retreiving initial user input
            int choice;

            while (true)
            {
                while (!int.TryParse(Console.ReadLine(), out choice))
                {
                    Console.WriteLine("Please enter a correct value.");
                }

                if (!(choice >= 1 && choice <= 3))
                {
                    Console.WriteLine("Please enter 1, 2, or 3.");
                }

                else if (choice == 1 || choice == 2 || choice == 3)
                {
                    break;
                }

                //
            }
            switch (choice)
            {
            case 1:    //CASH
                float changeDue = getChange(allTotals);
                Console.WriteLine($"Your change due is {changeDue.ToString("C")}");
                break;

            case 2:    //CHECK
                Random r      = new Random(DateTime.Now.Second);
                int    Verify = r.Next(1, 3);
                //Console.WriteLine($"Verify = {Verify}");  //<--------------------only using this to verify the variable, Verify
                Console.WriteLine("Please enter the check number");
                int checkNumber;
                while (!int.TryParse(Console.ReadLine(), out checkNumber))
                {
                    Console.WriteLine("Please enter an appropriate value.");
                }

                //So you have a 50/50 chance of the chaeck not being accepted
                if (Verify == 1)
                {
                    checkverify = false;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("CHECK DENIED");
                    Console.WriteLine("THE LOCAL POLICE DEPARTMENT HAS BEEN NOTIFIED");

                    List <string> symbols = new List <string>();
                    symbols.Add(".");
                    symbols.Add(".");
                    symbols.Add(".");
                    symbols.Add(".");
                    symbols.Add("have fun in prison");

                    foreach (string item in symbols)
                    {
                        Console.Write(item + " ");
                        Thread.Sleep(600);
                    }
                    Console.ResetColor();
                    Console.WriteLine();
                }
                else if (Verify == 2)
                {
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Check Accepted");
                    Console.ResetColor();
                }

                break;


            case 3:    //CARD

                //Initial variables used for card input and validation
                DateTime currentDate = new DateTime();
                currentDate = DateTime.Now;
                int  currentMonth = currentDate.Month;
                int  currentYear  = int.Parse(currentDate.Year.ToString().Substring(2));
                long cardNumber;
                int  CVV;
                bool getCVV = true;

                Console.WriteLine("Enter your 16 digit Card Number in the format below:");
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("XXXXXXXXXXXXXXXX");
                Console.ResetColor();
                ///////////////////////
                while (true)
                {
                    while (!long.TryParse(Console.ReadLine(), out cardNumber))
                    {
                        Console.WriteLine("Please enter an appropriate value.");
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine("XXXXXXXXXXXXXXXX");
                        Console.ResetColor();
                    }
                    if (cardNumber.ToString().Length != 16)
                    {
                        Console.WriteLine("Please enter a 16 digit value");
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine("XXXXXXXXXXXXXXXX");
                        Console.ResetColor();
                    }
                    else
                    {
                        break;
                    }
                }
                while (true)    /////
                {
                    Console.WriteLine("Enter the year of expiration (YY)");
                    int year;

                    //GET YEAR
                    while (true)
                    {
                        while (!int.TryParse(Console.ReadLine(), out year))
                        {
                            Console.WriteLine("Please enter a valid number for input of year.");
                            Console.WriteLine();
                        }
                        if (year.ToString().Length > 2 && year >= 0)
                        {
                            Console.WriteLine("Only enter the last two digits");
                            Console.WriteLine();
                        }
                        else if (year.ToString().Length > 2 && year < 0)
                        {
                            Console.WriteLine("Only enter the last two digits and also, the year can't be negative");
                            Console.WriteLine();
                        }
                        else if (year < 0 && year.ToString().Length <= 2)
                        {
                            Console.WriteLine("Year cannot be negative");
                            Console.WriteLine();
                        }
                        else
                        {
                            break;
                        }
                    }

                    //GET MONTH
                    Console.WriteLine("Select month of expiration Enter 1 - 12");
                    int month;
                    while (true)
                    {
                        while (!int.TryParse(Console.ReadLine(), out month))
                        {
                            Console.WriteLine("Please enter a valid number.");
                        }
                        if (month < 1 || month > 12)
                        {
                            Console.WriteLine("Please enter a value that corresponds to a month. Please try enter another month.");
                        }

                        else
                        {
                            break;
                        }
                    }

                    //CHECK FOR EXPIRATION
                    if (cardCount == 3)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine("CARD REJECTED");
                        Console.ResetColor();
                        getCVV = false;
                        break;
                    }

                    else if ((year < currentYear) || (year == currentYear && month <= currentMonth))
                    {
                        Console.WriteLine("Your card has expired. Please enter again.");
                        cardCount++;
                    }

                    else if ((year > currentYear + 5) || (year == currentYear + 5 && month > currentMonth))
                    {
                        Console.WriteLine("Expiration date cannot be beyond five years from current year. Please enter again.");
                        cardCount++;
                    }

                    else
                    {
                        break;
                    }
                }    ////
                //ONLY GET CVV IF CARD HASN'T EXPIRED
                if (getCVV == true)
                {
                    Console.WriteLine("Enter CVV");
                    while (true)
                    {
                        while (!int.TryParse(Console.ReadLine(), out CVV))
                        {
                            Console.WriteLine("Please enter an appropriate value.");
                        }
                        if (CVV.ToString().Length != 3)
                        {
                            Console.WriteLine("Please enter a 3 digit value");
                        }
                        else
                        {
                            break;
                        }
                    }
                    break;
                }
                break;
            }//end of switch (choice)

            //Won't print this friendly message if check isn't accepted
            if (checkverify == true)
            {
                Console.WriteLine("-------------------------------------------------------------------------");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Thank you for shopping at the Grand Circus Grocery Store, come back soon!");
                Console.ResetColor();
                Console.WriteLine();
                Console.WriteLine();
            }
            //
        }
		/// <summary>
		/// Cria uma instância de Cielo.Holder definindo os dados do cartão.
		/// </summary>
		/// <param name="number">Número do cartão</param>
		/// <param name="expirationYear">Ano de expiração do cartão</param>
		/// <param name="expirationMonth">Mês de expiração do cartão</param>
		/// <param name="cvv">CVV do cartão</param>
		/// <param name="indicator">Indicador do CVV do cartão; ; veja Cielo.Holder.CVV</param>
		public Holder (String number, String expirationYear, String expirationMonth, String cvv, CVV indicator)
			: this (number, expirationYear, expirationMonth, cvv)
		{
			this.indicator = indicator;
		}
Beispiel #14
0
        public static void Thread1(object sock)
        {
            X509Certificate2 caCertificate = new X509Certificate2("d:/file/ca.crt");
            X509Certificate2 gatewayCertificate;
            string           issuerPrivateKey = File.ReadAllText("d:/file/IssuerPrivateKey.xml");
            X509Certificate2 issuerCertificate = new X509Certificate2("d:/file/issuer.crt");
            string           sendMessage, receiveMessage;
            Common           c = new Common();
            Socket           socket = (Socket)sock;

            string message;

            //nhận authorization request từ gateway

            receiveMessage = c.receive(ref socket);
            string[] splitAuthReq = receiveMessage.Split('-');
            gatewayCertificate = new X509Certificate2(c.StringToByteArray(splitAuthReq[3]));
            if (c.VerifyCertificate(caCertificate, gatewayCertificate) == false)
            {
                Console.WriteLine("verify authorization request certificate from gateway false");
                message = "ERROR" + ":" + "3" + ":" + "xac thuc that bai";
                ForwardAuthorizationResponse forwardAuthorizationResponse = new ForwardAuthorizationResponse(message, issuerPrivateKey, c.ByteArrayToString(issuerCertificate.GetRawCertData()));
                c.send(forwardAuthorizationResponse.ToMessage(), ref socket);
            }
            else
            {
                Console.WriteLine("verify authorization request certificate from gateway true");
                ForwardAuthorizationRequest forwardAuthorization = new ForwardAuthorizationRequest(splitAuthReq[0], splitAuthReq[1], splitAuthReq[2], splitAuthReq[3]);
                if (forwardAuthorization.verify(issuerPrivateKey) == false)
                {
                    Console.WriteLine("verify authorization request from gateway false");
                    string message1 = "ERROR" + ":" + "3" + ":" + "xac thuc that bai";
                    ForwardAuthorizationResponse forwardAuthorizationResponse = new ForwardAuthorizationResponse(message1, issuerPrivateKey, c.ByteArrayToString(issuerCertificate.GetRawCertData()));
                    c.send(forwardAuthorizationResponse.ToMessage(), ref socket);
                }
                else
                {
                    Console.WriteLine("verify authorization request from gateway true");
                    string   PI = forwardAuthorization.getPI(issuerPrivateKey);
                    string   cardNumber, CVV, dateValid, transID;
                    long     tien;
                    string[] splitPI = PI.Split(':');
                    transID    = splitPI[0];
                    cardNumber = splitPI[3];
                    CVV        = splitPI[4];
                    dateValid  = splitPI[5];
                    tien       = Convert.ToInt64(splitPI[6]);

                    //connect SQL server
                    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                    builder.DataSource     = "localhost";
                    builder.UserID         = "sa";
                    builder.Password       = "******";
                    builder.InitialCatalog = "Bank";
                    using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                    {
                        connection.Open();
                        bool          flag = false;
                        string        sql;
                        StringBuilder sb = new StringBuilder();
                        sql = "SELECT CardNumber, CVV, DateValid FROM Issuer;";
                        using (SqlCommand command = new SqlCommand(sql, connection))
                        {
                            string a;
                            using (SqlDataReader sqlReader = command.ExecuteReader())
                            {
                                while (sqlReader.Read())
                                {
                                    a = sqlReader.GetString(2);
                                    if (cardNumber.Equals(sqlReader.GetString(0)) == true && CVV.Equals(sqlReader.GetString(1)) == true && dateValid.Equals(sqlReader.GetString(2)) == true)
                                    {
                                        flag = true;//kiểm tra tài khoản customer có đúng hay không
                                    }
                                }
                            }
                        }
                        if (flag == false)
                        {
                            string s = "ERROR" + ":" + "2" + ":" + "tai khoan khong chinh xac";
                            ForwardAuthorizationResponse forwardAuthorizationResponse = new ForwardAuthorizationResponse(s, issuerPrivateKey, c.ByteArrayToString(issuerCertificate.GetRawCertData()));
                            c.send(forwardAuthorizationResponse.ToMessage(), ref socket);
                        }
                        else
                        {
                            //ghi PI vào log Isuuer
                            sb.Clear();
                            sb.Append("INSERT LogIssuer (TransID, CardNumber, Money, Paid) ");
                            sb.Append("VALUES (@trans, @cardid, @money, @paid);");
                            sql = sb.ToString();
                            using (SqlCommand command = new SqlCommand(sql, connection))
                            {
                                command.Parameters.AddWithValue("@trans", transID);
                                command.Parameters.AddWithValue("@cardid", cardNumber);
                                command.Parameters.AddWithValue("@money", tien);
                                command.Parameters.AddWithValue("@paid", 0);
                                int rowsAffected = command.ExecuteNonQuery();
                            }
                            //gửi forward response
                            string issuerCert = c.ByteArrayToString(issuerCertificate.GetRawCertData());
                            ForwardAuthorizationResponse authorizationResponse = new ForwardAuthorizationResponse(transID, 1, cardNumber, issuerPrivateKey, issuerCert);
                            c.send(authorizationResponse.ToMessage(), ref socket);

                            //nhận capture request từ gateway
                            receiveMessage = c.receive(ref socket);
                            string[] splitCapture = receiveMessage.Split('-');
                            gatewayCertificate = new X509Certificate2(c.StringToByteArray(splitCapture[6]));
                            if (c.VerifyCertificate(caCertificate, gatewayCertificate) == false)
                            {
                                Console.WriteLine("verify capture request certificate from gateway false");
                                string s = "ERROR" + ":" + "3" + ":" + "xac thuc that bai";
                                s = s + "-" + c.Sign(issuerPrivateKey, s) + "-" + c.ByteArrayToString(issuerCertificate.GetRawCertData());
                                c.send(s, ref socket);
                            }
                            else
                            {
                                Console.WriteLine("verify capture request certificate from gateway true");
                                string captureRequest = getToken(receiveMessage);//thông tin tài khoản customer
                                if (captureRequest == null)
                                {
                                    string message1 = "ERROR" + ":" + "3" + ":" + "xac thuc that bai";
                                    message1 = message1 + "-" + c.Sign(issuerPrivateKey, message1) + "-" + c.ByteArrayToString(issuerCertificate.GetRawCertData());
                                    c.send(message1, ref socket);
                                }
                                else
                                {
                                    string   customerCardNumber;
                                    long     soTien;
                                    string[] splitCaptureRequest = captureRequest.Split(':');
                                    transID            = splitCaptureRequest[0];
                                    customerCardNumber = splitCaptureRequest[1];
                                    soTien             = Convert.ToInt64(splitCaptureRequest[2]);

                                    //nhập dữ liệu thanh toán vào sql server
                                    using (SqlConnection connection1 = new SqlConnection(builder.ConnectionString))
                                    {
                                        connection1.Open();
                                        string        sql1;
                                        StringBuilder sb1 = new StringBuilder();
                                        sb1.Clear();
                                        sb1.Append("UPDATE LogIssuer SET Paid = @paid WHERE TransID = @id");
                                        sql1 = sb1.ToString();
                                        using (SqlCommand command = new SqlCommand(sql1, connection1))
                                        {
                                            command.Parameters.AddWithValue("@id", transID);
                                            command.Parameters.AddWithValue("@paid", 1);
                                            int rowsAffected = command.ExecuteNonQuery();
                                        }
                                        long tienBanDau = 0;
                                        sql1 = "SELECT CardNumber, UsedMoney FROM Issuer;";
                                        using (SqlCommand command = new SqlCommand(sql1, connection1))
                                        {
                                            using (SqlDataReader sqlReader = command.ExecuteReader())
                                            {
                                                while (sqlReader.Read())
                                                {
                                                    if (cardNumber.Equals(sqlReader.GetString(0)) == true)
                                                    {
                                                        tienBanDau = sqlReader.GetInt64(1);
                                                    }
                                                }
                                            }
                                        }
                                        sb1.Clear();
                                        sb1.Append("UPDATE Issuer SET UsedMoney = @tien WHERE CardNumber = @id");
                                        sql1 = sb1.ToString();
                                        using (SqlCommand command = new SqlCommand(sql1, connection1))
                                        {
                                            command.Parameters.AddWithValue("@tien", soTien + tienBanDau);
                                            command.Parameters.AddWithValue("@id", customerCardNumber);
                                            int rowsAffected = command.ExecuteNonQuery();
                                        }
                                        connection1.Close();
                                        connection.Close();
                                    }

                                    //send message to acquirer
                                    sendMessage = splitCapture[0] + "-" + splitCapture[1] + "-" + splitCapture[2] + "-" + splitCapture[6];
                                    IPEndPoint iep    = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1237);
                                    Socket     client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                    client.Connect(iep);
                                    c.send(sendMessage, ref client);

                                    //nhận message từ acquirer
                                    receiveMessage = c.receive(ref client);
                                    string[]         splitAcquirer       = receiveMessage.Split('-');
                                    X509Certificate2 acquirerCertificate = new X509Certificate2(c.StringToByteArray(splitAcquirer[2]));
                                    if (c.VerifyCertificate(caCertificate, acquirerCertificate) == true)
                                    {
                                        Console.WriteLine("verify capture response certificate from acquirer true");
                                        string acquirerPublicKey = acquirerCertificate.GetRSAPublicKey().ToXmlString(false);
                                        if (c.Verify(acquirerPublicKey, splitAcquirer[1], splitAcquirer[0]) == true)
                                        {
                                            Console.WriteLine("verify capture response from acquirer true");
                                            message = splitAcquirer[0];
                                            c.send(message + "-" + c.Sign(issuerPrivateKey, message) + "-" + issuerCert, ref socket);
                                        }
                                    }
                                    //client.Close();
                                }
                            }
                        }
                    }
                }
            }

            socket.Close();
        }
        public void CadastraCartao()
        {
            BDConexao conexao = new BDConexao();

            conexao.connection.Open();

            conexao.command.CommandText = "DELETE FROM CARTAOCREDITO WHERE IDCLIENTE = @ID";
            conexao.command.Parameters.Clear();
            conexao.command.Parameters.Add("@ID", SqlDbType.VarChar).Value = IdCliente;
            conexao.command.ExecuteNonQuery();

            conexao.command.CommandText = "INSERT INTO CARTAOCREDITO VALUES(@BANDEIRA, @NUMCARTAO, @CVV, @VALIDADE, @IDCLIENTE, @TITULAR)";
            conexao.command.Parameters.Clear();
            conexao.command.Parameters.Add("@BANDEIRA", SqlDbType.VarChar).Value  = StatueStoreEncrypt.Encrypt(Bandeira);
            conexao.command.Parameters.Add("@NUMCARTAO", SqlDbType.VarChar).Value = StatueStoreEncrypt.Encrypt(NumeroCartao.ToString().Trim().Replace(".", "").Replace("-", "").Replace(" ", ""));
            conexao.command.Parameters.Add("@CVV", SqlDbType.VarChar).Value       = StatueStoreEncrypt.Encrypt(CVV.Trim().Replace(".", "").Replace("-", "").Replace(" ", ""));
            conexao.command.Parameters.Add("@VALIDADE", SqlDbType.VarChar).Value  = StatueStoreEncrypt.Encrypt(Validade);
            conexao.command.Parameters.Add("@IDCLIENTE", SqlDbType.VarChar).Value = IdCliente;
            conexao.command.Parameters.Add("@TITULAR", SqlDbType.VarChar).Value   = StatueStoreEncrypt.Encrypt(Titular);
            conexao.command.ExecuteNonQuery();
            conexao.connection.Close();
        }