示例#1
0
        /// <summary>
        ///	Returns receipts that were changed in the specified period in asynchronous manner
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="token">Cancellation token for cancelling call to endpoint</param>
        /// <returns></returns>
        public async Task <IEnumerable <Receipt> > GetOrdersAsync(DateTime startDate, DateTime endDate, CancellationToken token)
        {
            Condition.Requires(startDate).IsLessThan(endDate);

            var mark = Mark.CreateNew();
            IEnumerable <Receipt> response = null;

            long minLastModified = startDate.FromUtcTimeToEpoch();
            long maxLastModified = endDate.FromUtcTimeToEpoch();

            string url = String.Format(EtsyEndPoint.GetReceiptsUrl + "&min_last_modified={1}&max_last_modified={2}", Config.ShopName,
                                       minLastModified, maxLastModified);

            try
            {
                EtsyLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()));

                response = await base.GetEntitiesAsync <Receipt>(url, token, mark : mark).ConfigureAwait(false);

                EtsyLogger.LogEnd(this.CreateMethodCallInfo(url, mark, methodResult: response.ToJson(), additionalInfo: this.AdditionalLogInfo()));
            }
            catch (Exception exception)
            {
                var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), exception);
                EtsyLogger.LogTraceException(etsyException);
                throw etsyException;
            }

            return(response);
        }
        /// <summary>
        ///	Creates a new listing
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task CreateListing(PostListingRequest request, CancellationToken token)
        {
            var mark = Mark.CreateNew();
            var url  = String.Format(EtsyEndPoint.CreateListingUrl, Config.ShopName);

            try
            {
                EtsyLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()));

                var payload = new Dictionary <string, string>
                {
                    { "quantity", request.Quantity.ToString() },
                    { "title", request.Title },
                    { "description", request.Description },
                    { "price", request.Price.ToString() },
                    { "who_made", request.WhoMade.ToString() },
                    { "is_supply", request.IsSupply.ToString() },
                    { "when_made", request.WhenMade },
                    { "state", request.State.ToString() },
                    { "shipping_template_id", request.ShippingTemplateId.ToString() }
                };

                await base.PostAsync(url, payload, token, mark).ConfigureAwait(false);

                EtsyLogger.LogEnd(this.CreateMethodCallInfo(url, mark, methodResult: request.ToJson(), additionalInfo: this.AdditionalLogInfo()));
            }
            catch (Exception exception)
            {
                var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), exception);
                EtsyLogger.LogTraceException(etsyException);
                throw etsyException;
            }
        }
示例#3
0
        /// <summary>
        ///	Returns shop info
        /// </summary>
        /// <param name="shopName">Etsy's shop name</param>
        /// <param name="token">Token for cancelling calls to endpoint</param>
        /// <returns></returns>
        public async Task <Shop> GetShopInfo(string shopName, CancellationToken token)
        {
            Condition.Requires(shopName).IsNotNullOrEmpty();

            var mark = Mark.CreateNew();
            IEnumerable <Shop> response = null;
            string             url      = String.Format(EtsyEndPoint.GetShopInfoUrl, shopName);

            try
            {
                EtsyLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()));

                response = await GetEntitiesAsync <Shop>(url, token).ConfigureAwait(false);

                EtsyLogger.LogEnd(this.CreateMethodCallInfo(url, mark, methodResult: response.ToJson(), additionalInfo: this.AdditionalLogInfo()));
            }
            catch (Exception exception)
            {
                var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), exception);
                EtsyLogger.LogTraceException(etsyException);
                throw etsyException;
            }

            return(response.FirstOrDefault());
        }
