예제 #1
0
        private void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new DiscordSocketClient(new DiscordSocketConfig
            {
                // Add discord to the collection
                LogLevel         = LogSeverity.Verbose, // Tell the logger to give Verbose amount of info
                MessageCacheSize = 1000                 // Cache 1,000 messages per channel
            }))
            .AddSingleton(new CommandService(new CommandServiceConfig
            {
                // Add the command service to the collection
                LogLevel       = LogSeverity.Verbose, // Tell the logger to give Verbose amount of info
                DefaultRunMode = RunMode.Async,       // Force all commands to run async by default
            }))
            .AddSingleton <CommandHandler>()          // Add the command handler to the collection
            .AddSingleton <StartupService>()          // Add startupservice to the collection
            .AddSingleton <LoggingService>()          // Add loggingservice to the collection
            .AddSingleton <Random>()                  // Add random to the collection
            .AddSingleton(Configuration)              // Add the configuration to the collection
            .AddSingleton <TimerService>();


            if (!string.IsNullOrWhiteSpace(TokenConfiguration.Config.BunqApiKey))
            {
                ApiContext apiContext = ApiContext.Create(ApiEnvironmentType.PRODUCTION, TokenConfiguration.Config.BunqApiKey, "bunq-bot");
                apiContext.Save();
                BunqContext.LoadApiContext(apiContext);
            }
        }
        public void Run()
        {
            BunqContext.LoadApiContext(ApiContext.Restore());
            var monetaryAccount = BunqContext.UserContext.PrimaryMonetaryAccountBank;

            Console.WriteLine(monetaryAccount);
        }
예제 #3
0
        public void Run(string[] args)
        {
            Dictionary <string, string> allOption = AssertMandatoryOptions(args);

            BunqContext.LoadApiContext(
                ApiContext.Restore(allOption[OPTION_CONTEXT])
                );

            OauthClient oauthClient;

            if (File.Exists(FILE_OAUTH_CONFIGURATION))
            {
                oauthClient = OauthClient.CreateFromJsonString(File.ReadAllText(FILE_OAUTH_CONFIGURATION));
            }
            else
            {
                int oauthClientId = OauthClient.Create().Value;

                OauthCallbackUrl.Create(oauthClientId, allOption[OPTION_REDIRECT_URI]);
                oauthClient = OauthClient.Get(oauthClientId).Value;

                String serializedClient = BunqJsonConvert.SerializeObject(oauthClient);
                File.WriteAllText(FILE_OAUTH_CONFIGURATION, serializedClient);
            }

            OauthAuthorizationUri authorizationUri = OauthAuthorizationUri.Create(
                OauthResponseType.CODE,
                allOption[OPTION_REDIRECT_URI],
                oauthClient
                );

            Console.WriteLine(" | Created oauth client. Stored in {0}.", FILE_OAUTH_CONFIGURATION);
            Console.WriteLine(" | Point your user to {0} to obtain an Authorization code.", authorizationUri.AuthorizationUri);
        }
예제 #4
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World of The Free!");

            var store = await BunqStore.Load();

            try
            {
                var userStore = store.GetUser(BunqEnvironment.Sandbox);
                var context   = new BunqContext(userStore);

                await context.Setup(fastValidation : false);

                var response = await context.Api.Client.User().Get();

                var userPerson = response.Get <UserPerson>();
                Console.WriteLine($"Current user {userPerson.FirstName} {userPerson.MiddleName} {userPerson.LastName} ({userPerson.DisplayName})");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                await store.Save();
            }
        }
예제 #5
0
        public void Post([FromBody] JObject content)
        {
            JObject config = Settings.LoadConfig();

            Console.WriteLine("Hi there, we are connecting to the bunq API...\n");

            var apiContext = ApiContext.Restore();

            BunqContext.LoadApiContext(apiContext);
            Console.WriteLine(" -- Connected as: " + BunqContext.UserContext.UserPerson.DisplayName + " (" + BunqContext.UserContext.UserId + ")\n");


            var    amount      = content["amount"].ToString();
            string recipient   = content["recipient"].ToString();
            string description = content["description"].ToString();

            Console.WriteLine("Todo:");
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("Description:           " + description);
            Console.WriteLine("Send to:               " + recipient);
            Console.WriteLine("Amount:                € " + amount);
            Console.WriteLine("----------------------------------------------------------");

            if (Convert.ToDouble(amount) > 0)
            {
                Console.WriteLine("Executing...");
                RequestInquiry.Create(new Amount(amount, "EUR"), new Pointer("EMAIL", recipient), description, true);
                Console.WriteLine("Yeah, this one is completed!");
            }
            else
            {
                Console.WriteLine("Bummer, nothing to do!");
            }
            Console.WriteLine("----------------------------------------------------------\n");
        }
        public void Run()
        {
            BunqContext.LoadApiContext(ApiContext.Restore());
            var paginationCountOnly = new Pagination
            {
                Count = PAGE_SIZE,
            };

            Console.WriteLine(MESSAGE_LATEST_PAGE_IDS);
            var paymentResponse = Payment.List(urlParams: paginationCountOnly.UrlParamsCountOnly);

            PrintPayments(paymentResponse.Value);
            var pagination = paymentResponse.Pagination;

            if (pagination.HasPreviousPage())
            {
                Console.WriteLine(MESSAGE_SECOND_LATEST_PAGE_IDS);
                var previousPaymentResponse = Payment.List(urlParams: pagination.UrlParamsPreviousPage);
                PrintPayments(previousPaymentResponse.Value);
            }
            else
            {
                Console.WriteLine(MESSAGE_NO_PRIOR_PAYMENTS_FOUND);
            }
        }
        public void Run()
        {
            BunqContext.LoadApiContext(ApiContext.Restore());
            var timeSpanWeek = new TimeSpan(
                DAYS_IN_WEEK,
                TIME_UNIT_COUNT_NONE,
                TIME_UNIT_COUNT_NONE,
                TIME_UNIT_COUNT_NONE
                );
            var dateStart = DateTime.Now.Subtract(timeSpanWeek);
            var dateEnd   = DateTime.Now;

            var userId = BunqContext.UserContext.UserId;

            var userIdInt         = userId;
            var monetaryAccountId = BunqContext.UserContext.PrimaryMonetaryAccountBank.Id.Value;

            var monetaryAccountIdInt = monetaryAccountId;
            var customerStatementId  = CustomerStatementExport.Create(STATEMENT_FORMAT,
                                                                      dateStart.ToString(FORMAT_DATE_STATEMENT), dateEnd.ToString(FORMAT_DATE_STATEMENT)).Value;

            CustomerStatementExport.Delete(customerStatementId);

            BunqContext.ApiContext.Save();
        }
예제 #8
0
        public void Run()
        {
            BunqContext.LoadApiContext(ApiContext.Restore());
            var paymentId = Payment.Create(new Amount(PAYMENT_AMOUNT, PAYMENT_CURRENCY),
                                           new Pointer(COUNTERPARTY_POINTER_TYPE, COUNTERPARTY_EMAIL), PAYMENT_DESCRIPTION).Value;

            Console.WriteLine(Payment.Get(paymentId));

            // Save the API context to account for all the changes that might have occurred to it
            // during the sample execution
            BunqContext.ApiContext.Save();
        }
예제 #9
0
파일: Bunq.cs 프로젝트: SvenHamers/HueBunq
        public Bunq(string ApiKey, bool SandBox, PHue.Hue hueCommands)
        {
            ApiEnvironmentType EnvType = ApiEnvironmentType.PRODUCTION;

            if (SandBox)
            {
                EnvType = ApiEnvironmentType.SANDBOX;
            }

            _bunqApi = ApiContext.Create(EnvType, ApiKey, "BunqHue");
            BunqContext.LoadApiContext(_bunqApi);
            //Every minut
            _bunqUpdateTimer = new System.Timers.Timer(10000);
            _hueCommands     = hueCommands;
        }
예제 #10
0
        public void Run()
        {
            BunqContext.LoadApiContext(ApiContext.Restore());
            var customHeaders =
                new Dictionary <string, string>
            {
                { ApiClient.HEADER_CONTENT_TYPE, CONTENT_TYPE_IMAGE_JPEG },
                { ApiClient.HEADER_ATTACHMENT_DESCRIPTION, DESCRIPTION_TEST_JPG_ATTACHMENT }
            };
            var requestBytes  = File.ReadAllBytes(PATH_ATTACHMENT_IN);
            var uuid          = AttachmentPublic.Create(requestBytes, customHeaders).Value;
            var responseBytes = AttachmentPublicContent.List(uuid).Value;
            var fileOut       = new FileInfo(PATH_ATTACHMENT_OUT);

            fileOut.Directory.Create();
            File.WriteAllBytes(fileOut.FullName, responseBytes);
        }
예제 #11
0
        public void Run()
        {
            BunqContext.LoadApiContext(ApiContext.Restore());
            var users = User.List().Value;

            BunqContext.ApiContext.Save();

            foreach (var oneUser in users)
            {
                Console.WriteLine(oneUser.UserCompany);
            }

            // or

            Console.WriteLine(BunqContext.UserContext.UserCompany);
            Console.WriteLine(BunqContext.UserContext.UserPerson);
        }
