Trading API
 

Getting Started with a PHP Bidding/Buying Application
Searching and Bidding on an Item

Complete Code

The objective of this tutorial is to write a PHP sample that enables bidding and buying on eBay, using the PlaceOffer call. It currently does not not demonstrate all of the capabilities of PlaceOffer, however. For example, the sample does not support multi-variation listings. Also, the sample does not provide the user with a way to look up currency conversion for the case where the buyer and seller are using differency currencies. You might want to let them check currency conversion rates by sending them to the xe.com Universal Currency Converter provided by eBay.

Note that while you can use PlaceOffer in the Sandbox as you would other API calls, using PlaceOffer in the production environment requires approval from the eBay Partner Network along with other requirements. If you plan to build a PlaceOffer application for use in production, the PlaceOffer Policies are required for use of PlaceOffer in the Production environment. Please carefully write your application to follow all the PlaceOffer Policies.

The completed application will look like the following:

PlaceOffer Getting Started Application

If you want information and links for tutorial terms and API calls, see Tutorial Terms.

During the tutorial, or after completing it, please be sure to read all the sections in Additional Information and Next Steps, including the information about improving security for production applications.

eBay Partner Network (eBay Affiliate Program)

You may be able to earn money with the eBay Partner Network (eBay Affiliate Program). For more information, visit the eBay Partner Network. This tutorial contains affiliate-related code. The code is commented-out because affiliate functionality is not available in the Sandbox environment.

Prerequisites for Tutorial

Sandbox AppID

After you join the eBay Developers Program, please note your Sandbox AppID so you can substitute it in this tutorial where it says "MyAppID." This tutorial uses Sandbox data. To use PlaceOffer in the Production environment, your application must first be functional in the Sandbox environment (see the PlaceOffer Policies and Guidelines).

The complete code for the tutorial (PHP_PlaceOfferGS_TradingShopping.zip) requires that you substitute your Sandbox AppID for "MyAppID".

In the tutorial, you always must substitute your Sandbox AppID for "MyAppID" and remove unneeded spaces and new-line characters.

Tutorial Steps

There are several steps in this tutorial:

Step 1: Copy files into htdocs folder

Step 2: User Browsing

Step 3: User log-in (Authentication)

Step 4: Bidding and buying


Step 1: Copy files and Add Credentials

