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

Sample PHP for generating and renewing a Shopping token

Below is a PHP code example for creating and refreshing an Oauth token. The application will look at the timestamp on the token file to see if it has expired. If it has, or is close to expiration, the routine will generate a new token. Otherwise, it will read the existing token from file.

 

In this token example, the token will have a public scope, as required by the Shopping API. Other APIs may allow other scopes.

 

eBay Shopping API - OAUTH getBasicToken Example for PHP with cURL

 

The code below is a working example of creating and using an Application token (Client Credentials grant flow), typically implemented by programs that do not require access to a user account. For the Shopping API, the header will be 'X-EBAY-API-IAF-TOKEN' . There is no query parameter alternative, and both the earlier 'appid' query parameter and the 'X-EBAY-API-APP-ID' HTTP header were deprecated June 2021 and can no longer be used with the Shopping API.

 

Not shown here (and not used by the Shopping API) is the User token (Authorization Code grant flow) method that requires the user to log into their eBay account to grant permission.

 

The Code is presented in two parts:

  1. The first PHP code section is an "include" module that will get a token and will reset an expired token. The cURL code is written in longhand for easier understanding. You will need to place three text files in a folder behind your server's public firewall (we call the folder ebay_oauth). The files are:
    • ebay_apiuser.txt containing AppId (clientID).
    • ebay_apisecret.txt containing CertId (clientSecret).
    • ebay_basic_token.txt an empty Token file.
    The code will then work without modification if you name it "getBasicToken.php".
     
  2. The second code section is a skeleton PHP example that would be integrated into the application to call the token through the 'include' file. To run, the application code would need the additional input of $siteID, $selectorArr, and $itemNumArr that are used to build the URL call. Processing the $apiResponse data returned from eBay, and handling errors, would be your obligation.


 

Include file to create and renew token (getBasicToken.php)

<?php 
//=============================================================================================
// PHP include file -- basic api token  (basic scope, for Shopping api) utilizing CURL.
// We name this file as "getBasicToken.php" in our example application code.
//=============================================================================================
//The eBay OAuth token service generates, or mints, access tokens via two different grant flows:
//   1. Client credentials grant flow: mints a new Application access token that you can use 
//	to access the resources owned by the application.
// 	The Application token expires in two hours and must be reminted.
//   2. Authorization code grant flow: mints a new User access token that you can use to access 
//	the resources owned by the user, rather than the application.
//	The user token expires in two hours and can be renewed with the 
//	refresh token that is returned by the request.
//=============================================================================================

// The following generates an Application token (Client credentials grant flow).

// Set the server folder and path to hidden credential files on the private side of your server.
// The include module will then function without further modification.
// This file may be on the public side of your server, accessible to your applications.

$oauth_root 		= $_SERVER["DOCUMENT_ROOT"] . "/../ebay_oauth/"; // place secure data upstream behind your server's firewall.
$oauth_clientIdfile	= $oauth_root."ebay_apiuser.txt";     // file containing appID  = clientID
$oauth_secretIdfile	= $oauth_root."ebay_apisecret.txt";   // file containing certID = clientSecret
$oauth_basictokenfile	= $oauth_root."ebay_basic_token.txt"; // file containing token (that will update every 2 hours). 
					// Several similar token files could be created based on different scopes.


function createBasicOauthToken(){
	global $oauth_clientIdfile, $oauth_secretIdfile, $oauth_basictokenfile ;

	$url  		= 'https://api.ebay.com/identity/v1/oauth2/token'; 
	$clientID 	= file_get_contents($oauth_clientIdfile);	// AppID
	$clientSecret 	= file_get_contents($oauth_secretIdfile);	// CertID
	$headers 	= [ 
				'Content-Type: application/x-www-form-urlencoded', 
				'Authorization: Basic '.base64_encode($clientID.':'.$clientSecret) 
			]; 

	$body 		= http_build_query([ 
				'grant_type' => 'client_credentials',		  // application credentials 
				'scope' => 'https://api.ebay.com/oauth/api_scope' // space-delimit more scopes for other APIs
			]);  
	$curl 		= curl_init(); // prepare the url shell
	curl_setopt_array( 
			$curl, 
			array( 
				CURLOPT_URL => $url, 
				CURLOPT_RETURNTRANSFER => true,  // true means return result as string without output/echo
				CURLOPT_CUSTOMREQUEST => 'POST', // post format because we are including body data
				CURLOPT_HTTPHEADER => $headers, 
				CURLOPT_POSTFIELDS => $body 
				)
			); 
	$response 	= curl_exec($curl); 	// output string as result of CURLOPT_RETURNTRANSFER
	$err   		= curl_error($curl); 	// capture any URL errors
	curl_close($curl); 

	if ($err) { return "ERR: " . $err; } // this should be trapped by your application by testing for "ERR".

	else { 
		$token = json_decode($response,true);  // true means use keys
		if ($token["access_token"]){
			// write the token to server to use for next two hours (7200 secs).
			file_put_contents($oauth_basictokenfile,$token["access_token"]);
			return $token["access_token"];
		}  
		else{
			return "ERR: could not access token" ; 	//something went wrong, so trap in your application
		}
	} 
}

