Example #1
0
        public IActionResult GetPaymentInfo()
        {
            var tenantID = CookieHandler.GetCurrentUserID(Request.Cookies["AuthToken"]);
            var tenant   = Methods.Methods.GetTenant(tenantID);

            //New tenants with no previous payment method
            if (tenant.StripeID == "")
            {
                return(Json(new { success = false }));
            }

            //Tenants who has a payment method on file, but needs to verify a bank account
            if (tenant.StripeIsVerified == false)
            {
                BankAccount bank = StripeService.GetBankAccount(tenant);
                return(Json(new { success = true, isVerified = false, paymentInfo = bank }));
            }

            //Tenant who has payment method on file, and ready to make payments.
            if (tenant.StripeIsVerified == true)
            {
                BankAccount bank = StripeService.GetBankAccount(tenant);
                return(Json(new { success = true, isVerified = true, paymentInfo = bank }));
            }
            return(BadRequest());
        }
Example #2
0
        private static void Test_CreateCustomer()
        {
            Console.Write("[{0}] Testing create customer... ", Timestamp);
            var stripe = new StripeService(API_KEY);

            Customer customer = stripe.CreateCustomerAsync(SAMPLE_CUSTOMER_EMAIL, "A sample customer.").Result;

            if (customer == null)
            {
                Console.WriteLine();
                if (!stripe.HasError)
                {
                    throw new TestFailedException("Customer creation failed for unknown reasons.");
                }

                throw new TestFailedException("Customer creation failed ({0}): {1} {2}",
                                              stripe.Error.Type,
                                              stripe.Error.Message,
                                              stripe.Error.Parameter);
            }

            _testCustomerId = customer.Id;

            Console.WriteLine("pass");
        }
        public async Task <IActionResult> ConnectWebHook()
        {
            var   json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            Event stripeEvent;

            try
            {
                stripeEvent = EventUtility.ConstructEvent(
                    json,
                    Request.Headers["Stripe-Signature"],
                    Configuration.GetValue <string>("StripeCredentials:WebhookSecret")
                    );
                Console.WriteLine($"Webhook notification with type: {stripeEvent.Type} found for {stripeEvent.Id}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Something failed {e}");
                return(BadRequest());
            }

            if (stripeEvent.Type == Events.AccountUpdated)
            {
                Account       account = stripeEvent.Data.Object as Account;
                StripeService service = new StripeService(_userRepository, Configuration);
                if (account.ChargesEnabled)
                {
                    await service.UpdateStripeConnected(account.Id);
                }
            }
            return(Ok());
        }
Example #4
0
        public IActionResult VerifyBankAccount(string first, string second)
        {
            var tenantID = CookieHandler.GetCurrentUserID(Request.Cookies["AuthToken"]);
            var tenant   = Methods.Methods.GetTenant(tenantID);

            var deposits = new List <string>();

            deposits.Add(first);
            deposits.Add(second);
            try
            {
                if (StripeService.VerifyBankAccount(tenant, deposits))
                {
                    return(Json(new { success = true }));
                }
                else
                {
                    return(Json(new { success = false, error = "Could not verify bank." }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, error = ex.Message }));
            }
        }
 public PaymentController(AppDbContext context, ILogger <MatchController> logger, StripeService stripeService, IConfiguration configuration)
 {
     _context         = context;
     _logger          = logger;
     _stripeService   = stripeService;
     _stripeSignature = configuration["StripeSignature"];
 }
