skip to Main Content

I’m trying to obtain an eBay OAuth access & refresh token but keep getting a 401 Unauthorized response. I’ve been through every bit of documentation on this and tried just about everything but no joy.

I’ve been through the user permission flow, granted access to my application and have the authorize code – I’m manually pasting this into my code for now and have tried it both URL encoded and URL decoded but the same result.

I’m not sure if the problem lies with my java code or one of the values in my eBay developer account. Any ideas or pointers would be most welcome.

public int initialiseToken(String clientID, String clientSecret, String ruName)
{
    int responseCode = 0;
    try
    {
            String urlString = "https://api.ebay.com/identity/v1/oauth2/token";
            String clientCredentials = clientID + ":" + clientSecret;
            // base64 encode credentials
            byte[] base64clientCredentials = Base64.encodeBase64(clientCredentials.getBytes());

            // below authCode obtained from URI redirect following eBay auth sign-in 
            String authCodeURLEncoded = "v%5E1.1%23i%5E1%23I%5E3%23f.....xI0VeMjYw";
            String authCodeURLDecoded = URLDecoder.decode(authCodeURLEncoded, "UTF-8");
            
            URL url = new URL(urlString);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "Basic " + base64clientCredentials);
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Accept-Charset", "utf8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            
            conn.setRequestProperty("grant_type", "authorization_code");
            conn.setRequestProperty("redirect_uri", ruName);
            conn.setRequestProperty("code", authCodeURLDecoded);         // have tried both encoded & decoded versions
            
            String msg;
            if (conn.getResponseCode() != 200) 
            {
                    responseCode = conn.getResponseCode();
                    msg = conn.getResponseMessage();
            }
            else
            {
                    responseCode = conn.getResponseCode();
                    msg = conn.getResponseMessage();
                    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                    String line = br.readLine();
                    parseResult(line);
            }
    }
    catch (MalformedURLException e) 
    {
            e.printStackTrace();
    } 
    catch (IOException e) 
    {
            e.printStackTrace();
    }
    catch (Exception e) 
    {
            e.printStackTrace();
    }
    return responseCode;
}

2

Answers


  1. Chosen as BEST ANSWER

    Thanks Michael - will take a look at that when I pick this up again. In the meantime, here's some code that I've used to test the Search Cancellations interface - hopefully it may be of some use to you

        public static void searchCancellations(String authToken)
    {
        String urlString = "https://api.ebay.com/post-order/v2/cancellation/search";
        String urlStringParams = "?creation_date_range_from=2018-12-01T00:00:00.000Z&creation_date_range_to=2019-01-16T00:00:00.000Z";
        try
        {
            String encodedUrl = urlString + URLEncoder.encode(urlStringParams, "UTF-8");
            URL url = new URL(encodedUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Accept-Charset", "utf8");
            conn.setRequestProperty("Authorization", "IAF " + authToken);
            conn.setRequestProperty("Content-Type", "application/json");
    
            int responseCode = 0;
            String msg;
            if (conn.getResponseCode() != 200) 
            {
                responseCode = conn.getResponseCode();
                msg = conn.getResponseMessage();
            }
            else
            {
                responseCode = conn.getResponseCode();
                msg = conn.getResponseMessage();
            }
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String line = br.readLine();
            parseCancellationResult(line);
            responseCode = 0;
        }
        catch (MalformedURLException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    

  2. I have a piece of code that’s for OAuth Client credential ( for accessing general information) if it helps.

    I am working on something very similar. I am right now stuck on using the returned access token to actually implement an ebay method. If you have managed to do that, can you let me know?

    Dependency

    implementation 'com.squareup.okhttp3:okhttp:3.5.0'
    

    Code

    public class MainActivity extends AppCompatActivity {

    private static final String clientId = "-";//clientId
    private static final String clientSecret = "-";//client secret
    private static final String tokenUrl = "https://api.sandbox.ebay.com/identity/v1/oauth2/token";
    private static final String auth = clientId + ":" + clientSecret;
    private static final String authentication = Base64.encodeToString(auth.getBytes(),Base64.NO_WRAP);
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .addHeader("Authorization", "Basic " + authentication)
                .url(tokenUrl)
                .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded")
                        ,"grant_type=client_credentials"+
                                "&scope=https://api.ebay.com/oauth/api_scope"
                        )
                )
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("Testing_", "Error: " +e.getMessage());
            }
    
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
    
                JSONObject data = null;
                try {
                    data = new JSONObject(json);
                    String accessToken = data.optString("access_token");
                    String refreshToken = data.optString("refresh_token");
    
                    Log.d("Testing_", "Access Token = " + accessToken);
                    Log.d("Testing_", "Refresh Token = " + refreshToken);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    

    Output

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search