Consuming SAP NetWeaver Gateway Services from PHP Applications

Page created by Kristen Rogers
 
CONTINUE READING
Consuming SAP NetWeaver Gateway
Services from PHP Applications
Copyright
© Copyright 2011 SAP AG. All rights reserved.

SAP Library document classification: PUBLIC

No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission
of SAP AG. The information contained herein may be changed without prior notice.

Some software products marketed by SAP AG and its distributors contain proprietary software components of other
software vendors.

Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.

IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System
z9, z10, z9, iSeries, pSeries, xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390
Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+, POWER6, POWER5+, POWER5, POWER,
OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are
trademarks or registered trademarks of IBM Corporation.

Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.

Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registered trademarks of Adobe Systems
Incorporated in the United States and/or other countries.

Oracle is a registered trademark of Oracle Corporation.

UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.

Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin are trademarks or registered
trademarks of Citrix Systems, Inc.

HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C®, World Wide Web Consortium,
Massachusetts Institute of Technology.

Java is a registered trademark of Sun Microsystems, Inc.

JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and
implemented by Netscape.

SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects Explorer, StreamWork, and other SAP
products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP
AG in Germany and other countries.

Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence,
Xcelsius, and other Business Objects products and services mentioned herein as well as their respective logos are
trademarks or registered trademarks of Business Objects Software Ltd. Business Objects is an SAP company.

Sybase and Adaptive Server, iAnywhere, Sybase 365, SQL Anywhere, and other Sybase products and services mentioned
herein as well as their respective logos are trademarks or registered trademarks of Sybase, Inc. Sybase is an SAP
company.

All other product and service names mentioned are the trademarks of their respective companies. Data contained in this
document serves informational purposes only. National product specifications may vary.

These materials are subject to change without notice. These materials are provided by SAP AG and its affiliated companies
("SAP Group") for informational purposes only, without representation or warranty of any kind, and SAP Group shall not be
liable for errors or omissions with respect to the materials. The only warranties for SAP Group products and services are
those that are set forth in the express warranty statements accompanying such products and services, if any. Nothing
herein should be construed as constituting an additional warranty.

                                                                                                         Copyright/Trademark
Table of Contents
Consuming SAP NetWeaver Gateway Services on PHP Applications ......................................................... 4

   Prerequisites ................................................................................................................................................................. 5
   Building a PHP Application......................................................................................................................................... 6
     Function Import Example ....................................................................................................................................... 6
     Read Example ......................................................................................................................................................... 9
     Create Example ..................................................................................................................................................... 10
     Creation of Request Body for Create Method:.................................................................................................. 12
   Authentication Using X.509 Certificate ................................................................................................................... 13
     Prerequisites .......................................................................................................................................................... 13
     Read Example ....................................................................................................................................................... 14

Appendix 1 - RMTSAMPLEFLIGHT Service Metadata Description ...............................................................16

Appendix 2 – Code Snippets ...............................................................................................................................22

   Read - Get Carrier by Carrier ID.............................................................................................................................. 22
   Function Import – Get available Flights .................................................................................................................. 23
   Create - Booking a Flight .......................................................................................................................................... 24
   Read - Get Carrier by Carrier ID Using X.509 Certificate Authentication .......................................................... 25

                                                                                                                                                         Copyright/Trademark
CONSUMING SAP NETWEAVER GATEWAY SERVICES
FROM PHP APPLICATIONS
SAP NetWeaver Gateway technology provides a simple way to interact with SAP applications through
variety of devices, environments and platforms based on market standards. The framework enables
development of innovative, people-centric solutions that bring the power of SAP business software into
new experiences, such as: social networking and collaboration environments; mobile and tablet devices;
and rich internet applications. The framework supports rapid innovation while ensuring security, integrity,
management and optimized maintenance of the core SAP systems. Completely flexible, the software offers
connectivity to SAP applications using any programming language or model without the need for SAP
knowledge by taking advantage of REST services and OData/ATOM protocols.