Example #6
0
        private static void Test_AddBankAccountToCustomer()
        {
            Console.Write("[{0}] Testing add bank account to customer... ", Timestamp);
            var stripe = new StripeService(API_KEY);

            BankAccount bankAccount = stripe.AddBankAccountAsync(
                _testCustomerId,
                Guid.NewGuid().ToString(),
                AccountHolderType.Individual,
                "000123456789",
                "110000000").Result;

            if (bankAccount == null)
            {
                Console.WriteLine();
                if (!stripe.HasError)
                {
                    throw new TestFailedException("Add bank account failed for unknown reasons.");
                }

                throw new TestFailedException("Add bank account failed ({0}): {1} {2}",
                                              stripe.Error.Type,
                                              stripe.Error.Message,
                                              stripe.Error.Parameter);
            }

            _testBankAccountId = bankAccount.Id;

            Console.WriteLine("pass");
        }
Example #7
0
        private static void Test_FetchCustomer()
        {
            Console.Write("[{0}] Testing fetch customer... ", Timestamp);
            var stripe = new StripeService(API_KEY);

            Customer customer = stripe.GetCustomerAsync(_testCustomerId).Result;

            if (customer == null)
            {
                Console.WriteLine();
                if (!stripe.HasError)
                {
                    throw new TestFailedException("Fetch customer failed for unknown reasons.");
                }

                throw new TestFailedException("Fetch customer failed ({0}): {1} {2}",
                                              stripe.Error.Type,
                                              stripe.Error.Message,
                                              stripe.Error.Parameter);
            }

            if (customer.Email != SAMPLE_CUSTOMER_EMAIL)
            {
                throw new TestFailedException("Fetched customer has different email.");
            }

            Console.WriteLine("pass");
        }
Example #8
0
        private static void Test_AddCardToCustomer()
        {
            Console.Write("[{0}] Testing add card to customer... ", Timestamp);
            var stripe = new StripeService(API_KEY);

            Card card = stripe.AddCardAsync(
                _testCustomerId,
                7,
                DateTime.Now.AddYears(3).Year,
                123,
                "424242424242s242",
                "123 Address St",
                null,
                "Austin",
                "78729",
                "TX").Result;

            if (card == null)
            {
                Console.WriteLine();
                if (!stripe.HasError)
                {
                    throw new TestFailedException("Add card failed for unknown reasons.");
                }

                throw new TestFailedException("Add card failed ({0}): {1} {2}",
                                              stripe.Error.Type,
                                              stripe.Error.Message,
                                              stripe.Error.Parameter);
            }

            _testCardId = card.Id;

            Console.WriteLine("pass");
        }
Example #9
0
 public CohortController()
 {
     _activation = Config.Container.Resolve <ActivationService>(); //new ActivationService(user, auth, activation);
     _accounts   = Config.Container.Resolve <AccountService>();    // (new AccountService(user, security, auth));
     _email      = Config.Container.Resolve <EmailService>();      ////new EmailService(Cohort.Email.Engine, Cohort.Email.Provider, new EmailRepository());
     _stripe     = Config.Container.Resolve <StripeService>();
 }
Example #10
0
 public OrderService(IHttpContextAccessor accessor, OrderRepository orderRepository, IPInfoService ipInfo, StripeService stripeService, IMapper mapper)
 {
     this.Accessor        = accessor;
     this.OrderRepository = orderRepository;
     this.IPInfo          = ipInfo;
     this.StripeService   = stripeService;
     this.Mapper          = mapper;
 }
Example #11
0
 public StripeController(StripeService stripeService, PackageService cashService,
                         SessionHandler sessionHandler, DonationTransactionService cashTransactionService)
 {
     _stripeService              = stripeService;
     _packageService             = cashService;
     _donationTransactionService = cashTransactionService;
     _sessionUser = sessionHandler.GetSessionUser();
 }
