Login / Sign Up

Data Provider WordPress Examples

Jamie McDonald

HXP Admin

API Wrapper Class

Below is an example class which can be used to communicate with your data provider API. This is written in PHP with some WordPress specific functions, however it could also be modified slightly to use generic cUrl requests for a none WordPress environment.

/**
 * //MARK: Holidaymaker Providor Request : hmprovider_request
 *
 * Holidaymaker Providor API Wrapper for making a single request
 */
class hmprovider_request {

  /** //TODO: Add in your configuration here */   

  /** @var string Client Key provided by holidaymaker */  
  private static $CLIENT_KEY = 'xyzxyzxyzxyzxyz'; 
  /** @var string Client Secret provided by holidaymaker */    
  private static $CLIENT_SECRET = 'abcabcabcabc'; 
  /** @var string Endpoint provided by holidaymaker */    
  private static $END_POINT = 'https://yourholidaymakerinstall/wp-json/holidaymaker/data'; 
  /** @var bool If true this is tell the web request to ignore SSL verify for self-signed CAs and Certs */    
  private static $LOCAL_STACK = true; 
  /** @var int Request timeout in seconds */    
  private static $TIME_OUT = 30.0; 

  /** --- */
  private static $lastError = '';
  private static $lastResponse = [];

  /** --- */
  public $function;

  /**
   * @param string $function Required function of request. Defaults to 'me'
   */
  public function __construct($function = 'me') {
    $this->function = $function;
  }

  /** --- */
  private function getPostArgs() {
    $args = [
      'f' => $this->function,
      'key' => static::$CLIENT_KEY
    ];

    if ($this->function != 'me') {
      $checkTime = date('Y-m-d H:i:s');
      $hash = md5(sprintf(
        '%s|%s|%s|%s',
        static::$CLIENT_KEY,
        strtolower($this->function),
        $checkTime,
        static::$CLIENT_SECRET
      ));
      $args['c'] = $checkTime;
      $args['a'] = $hash;
    }

    return $args;
  }

  /**
   * Send request to holidaymaker and handle result
   *
   * @return array|bool Will return an array of json, or a false boolean on failure
   */
  public function fire() {
    $results = wp_remote_post(static::$END_POINT, [
      'sslverify' => !static::$LOCAL_STACK,
      'timeout'   => static::$TIME_OUT,
      'body'      => http_build_query($this->getPostArgs())
    ]);

    if (is_wp_error($results)) {
      return $this->setError($results->get_error_message());
    } else {
      $resultsJSON = json_decode(wp_remote_retrieve_body($results), true);
      if (($resultsJSON == null) || ($resultsJSON === false)) {
        return $this->setError('Unable to parse response as JSON');
      } else {
        $responseError = isset($resultsJSON['error']) ? $resultsJSON['error'] : '';
        if ($responseError != '') {
          return $this->setError($responseError);
        } else {
          static::$lastError = '';
          static::$lastResponse = $resultsJSON;
          return true;
        }
      }
    }
  }

  /**
   * @param string $message Error message to set to current request instance
   * @return bool Always returns false and can be used to set an error and return false on single statement
   */
  public function setError($message) {
    static::$lastError = $message;
    static::$lastResponse = ["error" => $message];
    return false;
  }

  /**
   * @return string Last error trigger by request. Will be an empty string on successful requests
   */
  public static function error() {
    return static::$lastError;
  }

  /**
   * @return array|bool Will return an array of json, or a false boolean if last request failed
   */
  public static function response() {
    return static::$lastResponse;
  }

  /**
   * Static helper to create, and fire request
   *
   * @param string $function Required function of request. Defaults to 'me'
   * @return array|bool Will return an array of json, or a false boolean on failure
   */
  public static function go($function = 'me') {
    $request = new hmprovider_request($function);
    if ($request->fire()) {
      return static::response();
    } else {
      return false;
    }
  }

  /** --- */
}

Example Usage

//Get latest offers - maybe this would be on a wp_cron trigger, or server level cron trigger

$lastCheck = intval(get_option('hmprovider_offers_lastcheck', 0));
if ($lastCheck >= strtotime('-60 mins')) {
  //Bail if request was made less than an hour ago
  return;
}

//Get request and error handle
$offersRequest = hmprovider_request::go('getOffers');
if ($offersRequest === false) {
  //Do something to error handle
  //Access to last error message : hmprovider_request::error()
  //eg
  echo('<p>Error fetching offers : ' . hmprovider_request::error() . '</p>');
} else {
  //Parse offer data
  
  //Categories
  $categories = (isset($offersRequest['categories']) && is_array($offersRequest['categories'])) ? $offersRequest['categories'] : [];
  //Options here could be to get a list of a custom taxonomy in your DB, and then add any new ones that are missing, and have create an index of the term IDs compared to the HM IDs so you can attach the offers to the correct terms

  //Offers
  $offers = (isset($offersRequest['offers']) && is_array($offersRequest['offers'])) ? $offersRequest['offers'] : [];  
  //You could get a list of published and drafted custom posts and make an index of their IDs compared to a metadata value on each post of their HM ID
  //Then check new received offer IDs, and draft any existing posts which no longer match to offers in the received packet
  //Then republish any existing posts which match and ID - while updating their meta data from the offer packet
  //Then publish any new offers including the metadata value for their HM ID which will then be used on the next parsing run
}

//Update last check time
update_option('hmprovider_offers_lastcheck', time());