예제 #12
0
        private BunqResponseRaw SendRequest(HttpRequestMessage requestMessage,
                                            IDictionary <string, string> customHeaders, string uriRelative)
        {
            if (!URIS_NOT_REQUIRING_ACTIVE_SESSION.Contains(uriRelative) && apiContext.EnsureSessionActive())
            {
                BunqContext.UpdateApiContext(apiContext);
            }

            SetDefaultHeaders(requestMessage);
            SetHeaders(requestMessage, customHeaders);
            SetSessionHeaders(requestMessage);
            var responseMessage = client.SendAsync(requestMessage).Result;

            AssertResponseSuccess(responseMessage);
            ValidateResponse(responseMessage);

            return(CreateBunqResponseRaw(responseMessage));
        }
예제 #13
0
        public void TestCreatePsd2Context()
        {
            ApiContext apiContext = null;

            if (File.Exists(FILE_TEST_CONFIGURATION))
            {
                apiContext = ApiContext.Restore(FILE_TEST_CONFIGURATION);
                Assert.NotNull(apiContext);

                BunqContext.LoadApiContext(apiContext);
                return;
            }

            apiContext = CreateApiContext();
            BunqContext.LoadApiContext(apiContext);

            Assert.True(File.Exists(FILE_TEST_CONFIGURATION));
        }
예제 #14
0
        protected static ApiContext SetUpApiContext()
        {
            ApiContext apiContext;

            if (File.Exists(FilenameContextConf))
            {
                apiContext = ApiContext.Restore(FilenameContextConf);
                apiContext.EnsureSessionActive();
            }
            else
            {
                var sandboxUser = GenerateNewSandboxUser();
                apiContext = ApiContext.Create(ApiEnvironmentType.SANDBOX, sandboxUser.ApiKey, DeviceDescription);
            }

            BunqContext.LoadApiContext(apiContext);

            return(apiContext);
        }
예제 #15
0
        public void TestAutoApiContextReLoad()
        {
            var contextJson = JObject.Parse(apiContext.ToJson());
            var expiredTime = DateTime.Now.Subtract(TimeSpan.FromDays(20));

            contextJson.SelectToken(FIELD_FIELD_SESSION_CONTEXT)[FIELD_FIELD_EXPIRY_TIME] = expiredTime.ToString();

            var expiredApiContext = ApiContext.FromJson(contextJson.ToString());

            Assert.NotEqual(apiContext, expiredApiContext);

            BunqContext.UpdateApiContext(expiredApiContext);

            Assert.Equal(expiredApiContext, BunqContext.ApiContext);

            BunqContext.UserContext.RefreshUserContext();

            Assert.True(BunqContext.ApiContext.IsSessionActive());
        }
예제 #16
0
        private const int MONETARY_ACCOUNT_ID = 0; // Put your monetaryAccount ID here

        public void Run()
        {
            BunqContext.LoadApiContext(ApiContext.Restore());
            var cardPinAssignment = new CardPinAssignment(
                CARD_PIN_ASSIGNMENT_TYPE_PRIMARY,
                PIN_CODE,
                MONETARY_ACCOUNT_ID
                );
            var allCardPinAssignments = new List <CardPinAssignment> {
                cardPinAssignment
            };

            Console.WriteLine(CardDebit.Create(GenerateRandomSecondLine(), NAME_YOUR_COMPANY,
                                               new Pointer(POINTER_TYPE_EMAIL, EMAIL_YOUR_COMPANY)
            {
                Name = POINTER_NAME_TEST
            },
                                               pinCodeAssignment: allCardPinAssignments));
        }
예제 #17
0
        public void CreateApiContext(Guid userId, string apiKey)
        {
            if (this.Environment == ApiEnvironmentType.SANDBOX)
            {
                var sandboxUser = GenerateNewSandboxUser();
                apiKey = sandboxUser.ApiKey;
            }

            var api = ApiContext.Create(
                this.Environment, apiKey, this.config.Description);

            api.Save(this.ComputeConfigPath(userId));

            BunqContext.LoadApiContext(api);

            if (this.Environment == ApiEnvironmentType.SANDBOX)
            {
                AddSandboxPayments();
            }
        }
