Exemple #1
0
        public void ApiWillAuthenticate_ValidCredentials_Successfully()
        {
            var api = new Api.Api();

            api.Initialize(_testAccount, _testToken, _dataFolder);
            Assert.IsTrue(api.Connected);
        }
Exemple #2
0
        public bool Fetch(Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
        {
            Log.Trace(
                string.Format(
                    "Attempting to get data from QuantConnect.com's data library for symbol({0}), resolution({1}) and date({2}).",
                    symbol.ID, resolution, date.Date.ToShortDateString()));

            var api = new Api.Api();

            api.Initialize(_uid, _token, _dataPath);

            var download = api.DownloadData(symbol, resolution, date);

            if (download)
            {
                Log.Trace(
                    string.Format(
                        "Successfully retrieved data for symbol({0}), resolution({1}) and date({2}).",
                        symbol.ID, resolution, date.Date.ToShortDateString()));
                return(true);
            }


            Log.Error(
                string.Format(
                    "Unable to remotely retrieve data for symbol({0}), resolution({1}) and date({2}). Please make sure you have the necessary data in your online QuantConnect data library.",
                    symbol.ID, resolution, date.Date.ToShortDateString()));
            return(false);
        }
Exemple #3
0
        /// <summary>
        /// Create an API Class with the specified credentials
        /// </summary>
        /// <param name="uid">User id</param>
        /// <param name="token">Token string</param>
        /// <returns>API class for placing calls</returns>
        private IApi CreateApiAccessor(int uid, string token)
        {
            var api = new Api.Api();

            api.Initialize(uid, token);
            return(api);
        }
Exemple #4
0
        public void DoesNotSetRunTimeErrorWhenReconnectMessageComesThrough()
        {
            var algorithm = new AlgorithmStub(equities: new List <string> {
                "SPY"
            });
            var referenceTime = DateTime.UtcNow;

            algorithm.SetDateTime(referenceTime);
            var localReferencTime = referenceTime.ConvertFromUtc(TimeZones.NewYork);
            var open        = localReferencTime.AddSeconds(1).TimeOfDay;
            var closed      = TimeSpan.FromDays(1);
            var marketHours = new MarketHoursSegment(MarketHoursState.Market, open, closed);

            algorithm.Securities[Symbols.SPY].Exchange.SetMarketHours(new [] { marketHours }, localReferencTime.DayOfWeek);
            var job     = new LiveNodePacket();
            var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
            var api     = new Api.Api();
            var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(.25));

            Assert.IsNull(algorithm.RunTimeError);

            handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));

            Thread.Sleep(100);

            handler.Handle(BrokerageMessageEvent.Reconnected("Reconnected!"));

            Thread.Sleep(500);

            Assert.IsNull(algorithm.RunTimeError);

            results.Exit();
        }