Example #12
0
        private static void Test_CreateCharge()
        {
            Console.Write("[{0}] Test creating a charge... ", Timestamp);
            var stripe = new StripeService(API_KEY);

            Charge charge = stripe.CreateChargeAsync("cus_9tvLjBM1FynkwG", "card_19a82RJB5O7unlMsd398UwIG", 100).Result;

            Console.WriteLine("pass");
        }
 public TicketController(CommonContext commonContext, IServiceProvider serviceProvider, RedisCache redisCache, IOptions <AppSettings> appSettings, CommonAccountService commonAccountSvc, FileService fileService, IDataProtectionProvider dataProtector, StripeService stripeSvc, CitationService citationSvc)
     : base(commonContext, serviceProvider, redisCache, appSettings)
 {
     _commonAccountSvc = commonAccountSvc;
     _dataProtector    = dataProtector.CreateProtector(GetType().FullName);
     _fileService      = fileService;
     _stripeSvc        = stripeSvc;
     _citationSvc      = citationSvc;
 }
Example #14
0
 public Dependencies(InteractivityModule interactivity, WebhookController whm, SubscriptionProcessor subProcessor, WhConfigHolder whConfig, StripeService stripe)
 {
     Interactivity         = interactivity;
     Whm                   = whm;
     SubscriptionProcessor = subProcessor;
     _configHolder         = whConfig;
     Stripe                = stripe;
     OsmManager            = new OsmManager();
 }
Example #15
0
 public Dependencies(InteractivityModule interactivity, WebhookManager whm, SubscriptionProcessor subProcessor, WhConfig whConfig, Translator language, StripeService stripe)
 {
     Interactivity         = interactivity;
     Whm                   = whm;
     SubscriptionProcessor = subProcessor;
     WhConfig              = whConfig;
     Language              = language;
     Stripe                = stripe;
     OsmManager            = new OsmManager();
 }
Example #16
0
 public PaymentMutations(PaymentContext context, IEventService template1EventService, IMapper mapper,
                         IAuthorizationService authorizationService, StripeService stripeService, IPaymentService service) : base(authorizationService)
 {
     _context = context ?? throw new ArgumentNullException(nameof(context));
     ;
     _eventService  = template1EventService ?? throw new ArgumentNullException(nameof(template1EventService));
     _mapper        = mapper;
     _stripeService = stripeService;
     _service       = service;
 }
 public CommerceRepository(
     IConfiguration config,
     StripeService str,
     SearchRepository cr,
     CartStore cs)
 {
     _conn   = config["ConnectionStrings:tc_dev"];
     _stripe = str;
     _crash  = cr;
     _cart   = cs;
 }
Example #18
0
 public IActionResult CalculateACHFee(decimal amount)
 {
     try
     {
         var fee = StripeService.CalculateTransactionFee(amount);
         return(Json(new { success = true, data = fee }));
     }
     catch (Exception ex)
     {
         return(Json(new { success = false, error = ex.Message }));
     }
 }
Example #19
0
        public StripeViewComponent(IUserService userService, IOrderService orderService, StripeService stripeService, IOptions <StripeSettings> stripeOptions)
        {
            _userService   = userService;
            _orderService  = orderService;
            _stripeService = stripeService;
            _stripeOptions = stripeOptions;

            _checkoutSessionService = new Stripe.Checkout.SessionService();

            _stripeFeePercent = 29;                              // 2.9%
            _stripeFeeFixed   = 30;                              // $0.30

            _stripeFeePercentInverse = 1000 - _stripeFeePercent; // 97.1%
        }
