Search code examples
c#jsonebay-api

Sending a JSON request to ebay API


Ok so I'm having a bit of trouble getting these JSON requests through to the Ebay API.

Here is the json request:

string jsonInventoryRequest = "{" +
                    "\"requests\": [";

        int commaCount = 1;
        foreach (var ep in productsToProcess)
        {
            jsonInventoryRequest += "{\"offers\": [{" +
                "\"availableQuantity\":" + ep.EbayProductStockQuantity + "," +
                "\"offerId\":\"" + ep.EbayID.ToString() + "\"," +
                "\"price\": {" +
                    "\"currency\": \"AUD\"," +
                    "\"value\":\"" + ep.EbayProductPrice.ToString() + "\"" +
                "}" +
            "}],";

            jsonInventoryRequest += "\"shipToLocationAvailability\": " + "{" +
                "\"quantity\":" + ep.EbayProductStockQuantity +
                "},";

            jsonInventoryRequest += "\"sku\": " + ep.EbayProductSKU.ToString() + "}";
            if (commaCount < productsToProcess.Count())
                jsonInventoryRequest += ",";

            commaCount++;
            sendEbayApiRequest = true;
        }

        jsonInventoryRequest += 
            "]" +
        "}";

And the Debug.WriteLine() output of the above JSON request is :

json string = {"requests": [{"offers": [{"availableQuantity":0,"offerId":"098772298312","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":0},"sku": 135779},{"offers": [{"availableQuantity":1,"offerId":"044211823133","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":1},"sku": 133607}]}

Here is the code in C# to send the request:

var ebayAppIdSetting = _settingService.GetSettingByKey(
                            "ebaysetting.appid", "");

        var ebayCertIdSetting = _settingService.GetSettingByKey(
                            "ebaysetting.certid", "");

        var ebayRuNameSetting = _settingService.GetSettingByKey(
                            "ebaysetting.appid", "");

        var stringToEncode = ebayAppIdSetting + ":" + ebayCertIdSetting;

        HttpClient client = new HttpClient();
        byte[] bytes = Encoding.UTF8.GetBytes(stringToEncode);
        var base64string = "Basic " + System.Convert.ToBase64String(bytes);
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);

        var stringContent = "?grant_type=client_credentials&" + "redirect_uri=" + ebayRuNameSetting + "&scope=https://api.sandbox.ebay.com/oauth/api_scope";
        var requestBody = new StringContent(stringContent.ToString(), Encoding.UTF8, "application/json");
        requestBody.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        var response = client.PostAsync("https://api.sandbox.ebay.com/identity/v1/oauth2/token", requestBody);

The output I get when I do Debug.WriteLine("response.Content = " + response.Result); is:

response.Content = StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: {
RlogId: t6ldssk%28ciudbq%60anng%7Fu2h%3F%3Cwk%7Difvqn*14%3F0513%29pqtfwpu%29pdhcaj%7E%29fgg%7E%606%28dlh-1613f3af633-0xbd X-EBAY-C-REQUEST-ID: ri=HNOZE3cmCr94,rci=6kMHBw5dW0vMDp8A
X-EBAY-C-VERSION: 1.0.0 X-EBAY-REQUEST-ID: 1613f3af62e.a096c6b.25e7e.ffa2b377!/identity/v1/oauth2/!10.9.108.107!r1esbngcos[]!token.unknown_grant!10.9.107.168!r1oauth-envadvcdhidzs5k[] Connection: keep-alive Date: Mon, 29 Jan 2018 00:04:44 GMT
Set-Cookie: ebay=%5Esbf%3D%23%5E;Domain=.ebay.com;Path=/
WWW-Authenticate: Basic Content-Length: 77 Content-Type: application/json }

Can anyone see where I'm going wrong. Cheers


Solution

  • Ok so the authentication was failing because I was sending wrong authentication token. Needed to get oauth token from application tokens.

    So instead of base64 encoding token like this:

    var base64string = "Basic " + System.Convert.ToBase64String(bytes);
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);
    

    I needed to do the following:

    url = "https://api.sandbox.ebay.com/sell/inventory/v1/bulk_update_price_quantity";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    
            request.Method = "POST";
            //request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("Authorization", "Bearer **OAUTH TOKEN GOES HERE WITHOUT ASTERIKS**");
    
            // Send the request
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(jsonInventoryRequest);
                streamWriter.Flush();
                streamWriter.Close();
            }
    
            // Get the response
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            if (response != null)
            {
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    // Parse the JSON response
                    var result = streamReader.ReadToEnd();
                }
            }