예제 #18
0
        /// <summary>
        /// Gets an Api Context, re-creates if needed and returns it.
        /// </summary>
        protected static ApiContext SetUpApiContext()
        {
            ApiContext apiContext;

            try
            {
                apiContext = ApiContext.Restore(FILENAME_CONTEXT_CONF);
            }
            catch (BunqException)
            {
                apiContext = CreateApiContext();
            }

            apiContext.EnsureSessionActive();
            apiContext.Save(FILENAME_CONTEXT_CONF);

            BunqContext.LoadApiContext(apiContext);

            return(apiContext);
        }
예제 #19
0
        public void RestoreApiContext(Guid userId)
        {
            string configPath = this.ComputeConfigPath(userId);

            if (!this.IsInitialized(userId))
            {
                throw new ArgumentException($"No configuration exists for user {userId}.");
            }

            var apiContext = ApiContext.Restore(configPath);

            apiContext.EnsureSessionActive();
            apiContext.Save(configPath);

            BunqContext.LoadApiContext(apiContext);

            if (BunqContext.ApiContext.EnvironmentType == ApiEnvironmentType.SANDBOX)
            {
                AddSandboxPayments();
            }
        }
예제 #20
0
        public void Run(string[] args)
        {
            Dictionary <string, string> allOption = AssertMandatoryOptions(args);

            ApiContext apiContext = ApiContext.Restore(allOption[OPTION_CONTEXT]);

            BunqContext.LoadApiContext(apiContext);

            OauthAccessToken accessToken = OauthAccessToken.Create(
                OauthGrantType.AUTHORIZATION_CODE,
                allOption[OPTION_AUTH_CODE],
                allOption[OPTION_REDIRECT],
                CreateOauthClientFromFile(allOption[OPTION_CLIENT_CONFIGURATION])
                );

            apiContext = CreateApiContextByOauthToken(
                accessToken,
                ShareLib.DetermineEnvironmentType(args)
                );
            BunqContext.LoadApiContext(apiContext);

            (new UserOverview()).Run(new String[] {});
        }
예제 #21
0
        private void SetupContext(bool resetConfigIfNeeded = true)
        {
            if (File.Exists(DetermineBunqConfFileName()))
            {
                // Config is already present
            }
            else if (ApiEnvironmentType.SANDBOX.Equals(EnvironmentType))
            {
                var sandboxUser = GenerateNewSandboxUser();
                ApiContext.Create(ApiEnvironmentType.SANDBOX, sandboxUser.ApiKey, Environment.MachineName)
                .Save(this.DetermineBunqConfFileName());
            }
            else
            {
                throw new BunqException(ErrorCouldNotFindAProductionConfiguration);
            }

            try
            {
                var apiContext = ApiContext.Restore(DetermineBunqConfFileName());
                apiContext.EnsureSessionActive();
                apiContext.Save(DetermineBunqConfFileName());

                BunqContext.LoadApiContext(apiContext);
            }
            catch (ForbiddenException forbiddenException)
            {
                if (resetConfigIfNeeded)
                {
                    HandleForbiddenExceeption(forbiddenException);
                }
                else
                {
                    throw;
                }
            }
        }
예제 #22
0
        private void SetupContext()
        {
            if (File.Exists(DetermineBunqConfFileName()))
            {
                // Config is already present
            }
            else if (ApiEnvironmentType.SANDBOX.Equals(EnvironmentType))
            {
                var sandboxUser = GenerateNewSandboxUser();
                ApiContext.Create(ApiEnvironmentType.SANDBOX, sandboxUser.ApiKey, Environment.MachineName)
                .Save(this.DetermineBunqConfFileName());
            }
            else
            {
                throw new BunqException("Could not find a production configuration.");
            }

            var apiContext = ApiContext.Restore(DetermineBunqConfFileName());

            apiContext.EnsureSessionActive();
            apiContext.Save(DetermineBunqConfFileName());

            BunqContext.LoadApiContext(apiContext);
        }
