Beispiel #1
0
        static public async Task PortCustomersAsync()
        {
            List <ShopifySharp.Customer> customers = Shopify.GetCustomers();

            foreach (ShopifySharp.Customer customer in customers)
            {
                CustomersApi api = new CustomersApi();
                if (customer.DefaultAddress != null)
                {
                    await api.CreateCustomerAsync(new CreateCustomerRequest(
                                                      GivenName : customer.FirstName,
                                                      FamilyName : customer.LastName,
                                                      EmailAddress : customer.Email,
                                                      Address : new Address(
                                                          AddressLine1 : customer.DefaultAddress.Address1,
                                                          AddressLine2 : customer.DefaultAddress.Address2,
                                                          Locality : customer.DefaultAddress.City,
                                                          AdministrativeDistrictLevel1 : customer.DefaultAddress.ProvinceCode,
                                                          PostalCode : customer.DefaultAddress.Zip,
                                                          Country : "US"),
                                                      PhoneNumber : customer.Phone,
                                                      ReferenceId : customer.Id.Value.ToString()
                                                      ));
                }
                else
                {
                    await api.CreateCustomerAsync(new CreateCustomerRequest(
                                                      GivenName : customer.FirstName,
                                                      FamilyName : customer.LastName,
                                                      EmailAddress : customer.Email,
                                                      PhoneNumber : customer.Phone,
                                                      ReferenceId : customer.Id.Value.ToString()));
                }
            }
        }
        /// <summary>
        /// Create the new customer
        /// </summary>
        /// <param name="customerRequest">Request parameters to create customer</param>
        /// <returns>Customer</returns>
        public Customer CreateCustomer(CreateCustomerRequest customerRequest)
        {
            try
            {
                //create customer API
                var configuration = CreateApiConfiguration();
                var customersApi = new CustomersApi(configuration);

                //create the new customer
                var createCustomerResponse = customersApi.CreateCustomer(customerRequest);
                if (createCustomerResponse == null)
                    throw new NopException("No service response");

                //check whether there are errors in the service response
                if (createCustomerResponse.Errors?.Any() ?? false)
                {
                    var errorsMessage = string.Join(";", createCustomerResponse.Errors.Select(error => error.ToString()));
                    throw new NopException($"There are errors in the service response. {errorsMessage}");
                }

                return createCustomerResponse.Customer;
            }
            catch (Exception exception)
            {
                var errorMessage = $"Square payment error: {exception.Message}.";
                if (exception is ApiException apiException)
                    errorMessage = $"{errorMessage} Details: {apiException.ErrorCode} - {apiException.ErrorContent}";

                //log errors
                _logger.Error(errorMessage, exception, _workContext.CurrentCustomer);

                return null;
            }
        }
Beispiel #3
0
        /// <summary>
        /// Create the new card of the customer
        /// </summary>
        /// <param name="customerId">Customer ID</param>
        /// <param name="cardRequest">Request parameters to create card of the customer</param>
        /// <returns>Card</returns>
        public Card CreateCustomerCard(string customerId, CreateCustomerCardRequest cardRequest)
        {
            try
            {
                //create customer API
                var configuration = CreateApiConfiguration();
                var customersApi  = new CustomersApi(configuration);

                //create the new card of the customer
                var createCustomerCardResponse = customersApi.CreateCustomerCard(customerId, cardRequest);
                if (createCustomerCardResponse == null)
                {
                    throw new NopException("No service response");
                }

                //check whether there are errors in the service response
                if (createCustomerCardResponse.Errors?.Any() ?? false)
                {
                    var errorsMessage = string.Join(";", createCustomerCardResponse.Errors.Select(error => error.ToString()));
                    throw new NopException($"There are errors in the service response. {errorsMessage}");
                }

                return(createCustomerCardResponse.Card);
            }
            catch (Exception exception)
            {
                //log full error
                _logger.Error($"Square payment error: {exception.Message}.", exception, _workContext.CurrentCustomer);

                return(null);
            }
        }
