cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

ebay api and oauth tokens

Hi there, 

 

I have a C# application, it just needs to query for one product (get details, affiliate link etc then will redirect the user to ebay), I can get this to work for an amount of time.

 

What I was doing is using the tokens from the API Explorer page (using "Get OAuth Application Token"). The URL I need to access is:

 

string url = $"https://api.ebay.com/buy/browse/v1/item_summary/search?q={query}&limit=1";

 

The problem is my tokens work for a while then they expire, I then get an unauthorised error. I came across this SO article:

 

https://stackoverflow.com/questions/44603838/ebay-oauth-token-and-refresh-tokens

 

Using this, I can now get the two tokens returned, an access token and a refresh token, I've now tried the refresh token but this is unauthorised also 😞

 

Presumed I could take my new token (which is meant to last for 18 months) and use it in the code below:

 

string url = $"https://api.ebay.com/buy/browse/v1/item_summary/search?q={query}&limit=1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add("Authorization", "Bearer " + #my new token#);

httpWebRequest.Headers.Add("X-EBAY-C-MARKETPLACE-ID", "EBAY_US");

httpWebRequest.Headers.Add("X-EBAY-C-ENDUSERCTX", "affiliateCampaignId=###,affiliateReferenceId=###");
httpWebRequest.Accept = "application/json";

 

I don't want to give up on this as its taken so long just to get this far, anyone out there any ideas? 

Message 1 of 8
latest reply
7 REPLIES 7

ebay api and oauth tokens

@mc-capital 

 

When using the Browse API and the "Search" call, you will only need an application access token (client_credential) because you will not need to get into any user accounts. The 18-month token is for accessing a private user account, but it appears to work when accessing public data. 

 

To acquire and use public client_credentials, your server would need to request, and store, a token for up to two hours, and then request another, when needed, after the two-hour token expires. 

https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html  

 

On the other hand, a private authorization_code is a three part process.

https://developer.ebay.com/api-docs/static/oauth-authorization-code-grant.html 

First, the user logs in to their account so that your application can acquire an authorization code. That code is used to retrieve an access token and a refresh token. The access token is good for 2 hours, while the refresh token is good for 18 months. When the 2-hour access token expires, a new 2-hour token must be minted using the 18-month refresh token.

 

So, as you can see, either process will require minting a new token every two hours. If you don't need to get into a user account, the public client_credentials for your application would be simplest.

 

ShipScript has been an eBay Community volunteer since 2003, specializing in HTML, CSS, Scripts, Photos, Active Content, Technical Solutions, and online Seller Tools.
Message 2 of 8
latest reply

ebay api and oauth tokens

Thanks for your help, sounds like I'm making this more complicated than it needs to be.

 

Just for clarification to use the browse api and get the correct token I go to:

 

https://developer.ebay.com/my/auth?env=production&index=0&auth_type=oauth

 

Ensure "Production" is chcked and get the token from "Get OAuth Application Token" link and copy this?

 

I've pasted this into live and at the moment it has worked, what I have been finding is it works for a period of time (not long) or a few requests then I get unauthorised, wonder what the policy is for revoking tokens 🤔

Again thanks for your help, will see how long it lasts this time 🙂

Message 3 of 8
latest reply

ebay api and oauth tokens

@mc-capital 

 

Yes, that looks about right.

Developer - API explorer - BrowseDeveloper - API explorer - Browse

 

This should work for only 2 hours, and then you will need a new token. I was using it all morning the other day and had to get tokens three times, which seems reasonable. I had found that I got a red "something went wrong" icon, when trying to retrieve a new token. Instead, I had to reload the explorer page each time before fetching a new token. 

 

If you are timing out sooner than 2 hours, there may be some sort of session cookie or something about the browser that interferes. When I'm running tokens on my website, I have no issues.

 

ShipScript has been an eBay Community volunteer since 2003, specializing in HTML, CSS, Scripts, Photos, Active Content, Technical Solutions, and online Seller Tools.
Message 4 of 8
latest reply

ebay api and oauth tokens

Ah ok, so it is likely to timeout shortly (after the 2 hours). You can probably guess my next question, how do we refresh the access token via C# code, is it as they have explained here:

 

https://stackoverflow.com/questions/44603838/ebay-oauth-token-and-refresh-tokens

Message 5 of 8
latest reply

ebay api and oauth tokens