예제 #23
0
        private static void Main(string[] args)
        {
            var environmentType   = ApiEnvironmentType.SANDBOX;
            var deviceDescription = "C# PSD2 test runner";
            var permittedIps      = new List <string>();
            var redirectUri       = "https://postman-echo.com/get";
            var certificateString =
                @"-----BEGIN CERTIFICATE-----
Please use the following command to generate a certificate for sandbox:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj '/CN=<YOUR COMPANY NAME> PISP AISP/C=NL'

Make sure to supply a company name or any other identifier so that we'll be able to assist you if you have any problems.

Replace that text with the contents of cert.pem

-----END CERTIFICATE-----";

            var privateKeyString =
                @"-----BEGIN PRIVATE KEY-----
Please use the command described above to get certificate and a private key.

Replace that text with the contents of key.pem

-----END PRIVATE KEY-----";

            var certificateChainString =
                @"-----BEGIN CERTIFICATE-----
MIID1zCCAr+gAwIBAgIBATANBgkqhkiG9w0BAQsFADB1MQswCQYDVQQGEwJOTDEW
MBQGA1UECBMNTm9vcmQtSG9sbGFuZDESMBAGA1UEBxMJQW1zdGVyZGFtMRIwEAYD
VQQKEwlidW5xIGIudi4xDzANBgNVBAsTBkRldk9wczEVMBMGA1UEAxMMUFNEMiBU
ZXN0IENBMB4XDTE5MDIxODEzNDkwMFoXDTI5MDIxODEzNDkwMFowdTELMAkGA1UE
BhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQxEjAQBgNVBAcTCUFtc3RlcmRh
bTESMBAGA1UEChMJYnVucSBiLnYuMQ8wDQYDVQQLEwZEZXZPcHMxFTATBgNVBAMT
DFBTRDIgVGVzdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALOv
zPl+uegBpnFhXsjuKs0ws00e+232wR9tvDqYBjGdOlYorw8CyrT+mr0HKO9lx7vg
xhJ3f+oonkZvBb+IehDmEsBbZ+vRtdjEWw3RTWVBT69jPcRQGE2e5qUuTJYVCONY
JsOQP8CoCHXa6+oUSmUyMZX/zNJhTvbLV9e/qpIWwWVrKzK0EEB5c71gITNgzOXG
+lIKJmOnvvJyWPCx02hIgQI3nVphDj8ydMEKuwTgBrFV5Lqkar3L6ngF7LgzjXPC
Nbf3JL/2Ccp0hYPb2MLVEpYba8/38eN6izjorJiwu+uGehOpj/RNcfv27iGyvXRY
FC2PfRP8ZP5CpoijJR8CAwEAAaNyMHAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E
FgQU38gzLVi6UQYiNLXKIhwoklPnSYMwCwYDVR0PBAQDAgEGMBEGCWCGSAGG+EIB
AQQEAwIABzAeBglghkgBhvhCAQ0EERYPeGNhIGNlcnRpZmljYXRlMA0GCSqGSIb3
DQEBCwUAA4IBAQBt6HBrnSvEbUX514ab3Zepdct0QWVLzzEKFC8y9ARLWttyaRJ5
AhzCa4t8LJnyoYuEPHOKDIsqLzmJlwqBnsXPuMdWEd3vnFRgj1oL3vVqoJwrfqDp
S3jHshWopqMKtmzAO9Q3BWpk/lrqJTP1y/6057LtMGhwA6m0fDmvA+VuTrh9mgzw
FgWwmahVa08h1Cm5+vc1Phi8wVXi3R1NzmVUQFYOixSwifs8P0MstBfCFlBFQ47C
EvGEYvOBLlEiiaoMUT6aoYj+L8zHWXakSQFAzIzQFJn668q2ds6zx67P7wKFZ887
VJSv7sTqspxON1s1oFlkRXu5JihaVJcHmFAY
-----END CERTIFICATE-----";

            if (certificateString.Contains("Please"))
            {
                Console.WriteLine("Please generate a certificate and a private key and update the code.");
                Console.WriteLine();
                Console.WriteLine("Use the following command:");
                Console.WriteLine("openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj '/CN=<YOUR COMPANY NAME> PISP AISP/C=NL'");
                return;
            }

            var certificatePublic = new X509Certificate2(Encoding.UTF8.GetBytes(certificateString));

            var keyPair = SecurityUtils.CreateKeyPairFromPrivateKeyFormattedString(
                privateKeyString);
            var certificate = certificatePublic.CopyWithPrivateKey(keyPair);

            var certificateChain = new X509Certificate2Collection();

            certificateChain.Import(Encoding.UTF8.GetBytes(
                                        certificateChainString
                                        ));

            var psd2ApiContext = ApiContext.CreateForPsd2(environmentType, certificate, certificateChain,
                                                          deviceDescription, permittedIps);

            BunqContext.LoadApiContext(psd2ApiContext);
            var allOauthClient = OauthClient.List();

            if (!allOauthClient.Value.Any())
            {
                OauthClient.Create("ACTIVE");
                allOauthClient = OauthClient.List();
            }

            var client = allOauthClient.Value.First();

            Debug.Assert(client.Id != null, "client.Id != null");
            if (OauthCallbackUrl.List(client.Id.Value).Value.All(ocu => ocu.Url != redirectUri))
            {
                OauthCallbackUrl.Create(client.Id.Value, redirectUri);
            }

            Console.WriteLine(JsonConvert.SerializeObject(client));

            Console.WriteLine("To continue, you'll need a user with an installed app. For sandbox it needs to be " +
                              "an android app downloadable from https://appstore.bunq.com/api/android/builds/bunq-android-sandbox-master.apk");
            Console.WriteLine("You can create a sandbox user using tinker, see links at https://www.bunq.com/developer");
            Console.WriteLine("Run UserOverview, that'll show the user's phone number and add some money to the account.");
            Console.WriteLine("You can then login in app with phone/email displayed by tinker script and login code 000000");
            Console.WriteLine("If the app tries to send a code to phone it's going to be 123456");
            Console.WriteLine("If the app tries to scan 4 fingers, any finger-like picture should be accepted");
            Console.WriteLine();
            Console.WriteLine("https://oauth.sandbox.bunq.com/auth?response_type=code&client_id=" + client.ClientId +
                              "&redirect_uri=" + redirectUri);
            Console.WriteLine();
            Console.WriteLine(
                "Please direct user to the above url. When you successfully authorized the code in the app," +
                "it'll redirect to the website with the code. Please input the code: \n");
            var code     = Console.ReadLine();
            var tokenUrl = "https://api-oauth.sandbox.bunq.com/v1/token?grant_type=authorization_code&code=" + code +
                           "&redirect_uri=" + redirectUri + "&client_id=" + client.ClientId + "&client_secret=" +
                           client.Secret;
            var httpClient         = new HttpClient();
            var tokenRequestResult = httpClient.PostAsync(tokenUrl, new StringContent("")).Result.Content
                                     .ReadAsStringAsync().Result;
            dynamic result = JsonConvert.DeserializeObject(
                tokenRequestResult
                );

            if (result.access_token != null)
            {
                string apiKey = result.access_token;

                var apiContext = ApiContext.Create(
                    environmentType, apiKey, deviceDescription, permittedIps);
                BunqContext.LoadApiContext(apiContext);
                Console.WriteLine(JsonConvert.SerializeObject(MonetaryAccount.List().Value.First()));
            }
            else
            {
                Console.WriteLine("Couldn't get token!");
                Console.WriteLine(tokenRequestResult);
            }
        }