Beispiel #4
0
        public void GetCustomerTest()
        {
            string authorization = "Basic asdadsa";
            string customerId    = "123123";

            mockRestClient.Expects.One.Method(v => v.Execute(new RestRequest())).With(NMock.Is.TypeOf(typeof(RestRequest))).WillReturn(customerResponse);
            ApiClient apiClient = new ApiClient(mockRestClient.MockObject);

            apiClient.Configuration = null;

            Configuration configuration = new Configuration
            {
                ApiClient      = apiClient,
                Username       = "******",
                Password       = "******",
                AccessToken    = null,
                ApiKey         = null,
                ApiKeyPrefix   = null,
                TempFolderPath = null,
                DateTimeFormat = null,
                Timeout        = 60000,
                UserAgent      = "asdasd"
            };

            instance = new CustomersApi(configuration);

            var response = instance.GetCustomer(authorization, customerId);

            Assert.IsInstanceOf <Customer>(response, "response is Customer");
        }
 public ContactsController(
     TourManagerContext tourManagerContext
     )
 {
     _tourManagerContext = tourManagerContext;
     _customersApi       = new CustomersApi(_tourManagerContext);
 }
Beispiel #6
0
        public void UpdateCustomerTest()
        {
            string authorization = "Basic asdadsa";
            string customerId    = "2345";

            mockRestClient.Expects.One.Method(v => v.Execute(new RestRequest())).With(NMock.Is.TypeOf(typeof(RestRequest))).WillReturn(customerResponse);
            ApiClient apiClient = new ApiClient(mockRestClient.MockObject);

            apiClient.Configuration = null;
            Identifier     identifier     = new Identifier("*****@*****.**", "Customer Reference");
            CreateCustomer updateCustomer = new CreateCustomer("create customer test", identifier, null);

            Configuration configuration = new Configuration
            {
                ApiClient      = apiClient,
                Username       = "******",
                Password       = "******",
                AccessToken    = null,
                ApiKey         = null,
                ApiKeyPrefix   = null,
                TempFolderPath = null,
                DateTimeFormat = null,
                Timeout        = 60000,
                UserAgent      = "asdasd"
            };

            instance = new CustomersApi(configuration);

            var response = instance.UpdateCustomer(customerId, updateCustomer, authorization);

            Assert.IsInstanceOf <Customer>(response, "response is Customer");
        }
Beispiel #7
0
 public PaystackApi(string apiKey)
 {
     _apiKey             = apiKey;
     SubAccounts         = new SubAccountApi(this);
     Transactions        = new TransactionsApi(this);
     Customers           = new CustomersApi(this);
     Miscellaneous       = new MiscellaneousApi(this);
     Charge              = new ChargeApi(this);
     _paystackApiBaseUrl = new Uri("https://api.paystack.co/");
 }
Beispiel #8
0
        public IObservable <Unit> Sync(string beginTime, ISourceCache <RewardsMember, string> rewardsMemberCache)
        {
            var customersApi = new CustomersApi();
            var filter       = new CustomerFilter(UpdatedAt: new TimeRange(beginTime));
            var query        = new CustomerQuery(filter);

            return(GetRecentlyUpdatedCustomers(customersApi, query, null)
                   .Where(x => x != null)
                   .SelectMany(x => x)
                   .Where(customer => !string.IsNullOrWhiteSpace(customer.PhoneNumber))
                   .Select(customer => HandlePotentialCustomerMerge(customer, rewardsMemberCache))
                   .SelectMany(rewardsMember => _rewardsMemberRepo.Upsert(rewardsMember)));
        }
Beispiel #9
0
        private async void OnSaveCustomer(object sender, RoutedEventArgs e)
        {
            Customer customer = new Customer
            {
                Name    = "John",
                Surname = "Doe",
                Mail    = "*****@*****.**"
            };

            var client   = new CustomersApi();
            var response = await client.SaveCustomerAsync(customer);

            txtCustomerName.Text = response;
        }
Beispiel #10
0
        static public async Task <List <Customer> > GetCustomersAsync()
        {
            List <Customer> customers = new List <Customer>();
            CustomersApi    api       = new CustomersApi();
            string          cursor    = null;

            do
            {
                ListCustomersResponse resp = await api.ListCustomersAsync(cursor);

                customers.AddRange(resp.Customers);
                cursor = resp.Cursor;
            } while (cursor != null);
            return(customers);
        }