Exemple #5
0
        /// <summary>
        /// Initialize a new instance of the <see cref="ApiDataProvider"/>
        /// </summary>
        public ApiDataProvider()
        {
            _api = new Api.Api();
            _unsupportedSecurityType = new HashSet <SecurityType> {
                SecurityType.Future, SecurityType.FutureOption, SecurityType.Index, SecurityType.IndexOption
            };
            _api.Initialize(_uid, _token, _dataPath);

            // If we have no value for organization get account preferred
            if (string.IsNullOrEmpty(_organizationId))
            {
                var account = _api.ReadAccount();
                _organizationId = account?.OrganizationId;
                Log.Trace($"ApiDataProvider(): Will use organization Id '{_organizationId}'.");
            }

            // Read in data prices and organization details
            _dataPrices = _api.ReadDataPrices(_organizationId);
            var organization = _api.ReadOrganization(_organizationId);

            // Determine if the user is subscribed to map and factor files (Data product Id 37)
            if (organization.Products.Where(x => x.Type == ProductType.Data).Any(x => x.Items.Any(x => x.Id == 37)))
            {
                _subscribedToEquityMapAndFactorFiles = true;
            }

            // Verify user has agreed to data provider agreements
            if (organization.DataAgreement.Signed)
            {
                //Log Agreement Highlights
                Log.Trace("ApiDataProvider(): Data Terms of Use has been signed. \r\n" +
                          $" Find full agreement at: {_dataPrices.AgreementUrl} \r\n" +
                          "==========================================================================\r\n" +
                          $"CLI API Access Agreement: On {organization.DataAgreement.SignedTime:d} You Agreed:\r\n" +
                          " - Display or distribution of data obtained through CLI API Access is not permitted.  \r\n" +
                          " - Data and Third Party Data obtained via CLI API Access can only be used for individual or internal employee's use.\r\n" +
                          " - Data is provided in LEAN format can not be manipulated for transmission or use in other applications. \r\n" +
                          " - QuantConnect is not liable for the quality of data received and is not responsible for trading losses. \r\n" +
                          "==========================================================================");
                Thread.Sleep(TimeSpan.FromSeconds(3));
            }
            else
            {
                // Log URL to go accept terms
                throw new InvalidOperationException($"ApiDataProvider(): Must agree to terms at {_dataPrices.AgreementUrl}, before using the ApiDataProvider");
            }

            // Verify we have the balance to maintain our purchase limit, if not adjust it to meet our balance
            var balance = organization.Credit.Balance;

            if (balance < _purchaseLimit)
            {
                if (_purchaseLimit != decimal.MaxValue)
                {
                    Log.Error("ApiDataProvider(): Purchase limit is greater than balance." +
                              $" Setting purchase limit to balance : {balance}");
                }
                _purchaseLimit = balance;
            }
        }
        public override RefundProcessPaymentResult RefundProcessPayment(RefundProcessPaymentEvaluationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Payment == null)
            {
                throw new ArgumentNullException("context.Payment");
            }

            var retVal = new RefundProcessPaymentResult();

            if (context.Payment.IsApproved && (context.Payment.PaymentStatus == PaymentStatus.Paid || context.Payment.PaymentStatus == PaymentStatus.Cancelled))
            {
                Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
                {
                    Eid        = Convert.ToInt32(AppKey),
                    Secret     = AppSecret,
                    IsLiveMode = false
                };
                Api.Api api = new Api.Api(configuration);

                var result = api.CreditInvoice(context.Payment.OuterId);
            }

            return(retVal);
        }
        public void DoesNotSetRunTimeErrorWhenReconnectMessageComesThrough()
        {
            var algorithm = new AlgorithmStub(equities: new List<string> { "SPY" });
            var referenceTime = DateTime.UtcNow;
            algorithm.SetDateTime(referenceTime);
            var localReferencTime = referenceTime.ConvertFromUtc(TimeZones.NewYork);
            algorithm.Securities["SPY"].Exchange.SetMarketHours(localReferencTime.AddSeconds(1).TimeOfDay, TimeSpan.FromDays(1), localReferencTime.DayOfWeek);
            var job = new LiveNodePacket();
            var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
            var api = new Api.Api();
            var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(.25));

            Assert.IsNull(algorithm.RunTimeError);

            handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));

            Thread.Sleep(100);

            handler.Handle(BrokerageMessageEvent.Reconnected("Reconnected!"));

            Thread.Sleep(500);

            Assert.IsNull(algorithm.RunTimeError);

            results.Exit();
        }
        public void SetsRunTimeErrorBeforeNextMarketOpen()
        {
            var algorithm = new AlgorithmStub(equities: new List <string> {
                "SPY"
            });
            var referenceTime = DateTime.UtcNow;

            algorithm.SetDateTime(referenceTime);
            var localReferenceTime = referenceTime.ConvertFromUtc(TimeZones.NewYork);

            algorithm.Securities["SPY"].Exchange.SetMarketHours(localReferenceTime.AddSeconds(1).TimeOfDay, TimeSpan.FromDays(1), localReferenceTime.DayOfWeek);
            var job     = new LiveNodePacket();
            var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
            var api     = new Api.Api();
            var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(.25));

            Assert.IsNull(algorithm.RunTimeError);

            handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));

            Thread.Sleep(1000);

            Assert.IsNotNull(algorithm.RunTimeError);

            results.Exit();
        }