That stack overflow instruction would be about right for a private user token if sandbox references are removed and endpoints are corrected.

 

However, you can get the same info on these pages, where you can verify proper endpoints:

 

I don't read C#, but eBay has a link on this page for a C#  "authorization_code" application:

https://developer.ebay.com/api-docs/static/oauth-authorization-code-grant.html

and on this page for a C#  "client_credentials" application to access public data: 

https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html 

 

 

I have a PHP version here for the simpler problem of minting application tokens for public data (and there are certainly other ways to tackle the problem, so this is just one way):

https://community.ebay.com/t5/Token-Messaging-Sandbox-related/Sample-PHP-for-generating-and-renewing... 

 

I've asked ChatGPT to translate my token-minting code to C#, below.

CAVEAT:  I have no idea if it works, but perhaps it will give you a starting point.  This would just mint tokens, so your application would have to call (or include) this module to retrieve an existing token or mint a new token.

 

using System;
using System.IO;
using System.Net;
using System.Text;

public class OAuthHelper
{
    private static readonly string oauthRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../ebay_oauth/");
    private static readonly string oauthClientIdFile = Path.Combine(oauthRoot, "ebay_apiuser.txt");
    private static readonly string oauthSecretIdFile = Path.Combine(oauthRoot, "ebay_apisecret.txt");
    private static readonly string oauthBasicTokenFile = Path.Combine(oauthRoot, "ebay_basic_token.txt");

    public static string CreateBasicOAuthToken()
    {
        string url = "https://api.ebay.com/identity/v1/oauth2/token";
        string clientId = File.ReadAllText(oauthClientIdFile).Trim();
        string clientSecret = File.ReadAllText(oauthSecretIdFile).Trim();
        string authorization = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
        string body = $"grant_type=client_credentials&scope=https://api.ebay.com/oauth/api_scope";

        try
        {
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.Headers.Add("Authorization", "Basic " + authorization);
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] data = Encoding.UTF8.GetBytes(body);
            request.ContentLength = data.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            using (WebResponse response = request.GetResponse())
            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(responseStream))
            {
                string jsonResponse = reader.ReadToEnd();
                dynamic token = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResponse);
                if (token.access_token != null)
                {
                    File.WriteAllText(oauthBasicTokenFile, token.access_token);
                    return token.access_token;
                }
                else
                {
                    return "ERR: could not access token";
                }
            }
        }
        catch (WebException ex)
        {
            return "ERR: " + ex.Message;
        }
    }

    public static string GetBasicOAuthToken()
    {
        if (File.Exists(oauthBasicTokenFile))
        {
            DateTime lastWriteTime = File.GetLastWriteTime(oauthBasicTokenFile);
            DateTime now = DateTime.Now;
            TimeSpan duration = TimeSpan.FromSeconds(7200); // 2 hours
            int margin = 30; // remaining seconds before we request a new token

            if (lastWriteTime.Add(duration).AddSeconds(-margin) > now)
            {
                return File.ReadAllText(oauthBasicTokenFile);
            }
            else
            {
                return CreateBasicOAuthToken();
            }
        }
        else
        {
            return CreateBasicOAuthToken();
        }
    }
}

 

 

ChatGPT says:  "This C# code should provide similar functionality to the PHP code you provided. Note that I've used Newtonsoft.Json for JSON serialization/deserialization, so you'll need to install that package if you haven't already. Also, I've handled exceptions using try-catch blocks to mimic the error handling in the PHP code."

 

To ask ChatGPT for help, one can open a free basic account here: https://chat.openai.com/ 

But accept responses with an abundance of caution. We see a lot of trolls who use Chat to answer questions here on the forums, and the answers often miss the mark.

 

ShipScript has been an eBay Community volunteer since 2003, specializing in HTML, CSS, Scripts, Photos, Active Content, Technical Solutions, and online Seller Tools.
Message 6 of 8
latest reply

ebay api and oauth tokens

Brill ty 🙂 shall give this a bash

Message 7 of 8
latest reply

ebay api and oauth tokens

Hi @mc-capital,

 

Browse API search call requires an access token created with the client credentials grant flow (which mints the Application access token), using the scope "https://api.ebay.com/oauth/api_scope" 

 

Application access token is valid for two hours from the time it was generated. For continued access after the token expires, you must mint a new token.

Best Regards,
eBay Developer Support
Message 8 of 8
latest reply