예제 #24
0
        public void Get()
        {
            JObject config = Settings.LoadConfig();

            Console.WriteLine("Hi there, we are connecting to the bunq API...\n");

            var apiContext = ApiContext.Restore();

            BunqContext.LoadApiContext(apiContext);
            Console.WriteLine(" -- Connected as: " + BunqContext.UserContext.UserPerson.DisplayName + " (" + BunqContext.UserContext.UserId + ")\n");

            foreach (JObject rule in config["rules"])
            {
                if (rule["if"]["type"].ToString() == "trigger")
                {
                    foreach (JObject action in rule["then"])
                    {
                        if (action.ContainsKey("email"))
                        {
                            Console.WriteLine(action);
                            //TODO: Create Mail on trigger!
                        }
                        if (action.ContainsKey("payment"))
                        {
                            var    AllMonetaryAccounts    = MonetaryAccountBank.List().Value;
                            int    MonetaryAccountId      = 0;
                            string MonetaryAccountBalance = null;


                            foreach (var MonetaryAccount in AllMonetaryAccounts)
                            {
                                foreach (var Alias in MonetaryAccount.Alias)
                                {
                                    if (Alias.Value == action["payment"]["origin"]["iban"].ToString())
                                    {
                                        MonetaryAccountId      = MonetaryAccount.Id.Value;
                                        MonetaryAccountBalance = MonetaryAccount.Balance.Value;
                                    }
                                }
                            }

                            double AmountToTransfer     = 0;
                            string DefinedTransaction   = null;
                            string SuggestedTransaction = null;

                            switch (action["payment"]["amount"]["type"].ToString())
                            {
                            case "exact":
                                if (Double.Parse(MonetaryAccountBalance) >= Double.Parse(action["payment"]["amount"]["value"].ToString()))
                                {
                                    AmountToTransfer     = Double.Parse(action["payment"]["amount"]["value"].ToString());
                                    DefinedTransaction   = "€" + action["payment"]["amount"]["value"].ToString() + " (Exact amount)";
                                    SuggestedTransaction = AmountToTransfer.ToString("0.00") + " - Reason: Due to insufficied balance on the account.";
                                }
                                else
                                {
                                    AmountToTransfer     = Double.Parse(MonetaryAccountBalance);
                                    DefinedTransaction   = "€ " + action["payment"]["amount"]["value"].ToString() + " (Exact amount)";
                                    SuggestedTransaction = AmountToTransfer.ToString("0.00");
                                }
                                break;

                            case "percent":
                                AmountToTransfer     = (Double.Parse(MonetaryAccountBalance) * (Double.Parse(action["payment"]["amount"]["value"].ToString()) / 100));
                                DefinedTransaction   = action["payment"]["amount"]["value"].ToString() + "% of € " + MonetaryAccountBalance;
                                SuggestedTransaction = AmountToTransfer.ToString("0.00");
                                break;

                            default:
                                break;
                            }

                            DateTime now          = DateTime.Today;
                            string   month        = now.ToString("MMMM", new CultureInfo("nl-NL"));
                            string   year         = now.ToString("yyyy");
                            string   payment_desc = String.Format(action["payment"]["description"].ToString(), month, year);

                            Console.WriteLine("Todo:");
                            Console.WriteLine("----------------------------------------------------------");
                            Console.WriteLine("Rule Name:             " + rule["name"].ToString());
                            Console.WriteLine("Description:           " + payment_desc);
                            Console.WriteLine("Origin Account:        " + action["payment"]["origin"]["iban"].ToString() + " (" + MonetaryAccountId.ToString() + ")");
                            Console.WriteLine("Destination Account:   " + action["payment"]["destination"]["iban"].ToString());
                            Console.WriteLine("Current Balance:       € " + MonetaryAccountBalance);
                            Console.WriteLine("Defined Transaction:   " + DefinedTransaction);
                            Console.WriteLine("Suggested Transaction: € " + SuggestedTransaction);
                            Console.WriteLine("----------------------------------------------------------");

                            if (AmountToTransfer > 0)
                            {
                                var Recipient = new Pointer("IBAN", action["payment"]["destination"]["iban"].ToString());
                                Recipient.Name = action["payment"]["destination"]["name"].ToString();
                                Console.WriteLine("Executing...");
                                var PaymentID = Payment.Create(new Amount(AmountToTransfer.ToString("0.00"), "EUR"), Recipient, payment_desc, MonetaryAccountId).Value;
                                Console.WriteLine("Yeah, this one is completed!");
                            }
                            else
                            {
                                Console.WriteLine("Bummer, nothing to do!");
                            }
                            Console.WriteLine("----------------------------------------------------------\n");
                        }
                    }
                }
            }
        }