Exemple #9
0
        public void ApiWillAuthenticate_InvalidCredentials_Unsuccessfully()
        {
            var api = new Api.Api();

            api.Initialize(_testAccount, "", _dataFolder);
            Assert.IsFalse(api.Connected);
        }
Exemple #10
0
        public void Setup()
        {
            _testAccount = Config.GetInt("job-user-id", 1);
            _testToken   = Config.Get("api-access-token", "ec87b337ac970da4cbea648f24f1c851");
            _dataFolder  = Config.Get("data-folder");

            _api = new Api.Api();
            _api.Initialize(_testAccount, _testToken, _dataFolder);
        }
Exemple #11
0
        public void Setup()
        {
            TestAccount      = Config.GetInt("job-user-id", 1);
            TestToken        = Config.Get("api-access-token", "EnterTokenHere");
            TestOrganization = Config.Get("job-organization-id", "EnterOrgHere");
            DataFolder       = Config.Get("data-folder");

            ApiClient = new Api.Api();
            ApiClient.Initialize(TestAccount, TestToken, DataFolder);
        }
Exemple #12
0
        public void Setup()
        {
            _testAccount      = Config.GetInt("job-user-id");
            _testToken        = Config.Get("api-access-token");
            _testOrganization = Config.Get("job-organization-id", "EnterOrgHere"); //This org must be your preferred org
            _dataFolder       = Config.Get("data-folder");

            _api = new Api.Api();
            _api.Initialize(_testAccount, _testToken, _dataFolder);
        }
        private PostProcessPaymentResult OldRegisterKlarnaOrder(PostProcessPaymentEvaluationContext context)
        {
            var retVal = new PostProcessPaymentResult();

            Uri resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.OuterId));

            var connector = Connector.Create(AppSecret);

            Order order = new Order(connector, resourceUri)
            {
                ContentType = _contentType
            };

            order.Fetch();
            var status = order.GetValue("status") as string;

            if (status == "checkout_complete")
            {
                var data = new Dictionary <string, object> {
                    { "status", "created" }
                };
                order.Update(data);
                order.Fetch();
                status = order.GetValue("status") as string;
            }

            if (status == "created")
            {
                var reservation = order.GetValue("reservation") as string;

                if (!string.IsNullOrEmpty(reservation))
                {
                    Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
                    {
                        Eid        = Convert.ToInt32(AppKey),
                        Secret     = AppSecret,
                        IsLiveMode = false
                    };

                    Api.Api api = new Api.Api(configuration);

                    var response = api.Activate(reservation);

                    order.Fetch();

                    var klarnaCart = order.GetValue("cart") as JObject;
                }
            }

            retVal.IsSuccess        = status == "created";
            retVal.NewPaymentStatus = retVal.IsSuccess ? PaymentStatus.Paid : PaymentStatus.Pending;
            retVal.OrderId          = context.Order.Id;

            return(retVal);
        }
        public override CaptureProcessPaymentResult CaptureProcessPayment(CaptureProcessPaymentEvaluationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Payment == null)
            {
                throw new ArgumentNullException("context.Payment");
            }

            var retVal = new CaptureProcessPaymentResult();

            Uri   resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.Payment.OuterId));
            var   connector   = Connector.Create(AppSecret);
            Order order       = new Order(connector, resourceUri)
            {
                ContentType = _contentType
            };

            order.Fetch();

            var reservation = order.GetValue("reservation") as string;

            if (!string.IsNullOrEmpty(reservation))
            {
                try
                {
                    Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
                    {
                        Eid        = Convert.ToInt32(AppKey),
                        Secret     = AppSecret,
                        IsLiveMode = false
                    };
                    Api.Api api      = new Api.Api(configuration);
                    var     response = api.Activate(reservation);

                    retVal.NewPaymentStatus      = context.Payment.PaymentStatus = PaymentStatus.Paid;
                    context.Payment.CapturedDate = DateTime.UtcNow;
                    context.Payment.IsApproved   = true;
                    retVal.IsSuccess             = true;
                    retVal.OuterId = context.Payment.OuterId = response.InvoiceNumber;
                }
                catch (Exception ex)
                {
                    retVal.ErrorMessage = ex.Message;
                }
            }
            else
            {
                retVal.ErrorMessage = "No reservation for this order";
            }

            return(retVal);
        }
Exemple #15
0
        private void InitializeKlarnaApi()
        {
            var configuration = GetConfiguration();

            configuration.Eid        = Convert.ToInt32(AppKey);
            configuration.Secret     = AppSecret;
            configuration.IsLiveMode = !IsTestMode;

            var api = new Api.Api(configuration);

            KlarnaApi = new KlarnaApiImpl(api);
        }
Exemple #16
0
        public void FormattingPathForDataRequestsAreCorrect(string dataFolder, string dataToDownload)
        {
            var api = new Api.Api();

            api.Initialize(TestAccount, TestToken, dataFolder);

            var path = Path.Combine(dataFolder, dataToDownload);

            var result = api.FormatPathForDataRequest(path);

            Assert.AreEqual(dataToDownload.Replace("\\", "/", StringComparison.InvariantCulture), result);
        }
Exemple #17
0
        public void FormattingPathForDataRequestsAreCorrect(string dataFolder)
        {
            var api = new Api.Api();

            api.Initialize(TestAccount, TestToken, dataFolder);

            var dataToDownload = "forex/oanda/daily/eurusd.zip";
            var path           = Path.Combine(dataFolder, dataToDownload);

            var result = api.FormatPathForDataRequest(path);

            Assert.AreEqual(dataToDownload, result);
        }
Exemple #18
0
 /// <summary>
 /// Authenticate API
 /// </summary>
 /// <param name="credentials">User id and access token to authenticate the API</param>
 /// <returns>true if successfully authenticated API, false otherwise</returns>
 public bool Login(Credentials credentials)
 {
     VSActivityLog.Info("Authenticating QuantConnect API");
     try
     {
         var api = new Api.Api();
         api.Initialize(int.Parse(credentials.UserId), credentials.AccessToken, Globals.DataFolder);
         if (api.Connected)
         {
             _api = api;
             return(true);
         }
     }
     catch (FormatException)
     {
         VSActivityLog.Error("User id is not a valid number");
     }
     return(false);
 }
        public void DoesNotSetAlgorithmRunTimeErrorOnDisconnectIfAllSecuritiesClosed()
        {
            var referenceTime = DateTime.UtcNow;
            var algorithm = new AlgorithmStub(equities: new List<string> { "SPY" });
            algorithm.SetDateTime(referenceTime);
            algorithm.Securities["SPY"].Exchange.SetMarketHours(TimeSpan.Zero, TimeSpan.Zero, referenceTime.ConvertFromUtc(TimeZones.NewYork).DayOfWeek);
            var job = new LiveNodePacket();
            var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
            var api = new Api.Api();
            var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.FromMinutes(15));

            Assert.IsNull(algorithm.RunTimeError);

            handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));

            Assert.IsNull(algorithm.RunTimeError);

            results.Exit();
        }
        public void SetsAlgorithmRunTimeErrorOnDisconnectIfNonCustomSecurityIsOpen()
        {
            var algorithm = new AlgorithmStub(equities: new List<string> { "SPY" });
            algorithm.Securities[Symbols.SPY].Exchange = new SecurityExchange(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork));
            var job = new LiveNodePacket();
            var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
            var api = new Api.Api();
            var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.Zero, TimeSpan.Zero);

            Assert.IsNull(algorithm.RunTimeError);

            handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));

            Thread.Sleep(100);

            Assert.IsNotNull(algorithm.RunTimeError);

            results.Exit();
        }
        /// <summary>
        /// Authenticate API
        /// </summary>
        /// <param name="credentials">User id and access token to authenticate the API</param>
        /// <returns>true if successfully authenticated API, false otherwise</returns>
        public async System.Threading.Tasks.Task <bool> Login(Credentials credentials)
        {
            VSActivityLog.Info("Authenticating QuantConnect API");
            try
            {
                var api = new Api.Api();
                api.Initialize(int.Parse(credentials.UserId), credentials.AccessToken, Globals.DataFolder);
                var apiConnected = await System.Threading.Tasks.Task.Run(() => api.Connected);

                if (apiConnected)
                {
                    _api = api;
                    return(true);
                }
            }
            catch (Exception exception)
            {
                VsUtils.ShowErrorMessageBox(ServiceProvider.GlobalProvider,
                                            "QuantConnect Exception", exception.ToString());
            }
            return(false);
        }
        public void SetsAlgorithmRunTimeErrorOnDisconnectIfNonCustomSecurityIsOpen()
        {
            var algorithm = new AlgorithmStub(equities: new List <string> {
                "SPY"
            });

            algorithm.Securities["SPY"].Exchange = new SecurityExchange(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork));
            var job     = new LiveNodePacket();
            var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
            var api     = new Api.Api();
            var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.Zero);

            Assert.IsNull(algorithm.RunTimeError);

            handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));

            Thread.Sleep(10);

            Assert.IsNotNull(algorithm.RunTimeError);

            results.Exit();
        }