Example #20
0
        private static void Test_CreateDuplicateCustomer()
        {
            Console.Write("[{0}] Testing create customer with existing email... ", Timestamp);
            var stripe = new StripeService(API_KEY);

            Customer customer = stripe.CreateCustomerAsync(SAMPLE_CUSTOMER_EMAIL, "A sample customer.").Result;

            if (customer != null)
            {
                Console.WriteLine();
                throw new TestFailedException("Customer was created and should not have been.");
            }

            Console.WriteLine("pass");
        }
        public static string ApplyAllParameters(this StripeService service, object obj, string url, bool isListMethod = false)
        {
            string requestString = url;

            if (obj != null)
            {
                foreach (PropertyInfo runtimeProperty in obj.GetType().GetRuntimeProperties())
                {
                    object value = runtimeProperty.GetValue(obj, null);
                    if (value == null)
                    {
                        continue;
                    }
                    foreach (JsonPropertyAttribute customAttribute in runtimeProperty.GetCustomAttributes <JsonPropertyAttribute>())
                    {
                        if (value is INestedOptions)
                        {
                            ApplyNestedObjectProperties(ref requestString, value);
                        }
                        else
                        {
                            RequestStringBuilder.ProcessPlugins(ref requestString, customAttribute, runtimeProperty, value, obj);
                        }
                    }
                }
            }
            if (service != null)
            {
                IEnumerable <string> enumerable = from p in service.GetType().GetRuntimeProperties()
                                                  where p.Name.StartsWith("Expand") && p.PropertyType == typeof(bool)
                                                  where (bool)p.GetValue(service, null)
                                                  select p.Name;
                foreach (string item in enumerable)
                {
                    string input = item.Substring("Expand".Length);
                    input = Regex.Replace(input, "([a-z])([A-Z])", "$1_$2").ToLower();
                    if (isListMethod)
                    {
                        input = "data." + input;
                    }
                    requestString = ApplyParameterToUrl(requestString, "expand[]", input);
                }
            }
            return(requestString);
        }
Example #22
0
        private static void Test_DeleteBankAccount()
        {
            Console.Write("[{0}] Testing delete bank account from customer... ", Timestamp);
            var stripe = new StripeService(API_KEY);

            stripe.DeleteBankAccountAsync(_testCustomerId, _testBankAccountId).Wait();

            if (stripe.HasError)
            {
                Console.WriteLine();
                throw new TestFailedException("Delete bank account failed ({0}): {1} {2}",
                                              stripe.Error.Type,
                                              stripe.Error.Message,
                                              stripe.Error.Parameter);
            }

            Console.WriteLine("pass");
        }
Example #23
0
        private static void Test_UpdateCard()
        {
            Console.Write("[{0}] Testing update card on customer... ", Timestamp);
            var    stripe     = new StripeService(API_KEY);
            string newCity    = "Testing City";
            string newLineOne = "123 Address St";
            string newZip     = "78729";

            Card card = stripe.UpdateCardAsync(
                _testCustomerId,
                _testCardId,
                city: newCity,
                lineOne: newLineOne,
                zip: newZip).Result;

            if (card == null)
            {
                Console.WriteLine();
                if (!stripe.HasError)
                {
                    throw new TestFailedException("Update card failed for unknown reasons.");
                }

                throw new TestFailedException("Update card failed ({0}): {1} {2}",
                                              stripe.Error.Type,
                                              stripe.Error.Message,
                                              stripe.Error.Parameter);
            }

            if (card.AddressZip != newZip)
            {
                throw new TestFailedException("Update card failed: zip is not equal");
            }
            if (card.AddressCity != newCity)
            {
                throw new TestFailedException("Update card failed: city is not equal");
            }
            if (card.AddressLineOne != newLineOne)
            {
                throw new TestFailedException("Update card failed: line1 is not equal");
            }

            Console.WriteLine("pass");
        }
Example #24
0
        public static void Main(string[] args)
        {
            try {
                var  stripe = new StripeService(API_KEY);
                Card card   = stripe.AddCardAsync(
                    "cus_9uJl7IpB8QLBYi",
                    7,
                    DateTime.Now.AddYears(3).Year,
                    123,
                    "4242424242424242",
                    "123 Address St",
                    null,
                    "Austin",
                    "78729",
                    "TXASFWQERWQE").Result;
                //Test_CreateCustomer();
                //Test_CreateDuplicateCustomer();
                //Test_FetchCustomer();

                //Test_AddCardToCustomer();
                //Test_FetchCard();
                //Test_UpdateCard();

                //Test_AddBankAccountToCustomer();
                //Test_FetchBankAccount();
                //Test_UpdateBankAccount();

                //Test_CreateCharge();

                //Test_DeleteCard();
                //Test_DeleteBankAccount();
            } catch (TestFailedException ex) {
                Console.WriteLine("[{0}]: {1}", Timestamp, ex.Message);
            } catch (Exception ex) {
                Console.WriteLine("[{0}] Unexpected exception: {1}\nInner Message: {2}\nStack Trace: {3}",
                                  Timestamp,
                                  ex.Message,
                                  ex.InnerException?.Message ?? "None",
                                  ex.StackTrace);
            }

            Console.WriteLine("Done...");
            Console.ReadLine();
        }