示例#4
0
        /// <summary>
        ///	Returns access token for making authorized API calls
        /// </summary>
        /// <returns></returns>
        public Task <OAuthCredentials> GetPermanentCredentials(string temporaryToken, string temporaryTokenSecret, string verifierCode)
        {
            Condition.Requires(temporaryToken).IsNotNullOrEmpty();
            Condition.Requires(temporaryTokenSecret).IsNotNullOrEmpty();
            Condition.Requires(verifierCode).IsNotNullOrEmpty();

            var mark = Mark.CreateNew();

            var requestParameters = new Dictionary <string, string>
            {
                { "oauth_token", temporaryToken },
                { "oauth_verifier", verifierCode }
            };

            return(Policy.HandleResult <OAuthCredentials>(credentials => credentials == null)
                   .WaitAndRetryAsync(Config.RetryAttempts,
                                      retryCount => TimeSpan.FromSeconds(ActionPolicy.GetDelayBeforeNextAttempt(retryCount)),
                                      (entityRaw, timeSpan, retryCount, context) =>
            {
                string retryDetails = CreateMethodCallInfo(EtsyEndPoint.GetAccessTokenUrl, mark, additionalInfo: this.AdditionalLogInfo());
                EtsyLogger.LogTraceRetryStarted(timeSpan.Seconds, retryCount, retryDetails);
            })
                   .ExecuteAsync(async() =>
            {
                OAuthCredentials credentials = null;
                string url = Config.ApiBaseUrl + EtsyEndPoint.GetAccessTokenUrl;

                try
                {
                    var oauthParameters = Authenticator.GetOAuthRequestParameters(url, "GET", temporaryTokenSecret, requestParameters);
                    url = Authenticator.GetUrl(url, oauthParameters);

                    EtsyLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()));

                    HttpResponseMessage response = await HttpClient.GetAsync(url).ConfigureAwait(false);
                    var result = response.Content.ReadAsStringAsync().Result;

                    ThrowIfError(response, result);

                    EtsyLogger.LogEnd(this.CreateMethodCallInfo(url, mark, methodResult: result.ToJson(), additionalInfo: this.AdditionalLogInfo()));

                    var queryParams = Misc.ParseQueryParams(result);
                    queryParams.TryGetValue("oauth_token", out var token);
                    queryParams.TryGetValue("oauth_token_secret", out var tokenSecret);

                    if (!(string.IsNullOrEmpty(token) ||
                          string.IsNullOrEmpty(tokenSecret)))
                    {
                        credentials = new OAuthCredentials(null, token, tokenSecret);
                    }
                }
                catch (Exception exception)
                {
                    var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), exception);
                    EtsyLogger.LogTraceException(etsyException);
                }

                return credentials;
            }));
        }
        /// <summary>
        ///	Returns listings in the draft state
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task <IEnumerable <Listing> > GetDraftListings(CancellationToken token)
        {
            var mark = Mark.CreateNew();
            var url  = String.Format(EtsyEndPoint.GetShopDraftListingsUrl, Config.ShopName);

            try
            {
                EtsyLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()));

                var listings = await GetEntitiesAsync <Listing>(url, token, mark : mark).ConfigureAwait(false);

                EtsyLogger.LogEnd(this.CreateMethodCallInfo(url, mark, methodResult: listings.ToJson(), additionalInfo: this.AdditionalLogInfo()));

                return(listings.ToArray());
            }
            catch (Exception exception)
            {
                var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), exception);
                EtsyLogger.LogTraceException(etsyException);
                throw etsyException;
            }
        }
        /// <summary>
        ///	Returns listing's products
        /// </summary>
        /// <param name="listing"></param>
        /// <param name="sku"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task <ListingInventory> GetListingInventoryBySku(Listing listing, string sku, CancellationToken token)
        {
            var    mark = Mark.CreateNew();
            string url  = String.Format(EtsyEndPoint.GetListingInventoryUrl, listing.Id);

            try
            {
                EtsyLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()));

                var inventory = await GetEntityAsync <ListingInventory>(url, token, mark).ConfigureAwait(false);

                EtsyLogger.LogEnd(this.CreateMethodCallInfo(url, mark, methodResult: inventory.ToJson(), additionalInfo: this.AdditionalLogInfo()));

                return(inventory);
            }
            catch (Exception exception)
            {
                var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), exception);
                EtsyLogger.LogTraceException(etsyException);
                throw etsyException;
            }
        }
        /// <summary>
        ///	Updates sku quantity asynchronously
        /// </summary>
        /// <param name="listing"></param>
        /// <param name="inventory"></param>
        /// <param name="sku"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private async Task UpdateSkuQuantityAsync(Listing listing, ListingInventory inventory, string sku, int quantity, CancellationToken token)
        {
            var mark = Mark.CreateNew();

            var updateInventoryRequest = new List <UpdateInventoryRequest>();

            // we should also add all product variations to request
            foreach (var product in inventory.Products)
            {
                var productOffering = product.Offerings.FirstOrDefault();

                if (productOffering == null)
                {
                    continue;
                }

                int productQuantity = productOffering.Quantity;

                if (product.Sku != null && product.Sku.ToLower().Equals(sku.ToLower()))
                {
                    productQuantity = quantity;
                }

                updateInventoryRequest.Add(new UpdateInventoryRequest()
                {
                    ProductId      = product.Id,
                    Sku            = product.Sku,
                    PropertyValues = DecodePropertyValuesWithQuotesAndEscape(product.PropertyValues),
                    // currently each product has one offering
                    ListingOffering = new ListingOfferingRequest[]
                    {
                        new ListingOfferingRequest()
                        {
                            Id       = productOffering.Id,
                            Quantity = productQuantity,
                            Price    = (decimal)productOffering.Price
                        }
                    }
                });
            }

            var url = String.Format(EtsyEndPoint.UpdateListingInventoryUrl, listing.Id);

            Dictionary <string, string> payload;

            try
            {
                EtsyLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()));

                payload = new Dictionary <string, string>
                {
                    { "products", JsonConvert.SerializeObject(updateInventoryRequest.ToArray()) }
                };

                if (inventory.PriceOnProperty.Length != 0)
                {
                    payload.Add("price_on_property", string.Join(",", inventory.PriceOnProperty));
                }

                if (inventory.QuantityOnProperty.Length != 0)
                {
                    payload.Add("quantity_on_property", string.Join(",", inventory.QuantityOnProperty));
                }

                if (inventory.SkuOnProperty.Length != 0)
                {
                    payload.Add("sku_on_property", string.Join(",", inventory.SkuOnProperty));
                }
            }
            catch (Exception exception)
            {
                var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), exception);
                EtsyLogger.LogTraceException(etsyException);
                throw etsyException;
            }

            var requestPayload = payload.ToJson();

            try
            {
                await base.PutAsync(url, payload, token, mark).ConfigureAwait(false);

                EtsyLogger.LogEnd(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo(), requestPayload: requestPayload));
            }
            catch (Exception exception)
            {
                var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo(), requestPayload: requestPayload), exception);
                EtsyLogger.LogTraceException(etsyException);
                throw etsyException;
            }
        }
