<?php if (!defined('ABSPATH')) { exit; } class WC_Helper_API { public static $api_base; public static function load() { self::$api_base = apply_filters('woocommerce_helper_api_base', 'https://woocommerce.com/wp-json/helper/1.0'); } public static function request($endpoint, $args = array()) { $url = self::url($endpoint); if (!empty($args['authenticated'])) { if (!self::_authenticate($url, $args)) { return new WP_Error('authentication', 'Authentication failed.'); } } $args = apply_filters('woocommerce_helper_api_request_args', $args, $endpoint); return wp_safe_remote_request($url, $args); } private static function _authenticate(&$url, &$args) { $auth = WC_Helper_Options::get('auth'); if (empty($auth['access_token']) || empty($auth['access_token_secret'])) { return false; } $request_uri = parse_url($url, PHP_URL_PATH); $query_string = parse_url($url, PHP_URL_QUERY); if (is_string($query_string)) { $request_uri .= '?' . $query_string; } $data = array('host' => parse_url($url, PHP_URL_HOST), 'request_uri' => $request_uri, 'method' => !empty($args['method']) ? $args['method'] : 'GET'); if (!empty($args['body'])) { $data['body'] = $args['body']; } $signature = hash_hmac('sha256', json_encode($data), $auth['access_token_secret']); if (empty($args['headers'])) { $args['headers'] = array(); } $headers = array('Authorization' => 'Bearer ' . $auth['access_token'], 'X-Woo-Signature' => $signature); $args['headers'] = wp_parse_args($headers, $args['headers']); $url = add_query_arg(array('token' => $auth['access_token'], 'signature' => $signature), $url); return true; } public static function get($endpoint, $args = array()) { $args['method'] = 'GET'; return self::request($endpoint, $args); } public static function post($endpoint, $args = array()) { $args['method'] = 'POST'; return self::request($endpoint, $args); } public static function put($endpoint, $args = array()) { $args['method'] = 'PUT'; return self::request($endpoint, $args); } public static function url($endpoint) { $endpoint = ltrim($endpoint, '/'); $endpoint = sprintf('%s/%s', self::$api_base, $endpoint); $endpoint = esc_url_raw($endpoint); return $endpoint; } } WC_Helper_API::load();