This guide provides information on how to consume SAP NetWeaver Gateway services from PHP
applications based on the following scenario:

   The user wants to fly from New York to San Francisco.
   He goes online and searches for the different flights available. He enters his search parameters: city of
    origin, destination city, departure date, and arrival date (Function Import).
   From the SAP NetWeaver Gateway, he receives the information for the option(s) that meet(s) his
    search parameters (Get Function).
   He can now select the one that suits him the most and book his flight (Create Function).

The links to access the service document and metadata document are provided the in table below.

Service        http://:/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/
Document
Metadata       http://:/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/
Document       $metadata?$format=xml

Each service URL should contain the following information:

   Gateway host
   Port
   SAP Client – no need to specify client if connecting to the default client.

Example:
http://:/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT?sap-client=100

To obtain information on the selected service (its properties, function imports, associations, etc.), refer to
Appendix 1, were we show the Metadata description of the RMTSAMPLEFLIGHT service.

To view the code snippets in a format that can be copied into new code, refer to Appendix 2 – Code
Snippets.

                                                                                               Copyright/Trademark
The Flight service contains the following collections:

Collection                                URL

FlightCollection (list of flights)        http://:/sap/opu/
                                          sdata/iwfnd/RMTSAMPLEFLIGHT/FlightCollection

CarrierCollection (list of carriers)      http://:/sap/opu/sdata/
                                          iwfnd/RMTSAMPLEFLIGHT/CarrierCollection

BookingsCollection (list of Bookings)     http://:/sap/opu/sdata/
                                          iwfnd/RMTSAMPLEFLIGHT/BookingCollection

The operation GetAvailableFlights on FlightCollection is used to get a list of flights. The following is the URL
for the same:

http://:/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/GetAvailableFlights

Each collection supports some or all of the operations listed below. The table below provides the list of
operations supported and the methods that each of this operations map to respectively:

Operation                                 Method

Create                                    HTTP POST

Read                                      GET

Update                                    PUT

Delete                                    DELETE

Prerequisites
The following tools are required for developing a PHP application:

Software                                  Version

SAP NetWeaver Gateway                     2.0

PHP                                       To download go to: http://www.php.net/

OData SDK for PHP

Contact your system administrator for landscape details to connect to the SAP NetWeaver Gateway system.

                                                                                                Copyright/Trademark
Make sure you have performed the following procedures:

  Install and configure OData SDK as described in the OData SDK for PHP User Guide. You can find the
   user guide in the OData SDK folder, at: \doc\User_Guide.htm.
 Add proxies for the relevant service to your PHP project as described in the OData SDK for PHP User
   Guide.
  Note: It is recommended to save the relevant service metadata into a local file and use it while
  generating the proxies.
 Require the generated proxy file.

       require_once "RMTSAMPLEFLIGHT.php";

Building a PHP Application
Function Import Example

To get a list of the available flights, based on filter criteria, trigger the “GetAvailableFlights” function import
with cityFrom, cityTo, fromDate and toDate parameters. The response will contain a list of flights that meet
the criteria.
Note: For more information on Function Import (also called Service Operation), refer to OData
documentation at http://www.odata.org/developers/protocols/uri-conventions under the Addressing
Service Operations section.
Refer to the code snippet below for details on how to do it from a PHP application:

1. Initialize the service proxy object, for example RMTSAMPLEFLIGHT, using the service URL.
    $proxy = new RMTSAMPLEFLIGHT
    ('http://:/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT');

2. Enter the service credentials.
    $proxy->Credential = new WindowsCredential('', '');

3. Add the XMLHttpRequest http header needed for POST requests.
    $proxy->addHeader('X-Requested-With', 'XMLHttpRequest');

4. Execute a query calling the GetAvailableFlights function import with the following parameters: flight
   departure date, arrival date, and cities.
    $city_from    = 'NEW YORK';
    $city_to =    'SAN FRANCISCO';
    $from_date    = '20110105';
    $to_date =    '20110728';

    $flights = $proxy->Execute("GetAvailableFlights?cityfrom=$city_from&cityto=$city_to
    &fromdate=$from_date&todate=$to_date")->Result;

                                                                                                  Copyright/Trademark
5. Iterate all objects in the result obtained above.
          foreach ($flights as $flight)
          {
              echo "Flight Carrier: " . $flight->carrid . "";
              echo "Flight Price: " . $flight->PRICE . "";
              echo "Flight Max. Seats: " . $flight->SEATSMAX . "";
          }

     Refer to the full code snippet found in Appendix 2.

     Response

- 
      http://:/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/FlightCollection
      
      FlightCollection
      2011-09-27T06:32:42Z
    - 
         
      - 
         - 
             AA
             0017
             2011-01-05T00:00:00
             889.00
             USD
             747-400
             385
             367
             185742.73
             31
             22
             21
             21
           - 
               US
               new york
               JFK
               US
               SAN FRANCISCO
               SFO
               361
               PT11H00M00S
               PT14H01M00S
               2574.0000
               SMI
               
               0
             
http://:/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/FlightCollection(carrid='AA',conn
 id='0017',fldate='20110105')

                                                                                                   Copyright/Trademark
Flight
  2011-09-27T06:32:42Z
     
- 
   
   - 
         - 
           AA
              0017
           2011-03-16T00:00:00
           422.94
           USD
           747-400
           385
           371
           192129.22
           31
           30
           21
           20
         - 
              US
              new york
              JFK
              US
              SAN FRANCISCO
              SFO
              361
              PT11H00M00S
              PT14H01M00S
              2574.0000
              SMI
              
              0
           
http://:/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/FlightCollection(carrid='AA',conn
      id='0017',fldate='20110316')

  Flight
  2011-09-27T06:32:42Z
     
                                                                                                   Copyright/Trademark
Read Example

     To read the carrier details, you must call the “CarrierCollection” using the Carrier ID parameter.

     Refer to the code snippet below for details on how to do it from a PHP application:

     1. Initialize the service proxy object, for example RMTSAMPLEFLIGHT using the service URL.
         $proxy = new RMTSAMPLEFLIGHT
         ('http://:/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT');

     2. Enter the service credentials.
         $proxy->Credential = new WindowsCredential('', '');

     3. Specify the carrier ID parameter for which we want to receive information.
         $carrier_id = 'AA'; //American Airlines

     4. Execute the query below on the service to retrieve the carrier and save the result. The result returned
        in the response is an array containing the specific Carrier object.
          $query = $proxy->CarrierCollection()->filter("carrid eq '$carrier_id'");
          $carriers = $query->Execute()->Result;

     5. Use the result to display the information obtained.
          echo   "Carrier   ID: " . $carriers[0]->carrid . "";
          echo   "Carrier   Name: " . $carriers[0]->CARRNAME . "";
          echo   "Carrier   Code: " . $carriers[0]->CURRCODE . "";
          echo   "Carrier   URL: " . $carriers[0]->URL . "";

     Refer the full code snippet found in Appendix 2.

     Response

- 
  
- 
  AA
  American Airlines
  USD
  http://www.aa.com
  
  :/sap/opu/sdata/iwfnd/RMTSAMPLEFLIGHT/CarrierCollection(carrid='AA')
  
  Carrier
  2011-09-27T10:00:38Z
     
                                                                                                   Copyright/Trademark
Create Example

To book a flight, trigger the HTTP POST method on the Booking Collection (with the Booking details in the
request body). Check for the HTTP response code. If the response code is 201, then the HTTP-POST is
successful. The response contains the newly created Booking ID in the bookid field, as well as the entire
information that was part of the request body.

Refer to the code snippet below for details on how to invoke a create request from a PHP application:

1. Initialize the service proxy object, for example RMTSAMPLEFLIGHT, using the service URL.
   $proxy = new RMTSAMPLEFLIGHT
   ('http://:/sap/opu/sdata/IWFND/RMTSAMPLEFLIGHT');

2. Enter the service credentials.
   $proxy->Credential = new WindowsCredential('', '');

3. Create the new Booking item.
    //Create a booking object with key properties:
    $carrid = 'AA';
    $connid = '0017';
    $fldate = '2011-12-21T00:00:00';
    $bookid = '';
    $booking = Booking::CreateBooking($carrid, $connid, $fldate, $bookid);

    //Define additional booking properties:
    $booking->CUSTOMID = '00004617';
    $booking->CUSTTYPE = 'P';
    $booking->WUNIT = 'KG';
    $booking->LUGGWEIGHT = '14.4000';
    $booking->CLASS = 'Y';
    $booking->FORCURAM = '879.82';
    $booking->FORCURKEY = 'USD';
    $booking->LOCCURAM = '803.58';
    $booking->LOCCURKEY = 'USD';
    $booking->ORDER_DATE = '2011-05-22T00:00:00';
    $booking->COUNTER = '00000000';
    $booking->AGENCYNUM = '00000325';
    $booking->PASSNAME = 'Joe Smith';
    $booking->PASSFORM = '1234567';
    $booking->PASSBIRTH = '1990-10-10T00:00:00';

4. Add the new Booking item to the BookingCollection.
   Note: The service is not aware of these changes until the SaveChanges method is called.
   $proxy->AddToBookingCollection($booking);

5. Add the XMLHttpRequest http header needed for POST requests.
   $proxy->SetEntityHeaders($booking, array('X-Requested-With' => 'XMLHttpRequest'));

                                                                                             Copyright/Trademark
6. Save all changes made to the service (this will trigger the request).
   Note: Define the ‘SaveChangesOptions’ property to send each change in a separate request, for
   services which do not support OData $batch function, as RMTSAMPLEFLIGHT.

   $proxy->SetSaveChangesOptions(SaveChangesOptions::None);
   $proxy->SaveChanges();

    Note: The SaveChanges method may cause printing of some PHP warnings. To hide these warnings, set
    the error_reporting configuration using the following code:
    error_reporting(E_ALL & ~E_NOTICE); //Show all errors, except for notices and coding
    standards warnings

Refer the full code snippet found in Appendix 2.

                                                                                        Copyright/Trademark
Creation of Request Body for Create Method:

The request body can be easily created by looking at the tags in the collection’s metadata. For example, the
metadata for Booking Collection provides information about the various fields (tags) that are needed for
creating a booking:

                                                                                            Copyright/Trademark
Authentication Using X.509 Certificate
In the code snippets above, the requests sent to the service use Basic Authentication.

If X.509 Certificate Authentication is needed, the X.509 Client Certificate should be attached to any request
sent to the service. In addition, a CA Certificate of the SAP NetWeaver Gateway server should be used for
server authentication, as part of the SSL Handshake process.

Note: OData generated proxies do not support X.509 Certificate Authentication. Therefore the service
requests should be sent using PHP libraries which support SSL and X.509 Certificate Authentication (as cURL
used in the code snippets below). In addition, the developer is responsible for parsing the service response
according to the OData / SAP Data Protocols.

Prerequisites

The following tools are required for developing a PHP application which uses X.509 Certificate
Authentication (in addition to the tools mentioned above as prerequisites for developing a PHP
application):

Software                                           Version

PHP cURL Extension

Note: OData SDK for PHP is not needed as a prerequisite since it does not support X.509 Certificate
Authentication.

Make sure you have performed the following procedures:

   Install and configure the cURL library.
    In a Windows operating system, this can be done by enabling the php_curl.dll in php.ini configuration
    file: Search for 'extension=php_curl.dll' in the php.ini file and remove the semicolon (;) in front of it.
   Export the root CA Certificate of the SAP NetWeaver Gateway server into a local file, which is accessible
    from your PHP project. You may use any browser program for that. Make sure the certificate is saved in
    Base64-encoded format.
    Store the X.509 Client Certificate (which should be attached to each request sent to the service) into a
    local file accessible from your PHP project. Make sure the certificate is saved in PEM format. If the
    certificate is saved in a different format, you must convert it to PEM format using a converter tool, such
    as OpenSSL.
    For example, to convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
    format, execute the following command:

    openssl pkcs12 -in .pfx -out .pem –nodes

                                                                                              Copyright/Trademark
Read Example

To read the carrier details, you must call the “CarrierCollection” using the Carrier ID parameter.

Refer to the code snippet below for details on how to do it from a PHP application using X.509 Certificate
Authentication:

1. Create a service request object using the cURL library.
    $curlReq = curl_init();

2. Specify the carrier ID parameter for which you want to receive information.
   $carrier_id = 'AA'; //American Airlines

3. Create a Get Specific Carrier query string and set it as the request URL.
   Note: Use an https protocol to trigger an SSL Handshake process which is needed for X.509 Certificate
   Authentication.
   $query_url = "https://:/sap/opu/sdata/IWFND/
        RMTSAMPLEFLIGHT/CarrierCollection(carrid='$carrier_id')";
   curl_setopt($curlReq, CURLOPT_URL, $query_url);

4. Set the request general options to support redirection and response returned as a string.
   curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($curlReq, CURLOPT_FOLLOWLOCATION, true);

5. Set request options for the server verification during the SSL Handshake, including defining the trusted
   CA Certificate location.
   curl_setopt($curlReq, CURLOPT_SSL_VERIFYHOST, 1);
   curl_setopt($curlReq, CURLOPT_SSL_VERIFYPEER, true);
   curl_setopt($curlReq, CURLOPT_CAINFO, '.cer');

6. Attach the stored X.509 Client Certificate to the request.
   curl_setopt($curlReq, CURLOPT_SSLCERT, '.pem');

7. Send the request and handle the service response.
   $curlRes = curl_exec($curlReq);

   //Handle response:
   if(!curl_errno($curlReq))
   {
     $info = curl_getinfo($curlReq);
     echo $curlRes;
   }
   else
   {
     echo 'CURL error: ' . curl_error($curlReq);
   }

                                                                                              Copyright/Trademark
Note: The service response should be parsed according to the OData/SAP Data Protocols to be used as
    demonstrated in the Basic Authentication Read Example. This parsing is not demonstrated in this code
    snippet, and should be implemented by the developer, if needed.

8. Close the request object.
   curl_close($curlReq);

Refer the full code snippet found in Appendix 2.

                                                                                          Copyright/Trademark
Appendix 1 - RMTSAMPLEFLIGHT Service Metadata
Description

                                                                                   Copyright/Trademark
Copyright/Trademark
Copyright/Trademark
Copyright/Trademark
Airline
      
        Flight Number
      
        Date
      
                                                                             Copyright/Trademark
Date
            
              Date
            
              Depart.city
            
              Arrival city
            
                                                                                   Copyright/Trademark
Appendix 2 – Code Snippets
Read - Get Carrier by Carrier ID
Function Import – Get available Flights

Execute("GetAvailableFlights?cityfrom=$city_from&cityto=$city_to
        &fromdate=$from_date&todate=$to_date")->Result;

    foreach ($flights as $flight)
    {
        echo "Flight Carrier: " . $flight->carrid . "";
        echo "Flight Price: " . $flight->PRICE . "";
        echo "Flight Max. Seats: " . $flight->SEATSMAX . "";
    }
}
catch(DataServiceRequestException $exception)
{
   echo $exception->Response->getError();
}
?>

                                                                            Copyright/Trademark
Create - Booking a Flight

SaveChanges();
}
catch(ODataServiceException $exception)
{
   echo $exception->getError();
}
?>

                                                                                Copyright/Trademark
Read - Get Carrier by Carrier ID Using X.509 Certificate Authentication
You can also read