1. Trang chủ
  2. » Công Nghệ Thông Tin

Pro PHP XML and Web Services phần 9 pot

94 512 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 94
Dung lượng 564,02 KB

Nội dung

Introducing the eBay Web Services Unless you are living under a rock, you have heard of eBay. eBay is an online marketplace where you can buy, sell, and auction off goods. With so much functionality, it is often difficult to keep track of everything. You might be working for a company whose business is merchan- dise sales. The company may already have a complete internal system for inventory, sales, and tracking and is branching out to selling on eBay. With a system already in place, the company does not want the hassle of having to manage its internal systems as well as its eBay account. Using eBay Web services can solve this. SOAP is but one of the possible methods that can be used to integrate with eBay, because it also provides REST support. The eBay example that is provided shows how to get your SOAP environment set up and enables you to understand what it is doing; it isn’t a run-through of the API. The reason those who use SOAP like it is because SOAP is supposed to be simple. You load a WSDL document, examine the available functionality, and begin consuming the service. After a good amount of time spent trying to get my first successful connection to the eBay SOAP server, I was wishing I had written about eBay’s REST implementation instead. Once over the initial hurdle, access- ing the rest of the API was not as difficult. The material I will present in this example should help you avoid all of the issues I personally ran into, decreasing the amount of your develop- ment time significantly. If you prefer to get straight to working with the eBay Web service, you should follow the steps and tips provided in the following steps and then skip to the section “Setting Up the Environment.” However, be forewarned that some of the information in the following sections may be useful in answering some questions you may have. 1. Sign up for the developer program at http://developer.ebay.com/join to receive your keys (DevID, AppID, and CertID). 2. Sign up for a sandbox user ID at http://developer.ebay.com/DevZone/ sandboxuser.asp. This ID allows you to access the sandbox (test) system just like accessing the live eBay system. 3. Generate a sandbox authentication token at http://developer.ebay.com/tokentool/, using the sandbox user ID. 4. Download the PHP 5 sample code from https://codesamples.codebase.ebay.com/ files/documents/14/74/php5_eBay_codesamples.zip. 5. Use the included ebay.ini file to set up your IDs and authentication token. Setting Up with eBay My experience began with the initial registration. You must register for the developer program at http://developer.ebay.com/join to use the Web services. Once you have registered, you will receive three keys: DevID, AppID, and CertID. You will need all three during this exercise. The next step is to get a copy of the documentation. I highly suggest you download the PDF version, because it’s a bit slow trying to access the online HTML version. Even if you are on a dial-up connection, it is well worth the wait in the long run to download the 16MB PDF file, because you will most likely need it. I personally thought the reason people liked SOAP was that it didn’t require you to have to read every piece of documentation because WSDL was considered the Holy Grail. Under that assumption, I created a SoapClient and passed in the location of the WSDL, CHAPTER 18 ■ SOAP736 6331_c18_final.qxd 2/16/06 4:27 PM Page 736 http://developer.ebay.com/webservices/latest/eBaySvc.wsdl. I wasn’t expecting everything to work right out of the box, but I at least wanted to see the function list and data types I would be using. After a few minutes, I finally got some output. I found out the WSDL docu- ment is more than 2MB in size. If you don’t end up saving a copy of the WSDL document locally, make sure the SOAP caching directives in the php.ini file are set properly: soap.wsdl_cache_enabled = 1 soap.wsdl_cache_ttl = (some large value) The default is to enable the WSDL cache for 86,400 seconds, which equates to one day. I couldn’t see downloading this large of a file every day and because other applications using SOAP could not increase the wsdl_cache_ttl. For this reason, I decided to store and read the WSDL document on the local file system. Although doing this requires that I must periodically check for an updated WSDL document manually, it saved greatly on bandwidth usage because I could check it every couple of weeks or so rather than every single day. Having seen some previous code using the SOAP extension, I knew additional authentica- tion than the keys received upon registration were needed. Here the documentation is lacking. It talks about programmatically retrieving this, but after a few unsuccessful tries, I resorted to searching the Web for the answer. Had I read the section “Executing Your First C# Call,” I would have found this out immediately, but for some reason logic got the best of me, and I was look- ing in the “Authentication & Authorization” section. A helpful page on the developer site is the Developer Tools page at http://developer.ebay.com/help/tools. From here you can create eBay test users, test the API, and create an authentication token (http://developer.ebay.com/ tokentool/). This will require you to register for an eBay account, but the account is within the sandbox system, so a normal eBay account login will not work here. Now with the token, I thought I was ready. I fired up the SOAP client again, loaded the WSDL document, and generated the authentication, and of course it didn’t work. A WSDL file is supposed to define the end point to access a service. The eBay WSDL does, but only if you are accessing the production system. After reading the documentation more, I come to find out, when working in the sandbox, you need to change the location for the SoapClient to https://api.sandbox.ebay.com/wsapi. On top of that, and it doesn’t matter whether running in a production environment or the sandbox, the URL needs to take parameters, and to top it off they must be built dynamically because the function name must be passed. These parame- ters are required for proper routing, which is something I thought the HTTP SOAPAction was for, but alas it’s not used, so it’s more like working with a REST/SOAP hybrid. By now, you should have the initial keys, authentication token, WSDL, and documentation as you move toward getting a PHP SoapClient to connect and make its first call. Setting Up the Environment Now that you have an idea of what to expect when working the SoapClient to access the eBay service, you need to decide how you want to go about your implementation. You can do this in two ways. The first is to create a bunch of functionality to build the location string, which of course is determined by the function you are calling. This would be required to be duplicated within any scripts you write accessing the eBay service. Of course, this was my first course of action. I just wanted to get something to work. The alternative is to create a custom class by subclassing the SoapClient and to provide the special functionality within the custom class. By doing this, you are able to use your custom class exactly as you have used the SoapClient CHAPTER 18 ■ SOAP 737 6331_c18_final.qxd 2/16/06 4:27 PM Page 737 throughout the rest of this chapter. You do not need to play around with the URL or deal with setting the authentication headers. ■Note You can find some sample code for an eBay SoapClient wrapper at https://codesamples. codebase.ebay.com/files/documents/14/74/php5_eBay_codesamples.zip . It is not required you use the same configuration methods as in the provided code, although until you understand how the calls are made to the service and have made a few successful requests, it is in your best interest to leave any changes there until later. To get you quickly interfacing with eBay, you will use this code base to make a couple of API calls. Rather than explaining the API to you (since you can find the functions and types in the documentation as well as from using the __getTypes() and __getFunctions() methods from the object), I will cover what the provided code does. You may wonder why this is neces- sary. In the event something is not working or new parameters or SOAP headers are ever required, you may need to change the base code yourself. It will also give you better insight into how PHP SOAP interacts with eBay, making understanding the eBay documentation much easier. The provided code uses the following: an INI file for your keys, the authentication token, the eBay system to connect with, and the API version. Each of your keys and token has two sets of entries. One section, labeled production, is used when you are ready to access the live eBay system with your client. The other section, labeled sandbox, contains the values when accessing the test system. The only setting in each of these sections you should not change is gatewaySOAP. This should already contain the correct locations for each of the two systems. The remaining section, labeled settings, has two entries. The site entry specifies whether you are working in the sandbox or production environment. The compatibilityLevel entry specifies the eBay API version you are using. This can be located at the top of the WSDL docu- ment within the comments. This is also another reason why you may want to keep the WSDL local. Always grabbing the latest WSDL from the eBay site is a sure way to get the version level out of sync. This is not something that is guaranteed to break your application, but there is always the possibility. After adding your entries and verifying the other settings, your ebay.ini should end up looking like the following: [production] authToken = "Your Auth & Auth Token" devId = "Your DevID" appId = "Your AppID" cert = "Your CertID" gatewaySOAP = "https://api.ebay.com/wsapi" [sandbox] authToken = "Your Auth & Auth Token" CHAPTER 18 ■ SOAP738 6331_c18_final.qxd 2/16/06 4:27 PM Page 738 devId = "Your DevID" appId = "Your AppID" cert = "Your CertID" gatewaySOAP = "https://api.sandbox.ebay.com/wsapi" [settings] site = "sandbox" compatibilityLevel = 437 If you open one of the example files, such as GetUser.php, you should notice the following code at the top of the file: require_once 'eBaySOAP.php'; // Load developer-specific configuration data from ini file $config = parse_ini_file('ebay.ini', true); $site = $config['settings']['site']; $version = $config['settings']['compatibilityLevel']; $dev = $config[$site]['devId']; $app = $config[$site]['appId']; $cert = $config[$site]['cert']; $token = $config[$site]['authToken']; $location = $config[$site]['gatewaySOAP']; // Create and configure session $session = new eBaySession($dev, $app, $cert); $session->token = $token; $session->location = $location; $session->site = 0; // 0 = US; This loads and parses the ebay.ini file and loads the settings into an eBaySession object, which is defined in the eBaySOAP.php file. The one property you may have to change, depend- ing upon your location, is site. The eBay documentation defines site as “This is the site that item of interest is (or will be) listed on or (for requests that get/set user information) that the requesting or target user is registered on.” The value is a numeric site ID found within the doc- umentation. I have provided them here for easy reference in Table 18-9. For the course of this chapter, the code will be using the site ID of 0, for the United States, but you can change this to a more appropriate site based on your needs. Table 18-9. eBay Site IDs and Codes by Name Site Name Site ID Site Code Australia 15 AU Austria 16 AT Belgium (Dutch) 123 BENL Continued CHAPTER 18 ■ SOAP 739 6331_c18_final.qxd 2/16/06 4:27 PM Page 739 Table 18-9. Continued Site Name Site ID Site Code Belgium (French) 23 BEFR Canada 2 CA China 223 CN France 71 FR Germany 77 DE Hong Kong 201 HK Ireland 205 IE India 203 IN Italy 101 IT Malaysia 207 MY Netherlands 146 NL Philippines 211 PH Poland 212 PL Singapore 216 SG Spain 186 ES Sweden 218 SE Switzerland 193 CH Taiwan 196 TW United Kingdom 3 UK United States 0 US US eBay Motors 100 — By default, the eBaySession object is set to disable exceptions and use the remote WSDL document. If you are fine with just using the WSDL cache settings from the php.ini file to handle this, then you should have no problem; otherwise, you should use a local copy requir- ing you to set the location using the wsdl property: $session->wsdl = 'eBaySvc.wsdl'; Whether or not you want to work with exceptions or have functions return SoapFault objects is up to you. The example code has exceptions disabled yet is using try/catch blocks and not testing for a SoapFault return value. For the sake of this chapter, you will use excep- tions, so they must be reenabled. The eBaySession object has an options property. The value is an array of options that are to be passed to the SoapClient constructor. You simply need to enable exceptions within the array: $session->options['exceptions'] = 1; With the eBaySession object, $session, finally initialized correctly and the site property properly set, you are now ready to make your first SOAP call to eBay. CHAPTER 18 ■ SOAP740 6331_c18_final.qxd 2/16/06 4:27 PM Page 740 Interacting with the eBay Service Using the eBaySession object previously created, you need to instantiate a new eBaySOAP object. The eBaySOAP class, being a subclass of the SoapClient class, takes an eBaySession object as its constructor parameter and uses the wsdl and options properties to call the parent SoapClient constructor: try { $client = new eBaySOAP($session); All that is left is to create any parameters that are to be passed to an eBay function and then call the function. Before the call can be made, however, it has a catch. All request types are based upon the AbstractRequestType type, and the version, being part of base type, must be passed within the SOAP body with every request. This means with every function call you make, you must pass the Version parameter as part of the structure. To demonstrate this additional parameter requirement, you will make a call to the GetUser() function. Looking at its signature using the __getFunctions() method, you can see that it takes a single parameter: GetUserResponseType GetUser(GetUserRequestType $GetUserRequest) The GetUserRequestType parameter is a structure that takes the following form: struct GetUserRequestType { ItemIDType ItemID; string UserID; } Both members of the structure are optional, but within the WSDL, they are defined as minOccurs="0". The ItemID member is in all fairness a string but is defined in the structure as an ItemIDType. A search through the types (__getTypes()) will show you exactly this. The GetUserRequestType structure, however, extends the AbstractRequestType from which the Version member comes. When called with only the Version parameter, the function returns data for the user identified by the authentication token used to make the request: $response = $client->GetUser(array('Version'=>$version)); When called with a UserID parameter, data pertinent to the specified user is returned. The amount of data depends upon the UserID requested. When requesting information on any user other than yourself, the returned structure omits certain information: $response = $client->GetUser(array('Version'=>$version, 'UserID'=>'pierre')); This is where the ItemID comes into play. If you are a seller and need to look up informa- tion for a user who has successfully purchased an item from you, you can include the ItemID in the request to retrieve the previously omitted information: $params = array('Version'=>$version, 'UserID'=>'pierre', 'ItemID'=>'1'); $response = $client->GetUser($params); Of course, if the specified user has no association with the specified item, the data is returned in a limited fashion. CHAPTER 18 ■ SOAP 741 6331_c18_final.qxd 2/16/06 4:27 PM Page 741 Just like the request types, the response types also extend a base type. In this case, the AbstractResponseType type can provide additional information such as a time stamp from when the request was processed or possibly messages from eBay. The type you are concerned with is the GetUserResponseType. In addition to members from the AbstractResponseType type, the GetUserResponseType adds a single User member of the UserType type and appears as the following: struct UserType { boolean AboutMePage; string EIASToken; string RESTToken; string Email; int FeedbackScore; int UniqueNegativeFeedbackCount; int UniquePositiveFeedbackCount; float PositiveFeedbackPercent; boolean FeedbackPrivate; FeedbackRatingStarCodeType FeedbackRatingStar; boolean IDVerified; boolean eBayGoodStanding; boolean NewUser; AddressType RegistrationAddress; dateTime RegistrationDate; SiteCodeType Site; UserStatusCodeType Status; UserIDType UserID; boolean UserIDChanged; dateTime UserIDLastChanged; VATStatusCodeType VATStatus; BuyerType BuyerInfo; SellerType SellerInfo; CharityAffiliationsType CharityAffiliations; CharitySellerType CharitySeller; boolean SiteVerified; <anyXML> any; } Assuming no exceptions were thrown and you have successfully retrieved a GetUserRe- sponseType structure, you simply access information as properties from the returned object: print $results->User->Status."\n"; print $results->User->Email."\n"; Confirmed Invalid Request Here is a case where information is unavailable to you. The email address is not given out unless you retrieve your own user record or the user is associated to you through an ItemID. CHAPTER 18 ■ SOAP742 6331_c18_final.qxd 2/16/06 4:27 PM Page 742 Looking Under the Hood Now that you can at least make calls to the eBay service, you should understand what is going on behind the scenes in PHP. Unlike many of the services you have seen and maybe tried in this chapter, much more is required to make a SOAP call than when simply calling a function. For starters, you need to add the authentication information to the SOAP message. Authentication Structure If you look within the eBaySOAP.php file, you will notice the eBayCredentials and eBayAuth classes. The eBayAuth class is the container for all authentication data. Upon creation, the eBaySession object, $session, is passed to the constructor. Using the keys and token that were added to $session at the beginning of the script, the proper structure is created using the correct data types. It is important that SoapVar objects are created because the data must not only be properly typed but also properly namespaced. Incorrect namespacing will result in a SoapFault being issued. The authentication information is not passed within the body of the message, but rather, it is set in the SOAP Header. When the eBaySOAP object, $client, is instantiated, the constructor makes a call to the __setHeaders() method, which is not part of the SOAP API but rather a cus- tom method that instantiates the eBayAuth object, creates a SoapVar for the object, and then creates a SoapHeader object using the resulting SoapVar. This is a bit confusing I know, but again, data typing and namespacing is essential when working with the eBay service. An array containing this header is then set as a property of $client because it will be used later when a function call is made. Remote Calls When calls are made to the eBay service, not only does the SOAP message need to be properly created, but also the URL being called must be dynamically created. The eBay system uses URL parameters to properly route and filter a SOAP request. It is possible to do this without resort- ing to method overloading, but you need to consider what has to occur to perform this. One of the required parameters is the name of the function being called. Without using overloading, you could hard-code the function name into the URL and call the function like a normal SOAP call. This presents a problem in reusability. The next time you need to call a different function, you need to also change the value of the URL parameter. You could use a variable to set the URL and call the function. For example: $function = 'GetUser'; /* Code to build URL using $function variable */ $client->$function($params); Although this works, it is not all that intuitive. You would always have to find what the value of $function was to know what function you were actually calling using the SoapClient. The example code from eBay uses a different technique. Within the eBaySOAP class method, overloading is employed through the use of the __call() method. When you make the call $client->GetUser($params), the call is routed through the __call() method. The CHAPTER 18 ■ SOAP 743 6331_c18_final.qxd 2/16/06 4:27 PM Page 743 name of the method, equating to an eBay function, is passed as the first parameter. The URL can now be dynamically created without having to change the calling convention you have grown accustomed to in SOAP. The method then calls the __soapCall() method, passing the name of the function to call, the new location as an input option, and lastly the authentication header that was created earlier. This example demonstrated only a single function call, but you should have a better understanding of the interaction between the PHP SOAP extension and the eBay service. Using a combination of the documentation and the type and using function information retrievable from a SoapClient, you should be able to move on to more complex calls and data structures. The most difficult parts should be behind you. Whether or not you decide to use the example code as the basis for your application is entirely up to you. It definitely is a good starting point to say the least. If you do plan on using the code, it is to your advantage to check on the eBay site itself because the example code is not static. Even as I wrote this chapter, new updates were made available on the site. Introducing the Google Web Services Google provides Web services to perform searches, do spell checks, and retrieve cached Web pages, all of which make up its search service. You even have access to manage AdWords accounts, using the AdWords API service. AdWords is an advertisement system where you can purchase cost-per-click or cost-per-impression ads to be displayed on Google search result pages. Both of these services are currently in beta status and provide SOAP-only access. The AdWords API service requires an AdWords account. Using your account credentials, you can register at https://adwords.google.com/select/ApiWelcome to receive your developer token. This token is required to access the service. Not everyone reading this has an AdWords account, so rather covering an API that only a few readers will benefit from, I will use the search service as the example. If you care to find out more about the AdWords API service, including the API documentation, you should browse to http://www.google.com/apis/adwords/. The search service is a free service for noncommercial use. The only restriction is that you are limited to 1,000 queries per day. Registration is required to access the service, because you need to obtain a license key. You will also need to download the developer’s kit, which includes the WSDL document you will be using to access the service. You can find reg- istration and the developer’s kit at http://www.google.com/apis/. Once you have downloaded the developer’s kit, extract the contents, and either note the location of the WSDL file or copy it to another accessible location. The kit actually contains three WSDL files, but the one you need to use is located within the root googleapi directory from the package. At this point, it is not required that you have your license key because all you want to do is load the WSDL file into a SOAPClient and inspect the API. The first step is to examine the types used within the WSDL file. This will give you an idea of the type of return data you should expect when making calls to the service. For example: <?php try { $GoogleClient = new SoapClient('GoogleSearch.wsdl'); $types = $GoogleClient->__getTypes(); foreach($types AS $type) { echo $type."\n\n"; } CHAPTER 18 ■ SOAP744 6331_c18_final.qxd 2/16/06 4:27 PM Page 744 } catch (SoapFault $e) { var_dump($e); } ?> struct GoogleSearchResult { boolean documentFiltering; string searchComments; int estimatedTotalResultsCount; boolean estimateIsExact; ResultElementArray resultElements; string searchQuery; int startIndex; int endIndex; string searchTips; DirectoryCategoryArray directoryCategories; double searchTime; } struct ResultElement { string summary; string URL; string snippet; string title; string cachedSize; boolean relatedInformationPresent; string hostName; DirectoryCategory directoryCategory; string directoryTitle; } ResultElement ResultElementArray[] DirectoryCategory DirectoryCategoryArray[] struct DirectoryCategory { string fullViewableName; string specialEncoding; } As you can see, few types are defined. Only three structures exist, and they are not overly complex. Now that you have an idea of what the types look like, you can then use the SoapClient to examine the callable operations from the service: CHAPTER 18 ■ SOAP 745 6331_c18_final.qxd 2/16/06 4:27 PM Page 745 [...]... GoogleSearchResult structure and displays the title, URL, snippet, and cachedSize for each of the ResultElement structures Search Time: 0.074 399 Title: Zend Technologies - PHP 5 In Depth - PHP SOAP Extension URL: http://www.zend.com /php5 /articles /php5 -SOAP .php Summary: PHP 5&# 39; s SOAP extension is the first attempt to implement the SOAP protocol for PHP in C It has some... 101k Title: Zend Technologies - PHP 5 In Depth - PHP SOAP Extension URL: http://www.zend.com /php5 /articles /php5 -SOAP .php? article =php5 SOAP&kind =php5 &id=6460&open=1&anc=0&view=1 Summary: PHP 5&# 39; s SOAP extension is the first attempt to implement the SOAP protocol Hi I couldn&# 39; t find the answer May be some problem with Php5 Soap extensions Cache... institutions, businesses, and consumers via the Internet CheckFree, Intuit, and Microsoft created it in early 199 7, and it is currently used by many banks, brokerages, and major payroll-processing companies 6331_c 19_ final.qxd 2/16/06 4:24 PM Page 763 CHAPTER 19 ■ UNIVERSAL DESCRIPTION, DISCOVERY, AND INTEGRATION (UDDI) . available on the site. Introducing the Google Web Services Google provides Web services to perform searches, do spell checks, and retrieve cached Web pages, all of which make up its search service http://www.zend.com /php5 /articles /php5 -SOAP .php Summary: <b> ;PHP 5&# 39; s SOAP</b> extension is the first attempt to implement the <b>SOAP</b> protocol for<br> <b> ;PHP& lt;/b>. Technologies - <b> ;PHP 5</b> In Depth - <b> ;PHP SOAP</b> Extension URL: http://www.zend.com /php5 /articles /php5 -SOAP .php? article =php5 - SOAP&kind =php5 &id=6460&open=1&anc=0&view=1 Summary:

Ngày đăng: 12/08/2014, 13:21

TỪ KHÓA LIÊN QUAN