예제 #25
0
        public void Post([FromBody] JObject content)
        {
            JObject config = Settings.LoadConfig();

            Console.WriteLine("Hi there, we are connecting to the bunq API...\n");

            var apiContext = ApiContext.Restore();

            BunqContext.LoadApiContext(apiContext);
            Console.WriteLine(" -- Connected as: " + BunqContext.UserContext.UserPerson.DisplayName + " (" + BunqContext.UserContext.UserId + ")\n");

            // Log all notifications to ElasticSearch
            string identifier  = Guid.NewGuid().ToString();
            var    http        = new HttpClient();
            var    body        = new StringContent(content.ToString(), Encoding.UTF8, "application/json");
            string url         = Environment.GetEnvironmentVariable("ELASTIC_BASEURL").ToString();
            string username    = Environment.GetEnvironmentVariable("ELASTIC_USERNAME").ToString();
            string password    = Environment.GetEnvironmentVariable("ELASTIC_PASSWORD").ToString();
            string credentials = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

            http.DefaultRequestHeaders.Add("Authorization", "Basic " + credentials);

            http.PutAsync(url + "aggregation/transactions/" + identifier, body);

            Console.WriteLine(content.ToString());

            string category    = content["NotificationUrl"]["category"].ToString();
            string amount      = content["NotificationUrl"]["object"]["Payment"]["amount"]["value"].ToString();
            string description = content["NotificationUrl"]["object"]["Payment"]["description"].ToString();
            string to_iban     = content["NotificationUrl"]["object"]["Payment"]["alias"]["iban"].ToString();
            string from_iban   = content["NotificationUrl"]["object"]["Payment"]["counterparty_alias"]["iban"].ToString();
            bool   match       = false;

            // Check for matching rules and actions!
            foreach (JObject rule in config["rules"])
            {
                if (!match)
                {
                    if (rule["if"]["type"].ToString() == "mutation")
                    {
                        Regex descRegex = new Regex(rule["if"]["description"].ToString());
                        if (
                            from_iban == rule["if"]["origin"]["iban"].ToString() &
                            to_iban == rule["if"]["destination"]["iban"].ToString() &
                            descRegex.IsMatch(description)
                            )
                        {
                            foreach (JObject action in rule["then"])
                            {
                                if (action.ContainsKey("email"))
                                {
                                    Console.WriteLine(action);
                                    //TODO: Create Mail on trigger!
                                }
                                if (action.ContainsKey("payment"))
                                {
                                    var    AllMonetaryAccounts    = MonetaryAccountBank.List().Value;
                                    int    MonetaryAccountId      = 0;
                                    string MonetaryAccountBalance = null;

                                    foreach (var MonetaryAccount in AllMonetaryAccounts)
                                    {
                                        foreach (var Alias in MonetaryAccount.Alias)
                                        {
                                            if (Alias.Value == action["payment"]["origin"]["iban"].ToString())
                                            {
                                                MonetaryAccountId      = MonetaryAccount.Id.Value;
                                                MonetaryAccountBalance = MonetaryAccount.Balance.Value;
                                            }
                                        }
                                    }

                                    double AmountToTransfer     = 0;
                                    string DefinedTransaction   = null;
                                    string SuggestedTransaction = null;

                                    switch (action["payment"]["amount"]["type"].ToString())
                                    {
                                    case "exact":
                                        if (Double.Parse(MonetaryAccountBalance) >= Double.Parse(action["payment"]["amount"]["value"].ToString()))
                                        {
                                            AmountToTransfer     = Double.Parse(action["payment"]["amount"]["value"].ToString());
                                            DefinedTransaction   = "€" + action["payment"]["amount"]["value"].ToString() + " (Exact amount)";
                                            SuggestedTransaction = AmountToTransfer.ToString("0.00") + " - Reason: Due to insufficied balance on the account.";
                                        }
                                        else
                                        {
                                            AmountToTransfer     = Double.Parse(MonetaryAccountBalance);
                                            DefinedTransaction   = "€ " + action["payment"]["amount"]["value"].ToString() + " (Exact amount)";
                                            SuggestedTransaction = AmountToTransfer.ToString("0.00");
                                        }
                                        break;

                                    case "percent":
                                        AmountToTransfer     = (Double.Parse(MonetaryAccountBalance) * (Double.Parse(action["payment"]["amount"]["value"].ToString()) / 100));
                                        DefinedTransaction   = action["payment"]["amount"]["value"].ToString() + "% of € " + MonetaryAccountBalance;
                                        SuggestedTransaction = AmountToTransfer.ToString("0.00");
                                        break;

                                    case "differance":
                                        AmountToTransfer     = (Double.Parse(MonetaryAccountBalance) - Double.Parse(amount));
                                        DefinedTransaction   = "The differance between: € " + MonetaryAccountBalance + " and € " + amount;
                                        SuggestedTransaction = AmountToTransfer.ToString("0.00");
                                        break;

                                    default:
                                        break;
                                    }

                                    DateTime now          = DateTime.Today;
                                    string   month        = now.ToString("MMMM", new CultureInfo("nl-NL"));
                                    string   year         = now.ToString("yyyy");
                                    string   payment_desc = String.Format(action["payment"]["description"].ToString(), month, year);

                                    Console.WriteLine("Todo:");
                                    Console.WriteLine("----------------------------------------------------------");
                                    Console.WriteLine("Rule Name:             " + rule["name"].ToString());
                                    Console.WriteLine("Description:           " + payment_desc);
                                    Console.WriteLine("Origin Account:        " + action["payment"]["origin"]["iban"].ToString() + " (" + MonetaryAccountId.ToString() + ")");
                                    Console.WriteLine("Destination Account:   " + action["payment"]["destination"]["iban"].ToString());
                                    Console.WriteLine("Current Balance:       € " + MonetaryAccountBalance);
                                    Console.WriteLine("Defined Transaction:   " + DefinedTransaction);
                                    Console.WriteLine("Suggested Transaction: € " + SuggestedTransaction);
                                    Console.WriteLine("----------------------------------------------------------");

                                    if (AmountToTransfer > 0)
                                    {
                                        var Recipient = new Pointer("IBAN", action["payment"]["destination"]["iban"].ToString());
                                        Recipient.Name = action["payment"]["destination"]["name"].ToString();
                                        Console.WriteLine("Executing...");
                                        var PaymentID = Payment.Create(new Amount(AmountToTransfer.ToString("0.00"), "EUR"), Recipient, payment_desc, MonetaryAccountId).Value;
                                        Console.WriteLine("Yeah, this one is completed!");
                                    }
                                    else
                                    {
                                        Console.WriteLine("Bummer, nothing to do!");
                                    }
                                }
                            }
                            match = true;
                        }
                    }
                }
            }
            if (!match)
            {
                Console.WriteLine("None of the conditions match!");
            }
        }