ImmoScoutAPI.php
24.1 KB
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
<?php
namespace fehrlich\ImmoScoutAPI;
use fehrlich\ImmoScoutAPI\exceptions\AuthException;
use fehrlich\ImmoScoutAPI\exceptions\InvalidResponse;
use fehrlich\ImmoScoutAPI\exceptions\InvalidTokenException;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;
use GuzzleHttp\Client;
use GuzzleHttp\Command\Guzzle\Description;
use GuzzleHttp\Command\Guzzle\GuzzleClient;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
use Psr\Http\Message\ResponseInterface;
/**
* An example implementation for the immoscout24 rest api in php. This Client is not complete and only
* implements some methods for the export/import api, but it should be quite easy to extend. Just look
* at the later methods that show the interaction after the auth is done.
*/
abstract class ImmoScoutAPI extends GuzzleClient
{
private $consumerKey;
private $consumerKeySecret;
private $client = null;
public $history = null;
private $user = 'me';
private $isSandbox = true;
/**
* should save the request token with tokenname + secret, the token can be temporarily saved within a session
* this token is only needed during the "request an access token" phase.
*
* @param string $token
* @param string $secret
*
* @return void
*/
abstract public function saveRequestToken($token, $secret);
/**
* restores the temporarily saved request token.
*
* @return array with 2 elements: first element is the token name, second element is the secret
*/
abstract public function restoreRequestToken();
/**
* saves the access token, the information should be stored persistently, for example in a database or file.
* the progress of getting an access token only needs to be done once per user.
*
* @param string $token
* @param string $secret
*
* @return void
*/
abstract public function saveAccessToken($token, $secret);
/**
* restores the saved access token.
*
* @return array with 2 elements: first element is the token name, second element is the secret
*/
abstract public static function restoreAccessToken();
/**
* checks for the right format of a token.
*
* @param array a token array [name, secret]
*
* @return void
*/
private function validateToken($tokenArray)
{
if (!is_array($tokenArray)) {
throw new InvalidTokenException('restored Token is not an Array need to be of the form [token, token_secret]');
}
if (!isset($tokenArray[1])) {
throw new InvalidTokenException('restored Token array does not have a second element needs to be of the form [token, token_secret]');
}
}
private function getValidatedRequestToken()
{
$token = $this->restoreRequestToken();
$this->validateToken($token);
return $token;
}
private function getValidatedAccessToken()
{
$token = static::restoreAccessToken();
$this->validateToken($token);
return $token;
}
/**
* use the sandbox api.
*
* @return boolean
*/
public function useSandbox()
{
$this->isSandbox = true;
}
/**
* use the production api.
*
* @return boolean
*/
public function dontUseSandbox()
{
$this->isSandbox = false;
}
/**
* creates a new client.
*
* @param string $key consumer key
* @param string $secret consumer secret
* @param bool $authorized this should only be false for non 3-legged-authented requests
*
* @return static
*/
public static function createClient($key, $secret, $authorized = true)
{
$token = '';
$token_secret = '';
if ($authorized) {
$tokenArray = static::restoreAccessToken();
$token = $tokenArray[0];
$token_secret = $tokenArray[1];
}
$stack = HandlerStack::create();
$oAuth = new Oauth1([
'consumer_key' => $key,
'consumer_secret' => $secret,
'token' => $token,
'token_secret' => $token_secret,
]);
$stack->push($oAuth);
$client = new Client([
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
],
'handler' => $stack,
'auth' => 'oauth',
]);
$newGuzzleClient = new static($client, new Description([]));
$newGuzzleClient->client = $client;
$newGuzzleClient->oAuth = $oAuth;
$newGuzzleClient->consumerKey = $key;
$newGuzzleClient->consumerKeySecret = $secret;
return $newGuzzleClient;
}
/**
* get is24 domain depending on the sandbox.
*
* @return string base url
*/
public function getDomain()
{
return $this->isSandbox ? 'sandbox-immobilienscout24.de' : 'immobilienscout24.de';
}
/**
* get base api url depending on the sandbox.
*
* @return string base url
*/
private function getBaseUrl()
{
$domain = $this->getDomain();
return 'https://rest.' . $domain . '/restapi/';
}
/**
* get the current uri, this can be used to return to the current site after authentification.
*
* @return string current url
*/
private static function getSelfURI()
{
if (!isset($_SERVER) || !isset($_SERVER['HTTP_HOST']) || !isset($_SERVER['REQUEST_URI'])) {
throw new \Exception("coudn't detect request uri for callback (please specify one)");
}
$url = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$url .= '://';
$url .= $_SERVER['HTTP_HOST'];
$url .= $_SERVER['REQUEST_URI'];
return $url;
}
/**
* sets the user for the api, this is only needed if you want to have multiple users,
* default authenticated user is "me".
*
* @param string $user
*
* @return void
*/
public function setUser($user)
{
$this->user = $user;
}
/**
* this creates a default oAuth with a token and secret, this method is used for calls
* before the app is authenticated, so for requesting a request token and requesting an access token.
*
* @param string $uri
* @param array $oAuthData
*
* @return ResponseInterface
*/
private function callOAuth($uri, $oAuthData)
{
$oAuthData['consumer_key'] = $this->consumerKey;
$oAuthData['consumer_secret'] = $this->consumerKeySecret;
$oAuthData['token'] = isset($oAuthData['token']) ? $oAuthData['token'] : '';
$oAuthData['token_secret'] = isset($oAuthData['token_secret']) ? $oAuthData['token_secret'] : '';
$stack = HandlerStack::create();
$oAuth = new Oauth1($oAuthData);
$stack->push($oAuth);
$client = new Client([
'base_uri' => 'https://rest.sandbox-immobilienscout24.de/restapi/',
'handler' => $stack,
'auth' => 'oauth',
]);
return $client->get($uri);
}
/**
* get a request token.
*
* @param string $callback the callack url, where you get redirected after you authenticated the application on is24
*
* @return void
*/
private function requestRequestToken($callback)
{
try {
$res = static::callOAuth('/restapi/security/oauth/request_token', [
'callback' => $callback,
]);
} catch (ClientException $ex) {
throw new AuthException('Failed to get the request token');
}
parse_str((string) $res->getBody(), $body);
if (!isset($body['oauth_token']) || !isset($body['oauth_token_secret'])) {
throw new InvalidResponse('Could not parse the requested request token');
}
$this->saveRequestToken($body['oauth_token'], $body['oauth_token_secret']);
header('Location: ' . $this->getBaseUrl() . 'security/oauth/confirm_access?oauth_token=' . $body['oauth_token']);
exit();
}
/**
* request the access token.
*
* @param string $verifier
*
* @return void
*/
private function requestAccessToken($verifier)
{
$requestToken = $this->getValidatedRequestToken();
try {
$res = $this->callOAuth('security/oauth/access_token', [
'token' => $requestToken[0],
'token_secret' => $requestToken[1],
'verifier' => $verifier,
]);
} catch (ClientException $ex) {
throw new AuthException('Failed to get the access token');
}
parse_str((string) $res->getBody(), $body);
if (!isset($body['oauth_token']) || !isset($body['oauth_token_secret'])) {
throw InvalidResponse('Could not parse the requested access token');
}
$this->saveAccessToken($body['oauth_token'], $body['oauth_token_secret']);
}
/**
* this method will verify the application, this is needed if the application doesn't have an
* access token yet, this step only needs to be performed once, general the process looks like this:
* - getRequest token -> save Request token
* -> verify with is24 (receive a verifier) (external site that will redirect to the specified callBackUrl)
* -> get access token (with verifier)
* -> save access token.
*
* @param bool $callBackUrl the url where you want to be redirected after your verification on is24, this
* url needs to recall this method, to consume the oauth_verifier GET variable
*
* @return bool if auth is complete it returns true, on the verifiaction step returns false
*/
public function verifyApplication($callBackUrl = false)
{
$key = $this->consumerKey;
$secret = $this->consumerKeySecret;
$callBackUrl = $callBackUrl ? $callBackUrl : static::getSelfURI();
$api = self::createClient($key, $secret, false);
if (isset($_GET['oauth_verifier']) && isset($_GET['oauth_token'])) {
$api->requestAccessToken($_GET['oauth_verifier']);
return true;
} else {
$api->requestRequestToken($callBackUrl);
return false;
}
}
/**
* returns if the app is verified. this is the case if it can restore the access token.
*
* @return boolean
*/
public function isVerified()
{
$validToken = true;
try {
$this->getValidatedAccessToken();
} catch (InvalidTokenException $ex) {
$validToken = false;
}
return $validToken;
}
/**
* get the deep base url, that includes the parsed user.
*
* @param string $methodUri
*
* @return string url
*/
private function getUrl($methodUri, $withUser = true)
{
$url = $this->getBaseUrl();
$path = 'api/offer/v1.0/';
if ($withUser) {
$path .= 'user/{user}/';
}
if (substr($methodUri, 0, 1) !== '/') {
$path .= $methodUri;
} else {
$path = $methodUri;
}
$path = str_replace('{user}', $this->user, $path);
return $url . $path;
}
/**
* parses the default message body of an response (includes errors and success messages).
*
* @param ResponseInterface $res
*
* @return array message array
*/
private function parseMessages($res)
{
$return = [
'parsed' => [],
];
if (!empty($res->getBody())) {
try {
if ($res->getStatusCode() == "401") {
throw new AuthException("Immoscout24-API: " . $res->getReasonPhrase());
}
$json = json_decode($res->getBody(), true);
} catch (InvalidArgumentException $ex) {
$json = [];
}
if (isset($json['common.messages']) && is_array($json['common.messages'])) {
foreach ($json['common.messages'] as $message) {
if (isset($message['message']) && isset($message['message'][0])) {
foreach ($message['message'] as $msg) {
if (isset($msg['messageCode'])) {
if (!isset($return[$msg['messageCode']])) {
$return[$msg['messageCode']] = [];
}
$return[$msg['messageCode']][] = $msg['message'];
}
}
} elseif (isset($message['message']) && isset($message['message']['messageCode'])) {
if (!isset($return[$message['message']['messageCode']])) {
$return[$message['message']['messageCode']] = [];
}
$return[$message['message']['messageCode']][] = $message['message']['message'];
}
}
}
$parsedErrors = [];
foreach ($return as $errorCode => $msgArr) {
foreach ($msgArr as $msg) {
$add = null;
switch ($errorCode) {
case 'ERROR_RESOURCE_VALIDATION':
preg_match('/MESSAGE: (.*?) :/', $msg, $matches);
if (isset($matches[1])) {
$add = $matches[1];
} else {
preg_match('/MESSAGE: (.*?)\]/', $msg, $matches);
if (isset($matches[1])) {
$add = $matches[1];
if ($matches[1] == 'RealEstate already exists for external id.') {
$parsedErrors['ERROR_RESOURCE_DUPLICATE'] = true;
}
}
}
break;
case 'MESSAGE_RESOURCE_CREATED':
preg_match('/with id \[(.*?)\] /', $msg, $matches);
if (isset($matches[1])) {
$add = $matches[1];
}
break;
case 'MESSAGE_RESOURCE_UPDATED':
$add = '1';
break;
case 'MESSAGE_RESOURCE_DELETED':
$add = '1';
break;
case 'ERROR_RESOURCE_NOT_FOUND':
$add = '404';
break;
}
if ($add) {
if (!isset($parsedErrors[$errorCode])) {
$parsedErrors[$errorCode] = [];
}
$parsedErrors[$errorCode][] = $add;
}
}
}
$return['parsed'] = $parsedErrors;
}
return $return;
}
/**
* make an internal call.
*
* @param string $method like GET, POST, PUT, DELETE
* @param string $methodUri
* @param array $data
*
* @return void
*/
private function call($method, $methodUri, $data = [], $withUser = false)
{
$methodUri = $this->getUrl($methodUri, $withUser);
try {
return $this->client->request($method, $methodUri, $data);
} catch (ClientException $ex) {
$res = $ex->getResponse();
$messages = $this->parseMessages($res);
return $res;
}
}
private function callMethod($methodUri, $method = 'GET', $jsonData = null, $useJson = true, $withUser = false)
{
$data = [];
if ($jsonData && $useJson) {
$data = [
'json' => $jsonData,
];
} elseif ($jsonData) {
$data = $jsonData;
}
return $this->call($method, $methodUri, $data, $withUser);
}
private function callUserMethod($methodUri, $method = 'GET', $jsonData = null, $useJson = true)
{
return $this->callMethod($methodUri, $method, $jsonData, $useJson, true);
}
/**
* check for a specific response, if it isn't present a InvalidResponse is thrown.
*
* @param ResponseInterface $res
* @param string $expectedResponse the expected response
*
* @return bool
*/
private function checkForResponse($res, $expectedResponse = 'MESSAGE_RESOURCE_CREATED')
{
if (is_null($res)) {
throw new InvalidResponse('Got empty response ');
}
$msgs = $this->parseMessages($res);
if (!isset($msgs['parsed'][$expectedResponse])) {
$code = isset($msgs['parsed']['ERROR_RESOURCE_NOT_FOUND']) ? 404 : null;
throw new InvalidResponse('Did not get expected response: ' . $res->getBody(), $code, null, $res, $msgs);
}
if ($expectedResponse == 'MESSAGE_RESOURCE_CREATED') {
return $msgs['parsed'][$expectedResponse][0];
}
return true;
}
private function checkForResponseCreated($res)
{
return $this->checkForResponse($res, 'MESSAGE_RESOURCE_CREATED');
}
private function checkForResponseUpdated($res)
{
return $this->checkForResponse($res, 'MESSAGE_RESOURCE_UPDATED');
}
private function checkForResponseDeleted($res)
{
return $this->checkForResponse($res, 'MESSAGE_RESOURCE_DELETED');
}
private function parseGetResponse($res)
{
try {
return json_decode((string) $res->getBody(), true);
} catch (\Exception $ex) {
throw new InvalidResponse('invalid json response');
}
}
/**
* get a list of possible channels, to publish to.
*
* @return ResponseInterface
*/
public function getPublishChannels()
{
return $this->callUserMethod('publishchannel');
}
/**
* create a realestate object.
*
* @param array $obj realestate object compatible with: https://api.immobilienscout24.de/our-apis/import-export/ftp-vs-api.html
*
* @return string id used by immoscout24, this should be saved in order to update the realestate later
*/
public function createRealEstate($obj)
{
$res = $this->callUserMethod('realestate/?usenewenergysourceenev2014values=true', 'POST', $obj);
return $this->checkForResponseCreated($res);
}
/**
* update a realestate.
*
* @param string $id id used by immoscout
* @param array $obj realestate object compatible with: https://api.immobilienscout24.de/our-apis/import-export/ftp-vs-api.html
*
* @return bool
*/
public function updateRealEstate($id, $obj)
{
$res = $this->callUserMethod('realestate/' . $id . '?usenewenergysourceenev2014values=true', 'PUT', $obj);
return $this->checkForResponseUpdated($res);
}
/**
* delete an attachment.
*
* @param string $reId realestate id used by is24
* @param string $attachmentId attachment id used by is24
*
* @return void
*/
public function deleteAttachment($reId, $attachmentId)
{
$res = $this->callUserMethod('realestate/' . $reId . '/attachment/' . $attachmentId, 'DELETE');
return $this->checkForResponseDeleted($res);
}
/**
* create an attachment for an realestate.
*
*
* @return void
*/
/**
* create an attachment for an realestate.
*
* @param string $objId realestate id used by is24
* @param array $attachmentData compatible with https://api.immobilienscout24.de/our-apis/import-export/attachments/post.html
* @param string $content file content
* @param string $mimeType file mime type
* @param string $fileName filename (the right extension is important)
*
* @return string returns the id that is used by is24, this should be saved
*/
public function createAttachment($objId, $attachmentData, $content, $mimeType = 'image/jpeg', $fileName = 'image.jpg')
{
$res = $this->callUserMethod('realestate/' . $objId . '/attachment/', 'POST', [
'multipart' => [
[
'Content-type' => 'application/json',
'name' => 'metadata',
'filename' => 'metadata.json',
'contents' => json_encode($attachmentData),
], [
'Content-type' => $mimeType,
'name' => 'attachment',
'filename' => $fileName,
'contents' => $content,
],
],
], false);
return $this->checkForResponseCreated($res);
}
/**
* update realestate attachment.
*
* @param string $objId realestate id used by is24
* @param string $id id of the attachment used by is24
* @param array $attachmentData compatible with https://api.immobilienscout24.de/our-apis/import-export/attachments/post.html
*
* @return void
*/
public function updateAttachment($objId, $id, $attachmentData)
{
$res = $this->callUserMethod('realestate/' . $objId . '/attachment/' . $id, 'PUT', $attachmentData);
return $this->checkForResponseUpdated($res);
}
/**
* Undocumented function.
*
* @param string $objId realestate id used by is24
* @param array $orderArray ordered array of the ids used by is24
*
* @return void
*/
public function updateAttachmentOrder($objId, $orderArray)
{
$res = $this->callUserMethod('realestate/' . $objId . '/attachment/attachmentsorder', 'PUT', [
'attachmentsorder.attachmentsorder' => [
'@xmlns' => [
'attachmentsorder' => 'http://rest.immobilienscout24.de/schema/attachmentsorder/1.0',
],
'attachmentId' => $orderArray,
],
]);
return $this->checkForResponseUpdated($res);
}
/**
* Get an array of all contacts that can be specified for a real estate.
*
* @return array array in the form of https://api.immobilienscout24.de/our-apis/import-export/contact/get-by-id.html
*/
public function getContacts()
{
$res = $this->callUserMethod('contact');
$arr = $this->parseGetResponse($res);
if (!isset($arr['common.realtorContactDetailsList']) || !isset($arr['common.realtorContactDetailsList']['realtorContactDetails'])) {
throw new InvalidResponse('Response doesnt have the expected format');
}
return $arr['common.realtorContactDetailsList']['realtorContactDetails'];
}
/**
* Get an array of all contacts that can be specified for a real estate.
* @param string $reId realestate id used by is24 *
*/
public function delete($reId)
{
$res = $this->callUserMethod('realestate/' . $reId, 'DELETE');
return $this->checkForResponseDeleted($res);
}
/**
* Get an array of all contacts that can be specified for a real estate.
* @param string $reId realestate id used by is24
* @param string $publishchannel publish channel id like 10000
*/
public function publish($reId, $publishchannel = '10000')
{
$res = $this->callMethod('publish/', 'POST', [
'common.publishObject' => [
'realEstate' => [
'@id' => $reId,
],
'publishChannel' => [
'@id' => $publishchannel,
],
],
]);
return $this->checkForResponseCreated($res);
}
/**
* unpublish a real estate
* @param string $reId realestate id used by is24
* @param string $publishchannel publish channel id like 10000
*/
public function unpublish($reId, $publishchannel = '10000')
{
$res = $this->callMethod('publish/' . $reId . '_' . $publishchannel, 'DELETE');
return $this->checkForResponseDeleted($res);
}
}