Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Get eBay Application Token

See more eBay Examples

This example shows how to request an eBay Application token.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.FileAccess;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpRequest;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example assumes the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // See the Ebay documentation about Access token types
        // Also see the Ebay documentation about client credentials grant flow

        Http http = new Http();

        // If using the sandbox, the target endpoint will be:
        // POST https://api.sandbox.ebay.com/identity/v1/oauth2/token

        // If using the production (live) system, the target endpoint will be:
        // POST https://api.ebay.com/identity/v1/oauth2/token

        // The eBay client_id and client_secret needs to be sent
        // in a Basic Authorization  request header, which has this format:
        // Authorization: Basic <B64_encoded_oauth_credentials>

        // Chilkat takes care of it.  You only need to set the Login = client_id,
        // and password = client_secret, and indicate you want "Basic" HTTP Authorization.
        http.setLogin("EBAY_CLIENT_ID");
        http.setPassword("EBAY_CLIENT_SECRET");
        http.setBasicAuth(true);

        // Let's do the following POST:

        //   HTTP method:   POST
        //   URL (Sandbox): https://api.sandbox.ebay.com/identity/v1/oauth2/token
        //
        //   HTTP headers:
        //     Content-Type = application/x-www-form-urlencoded
        //     Authorization = Basic <B64-encoded-oauth-credentials>
        //
        //   Request body (wrapped for readability):
        //     grant_type=client_credentials&
        //     redirect_uri=<RuName-value>&
        //     scope=<SPACE separated list of scopes>
        //

        // Create an HttpRequest object to hold the request params.
        HttpRequest req = new HttpRequest();
        req.setHttpVerb("POST");
        req.addParam("grant_type", "client_credentials");

        // The scope query param indicates the access to be provided by the token.
        // Multiple scopes can be specified by separating each with a SPACE char.
        // See the Ebay OAuth scopes documentation

        req.addParam("scope", "https://api.ebay.com/oauth/api_scope");

        String endPoint = "https://api.sandbox.ebay.com/identity/v1/oauth2/token";
        req.setContentType("application/x-www-form-urlencoded");

        HttpResponse resp = new HttpResponse();
        try {
            http.httpReq(endPoint, req, resp);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // The response is JSON..
        JsonObject json = new JsonObject();
        json.load(resp.getBodyStr());
        json.setEmitCompact(false);

        // If the response status code is not 200, then it failed.
        System.out.println("Response status code = " + resp.getStatusCode());
        if (resp.getStatusCode() != 200) {
            System.out.println(json.emit());
            System.out.println("Failed.");
            return;
        }

        // We successfully retrieved an eBay access token.
        // The actual access token string can be parsed from the JSON like this:
        String accessToken = json.stringOf("access_token");

        // This application token is only valid for 7200 seconds (2 hours).  We'll want to refresh
        // it before it expires.  (There is an online example for that..)
        // For now, let's save the JSON to a file for our application to use.

        // But before doing that, let's add to the JSON an expiration timestamp
        // so we know when to refresh the token.
        DateTime dtExpire = new DateTime();
        dtExpire.setFromCurrentSystemTime();
        dtExpire.addSeconds(json.intOf("expires_in"));
        json.appendString("expire_time", dtExpire.getAsTimestamp(false));

        // Persist the JSON to a file.
        FileAccess fac = new FileAccess();
        try {
            fac.writeEntireTextFile("qa_data/tokens/ebay.json", json.emit(), "utf-8", false);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            System.out.println("Failed to save eBay Application token to file.");
            return;
        }

        System.out.println(json.emit());
        System.out.println("Success.");

        // The output of this example is:

        //     {
        //       "access_token": "v^1.1#i^1#p^1#I^3#r^0# ... Ajp1BQhJDgAA",
        //       "token_type": "Application Access Token",
        //       "expires_in": 7200,
        //       "refresh_token": "N/A",
        //       "expire_time": "2017-04-16T14:44:20Z"
        //     }
        //
        //     Success.
        //
    }
}