Exemple #23
0
        public void DoesNotSetAlgorithmRunTimeErrorOnDisconnectIfAllSecuritiesClosed()
        {
            var referenceTime = DateTime.UtcNow;
            var algorithm     = new AlgorithmStub(equities: new List <string> {
                "SPY"
            });

            algorithm.SetDateTime(referenceTime);
            algorithm.Securities[Symbols.SPY].Exchange.SetMarketHours(Enumerable.Empty <MarketHoursSegment>(), referenceTime.ConvertFromUtc(TimeZones.NewYork).DayOfWeek);
            var job     = new LiveNodePacket();
            var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
            var api     = new Api.Api();
            var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.FromMinutes(15));

            Assert.IsNull(algorithm.RunTimeError);

            handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));

            Assert.IsNull(algorithm.RunTimeError);

            results.Exit();
        }
 /// <summary>
 /// Authenticate API
 /// </summary>
 /// <param name="userId">User id to authenticate the API</param>
 /// <param name="accessToken">Access token to authenticate the API</param>
 /// <returns>true if successfully authenticated API, false otherwise</returns>
 public bool LogIn(Credentials credentials, string dataFolderPath)
 {
     _log.Info($"Authenticating QuantConnect API with data folder {dataFolderPath}");
     try
     {
         var api = new Api.Api();
         api.Initialize(int.Parse(credentials.UserId), credentials.AccessToken, dataFolderPath);
         if (api.Connected)
         {
             _api = api;
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (FormatException)
     {
         // User id is not a number
         return(false);
     }
 }
 /// <summary>
 /// Logout the API
 /// </summary>
 public void Logout()
 {
     _api = null;
 }
Exemple #26
0
        public void NullDataFolder()
        {
            var api = new Api.Api();

            Assert.DoesNotThrow(() => api.Initialize(TestAccount, "", null));
        }
		public override RefundProcessPaymentResult RefundProcessPayment(RefundProcessPaymentEvaluationContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			if (context.Payment == null)
				throw new ArgumentNullException("context.Payment");

			var retVal = new RefundProcessPaymentResult();

			if (context.Payment.IsApproved && (context.Payment.PaymentStatus == PaymentStatus.Paid || context.Payment.PaymentStatus == PaymentStatus.Cancelled))
			{
				Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
				{
					Eid = Convert.ToInt32(AppKey),
					Secret = AppSecret,
					IsLiveMode = false
				};
				Api.Api api = new Api.Api(configuration);

				var result = api.CreditInvoice(context.Payment.OuterId);
			}

			return retVal;
		}
 /// <summary>
 /// Constructor that initializes Api Connection
 /// </summary>
 public ApiDataQueueHandler()
 {
     _api = new Api.Api();
     _api.Initialize(Config.GetInt("job-user-id", 0), Config.Get("api-access-token", ""), Config.Get("data-folder"));
 }
Exemple #29
0
 public void Setup()
 {
     _api = new Api.Api();
     _api.Initialize(_testAccount, _testToken, _dataFolder);
 }
Exemple #30
0
 /// <summary>
 /// Create an API Class with the specified credentials
 /// </summary>
 /// <param name="uid">User id</param>
 /// <param name="token">Token string</param>
 /// <returns>API class for placing calls</returns>
 private IApi CreateApiAccessor(int uid, string token)
 {
     var api = new Api.Api();
     api.Initialize(uid, token);
     return api;
 }
 public KlarnaApiImpl(Api.Api klarnaApi)
 {
     _klarnaApi = klarnaApi;
 }
Exemple #32
0
 public Bot()
 {
     _api = new Api.Api("");
 }
 /// <summary>
 /// Constructor that initializes Api Connection
 /// </summary>
 public ApiDataQueueHandler()
 {
     _api = new Api.Api();
     _api.Initialize(Config.GetInt("job-user-id", 0), Config.Get("api-access-token", ""), Config.Get("data-folder"));
 }
		public override CaptureProcessPaymentResult CaptureProcessPayment(CaptureProcessPaymentEvaluationContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			if (context.Payment == null)
				throw new ArgumentNullException("context.Payment");

			var retVal = new CaptureProcessPaymentResult();

			Uri resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.Payment.OuterId));
			var connector = Connector.Create(AppSecret);
			Order order = new Order(connector, resourceUri)
			{
				ContentType = _contentType
			};
			order.Fetch();

			var reservation = order.GetValue("reservation") as string;
			if (!string.IsNullOrEmpty(reservation))
			{
				try
				{
					Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
					{
						Eid = Convert.ToInt32(AppKey),
						Secret = AppSecret,
						IsLiveMode = false
					};
					Api.Api api = new Api.Api(configuration);
					var response = api.Activate(reservation);

					retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Paid;
					context.Payment.CapturedDate = DateTime.UtcNow;
					context.Payment.IsApproved = true;
					retVal.IsSuccess = true;
					retVal.OuterId = context.Payment.OuterId = response.InvoiceNumber;
				}
				catch(Exception ex)
				{
					retVal.ErrorMessage = ex.Message;
				}
			}
			else
			{
				retVal.ErrorMessage = "No reservation for this order";
			}

			return retVal;
		}
		public override VoidProcessPaymentResult VoidProcessPayment(VoidProcessPaymentEvaluationContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			if (context.Payment == null)
				throw new ArgumentNullException("context.Payment");

			var retVal = new VoidProcessPaymentResult();

			if (!context.Payment.IsApproved && (context.Payment.PaymentStatus == PaymentStatus.Authorized || context.Payment.PaymentStatus == PaymentStatus.Cancelled))
			{
				Uri resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.Payment.OuterId));
				var connector = Connector.Create(AppSecret);
				Order order = new Order(connector, resourceUri)
				{
					ContentType = _contentType
				};
				order.Fetch();

				var reservation = order.GetValue("reservation") as string;
				if (!string.IsNullOrEmpty(reservation))
				{
					try
					{
						Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
						{
							Eid = Convert.ToInt32(AppKey),
							Secret = AppSecret,
							IsLiveMode = false
						};
						Api.Api api = new Api.Api(configuration);
						var result = api.CancelReservation(reservation);
						if (result)
						{
							retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Voided;
							context.Payment.VoidedDate = context.Payment.CancelledDate = DateTime.UtcNow;
							context.Payment.IsCancelled = true;
							retVal.IsSuccess = true;
						}
						else
						{
							retVal.ErrorMessage = "Payment was not canceled, try later";
						}
					}
					catch(Exception ex)
					{
						retVal.ErrorMessage = ex.Message;
					}
				}
			}
			else if(context.Payment.IsApproved)
			{
				retVal.ErrorMessage = "Payment already approved, use refund";
				retVal.NewPaymentStatus = PaymentStatus.Paid;
			}
			else if(context.Payment.IsCancelled)
			{
				retVal.ErrorMessage = "Payment already canceled";
				retVal.NewPaymentStatus = PaymentStatus.Voided;
			}

			return retVal;
		}
        public override VoidProcessPaymentResult VoidProcessPayment(VoidProcessPaymentEvaluationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Payment == null)
            {
                throw new ArgumentNullException("context.Payment");
            }

            var retVal = new VoidProcessPaymentResult();

            if (!context.Payment.IsApproved && (context.Payment.PaymentStatus == PaymentStatus.Authorized || context.Payment.PaymentStatus == PaymentStatus.Cancelled))
            {
                Uri   resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.Payment.OuterId));
                var   connector   = Connector.Create(AppSecret);
                Order order       = new Order(connector, resourceUri)
                {
                    ContentType = _contentType
                };
                order.Fetch();

                var reservation = order.GetValue("reservation") as string;
                if (!string.IsNullOrEmpty(reservation))
                {
                    try
                    {
                        Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
                        {
                            Eid        = Convert.ToInt32(AppKey),
                            Secret     = AppSecret,
                            IsLiveMode = false
                        };
                        Api.Api api    = new Api.Api(configuration);
                        var     result = api.CancelReservation(reservation);
                        if (result)
                        {
                            retVal.NewPaymentStatus     = context.Payment.PaymentStatus = PaymentStatus.Voided;
                            context.Payment.VoidedDate  = context.Payment.CancelledDate = DateTime.UtcNow;
                            context.Payment.IsCancelled = true;
                            retVal.IsSuccess            = true;
                        }
                        else
                        {
                            retVal.ErrorMessage = "Payment was not canceled, try later";
                        }
                    }
                    catch (Exception ex)
                    {
                        retVal.ErrorMessage = ex.Message;
                    }
                }
            }
            else if (context.Payment.IsApproved)
            {
                retVal.ErrorMessage     = "Payment already approved, use refund";
                retVal.NewPaymentStatus = PaymentStatus.Paid;
            }
            else if (context.Payment.IsCancelled)
            {
                retVal.ErrorMessage     = "Payment already canceled";
                retVal.NewPaymentStatus = PaymentStatus.Voided;
            }

            return(retVal);
        }
		private PostProcessPaymentResult OldRegisterKlarnaOrder(PostProcessPaymentEvaluationContext context)
		{
			var retVal = new PostProcessPaymentResult();

			Uri resourceUri = new Uri(string.Format("{0}/{1}", _euroTestBaseUrl, context.OuterId));

			var connector = Connector.Create(AppSecret);

			Order order = new Order(connector, resourceUri)
			{
				ContentType = _contentType
			};

			order.Fetch();
			var status = order.GetValue("status") as string;

			if (status == "checkout_complete")
			{
				var data = new Dictionary<string, object> { { "status", "created" } };
				order.Update(data);
				order.Fetch();
				status = order.GetValue("status") as string;
			}

			if (status == "created")
			{
				var reservation = order.GetValue("reservation") as string;

				if (!string.IsNullOrEmpty(reservation))
				{
					Configuration configuration = new Configuration(Country.Code.SE, Language.Code.SV, Currency.Code.SEK, Encoding.Sweden)
					{
						Eid = Convert.ToInt32(AppKey),
						Secret = AppSecret,
						IsLiveMode = false
					};

					Api.Api api = new Api.Api(configuration);

					var response = api.Activate(reservation);

					order.Fetch();

					var klarnaCart = order.GetValue("cart") as JObject;
				}
			}

			retVal.IsSuccess = status == "created";
			retVal.NewPaymentStatus = retVal.IsSuccess ? PaymentStatus.Paid : PaymentStatus.Pending;
			retVal.OrderId = context.Order.Id;

			return retVal;
		}
Exemple #38
0
 public void Setup()
 {
     _api = new Api.Api();
     _api.Initialize(_testAccount, _testToken, _dataFolder);
 }
        /// <summary>
        /// Initialize a new instance of the <see cref="ApiDataProvider"/>
        /// </summary>
        public ApiDataProvider()
        {
            _api = new Api.Api();

            _api.Initialize(_uid, _token, _dataPath);
        }