Example #25
0
        public IActionResult UpdateBillingInfo(string StripeToken)
        {
            //FIRST: check if Stripe customer exists,
            // If true: get stripe customer ID, send token, and store bank_id in DB
            // If false: Create stripe customer and send token (one call), then store bank_id in DB

            var tenantID   = CookieHandler.GetCurrentUserID(Request.Cookies["AuthToken"]);
            var isTypeBank = true; //hardcoded type
            var isVerified = false;

            if (isTypeBank)
            {
                isVerified = false;
            }

            if (StripeToken == null)
            {
                return(Json(new { success = false, error = "No Stripe Token provided." }));
            }

            var currentTenant = Methods.Methods.GetTenant(tenantID);

            //Check if Stripe customer doesnt exist, create one. Else, update customer in Stripe.
            if (currentTenant.StripeID == "" || currentTenant.StripeID == null)
            {
                if (StripeService.CreateCustomer(currentTenant, StripeToken, isVerified))
                {
                    return(Json(new { success = true }));
                }
                return(Json(new { success = false, error = "Could not create Stripe customer." }));
            }
            else
            {
                var tenant = Methods.Methods.GetTenant(tenantID);
                StripeService.UpdateCustomer(tenant.TenantID, tenant.StripeID, StripeToken, isVerified);

                return(Json(new { success = true, isVerified = isVerified, hasBillingInfo = true }));
            }
        }
Example #26
0
        private static void Test_UpdateBankAccount()
        {
            Console.Write("[{0}] Testing update bank account from customer... ", Timestamp);
            var    stripe = new StripeService(API_KEY);
            string newAccountHolderName = Guid.NewGuid().ToString();

            BankAccount bankAccount = stripe.UpdateBankAccountAsync(
                _testCustomerId,
                _testBankAccountId,
                newAccountHolderName,
                AccountHolderType.Company).Result;

            if (bankAccount == null)
            {
                Console.WriteLine();
                if (!stripe.HasError)
                {
                    throw new TestFailedException("Update bank account failed for unknown reasons.");
                }

                throw new TestFailedException("Update bank account failed ({0}): {1} {2}",
                                              stripe.Error.Type,
                                              stripe.Error.Message,
                                              stripe.Error.Parameter);
            }

            if (bankAccount.AccountHolderName != newAccountHolderName)
            {
                Console.WriteLine();
                throw new TestFailedException("Update bank account failed: account holder names differ");
            }
            if (bankAccount.AccountHolderType != AccountHolderType.Company)
            {
                Console.WriteLine();
                throw new TestFailedException("Update bank account failed: account holder types differ");
            }

            Console.WriteLine("pass");
        }
