API Ebay получает токен пользователя, чтобы приложение могло выполнять вызовы API - PullRequest
0 голосов
/ 28 мая 2020

Итак, насколько я понимаю, читая документацию, мне нужен токен, чтобы делать мои вызовы API на ebay. Мне нужно сделать это в. NET, чтобы приложение могло управлять листингом ebay et c.

Однако у меня проблемы с авторизацией. Пока у меня есть запрос на ebay, и он больше не возвращает ошибок, но тело ответа пустое, поэтому я не уверен, что случилось.

Вот моя функция, чтобы получить токен:

private string GetAuthTokenEbay()
        {
            bool isTestSite = false;
            var url = "";
            var oAuthToken = "";

            // Use the refresh token to generate a new OAuth token
            var refreshTokenSetting = _settingService.GetSettingByKey("ebaysetting.refreshtoken", "");
            if (!String.IsNullOrEmpty(refreshTokenSetting))
            {
                // App ID (Client ID)
                var ebayAppIdSetting = isTestSite ? _settingService.GetSettingByKey(
                    "ebaydevsetting.appid", "") : _settingService.GetSettingByKey(
                    "ebaysetting.appid", "");

                // Cert ID (Client Secret)
                var ebaySecretSetting = isTestSite ? _settingService.GetSettingByKey(
                    "ebaydevsetting.certid", "") : _settingService.GetSettingByKey(
                    "ebaysetting.certid", "");

                // RuName (taken from branded eBay Sign In URL)
                var ebayRuNameSetting = isTestSite ? _settingService.GetSettingByKey(
                    "ebaydevsetting.runame", "") : _settingService.GetSettingByKey(
                    "ebaysetting.runame", "");

                // Configure the request
                var apiurl = isTestSite ? "https://auth.sandbox.ebay.com" : "https://auth.ebay.com";

                // Configure the request body
                url += apiurl + "/oauth2/authorize?client_id=" + ebayAppIdSetting + "&" +
                       "redirect_uri=" + ebayRuNameSetting + "&response_type=code&state=sa&" +
                       "scope=" + apiurl + "/oauth/api_scope " + apiurl + "/oauth/api_scope/buy.order.readonly " + apiurl + "/oauth/api_scope/buy.guest.order " + apiurl + "/oauth/api_scope/sell.marketing.readonly " + apiurl + "/oauth/api_scope/sell.marketing " + apiurl + "/oauth/api_scope/sell.inventory.readonly " + apiurl + "/oauth/api_scope/sell.inventory " + apiurl + "/oauth/api_scope/sell.account.readonly " + apiurl + "/oauth/api_scope/sell.account " + apiurl + "/oauth/api_scope/sell.fulfillment.readonly " + apiurl + "/oauth/api_scope/sell.fulfillment " + apiurl + "/oauth/api_scope/sell.analytics.readonly " + apiurl + "/oauth/api_scope/sell.marketplace.insights.readonly " + apiurl + "/oauth/api_scope/commerce.catalog.readonly " + apiurl + "/oauth/api_scope/buy.shopping.cart " + apiurl + "/oauth/api_scope/buy.offer.auction " + apiurl + "/oauth/api_scope/commerce.identity.readonly " + apiurl + "/oauth/api_scope/commerce.identity.email.readonly " + apiurl + "/oauth/api_scope/commerce.identity.phone.readonly " + apiurl + "/oauth/api_scope/commerce.identity.address.readonly " + apiurl + "/oauth/api_scope/commerce.identity.name.readonly " + apiurl + "/oauth/api_scope/commerce.identity.status.readonly " + apiurl + "/oauth/api_scope/sell.finances " + apiurl + "/oauth/api_scope/sell.item.draft " + apiurl + "/oauth/api_scope/sell.payment.dispute " + apiurl + "/oauth/api_scope/sell.item";

                // Generate request
                var authRequest = (HttpWebRequest)WebRequest.Create(url);

                authRequest.Method = "POST";
                authRequest.ContentType = "application/x-www-form-urlencoded";
                byte[] bytes = Encoding.UTF8.GetBytes(ebayAppIdSetting + ":" + ebaySecretSetting);
                authRequest.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(bytes));

                // Get the response
                //authRequest.CookieContainer = new CookieContainer();//tried this with no luck
                authRequest.AllowAutoRedirect = false;//had to use this to prevent too many redirects error from ebay
                using (var response = (HttpWebResponse)authRequest.GetResponse())
                {
                    if (response != null)
                    {
                        using (var streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            // Parse the JSON response
                            var result = streamReader.ReadToEnd();
                            var resultObject = JsonConvert.DeserializeObject<EbayAuthenticationResponse>(result);

                            if (resultObject != null)
                            {
                                // Get the auth token and store it in our variable
                                oAuthToken = resultObject.access_token;
                            }

                        }
                    }
                }
            }

            return oAuthToken;
        }