After you complete the Prerequisites for this Tutorial, you are ready to review and copy the tutorial files into your htdocs folder and then add your credentials to the code.

  1. Copy the tutorial files into your htdocs folder. To copy the tutorial files:
    1. Download the complete code (PHP_PlaceOfferGS_TradingShopping.zip).
    2. Unzip PHP_PlaceOfferGS_TradingShopping.zip into a Temp folder.
    3. Copy all the files, and the js folder, from the Temp folder into C:\Program Files\Apache Software Foundation\Apache2.2\htdocs.
      For your reference, the files are the following:


    4. Name     Description
      Browsing.php Displays item information after a search.
      eBaySession.php Contains a class for making API calls.
      index.html Landing page of the application; the user will enter an item search on this page.
      keys.php Stores the application's keys and token.
      You must substitute your Sandbox keys for the existing values in this file.
      Do not store the user token; the user token is stored in a session variable (see Token.php).
      Login.php Begins the process of obtaining a Sandbox authentication token.
      Logout.php Logs out a user, destroying the session and session variables.
      Offer.php Contains the Offer class, used for the PlaceOffer request.
      PlaceOffer.php Creates an Item object, on which an offer will be placed.
      Presents a form for bid submission.
      Submits a bid and presents the results of the bid.
      sessionHeader.php Controls session settings.
      It is intended to make sessions safer.
      SingleItem.php Contains the SingleItem class for displaying item information.
      Your PlaceOffer call will input an Action field containing Bid or Purchase (for a user's bid or a user's buy).
      Whether Bid or Purchase is specified is based on the listing type determined by the getDetailsAsHTML_Div function of the SingleItem class.
      ShowDescriptionForItem.php Enables a user to view a full item description.
      style.css Style sheet for the application.
      Token.php Contains the Token class, which gets an authentication token for a user.
      VerifyToken.php Enables you to verify that a user token was obtained.
      js\JQuery.js Toggles between the compressed and uncompressed versions of jQuery.
      js\ShowDetails.js Used for revealing item details.
      js\jquery-1.1.3.1.js_uncompressed.js Uncompressed version of jQuery; useful for development and debugging.
      js\jquery-1.1.3.1.pack.js Compressed version of jQuery.

  • Add your credentials and other values to the code. To add your credentials and other values:
    1. Open keys.php in a text editor.
    2. Add your credentials and other values, as described in the following table:


    3. Value Description Location for insertion in keys.php
      Sandbox key: DevID Your Developer ID, as registered with the eBay Developers Program;
      see the My Account page
      Sandbox section of keys.php: value for $devID
      Sandbox key: AppID Your Application ID, as registered with the eBay Developers Program;
      see the My Account page
      Sandbox section of keys.php: value for $appID
      Sandbox key: CertID Your Certificate ID, as registered with the eBay Developers Program;
      see the My Account page
      Sandbox section of keys.php: value for $certID
      Initial auth token An initial Sandbox user token (it must not be the buyer's user token) to be used by your application,
      before a FetchToken call is made;
      with a Sandbox test user, create this initial token at the following location:
      Auth and Auth Token Generator
      Sandbox section of keys.php: value for $appToken
      runame Unique identifier that is part of the mechanism for redirecting users
      from the standard eBay sign-in and consent page to the URL of your choice
      (see Prerequisites for this Tutorial).
      Value for $runame
    4. Optionally, set the $debug variable to true if you'd like debug information to be printed as you're running the application. If you do so, search other code files for the word "debug" for other minor changes that need to be made for running the code in debug mode. In general, for information about running the application in debug mode, see the comments in the downloaded code.
    5. Save and close keys.php.

  • Back to Top

    Step 2: User Browsing

    In this step you review the code that enables a user to search for Sandbox items using the Shopping API. Then you confirm that the code runs.

    1. Open index.html (located in your htdocs folder) in a text editor. Note that this file is the landing page of the application. The user will enter an item search on this page:
    2. PlaceOffer Getting Started Application

    3. Open Browsing.php in a text editor. Note that this file includes code for a FindItemsAdvanced call, including the following snippet:
      //need to urlencode the user-input keyword for the Finding API
      $safeQuery = urlencode($_POST['QueryString']);
      $apicall  = "$findingURL?OPERATION-NAME=findItemsAdvanced&SERVICE-VERSION=$findingVer"
                . "&GLOBAL-ID=EBAY-US"
                . "&SECURITY-APPNAME=$appID"
                . "&keywords=$safeQuery"
                . "&MaxEntries=1"
                . "&paginationInput.entriesPerPage=1"
                . "&outputSelector=SellerInfo";
      
      For purposes of this tutorial, only one item is returned from the query (this is specified by paginationInput.entriesPerPage=1 as shown in the code snippet).

      Browsing.php is just a sample file and it doesn't display all the information that should be displayed before a first bid and before a purchase (see the PlaceOffer Policies and Guidelines). For example, the Browsing.php file displays a link to the item description instead of displaying the text of the description. To see ways to list search results, choose a Search tutorial from Tutorials.
    4. Test the search functionality of the code. In a browser, do the following:
      1. Open your index.html file using http://localhost/index.html.
      2. Enter part or all of the title of your Sandbox test item, or alternatively enter its item ID (see Prerequisites for Tutorial). Normally, a user enters a keyword for a keyword search, but for this tutorial you could use an item ID to ensure you bid on the test item you added.
      3. Click Search.
      4. Confirm that an item is displayed by the code in Browsing.php. It should be similar to the following:
      5. PlaceOffer Getting Started Application



    Back to Top

    Step 3: User log-in (Authentication)

    See Working with token/authentication calls for an explanation of the authentication process.

    The objective of this step is to review the files necessary for user authentication. Please note that an application cannot in any way, shape, or form collect a user's eBay username and password (see the PlaceOffer Policies and Guidelines).

    To enable a user to bid or buy, an application uses a user authentication token. This tutorial does not explain user authentication; for links to information about user authentication, see Prerequisites for this Tutorial.

    In this step, you review code that obtains a user authentication token (for your buyer) for Sandbox environment. This includes code that enables your application to make a FetchToken call.

    1. Review Login.php. The file is located at C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\Login.php. You may need to increase the size and maxlength values in the input line from their current value of 50 if your test user names exceed 50 characters. (Remember that all user names in the sandbox have TESTUSER_ prepended to them.) The Login.php file contains code that sends the user to the eBay Authorization page where the user authorizes the application to access eBay. For sample code for beginning the process of obtaining a Sandbox authentication token, see the following code in Login.php:
      	// Get session ID for the Auth & Auth, save it in session variable for subsequent FetchToken call in Token.php.
      	$verb1 = 'GetSessionID';
      
      	///Build the request Xml string
      	$requestBody1 = '<?xml version="1.0" encoding="utf-8" ?>';
      	$requestBody1 .= '<GetSessionIDRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
      	$requestBody1 .= "<Version>$compatabilityLevel</Version>";
      	$requestBody1 .= "<RuName>$runame</RuName>";
      	$requestBody1 .= '</GetSessionIDRequest>';
      
      	//Create a new eBay session with all details pulled in from included keys.php
      	$sessN = new eBaySession($devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb1);
      	//send the request and get response
      	$responseBody1 = $sessN->sendHttpRequest($requestBody1);
      
      	if(stristr($responseBody1, 'HTTP 404') || $responseBody1 == '')
      		die('<P>Error sending request');
      
      
      	$resp1 = simplexml_load_string($responseBody1);
      	$_SESSION['ebSession']  = (string)$resp1->SessionID;
      
              //You MUST urlencode the session ID before sending it to the Auth and Auth
      	$sesId = urlencode($_SESSION['ebSession']);
      
      	$results .= "<form	name=\"form_auth\" method=\"post\" action=\"./Login.php\" >";
      	$results .= "<table><tr>\n<td>eBay User ID:</td> <td align=\"left\">"
      			 .  "<input	type=\"text\" name=\"username\" size=\"50\" maxlength=\"20\"></td>\n";
      
      	// loginURL and runame in next line comes from the required keys.php file
      	$results .= "<td><INPUT TYPE=\"submit\" NAME=AUTHORIZE VALUE=\"Launch Auth & Auth\" "
      			. "onclick=\"window.open('$loginURL?SignIn&runame=$runame&SessID=$sesId');\">\n";
      
      	$results .= "</td></tr></table>\n";
      	// use hidden field to retain fact that we're waiting on outcome of Auth and Auth call
      	$results .= "<input type=\"hidden\" name=\"loginPending\" value=\"true\">\n";
      
    2. Review Token.php. The Token class in the Token.php file enables your application to get an authentication token for a user. The sessionID is supplied from Login.php and is used in the FetchToken call. Notice that the session ID is not urlencoded here.
      class Token
      {
          public $resp;  // This is the entire response as a Simple XML object
          public $token;
          public $expiration;
      
          function __construct($username, $theID)
          {
              global  $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID; // defined in keys.php
      
              //the call being made:
              $verb = 'FetchToken';
      
              ///Build the request Xml string
              $requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
              $requestXmlBody .= '<FetchTokenRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
              $requestXmlBody .= "<SessionID>$theID</SessionID>";
              $requestXmlBody .= '</FetchTokenRequest>';
      
              //Create a new eBay session with all details pulled in from included keys.php
              $session = new eBaySession($devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
              //send the request and get response
              $responseXml = $session->sendHttpRequest($requestXmlBody);
      
              if(stristr($responseXml, 'HTTP 404') || $responseXml == '')
                  die('<P>Error sending request');
      
              //print "RESPONSE_XML = \n $responseXml \n\n";
      
              $resp = simplexml_load_string($responseXml);
              $this->token = (string)$resp->eBayAuthToken;  // need to cast to string (not SimpleXML element) to persist in SESSION
              $this->expiration = $resp->HardExpirationTime;
      
          } // __construct
      
      } // class
      
      
      Important: You must substitute your Sandbox keys for the existing values in the keys.php file (see Step 1).


    3. Review VerifyToken.php. The code in VerifyToken.php enables you to verify the token obtained by the application's FetchToken call:
      $results = '';
      $results .= "<DIV ALIGN=CENTER> \n";
      
      //the session ID
      $theID = $_SESSION['ebSession'];
      
      // Get our token which we'll need to call PlaceOffer
      $tokenObj = new Token($_SESSION['username'], $theID);
      
      // Check for existence of something that looks like a token
      // Should be character string of length greater than 500 chars
      // This is stronger verification of a token than simply checking for existence
      
      if (strlen($tokenObj->token) > 500) {
          $_SESSION['token'] = $tokenObj->token;
          $_SESSION['loginState'] = 'loggedIn';
          $results .= "<form	name=\"form_auth\" method=\"post\" action=\"./PlaceOffer.php\" >";
          $results .= "<INPUT TYPE=\"submit\" NAME=\"ContinueToBid\" VALUE=\"Continue to Bid / Buy\">";
      } else {
          $results .= "ERROR - We did not get a token";
      }
      
      $results .= "</form>\n";
      $results .= "</DIV> \n";
      
      print $results;
      
      After the user logs into eBay, and clicks the Continue to Verify Token button, the token is verified.


    4. Test the log-in functionality of the code. In a browser, do the following:
      1. Using http://localhost/index.html, open the index.html file that you created above.
      2. Enter the item ID of your Sandbox test item.
      3. Click Search.
      4. Confirm that an item is displayed.
      5. Click Bid or Buy.
      6. Enter the user ID of your test buyer, and click Launch Auth and Auth.
      7. A new window opens. On the Sign In page, enter the user ID and password of your test buyer, and click Sign In. Complete a sign-in of your test buyer. As soon as you've signed in your test buyer, close the window because it is unneeded.
      8. In the original window (where you clicked Launch Auth and Auth), click Continue to Verify Token.
      9. If a token was received (and thus if login was successful), then for debug purposes, the token is displayed.
        A production application would not display the token.
      10. Click the Continue to Bid/Buy button.


    Back to Top

    Step 4: Bidding and buying

    The objectives of this step are the following:

    The PlaceOffer call enables a user to bid (make an offer) on an item. For competitive-bidding listings (Chinese and Dutch auctions), a user can make a bid. For fixed-price listings (Basic Fixed-Price and eBay Stores Inventory listings), a user can purchase an item. For information about the input and output fields of the call, see PlaceOffer.

    1. Review the PlaceOffer Policies and Guidelines. The policies are required for applications that use PlaceOffer in the Production environment. If you are unclear about the PlaceOffer Policies and Guidelines, please file a support ticket.


    2. Review PlaceOffer.php. The code in PlaceOffer.php instantiates an Item object (as $offerItem) for the item on which an offer will be placed:
      $offerItem = new SingleItem($_SESSION['ItemID']);
      
      Additionally, the PlaceOffer.php code:
      • Presents a form for a bid submission
      • Submits a bid
      • Presents the results of the bid
      • Handles bids that are too low by notifying the user
    3. In the following snippet (from PlaceOffer.php), the value that is supplied in the Action input value (see the table below) is determined.

       if ( ($offerItem->resp->Item->ListingType == 'FixedPriceItem') ||
               ($offerItem->resp->Item->ListingType == 'StoresFixedPrice') ) {
              $Action = 'Purchase';  // action needed in PlaceOffer call
          } else {
              $Action = 'Bid';
      

    4. Review Offer.php. See the following table for descriptions of the main PlaceOffer fields that are used in Offer.php.

      Example of PlaceOffer Field Input or Output? Value to Your Application
      Action Input The type of offer being made on the specified listing.
      EndUserIP Input The public IP address of the machine from which the request is sent. Your application captures that IP address and includes it in a call request. As described in the PlaceOffer Guidelines, when passing in EndUserIP, use the client's external IP address (do not pass the private or LAN IP address such as 192.168.x.x).
      ItemID Input Unique item ID that identifies the item the user is bidding on or buying.
      MaxBid Input Amount of the offer placed. For competitive-bidding listings, the amount bid on the item (subject to outbid by other buyers). For fixed-price listings, the fixed sale price at which the item is purchased. For competitive-bidding listings with an active Buy It Now option, this amount will be either the Buy It Now price for purchase or the amount of a bid, depending on the offer type (as specified in Action). For PlaceOffer, the currencyID attribute is ignored if provided.
      Quantity Input Specifies the number of items from the specified listing the user tendering the offer intends to purchase or bid on.
      trackingpartnercode, trackingid, affiliateuserid Input These URL parameters enable affiliate tracking so you can earn money through the eBay Partner Network. Sample values are used. Additionally, the parameters are commented out because this is a Sandbox application.
      UserConsent Input If true, confirms that the bidder read and agrees to eBay's privacy policy.
      HighBidder.UserID Output The current high bidder.
      MinimumToBid Output Smallest amount the next bid on the item can be.
      CurrentPrice Output For competitive-bidding listings (Chinese and Dutch auctions), current minimum asking price (start price) or the current highest bid for the item if bids have been placed. For Basic Fixed-Price (FixedPriceItem), or Ad type (AdType) listings this returns the original price specified when the item was listed.
    5. Review the Offer class. See the Offer class in Offer.php; it provides functionality for creating a PlaceOffer request. The affiliate-tracking input (trackingpartnercode, trackingid, and affiliateuserid) is commented out because affiliate tracking is not supported in the Sandbox environment. You can use affiliate-tracking input in the Production environment.
    6. Test the code. After you place a bid, the result should be similar to the following:
    7. PlaceOffer Getting Started Application



    Back to Top


    Tutorial Terms

    Additional Information and Next Steps

    About the Sample

    The tutorial sample was tested on Windows 2003 Server with PHP 5 for Win32 and Apache 2.2.4 for Windows.

    Security must be improved for production use. This tutorial contains sample-code only and is not meant for production use. For example, the tutorial relies on session time-out for example purposes only. It is recommended that you put the user token in a secure database. You would require your own login for your users, and you would reuse a user's token after the user logged into your application. Additionally, other security improvements need to be made.

    The limitations of the sample include the following:

    API Documentation

    API documentation is available at the following location: Developer Documentation Center.

    Next Steps

    If you'd like to further develop the sample application described in this tutorial, you could consider doing one or more of the following steps: