Building a WordPress Plugin with Amadeus APIs: Part 2

Introduction

In Part 1 of this series, you created a simple WordPress plugin, added an admin page for users to set the credentials to connect to Amadeus Self-Service APIs, and gave the plugin the ability to communicate with the Flight Offers Search API. In Part 2, you’ll equip your plugin with a web form for users to enter and submit their travel details via AJAX requests. Then, you’ll finish by giving it the ability to extract flight deals and display them in a table.

You can find the source code used in the article on our GitHub repository.

Receiving user input

Your plugin will provide a web form for users to submit their origin and destination, departure date, return date (if round-trip) and number of travelling adults, via AJAX requests. You’ll reuse the get_flight_offers function to receive the AJAX requests. Let’s get started!

Create the following function called flight_offers_form, which outputs a web form when called and saves it in a new PHP file called flight-offers-form.php:

				
					Query the Flight Offers Search API using the user input as the parameters.

Return the API’s response to the front end in a JSON string.
				
			

Let’s get started. Instead of hardcoding the travel data in the get_flight_offers function, obtain it dynamically from the user input submitted via an AJAX request, with this code:

				
					/*
$travel_data = array(
  'originLocationCode' 	  => 'SIN',
  'destinationLocationCode' => 'BKK',
  'departureDate' 	      => '2020-08-14',
  'returnDate' 	          => '2020-08-17',
  'adults'                  => 2
);
*/
$travel_data = array(
  'originLocationCode' 	  => sanitize_text_field( $_POST["originLocationCode"] ),
  'destinationLocationCode' => sanitize_text_field( $_POST["destinationLocationCode"] ),
  'departureDate' 	      => sanitize_text_field( $_POST["departureDate"] ),
  'adults'                  => sanitize_text_field( $_POST["adults"] ),
);
if ( $_POST["returnDate"] !== '' ) {
  $travel_data['returnDate'] = sanitize_text_field( $_POST["returnDate"]
}
				
			

Next, remove these two blocks of redundant output statements from the get_flight_offers function:

				
					echo 'Response from the authorization server:';
echo '
', json_encode($response_body, JSON_PRETTY_PRINT), '
';

echo 'Response from the Flight Offers Search API:';
				
			

Then rewrite these three respective code blocks in the get_flight_offers function:

				
					// if(property_exists( $response_body, 'error' ) ) die; 
if ( property_exists($response_body, 'error') ) {
  die( '
' . ( $response_body -> error_description ) . '.

' ); } // print_r( $e->getMessage() ); die( '

' . ( $e -> getMessage() ) . '.

' ); // echo '

', substr( json_encode($response_body, JSON_PRETTY_PRINT), 0, 5000 ), '
';
echo json_encode($requests_response->body);
				
			

Finally, add the following statement to the end of the get_flight_offers function to terminate immediately and return a response:

				
					wp_die();
				
			

At this point, the get_flight_offers function in the get_flight_offers.php file should contain the following code:

				
					function get_flight_offers() {
  Requests::register_autoloader();
  $url = 'https://test.api.amadeus.com/v1/security/oauth2/token';
  $options = get_option( 'amadeus_api_options' ); 
  $auth_data = array();
  $auth_data[ 'client_id' ] = $options[ 'api_key_text_field_0' ];
  $auth_data[ 'client_secret' ] = $options[ 'api_secret_text_field_1' ];
  $auth_data[ 'grant_type' ] = 'client_credentials';
  $headers = array( 'Content-Type' => 'application/x-www-form-urlencoded' );
try {
  $requests_response = Requests::post( $url, $headers, $auth_data );
  $response_body = json_decode( $requests_response->body );
  if ( property_exists($response_body, 'error') ) {
    die( '
' . ( $response_body -> error_description ) . '.

' ); } $access_token = $response_body->access_token; } catch (Exception $e) { die( '

' . ( $e -> getMessage() ) . '.

' ); } if ( isset( $access_token ) ) { $endpoint = 'https://test.api.amadeus.com/v2/shopping/flight-offers'; $travel_data = array( 'originLocationCode' => sanitize_text_field( $_POST["originLocationCode"] ), 'destinationLocationCode' => sanitize_text_field( $_POST["destinationLocationCode"] ), 'departureDate' => sanitize_text_field( $_POST["departureDate"] ), 'adults' => sanitize_text_field( $_POST["adults"] ), ); if ( $_POST["returnDate"] !== '' ) { $travel_data['returnDate'] = sanitize_text_field( $_POST["returnDate"] ); } $params = http_build_query( $travel_data ); $url = $endpoint.'?'.$params; $headers = array( 'Authorization' => 'Bearer '.$access_token ); $options = array( 'timeout' => 10, ); try { $requests_response = Requests::get( $url, $headers, $options ); $response_body = json_decode( $requests_response->body ); if ( property_exists($response_body, 'error') ) { die( '

' . ( $response_body -> error_description ) . '.

' ); } echo json_encode($requests_response->body); } catch ( Exception $e ) { die( '

' . ( $e -> getMessage() ) . '.

' ); } } wp_die(); }
				
			

All that’s left to do is to get your plugin to extract useful information from the data returned by the get_flight_offers function and display it in a table. Ready?

Showing the data

When a user submits a form, the $.ajax method in the amadeus-flight-offers-search.js file makes the AJAX request and returns a jQuery XMLHttpRequest (jqXHR) object. The jqXHR object’s done method captures and handles the data returned from a successful AJAX request, while the object’s fail method handles the data from a failed AJAX request.

Let’s start with the easiest one. Add this code to the fail method to format and display the text response from a failed AJAX request:

				
					.fail(function( jqXHR, textStatus ) {
    $( "#response" ).html( '
' + jqXHR.responseText + '

' ); })
				
			

Then add the following code to the done method to extract, format, and display useful information from data returned from a successful AJAX request in a table:

				
					.done ( function( response ){
  var responseObj = $.parseJSON( response );
  var content = '';
  content += '
Flight offers from ' + $( '#originLocationCode' ).val() + ' to ' + $( '#destinationLocationCode' ).val() + ' departing on ' + $( '#departureDate' ).val() + ( ( $( '#returnDate' ).val() !== '' ) ? ( ' and returning on ' + $( '#returnDate' ).val() ) : '') + ' for ' + $( '#adults' ).val() + ' adult' + ( $( '#adults' ).val() > 1 ? 's.' : '.' ) + '

'; content += '

'; content += ''; $.each( responseObj.data, function( idx, data ) { var id = data.id; var currency = data.price.currency; var total = data.price.total; var segment_count = 0; $.each( data.itineraries, function( idx, itinerary ) { $.each( itinerary.segments, function( idx, segment ) { var departure_from = segment.departure.iataCode; var departure_time = segment.departure.at; var arrival_at = segment.arrival.iataCode; var arrival_time = segment.arrival.at; var carrierCode = segment.carrierCode; var number = segment.number; var duration = segment.duration; content += ''; content += ''; content += ''; segment_count++; }) }) }) content += '
				
			

 

IDDeparture PlaceDeparture TimeArrival PlaceArrival TimeFlight NoDurationTotal Price
‘ + ( ( segment_count === 0 ) ? id : ” ) + ‘‘; content += departure_from + ‘‘ + departure_time + ‘‘ + arrival_at + ‘‘ + arrival_time + ‘‘ + carrierCode + ‘ ‘ + number + ‘‘ + duration + ‘‘ + ( ( segment_count === 0 ) ? currency + ‘ ‘ + total : ” ) + ‘‘; content += ‘

				
					'; $( '#response' ).html( content ); })
				
			

Once it’s complete, the amadeus-flight-offers-search.js file should contain the following code:

				
					jQuery(function($){
  $( "#departureDate" ).datepicker( { dateFormat: "yy-mm-dd" } );
  $( "#returnDate" ).datepicker( { dateFormat: "yy-mm-dd" } );
  $( "#flight_offers_request_form" ).submit( function( event ) {
    event.preventDefault();
    $( "#response" ).html( '' );
    $.ajax({
        url: ajax_object.ajax_url,
        type: "post",
        dataType: 'JSON',
        data: $( this ).serialize(),
    })
    .done ( function( response ){
      var responseObj = $.parseJSON( response );
      var content = '';
      content += '
Flight offers from ' + $( '#originLocationCode' ).val() + ' to ' + $( '#destinationLocationCode' ).val() + ' departing on ' + $( '#departureDate' ).val() + ( ( $( '#returnDate' ).val() !== '' ) ? ( ' and returning on ' + $( '#returnDate' ).val() ) : '') + ' for ' + $( '#adults' ).val() + ' adult' + ( $( '#adults' ).val() > 1 ? 's.' : '.' ) + '

'; content += '

'; content += ''; $.each( responseObj.data, function( idx, data ) { var id = data.id; var currency = data.price.currency; var total = data.price.total; var segment_count = 0; $.each( data.itineraries, function( idx, itinerary ) { $.each( itinerary.segments, function( idx, segment ) { var departure_from = segment.departure.iataCode; var departure_time = segment.departure.at; var arrival_at = segment.arrival.iataCode; var arrival_time = segment.arrival.at; var carrierCode = segment.carrierCode; var number = segment.number; var duration = segment.duration; content += ''; content += ''; content += ''; segment_count++; }) }) }) content += '
				
			
IDDeparture PlaceDeparture TimeArrival PlaceArrival TimeFlight NoDurationTotal Price
‘ + ( ( segment_count === 0 ) ? id : ” ) + ‘‘; content += departure_from + ‘‘ + departure_time + ‘‘ + arrival_at + ‘‘ + arrival_time + ‘‘ + carrierCode + ‘ ‘ + number + ‘‘ + duration + ‘‘ + ( ( segment_count === 0 ) ? currency + ‘ ‘ + total : ” ) + ‘‘; content += ‘

				
					 '; $( '#response' ).html( content ); }) .fail(function( jqXHR, textStatus ) { $( "#response" ).html( '
' + jqXHR.responseText + '

' ); }) }) });
				
			

Finally, launch the WordPress post or page containing the added [amadeus-flight-offers-search] tag, enter the trip details into the web form and click the search button. In this example, the trip is for two adults from SIN (Singapore) to BKK (Bangkok), departing on 2020-08-14 and returning on 2020-08-17. You will then see a list of flight offers found for the trip displayed in a table, like so:

Conclusion

In this two-part series, you built and tested a WordPress plugin using the Amadeus Flight Offers Search API and with a small amount of code, were able to add basic flight search data to WordPress. This is just the start of what’s possible. All of the lessons learned in this series can easily be used to integrate other Amadeus Self-Service APIs with WordPress.

This article was originally published on Amadeus’s blog.

If you’re interested in developing expert technical content that performs, let’s have a conversation today.

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on reddit
Reddit
Share on email
Email

POST INFORMATION

If you work in a tech space and aren’t sure if we cover you, hit the button below to get in touch with us. Tell us a little about your content goals or your project, and we’ll reach back within 2 business days. 

Share via
Copy link
Powered by Social Snap