Я могу подтвердить, что URL-адрес ebay выглядит правильным, я пропустил личную информацию, но это определенно настройка разработчика

"https://auth.sandbox.ebay.com/oauth2/authorize?client_id=clientid&redirect_uri=runame&response_type=code&state=sa&scope=https://auth.sandbox.ebay.com/oauth/api_scope https://auth.sandbox.ebay.com/oauth/api_scope/buy.order.readonly https://auth.sandbox.ebay.com/oauth/api_scope/buy.guest.order https://auth.sandbox.ebay.com/oauth/api_scope/sell.marketing.readonly https://auth.sandbox.ebay.com/oauth/api_scope/sell.marketing https://auth.sandbox.ebay.com/oauth/api_scope/sell.inventory.readonly https://auth.sandbox.ebay.com/oauth/api_scope/sell.inventory https://auth.sandbox.ebay.com/oauth/api_scope/sell.account.readonly https://auth.sandbox.ebay.com/oauth/api_scope/sell.account https://auth.sandbox.ebay.com/oauth/api_scope/sell.fulfillment.readonly https://auth.sandbox.ebay.com/oauth/api_scope/sell.fulfillment https://auth.sandbox.ebay.com/oauth/api_scope/sell.analytics.readonly https://auth.sandbox.ebay.com/oauth/api_scope/sell.marketplace.insights.readonly https://auth.sandbox.ebay.com/oauth/api_scope/commerce.catalog.readonly https://auth.sandbox.ebay.com/oauth/api_scope/buy.shopping.cart https://auth.sandbox.ebay.com/oauth/api_scope/buy.offer.auction https://auth.sandbox.ebay.com/oauth/api_scope/commerce.identity.readonly https://auth.sandbox.ebay.com/oauth/api_scope/commerce.identity.email.readonly https://auth.sandbox.ebay.com/oauth/api_scope/commerce.identity.phone.readonly https://auth.sandbox.ebay.com/oauth/api_scope/commerce.identity.address.readonly https://auth.sandbox.ebay.com/oauth/api_scope/commerce.identity.name.readonly https://auth.sandbox.ebay.com/oauth/api_scope/commerce.identity.status.readonly https://auth.sandbox.ebay.com/oauth/api_scope/sell.finances https://auth.sandbox.ebay.com/oauth/api_scope/sell.item.draft https://auth.sandbox.ebay.com/oauth/api_scope/sell.payment.dispute https://auth.sandbox.ebay.com/oauth/api_scope/sell.item"

Я добавил параметр состояния, как было предложено, хотя это необязательно. Мне все кажется нормально, может кто-нибудь поймет, где я ошибаюсь. Спасибо

Обновить. Я заметил, что URL-адрес области видимости неправильный, поэтому я обновил его, но все равно получил пустой ответ.

"https://auth.sandbox.ebay.com/oauth2/authorize?client_id=clientid&redirect_uri=runame&response_type=code&state=sa&scope=https://api.ebay.com/oauth/api_scope/sell.item"
...