class DistanceShipping { private $google_matrix_api; public function __construct() { $this->google_matrix_api = new GoogleMatrixAPI(); } public function calculate_shipping_cost($store_address, $customer_address) { $distance = $this->google_matrix_api->get_distance($store_address, $customer_address); if (is_wp_error($distance)) { return $distance; // Return the error } // Example calculation: $cost = $distance * rate_per_km $rate_per_km = 1.5; // Example rate $cost = $distance * $rate_per_km; return $cost; } }class GoogleMatrixAPI { private $apiKey; private $baseUrl = 'https://maps.googleapis.com/maps/api/distancematrix/json'; public function __construct($apiKey) { $this->apiKey = $apiKey; } public function getDistance($origin, $destination) { $url = $this->buildUrl($origin, $destination); $response = $this->makeRequest($url); if (isset($response['error_message'])) { return ['error' => $response['error_message']]; } if ($response['status'] === 'OK') { return $this->parseResponse($response); } return ['error' => 'Unable to calculate distance.']; } private function buildUrl($origin, $destination) { return sprintf('%s?origins=%s&destinations=%s&key=%s', $this->baseUrl, urlencode($origin), urlencode($destination), $this->apiKey ); } private function makeRequest($url) { $response = wp_remote_get($url); if (is_wp_error($response)) { return ['error' => $response->get_error_message()]; } return json_decode(wp_remote_retrieve_body($response), true); } private function parseResponse($response) { $distance = $response['rows'][0]['elements'][0]['distance']['text']; $duration = $response['rows'][0]['elements'][0]['duration']['text']; return [ 'distance' => $distance, 'duration' => $duration, ]; } } Sony – Utoaji Express

Main Menu