Beispiel #11
0
        /// <summary>
        /// Client http customizado e dados da conexão de externos ao seu arquivo de configuração
        /// </summary>
        /// <param name="client">Sua versão do HttpClient</param>
        /// <param name="clientConnection">Dados de conexão com a api</param>
        public BoletoSimplesClient(HttpClient client, ClientConnection clientConnection)
        {
            _client             = client;
            _client.BaseAddress = clientConnection.GetBaseUri();
            Connection          = clientConnection;

            Auth = new AuthApi(this);
            BankBilletAccounts    = new BankBilletAccountsApi(this);
            BankBillets           = new BankBilletsApi(this);
            Discharges            = new DischargesApi(this);
            Remittances           = new RemittancesApi(this);
            Installments          = new InstallmentsApi(this);
            CustomerSubscriptions = new CustomerSubscriptionApi(this);
            Events    = new EventsApi(this);
            Customers = new CustomersApi(this);
        }
Beispiel #12
0
        static public async Task <Customer> GetCustomer(string lastName, string firstName)
        {
            Customer retval            = null;
            ListCustomersResponse resp = null;

            CustomersApi api    = new CustomersApi();
            string       cursor = null;

            do
            {
                resp = await api.ListCustomersAsync(cursor);

                retval = resp.Customers.FirstOrDefault(c => c.FamilyName == lastName && c.GivenName == firstName);
                cursor = resp.Cursor;
            } while (retval == null && resp.Cursor != null);
            return(retval);
        }
Beispiel #13
0
        public void CustomersApi_CreateCustomer()
        {
            CustomersApi api = new CustomersApi(BaseUrl, apiToken, apiKey);

            CreateCustomersRequest req = new CreateCustomersRequest();

            req.BirthDate = DateTime.Today.AddYears(-30);
            req.Email     = "*****@*****.**";
            req.Fullname  = "Teste moip client 4";
            req.OwnId     = "3";
            req.Phone     = new PhoneDto()
            {
                AreaCode    = 11,
                CountryCode = 55,
                Number      = 98985959
            };
            req.ShippingAddress = new AddressDto()
            {
                City         = "Sao Paulo",
                Complement   = "A",
                Country      = "BR",
                District     = "SP",
                State        = "SP",
                Street       = "Sao paullo",
                StreetNumber = "12",
                ZipCode      = "09090170"
            };
            req.TaxDocument = new DocumentDto()
            {
                Number = "95672830013",
                Type   = DocumentType.CPF
            };



            var retorno = api.CreateCustomer(req);

            Assert.IsNotNull(retorno);
            Assert.IsNotNull(retorno.Id);
        }
Beispiel #14
0
        /// <summary>
        /// Get customer by identifier
        /// </summary>
        /// <param name="customerId">Customer ID</param>
        /// <returns>Customer</returns>
        public Customer GetCustomer(string customerId)
        {
            try
            {
                //whether passed customer identifier exists
                if (string.IsNullOrEmpty(customerId))
                {
                    return(null);
                }

                //create customer API
                var configuration = CreateApiConfiguration();
                var customersApi  = new CustomersApi(configuration);

                //get customer by identifier
                var retrieveCustomerResponse = customersApi.RetrieveCustomer(customerId);
                if (retrieveCustomerResponse == null)
                {
                    throw new NopException("No service response");
                }

                //check whether there are errors in the service response
                if (retrieveCustomerResponse.Errors?.Any() ?? false)
                {
                    var errorsMessage = string.Join(";", retrieveCustomerResponse.Errors.Select(error => error.ToString()));
                    throw new NopException($"There are errors in the service response. {errorsMessage}");
                }

                return(retrieveCustomerResponse.Customer);
            }
            catch (Exception exception)
            {
                //log full error
                _logger.Error($"Square payment error: {exception.Message}.", exception, _workContext.CurrentCustomer);

                return(null);
            }
        }