Example #27
0
        public async Task <IHttpActionResult> Fund([FromBody] FundWalletBindingModel model)
        {
            StripeService stripe   = new StripeService();
            var           response = await stripe.ChargeCustomer(model.StripeToken, model.TransactionAmount);

            if (response)
            {
                var user = await HGContext.Users.FirstOrDefaultAsync(x => x.Id == model.UserId);

                var wallet = await HGContext.Wallets.FirstOrDefaultAsync(x => x.Id == model.WalletId);

                if (wallet != null && user.WalletId == wallet.Id)
                {
                    wallet.Transactions.Add(new Transaction()
                    {
                        TransactedAt      = DateTimeOffset.UtcNow,
                        TransactionAmount = model.TransactionAmount / 100M,
                        TransactionCharge = 0M,
                        TransactionStatus = TransactionStatusEnum.CLEARED,
                        TransactionType   = TransactionTypeEnum.DEPOSIT
                    });

                    var result = HGContext.SaveChanges();
                    if (result == 0)
                    {
                        return(BadRequest("Something went wrong"));
                    }
                    return(Ok());
                }
                return(BadRequest("Something went wrong"));
            }
            else
            {
                _logger.ErrorFormat("Failed to finalize payment user {0} amount {1}", model.UserId, model.TransactionAmount);
                return(BadRequest("Something went wrong"));
            }
            //return Ok(response);
        }
Example #28
0
        private static void Test_FetchBankAccount()
        {
            Console.Write("[{0}] Testing fetch bank account from customer... ", Timestamp);
            var stripe = new StripeService(API_KEY);

            BankAccount bankAccount = stripe.GetBankAccountAsync(_testCustomerId, _testBankAccountId).Result;

            if (bankAccount == null)
            {
                Console.WriteLine();
                if (!stripe.HasError)
                {
                    throw new TestFailedException("Fetch bank account failed for unknown reasons.");
                }

                throw new TestFailedException("Fetch bank account failed ({0}): {1} {2}",
                                              stripe.Error.Type,
                                              stripe.Error.Message,
                                              stripe.Error.Parameter);
            }

            Console.WriteLine("pass");
        }
Example #29
0
        public static string ApplyAllParameters(this StripeService service, object obj, string url, bool isListMethod = false)
        {
            // store the original url from the service call into requestString (e.g. https://api.stripe.com/v1/accounts/account_id)
            // before the stripe attributes get applied. all of the attributes that will get passed to stripe will be applied to this string,
            // don't worry - if the request is a post, the Requestor will take care of moving the attributes to the post body
            var requestString = url;

            // obj = the options object passed from the service
            if (obj != null)
            {
                foreach (var property in obj.GetType().GetRuntimeProperties())
                {
                    var value = property.GetValue(obj, null);
                    if (value == null)
                    {
                        continue;
                    }

                    foreach (var attribute in property.GetCustomAttributes <JsonPropertyAttribute>())
                    {
                        if (value is INestedOptions)
                        {
                            ApplyNestedObjectProperties(ref requestString, value);
                        }
                        else
                        {
                            RequestStringBuilder.ProcessPlugins(ref requestString, attribute, property, value, obj);
                        }
                    }
                }
            }

            if (service != null)
            {
                // expandable properties
                var propertiesToExpand = service.GetType()
                                         .GetRuntimeProperties()
                                         .Where(p => p.Name.StartsWith("Expand") && p.PropertyType == typeof(bool))
                                         .Where(p => (bool)p.GetValue(service, null))
                                         .Select(p => p.Name);

                foreach (var propertyName in propertiesToExpand)
                {
                    string expandPropertyName = propertyName.Substring("Expand".Length);
                    expandPropertyName = Regex.Replace(expandPropertyName, "([a-z])([A-Z])", "$1_$2").ToLower();

                    if (isListMethod)
                    {
                        expandPropertyName = "data." + expandPropertyName;
                    }

                    requestString = ApplyParameterToUrl(requestString, "expand[]", expandPropertyName);

                    // note: I had no idea you could expand properties beyond the first level (up to 4 before stripe throws an exception).
                    // something to consider adding to the project.
                    //
                    // example:
                    // requestString = ApplyParameterToUrl(requestString, "expand[]", "data.charge.dispute.charge.dispute.charge.dispute");
                }
            }

            return(requestString);
        }
Example #30
0
 public UserCreatedEventConsumer(PaymentContext paymentContext, StripeService stripeService)
 {
     _paymentContext = paymentContext;
     _stripeService  = stripeService;
 }