This repository has been archived by the owner on Sep 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.php
230 lines (206 loc) · 7.64 KB
/
api.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<?php
/**
* Yelp Fusion API code sample.
*
* This program demonstrates the capability of the Yelp Fusion API
* by using the Business Search API to query for businesses by a
* search term and location, and the Business API to query additional
* information about the top result from the search query.
*
* Please refer to http://www.yelp.com/developers/v3/documentation
* for the API documentation.
*
* Sample usage of the program:
* `php sample.php --term="dinner" --location="San Francisco, CA"`
*/
$error = false;
// OAuth credential placeholders that must be filled in by users.
// You can find them on
// https://www.yelp.com/developers/v3/manage_app
define( 'CLIENT_ID', 'aZoS8TThDELadH3-NQVD1g' );
define( 'CLIENT_SECRET', 'rrbxrRqjXUs4t8so5q8kgTagIXkuML5wp8oWT1e7HDnnAObv9GtlZpiYObk6xgl3' );
// Complain if credentials haven't been filled out.
if( ! defined( 'CLIENT_ID' ) && empty( CLIENT_ID ) )
$error = "Please supply your client_id.";
if( ! defined( 'CLIENT_SECRET' ) && empty( CLIENT_SECRET ) )
$error = "Please supply your client_secret.";
// API constants, you shouldn't have to change these.
define( 'API_HOST', "https://api.yelp.com" );
define( 'SEARCH_PATH', "/v3/businesses/search" );
define( 'BUSINESS_PATH', '/v3/businesses/' );
define( 'TOKEN_PATH', "/oauth2/token" );
define( 'GRANT_TYPE', "client_credentials" );
define( 'SEARCH_LIMIT', 1 );
define( 'BUSINESS_CATEGORY', 'tattoo' );
/**
* Given a bearer token, send a GET request to the API.
*
* @return OAuth bearer token, obtained using client_id and client_secret.
*/
function obtain_bearer_token() {
try {
# Using the built-in cURL library for easiest installation.
# Extension library HttpRequest would also work here.
$curl = curl_init();
if (FALSE === $curl)
throw new Exception('Failed to initialize');
$postfields = "client_id=" . CLIENT_ID .
"&client_secret=" . CLIENT_SECRET .
"&grant_type=" . GRANT_TYPE;
curl_setopt_array($curl, array(
CURLOPT_URL => API_HOST . TOKEN_PATH,
CURLOPT_RETURNTRANSFER => true, // Capture response.
CURLOPT_ENCODING => "", // Accept gzip/deflate/whatever.
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded",
),
));
$response = curl_exec($curl);
if (FALSE === $response)
throw new Exception(curl_error($curl), curl_errno($curl));
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (200 != $http_status)
throw new Exception($response, $http_status);
curl_close($curl);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
$body = json_decode($response);
$bearer_token = $body->access_token;
return $bearer_token;
}
/**
* Makes a request to the Yelp API and returns the response
*
* @param $bearer_token API bearer token from obtain_bearer_token
* @param $host The domain host of the API
* @param $path The path of the API after the domain.
* @param $url_params Array of query-string parameters.
* @return The JSON response from the request
*/
function request($bearer_token, $host, $path, $url_params = array()) {
// Send Yelp API Call
try {
$curl = curl_init();
if (FALSE === $curl)
throw new Exception('Failed to initialize');
$url = $host . $path . "?" . http_build_query($url_params);
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true, // Capture response.
CURLOPT_ENCODING => "", // Accept gzip/deflate/whatever.
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer " . $bearer_token,
"cache-control: no-cache",
),
));
$response = curl_exec($curl);
if (FALSE === $response)
throw new Exception(curl_error($curl), curl_errno($curl));
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (200 != $http_status)
throw new Exception($response, $http_status);
curl_close($curl);
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
return $response;
}
/**
* Query the Search API by a search term and location
*
* @param $bearer_token API bearer token from obtain_bearer_token
* @param $term The search term passed to the API
* @param $location The search location passed to the API
* @return The JSON response from the request
*/
function search($bearer_token, $term, $location) {
$url_params = array();
$url_params['term'] = $term;
$url_params['latitude'] = $location['latitude'];
$url_params['longitude'] = $location['longitude'];
$url_params['limit'] = SEARCH_LIMIT;
$url_params['categories'] = BUSINESS_CATEGORY;
return request($bearer_token, API_HOST, SEARCH_PATH, $url_params);
}
/**
* Query the Business API by business_id
*
* @param $bearer_token API bearer token from obtain_bearer_token
* @param $business_id The ID of the business to query
* @return The JSON response from the request
*/
function get_business($bearer_token, $business_id) {
$business_path = BUSINESS_PATH . urlencode($business_id);
return request($bearer_token, API_HOST, $business_path);
}
/**
* Queries the API by the input values from the user
*
* @param $term The search term to query
* @param $location The location of the business to query
*/
function query_api($term, $location) {
$return = array(
'status' => 'success',
'found_results' => 0,
'results' => ''
);
$bearer_token = obtain_bearer_token();
$response = json_decode(search($bearer_token, $term, $location));
$return['found_results'] = count($response->businesses);
$allowed_fields = array(
'image_url',
'url',
'phone',
'display_phone'
);
if( $return['found_results'] > 0 ) {
$business_id = $response->businesses[0]->id;
$response = json_decode(get_business($bearer_token, $business_id));
foreach( $response as $key => $value ) {
if( in_array( $key, $allowed_fields ) )
$return['results'][$key] = $value;
}
}
return $return;
}
/**
* User input is handled here
*/
$search_term = isset( $_GET['search_term'] ) ? $_GET['search_term'] : false;
$latitude = isset( $_GET['latitude'] ) ? $_GET['latitude'] : false;
$longitude = isset( $_GET['longitude'] ) ? $_GET['longitude'] : false;
if( ! $search_term || ! $latitude || ! $longitude )
$error = "You must provide all required parameters!";
$search_location = array(
'latitude' => $latitude,
'longitude' => $longitude
);
if( $error ) {
$json_res = array(
'status' => 'error',
'message' => $error
);
}
else {
$json_res = query_api($search_term, $search_location);
}
header( 'Content-Type: application/json; charset=UTF-8' );
echo $_GET['callback'] . '(' . json_encode($json_res) . ')';