Beispiel #15
0
        private IObservable <IList <Customer> > GetRecentlyUpdatedCustomers(CustomersApi customersApi, CustomerQuery query, string cursor)
        {
            var request = new SearchCustomersRequest(Cursor: cursor, Query: query);

            return(customersApi
                   .SearchCustomersAsync(request)
                   .ToObservable()
                   .SelectMany(
                       response =>
            {
                if (response.Cursor == null)
                {
                    return Observable
                    .Return(response.Customers);
                }
                else
                {
                    return Observable
                    .Return(response.Customers)
                    .Concat(GetRecentlyUpdatedCustomers(customersApi, query, response.Cursor));
                }
            }));
        }
Beispiel #16
0
        public void CustomersApi_AddCreditCard()
        {
            CustomersApi api = new CustomersApi(BaseUrl, apiToken, apiKey);

            string idcliente             = "CUS-1IO9IR204YI4";
            AddCreditCardRequest request = new AddCreditCardRequest();

            request.Method     = MethodType.CREDIT_CARD;
            request.CreditCard = new CreditCardAddCreditCardRequest()
            {
                Cvc             = 546,
                ExpirationMonth = 9,
                ExpirationYear  = 2018,
                Holder          = new HolderDto()
                {
                    Birthdate = DateTime.Now.AddYears(-25),
                    Fullname  = "TESTE MOIP NET",
                    Phone     = new PhoneDto()
                    {
                        AreaCode    = 11,
                        CountryCode = 55,
                        Number      = 98985959
                    },
                    TaxDocument = new DocumentDto()
                    {
                        Number = "95672830013",
                        Type   = DocumentType.CPF
                    }
                },
                Number = "4556832098622729"
            };

            var retorno = api.AddCreditCard(idcliente, request);

            Assert.IsNotNull(retorno);
            Assert.IsNotNull(retorno.Id);
        }
Beispiel #17
0
 public CallDeleteCustomer(CustomersApi customersApi) : base(customersApi)
 {
 }
Beispiel #18
0
        public static TransactionResult ProcessPayment(TransactionRequest request, SquareSettings squareSettings, ILogger logger)
        {
            var order           = request.Order;
            var config          = GetConfiguration(squareSettings);
            var nonce           = request.GetParameterAs <string>("nonce");
            var location        = GetApplicationLocations(squareSettings, logger).FirstOrDefault(x => x.Id == squareSettings.LocationId);
            var billingAddress  = order.BillingAddressSerialized.To <EvenCart.Data.Entity.Addresses.Address>();
            var shippingAddress = order.ShippingAddressSerialized?.To <EvenCart.Data.Entity.Addresses.Address>();
            var customerId      = order.User.GetPropertyValueAs <string>(SquareCustomerIdKey);

            if (customerId.IsNullEmptyOrWhiteSpace())
            {
                var createCustomerRequest  = new CreateCustomerRequest(EmailAddress: order.User.Email, GivenName: order.User.Name);
                var customerApi            = new CustomersApi(config);
                var customerCreateResponse = customerApi.CreateCustomer(createCustomerRequest);
                customerId = customerCreateResponse.Customer.Id;
            }
            var paymentRequest = new CreatePaymentRequest(SourceId: nonce,
                                                          IdempotencyKey: Guid.NewGuid().ToString(),
                                                          LocationId: location?.Id,
                                                          CustomerId: customerId,
                                                          AmountMoney: new Money()
            {
                Amount   = (long)((request.Amount ?? order.OrderTotal) * 100),
                Currency = order.CurrencyCode
            },
                                                          AppFeeMoney: new Money()
            {
                Amount   = (long)(100 * order.PaymentMethodFee),
                Currency = order.CurrencyCode
            },
                                                          BillingAddress: new Address(billingAddress.Address1, billingAddress.Address2,
                                                                                      FirstName: billingAddress.Name, Locality: billingAddress.Landmark,
                                                                                      PostalCode: billingAddress.ZipPostalCode),
                                                          BuyerEmailAddress: order.User.Email
                                                          );

            if (shippingAddress != null)
            {
                paymentRequest.ShippingAddress = new Address(shippingAddress.Address1, shippingAddress.Address2,
                                                             FirstName: shippingAddress.Name, Locality: shippingAddress.Landmark,
                                                             PostalCode: shippingAddress.ZipPostalCode);
            }
            if (squareSettings.AuthorizeOnly)
            {
                paymentRequest.Autocomplete = false; //authorize only
            }
            var paymentsApi       = new PaymentsApi(config);
            var paymentResponse   = paymentsApi.CreatePayment(paymentRequest);
            var transactionResult = new TransactionResult()
            {
                OrderGuid       = order.Guid,
                TransactionGuid = Guid.NewGuid().ToString(),
            };

            if (paymentResponse != null)
            {
                var payment = paymentResponse.Payment;
                transactionResult.Success            = true;
                transactionResult.TransactionAmount  = (decimal)(payment.AmountMoney.Amount ?? 0) / 100;
                transactionResult.ResponseParameters = new Dictionary <string, object>()
                {
                    { "paymentId", payment.Id },
                    { "referenceId", payment.ReferenceId },
                    { "orderId", payment.OrderId },
                    { "cardDetails", payment.CardDetails }
                };
                if (payment.Status == "APPROVED")
                {
                    transactionResult.NewStatus = PaymentStatus.Authorized;
                }
                else if (payment.Status == "COMPLETED")
                {
                    transactionResult.NewStatus = PaymentStatus.Complete;
                }
                else
                {
                    transactionResult.NewStatus = PaymentStatus.Failed;
                    var errors = string.Join(",", paymentResponse.Errors);
                    logger.Log <TransactionResult>(LogLevel.Warning, "The payment for Order#" + order.Id + " by square failed." + errors);
                    transactionResult.Exception = new Exception("An error occurred while processing payment. Error Details: " + errors);
                    transactionResult.Success   = false;
                }
            }
            else
            {
                logger.Log <TransactionResult>(LogLevel.Warning, "The payment for Order#" + order.Id + " by square failed. No response received.");
                transactionResult.Success   = false;
                transactionResult.Exception = new Exception("An error occurred while processing payment");
            }

            return(transactionResult);
        }
