baseUrl = config('services.rajaongkir.base_url'); $this->apiKey = config('services.rajaongkir.api_key'); } public function getProvinces($id = null) { try { $curl = curl_init(); $url = $this->baseUrl . "/province"; if ($id) { $url .= "?id=" . $id; } curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "key: " . $this->apiKey ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { throw new \Exception("cURL Error #:" . $err); } return json_decode($response, true); } catch (\Exception $e) { throw new \Exception('Gagal mengambil data provinsi: ' . $e->getMessage()); } } public function getCities($provinceId = null, $id = null) { try { $curl = curl_init(); $url = $this->baseUrl . "/city"; $params = []; if ($provinceId) { $params[] = "province=" . $provinceId; } if ($id) { $params[] = "id=" . $id; } if (!empty($params)) { $url .= "?" . implode("&", $params); } curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "key: " . $this->apiKey ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { throw new \Exception("cURL Error #:" . $err); } return json_decode($response, true); } catch (\Exception $e) { throw new \Exception('Gagal mengambil data kota: ' . $e->getMessage()); } } public function calculateCost($origin, $destination, $weight, $courier) { try { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $this->baseUrl . "/cost", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => http_build_query([ 'origin' => $origin, 'destination' => $destination, 'weight' => $weight, 'courier' => $courier ]), CURLOPT_HTTPHEADER => array( "content-type: application/x-www-form-urlencoded", "key: " . $this->apiKey ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { throw new \Exception("cURL Error #:" . $err); } return json_decode($response, true); } catch (\Exception $e) { throw new \Exception('Gagal menghitung ongkos kirim: ' . $e->getMessage()); } } }