-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathRajaOngkir.php
112 lines (91 loc) · 2.49 KB
/
RajaOngkir.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
namespace Agungjk\Rajaongkir;
class RajaOngkir {
protected $endpoint;
protected $key;
private $error;
public function __construct(){
$this->endpoint = config('rajaongkir.end_point_api', 'http://rajaongkir.com/api/starter');
$this->key = config('rajaongkir.api_key');
$this->city = json_decode(file_get_contents(__DIR__ . '/config/city.json'));
$this->province = json_decode(file_get_contents(__DIR__ . '/config/province.json'));
}
private function _request($path, $options = null)
{
$url = $this->endpoint . "/" . $path;
$curl = curl_init();
$config = 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->key
),
);
$config = array_merge($config, $options);
curl_setopt_array($curl, $config);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
throw new Exception($err, 1);
}
if (! isset($response->rajaongkir)) {
$this->error = 'Response not valid';
return false;
}
$rajaongkir = $response->rajaongkir;
if ( $rajaongkir->status->code == 400 ) {
$this->error = $rajaongkir->status->description;
}
if ( $rajaongkir->status->code == 200 ) {
return $rajaongkir->results;
}
}
public function province($id = null)
{
if ($id = null) {
return empty($this->province) ? self::_request('/province') : $this->province;
}
if (empty($this->province)) {
return self::_request('/province?id=' . $id);
}
foreach ($this->province as $key => $value) {
if ($value->province_id == $id) {
return $value;
}
}
return null;
}
public function city($id = null)
{
if ($id == null) {
return empty($this->city) ? self::_request('/city') : $this->city;
}
if (empty($this->city)) {
return self::_request('/city?id=' . $id);
}
foreach ($this->city as $key => $value) {
if ($value->city_id == $id) {
return $value;
}
}
return null;
}
public function cost($origin, $destination, $weight, $courier)
{
$options = [
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "origin=". $origin ."&destination=". $destination ."&weight=". $weight ."&courier=". $courier,
CURLOPT_HTTPHEADER => array(
"content-type: application/x-www-form-urlencoded",
"key: " . self::key
),
];
return self::_request('/cost', $options);
}
}