Beispiel #19
0
 internal CustomerCallerBase(CustomersApi customersApi)
 {
     this.customersApi = customersApi;
 }
Beispiel #20
0
 public CallListCustomers(CustomersApi customersApi) : base(customersApi)
 {
 }
Beispiel #21
0
        static async Task MainAsync(string[] args)
        {
            using (var customersApi = new CustomersApi())
                using (var transactionsApi = new TransactionsApi())
                    using (var accountsApi = new AccountsApi())
                    {
                        var taskApi = new AzureFamilyDatabase();

                        await taskApi.CreateTask(123200000, 123230000, "Mow The Lawn", 5.00M);

                        var accountId = 152300000;

                        var response = await customersApi.MakeRequestAsync(new CustomerApiRequest { AccountId = accountId });

                        var account = await accountsApi.MakeRequestAsync(new AccountApiRequest { AccountId = accountId });

                        var primary = account.Single().PrimaryCustomerId;

                        var random = new Random();

                        var now = DateTimeOffset.UtcNow;

                        foreach (var customer in response.Single().Customers)
                        {
                            var accountTransactions = await transactionsApi.MakeRequestAsync(new TransactionApiRequest { CustomerId = customer.CustomerId });

                            var transactions =
                                accountTransactions
                                .Single().CustomerTransactions
                                .Single().Transactions;

                            var lowerBounds = random.Next(25, 250);
                            var upperBounds = lowerBounds + (lowerBounds * random.NextDouble()) + random.Next(0, 25);

                            // await taskApi.UpdateCreditLimitRange(accountId, customer.CustomerId, (decimal)lowerBounds, (decimal)Math.Round(upperBounds, 0));

                            var balance = 0M;

                            foreach (var transaction in transactions.Where(t => t.ToDateTimeOffset().AddDays(30) > now))
                            {
                                balance += transaction.Amount;

                                var taskDescriptions = new[] { "Random Task" };

                                var tasks = new List <(decimal value, string description, DateTimeOffset when)>();

                                Console.WriteLine($"++ {customer.FirstName} {transaction.Amount:C}");

                                await taskApi.CreateTask(
                                    accountId : accountId,
                                    creator : primary,
                                    description : $"Paid back for transaction for {transaction.MerchantName}",
                                    value : transaction.Amount,
                                    whenCompleted : transaction.ToDateTimeOffset().AddDays(random.Next(0, 10)),
                                    whenCreated : transaction.ToDateTimeOffset(),
                                    completedBy : customer.CustomerId);

                                await Task.Delay(TimeSpan.FromSeconds(0.5));
                            }
                        }

                        Console.ReadLine();
                    }
        }
 public CallCreateCustomer(CustomersApi customersApi) : base(customersApi)
 {
 }
        public async Task <PurchaseResponseModel> Purchase(PurchaseModel purchaseModel, User user)
        {
            var purchaseResponse = new PurchaseResponseModel
            {
                Success = false,
                Nanrs   = 0
            };

            try
            {
                if (purchaseModel.SaveBilling)
                {
                    CustomersApi customerApi = new CustomersApi(configuration);
                    if (string.IsNullOrWhiteSpace(user.BillingId))
                    {
                        CreateCustomerRequest createCustomer = new CreateCustomerRequest(Guid.NewGuid().ToString(), Nickname: user.Username, EmailAddress: user.Email, ReferenceId: user.Id.ToString());
                        var customerResponse = await customerApi.CreateCustomerAsync(createCustomer);

                        if (customerResponse.Errors != null && customerResponse.Errors.Any())
                        {
                            return(purchaseResponse);
                        }
                        user.BillingId = customerResponse.Customer.Id;
                    }
                    CreateCustomerCardRequest cardRequest = new CreateCustomerCardRequest(purchaseModel.Token);
                    var cardResponse = await customerApi.CreateCustomerCardAsync(user.BillingId, cardRequest);

                    if (cardResponse.Errors != null && cardResponse.Errors.Any())
                    {
                        return(purchaseResponse);
                    }
                    user.CardId = cardResponse.Card.Id;
                }
                (int price, int amount) = GetPricing(purchaseModel.Amount !);
                string idempotencyKey = Guid.NewGuid().ToString();
                Money  money          = new Money(price, "USD");
                CreatePaymentRequest body;
                if (purchaseModel.UseSaved || purchaseModel.SaveBilling)
                {
                    body = new CreatePaymentRequest(SourceId: user.CardId, CustomerId: user.BillingId, IdempotencyKey: idempotencyKey, AmountMoney: money, Note: $"{user.Id} {purchaseModel.Amount}");
                }
                else
                {
                    body = new CreatePaymentRequest(SourceId: purchaseModel.Token, IdempotencyKey: idempotencyKey, AmountMoney: money, Note: $"{user.Id} {purchaseModel.Amount}");
                }
                PaymentsApi paymentsApi = new PaymentsApi(configuration);
                var         response    = await paymentsApi.CreatePaymentAsync(body);

                if (response.Payment.Status == "COMPLETED")
                {
                    user.Balance   += amount;
                    user.Repurchase = purchaseModel.Refill;
                    if (user.Repurchase)
                    {
                        user.RepurchaseAmount = purchaseModel.Amount;
                    }
                    else
                    {
                        user.RepurchaseAmount = null;
                    }
                    var purchase = new Purchase
                    {
                        Id         = Guid.NewGuid(),
                        NanrAmount = amount,
                        UsdAmount  = price,
                        Timestamp  = DateTime.UtcNow
                    };
                    context.Purchases.Add(purchase);
                    await emailManager.SendPurchase(user, purchase);
                }
                else
                {
                    return(purchaseResponse);
                }
                await context.SaveChangesAsync();

                purchaseResponse.Success = true;
                purchaseResponse.Nanrs   = amount;
                return(purchaseResponse);
            } catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(purchaseResponse);
            }
        }
 public SquareCustomersService(SquareConfig config, SquareMerchantCredentials credentials) : base(config, credentials)
 {
     _customersApi = new CustomersApi(base.ApiConfiguration);
 }
 public void Init()
 {
     instance = new CustomersApi();
 }