示例#8
0
        /// <summary>
        ///	Returns temporary credentials and login url for customer
        /// </summary>
        /// <param name="scopes">Permissions</param>
        /// <returns></returns>
        public Task <OAuthCredentials> GetTemporaryCredentials(string[] scopes)
        {
            Condition.Requires(scopes).IsNotEmpty();

            var mark = Mark.CreateNew();

            var requestParameters = new Dictionary <string, string>
            {
                { "scopes", string.Join(" ", scopes) },
                { "oauth_callback", "oob" }
            };

            return(Policy.HandleResult <OAuthCredentials>(credentials => credentials == null)
                   .WaitAndRetryAsync(Config.RetryAttempts,
                                      retryCount => TimeSpan.FromSeconds(ActionPolicy.GetDelayBeforeNextAttempt(retryCount)),
                                      (entityRaw, timeSpan, retryCount, context) =>
            {
                string retryDetails = CreateMethodCallInfo(EtsyEndPoint.GetRequestTokenUrl, mark, additionalInfo: this.AdditionalLogInfo());
                EtsyLogger.LogTraceRetryStarted(timeSpan.Seconds, retryCount, retryDetails);
            })
                   .ExecuteAsync(async() =>
            {
                OAuthCredentials credentials = null;

                string absoluteUrl = Config.ApiBaseUrl + EtsyEndPoint.GetRequestTokenUrl;

                var oauthParameters = Authenticator.GetOAuthRequestParameters(absoluteUrl, "GET", null, requestParameters);
                string url = Authenticator.GetUrl(absoluteUrl, oauthParameters);

                try
                {
                    EtsyLogger.LogStarted(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()));

                    HttpResponseMessage response = await HttpClient.GetAsync(url).ConfigureAwait(false);

                    var result = response.Content.ReadAsStringAsync().Result;

                    EtsyLogger.LogEnd(this.CreateMethodCallInfo(url, mark, methodResult: result.ToJson(), additionalInfo: this.AdditionalLogInfo()));

                    ThrowIfError(response, result);

                    if (!string.IsNullOrEmpty(result) &&
                        result.IndexOf("login_url", StringComparison.InvariantCulture) > -1)
                    {
                        string loginUrl = Uri.UnescapeDataString(result.Replace("login_url=", ""));

                        string[] temp = loginUrl.Split('?');

                        if (temp.Length == 2)
                        {
                            var queryParams = Misc.ParseQueryParams(temp[1]);
                            queryParams.TryGetValue("oauth_token", out var token);
                            queryParams.TryGetValue("oauth_token_secret", out var tokenSecret);

                            if (token != null && tokenSecret != null)
                            {
                                credentials = new OAuthCredentials(loginUrl, token, tokenSecret);
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    var etsyException = new EtsyException(this.CreateMethodCallInfo(url, mark, additionalInfo: this.AdditionalLogInfo()), exception);
                    EtsyLogger.LogTraceException(etsyException);
                }

                return credentials;
            }));
        }