function getBasicOauthToken(){
	global $oauth_basictokenfile;
	// this is the routine called by the application
	// look at time stamp to see if token has expired
	$now 	  = time();
	$duration = 7200 ; // life of the token, 2 hours
	$margin	  =   30 ; // remaining seconds before we request a new token (depends on how long it will take the application to make all related calls. 
	if (file_exists($oauth_basictokenfile)){
	  	$tstamp	= getdate(filemtime($oauth_basictokenfile));	// this is the last write or update time, not the creation date.
		if ($tstamp[0] + $duration - $now > $margin){		// some time still remains on token.
			return file_get_contents($oauth_basictokenfile);
		}
		else{ 
			return createBasicOauthToken(); 		// if time has run out, then generate a new token.
		}
	}
	else{ 
		return createBasicOauthToken();  // if first time use, then create a new token.
	}
}
?>

 

Application that uses the above include file

<?php 
//============================================================
// Token usage in application (Shopping API)
//============================================================

	//--------------------------------------
	// get developer application oauth
	//--------------------------------------

	include ('../oauth_support/getBasicToken.php'); // path from your application to the above token file
	$token 	= getBasicOauthToken();  		// make a call into the include file
	if (strpos($token, "ERR")===0){failure("Internal error. Token Failure"); } 
			// If the token routine returned ERR, then something went wrong fetching token,
			// so call the failure routine to process error and exit.

	//--------------------------------------
	//  Build headers and URL for CURL
	//--------------------------------------

	// the url parameters ($siteID, $selectorArr, $itemNumArr ) would be 
	// previously collected by the application, to be applied here.
	$url = 'https://open.api.ebay.com/shopping'	
		.'?callname=GetMultipleItems'
		.'&version=1199'
		.'&responseencoding=JSON'
		.'&siteid='. $siteID  		
		.'&IncludeSelector='. implode(",",$selectorArr)
		.'&ItemID='. implode(",",$itemNumArr)  // Shopping API limit is 20 items per call
		;

	$headers 	= [ 							// array of headers
				'X-EBAY-API-IAF-TOKEN:' .$token  		// header to pass OAuth token
			]; 

	$curl 		= curl_init(); 
	curl_setopt_array( 
			$curl, 
			array(  // this is a GET, so there is no body content
				CURLOPT_URL => $url, 
				CURLOPT_RETURNTRANSFER => true, // return result as string without output/echo
				CURLOPT_HTTPHEADER => $headers, 
				)
			); 
	$apiResponse 	= curl_exec($curl); 	// string, as specified by result of CURLOPT_RETURNTRANSFER 
						// this is the requested shopping API data.

	//--------------------------------------
	//  Close CURL and check for response failure
	//--------------------------------------

	$err   		= curl_error($curl); 
	curl_close($curl);
	if ($err) { failure("Internal access error. " . $err)  ; } 
			// failure to connect with the api 
			// so call the failure routine to process the error.

	//--------------------------------------
	// otherwise, process the data returned in the $apiResponse string.
	//--------------------------------------

			// your code to process the API data goes here.


function failure($msg){
	// deal with errors here and exit gracefully
	exit;
}
?>

 

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

Re: Sample PHP for generating and renewing a Shopping token

I am getting this, Error Please guide me. I am used above process.
{
"error": "invalid_scope",
"error_description": "The requested scope is invalid, unknown, malformed, or exceeds the scope granted to the client"
}
Message 2 of 2
latest reply