b443325d by fehrlich

init

1 parent c5f88e3b
vendor
\ No newline at end of file
# immoscout24-api-php
An example implementation for the immoscout24 rest api in php.
\ No newline at end of file
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.
## install
`composer install fehrlich/immoscout24-api-php`
## usage
The libary contains an abstract class that needs to be extended by an user defined class and implement 4 methods, that are needed to restore and save tokens.
### example implementation
```
class MyAPI extends \fehrlich\ScoutAPI\ImmoScoutAPI
{
/**
* 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
*/
public function saveRequestToken($token, $secret){
$_SESSION['is24reqtoken'] = $token;
$_SESSION['is24reqsecret'] = $secret;
}
/**
* restores the temporarily saved request token.
*
* @return array with 2 elements: first element is the token name, second element is the secret
*/
public function restoreRequestToken(){
if(isset($_SESSION['is24reqtoken']) && isset($_SESSION['is24reqsecret'])){
return [
$_SESSION['is24reqtoken'],
$_SESSION['is24reqsecret']
];
}
return null;
}
/**
* 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
*/
public function saveAccessToken($token, $secret){
file_put_contents('accessToken', serialize([$token, $secret]));
}
/**
* restores the saved access token.
*
* @return array with 2 elements: first element is the token name, second element is the secret
*/
public static function restoreAccessToken(){
if(file_exists('accessToken')) {
return unserialize(file_get_contents('accessToken'));
}
return null;
}
}
```
If you want to support multiple user, you can use `$this->getUser()` within the class.
### example usage
```
$key = 'my consumer key';
$secret = 'my consumer secret';
// $api->dontUseSandbox();
$api = MyAPI::createClient($key, $secret);
if ($api->isVerified()) {
// get a list of possible contacts used in a real estate
$contactArray = $api->getContacts();
var_dump($contactArray);
} else {
// this will trigger the verifiaction with immoscout24, and will try to reconnect
// to the current url else you can also use a paramater to specify the callback url
$api->verifyApplication();
}
```
\ No newline at end of file
......
{
"name": "fehrlich/immoscout24-api-php",
"description": "PHP Client for interacting with the Immoscout24 REST API",
"type": "library",
"authors": [
{
"name": "fehrlich",
"email": "franz.ehrlich@googlemail.com"
}
],
"require": {
"guzzlehttp/guzzle-services": "^1.1",
"guzzlehttp/oauth-subscriber": "^0.3.0",
"guzzlehttp/guzzle": "^6.3"
}
}
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "18a9f9bc0a2116a603ecb4b314774471",
"packages": [
{
"name": "guzzlehttp/command",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/command.git",
"reference": "2aaa2521a8f8269d6f5dfc13fe2af12c76921034"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/command/zipball/2aaa2521a8f8269d6f5dfc13fe2af12c76921034",
"reference": "2aaa2521a8f8269d6f5dfc13fe2af12c76921034",
"shasum": ""
},
"require": {
"guzzlehttp/guzzle": "^6.2",
"guzzlehttp/promises": "~1.3",
"guzzlehttp/psr7": "~1.0",
"php": ">=5.5.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0|~5.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "0.9-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Command\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Jeremy Lindblom",
"email": "jeremeamia@gmail.com",
"homepage": "https://github.com/jeremeamia"
}
],
"description": "Provides the foundation for building command-based web service clients",
"time": "2016-11-24T13:34:15+00:00"
},
{
"name": "guzzlehttp/guzzle",
"version": "6.4.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "0895c932405407fd3a7368b6910c09a24d26db11"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/0895c932405407fd3a7368b6910c09a24d26db11",
"reference": "0895c932405407fd3a7368b6910c09a24d26db11",
"shasum": ""
},
"require": {
"ext-json": "*",
"guzzlehttp/promises": "^1.0",
"guzzlehttp/psr7": "^1.6.1",
"php": ">=5.5"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.4 || ^7.0",
"psr/log": "^1.1"
},
"suggest": {
"psr/log": "Required for using the Log middleware"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "6.3-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle is a PHP HTTP client library",
"homepage": "http://guzzlephp.org/",
"keywords": [
"client",
"curl",
"framework",
"http",
"http client",
"rest",
"web service"
],
"time": "2019-10-23T15:58:00+00:00"
},
{
"name": "guzzlehttp/guzzle-services",
"version": "1.1.3",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle-services.git",
"reference": "9e3abf20161cbf662d616cbb995f2811771759f7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle-services/zipball/9e3abf20161cbf662d616cbb995f2811771759f7",
"reference": "9e3abf20161cbf662d616cbb995f2811771759f7",
"shasum": ""
},
"require": {
"guzzlehttp/command": "~1.0",
"guzzlehttp/guzzle": "^6.2",
"php": ">=5.5"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"suggest": {
"gimler/guzzle-description-loader": "^0.0.4"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Command\\Guzzle\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Jeremy Lindblom",
"email": "jeremeamia@gmail.com",
"homepage": "https://github.com/jeremeamia"
},
{
"name": "Stefano Kowalke",
"email": "blueduck@mail.org",
"homepage": "https://github.com/konafets"
}
],
"description": "Provides an implementation of the Guzzle Command library that uses Guzzle service descriptions to describe web services, serialize requests, and parse responses into easy to use model structures.",
"time": "2017-10-06T14:32:02+00:00"
},
{
"name": "guzzlehttp/oauth-subscriber",
"version": "0.3.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/oauth-subscriber.git",
"reference": "04960cdef3cd80ea401d6b0ca8b3e110e9bf12cf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/oauth-subscriber/zipball/04960cdef3cd80ea401d6b0ca8b3e110e9bf12cf",
"reference": "04960cdef3cd80ea401d6b0ca8b3e110e9bf12cf",
"shasum": ""
},
"require": {
"guzzlehttp/guzzle": "~6.0",
"php": ">=5.5.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "0.3-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Subscriber\\Oauth\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle OAuth 1.0 subscriber",
"homepage": "http://guzzlephp.org/",
"keywords": [
"Guzzle",
"oauth"
],
"time": "2015-08-15T19:44:28+00:00"
},
{
"name": "guzzlehttp/promises",
"version": "v1.3.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
"reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646",
"reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646",
"shasum": ""
},
"require": {
"php": ">=5.5.0"
},
"require-dev": {
"phpunit/phpunit": "^4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.4-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle promises library",
"keywords": [
"promise"
],
"time": "2016-12-20T10:07:11+00:00"
},
{
"name": "guzzlehttp/psr7",
"version": "1.6.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
"reference": "239400de7a173fe9901b9ac7c06497751f00727a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/psr7/zipball/239400de7a173fe9901b9ac7c06497751f00727a",
"reference": "239400de7a173fe9901b9ac7c06497751f00727a",
"shasum": ""
},
"require": {
"php": ">=5.4.0",
"psr/http-message": "~1.0",
"ralouphie/getallheaders": "^2.0.5 || ^3.0.0"
},
"provide": {
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"ext-zlib": "*",
"phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8"
},
"suggest": {
"zendframework/zend-httphandlerrunner": "Emit PSR-7 responses"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.6-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Tobias Schultze",
"homepage": "https://github.com/Tobion"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": [
"http",
"message",
"psr-7",
"request",
"response",
"stream",
"uri",
"url"
],
"time": "2019-07-01T23:21:34+00:00"
},
{
"name": "psr/http-message",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"time": "2016-08-06T14:39:51+00:00"
},
{
"name": "ralouphie/getallheaders",
"version": "3.0.3",
"source": {
"type": "git",
"url": "https://github.com/ralouphie/getallheaders.git",
"reference": "120b605dfeb996808c31b6477290a714d356e822"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822",
"reference": "120b605dfeb996808c31b6477290a714d356e822",
"shasum": ""
},
"require": {
"php": ">=5.6"
},
"require-dev": {
"php-coveralls/php-coveralls": "^2.1",
"phpunit/phpunit": "^5 || ^6.5"
},
"type": "library",
"autoload": {
"files": [
"src/getallheaders.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ralph Khattar",
"email": "ralph.khattar@gmail.com"
}
],
"description": "A polyfill for getallheaders.",
"time": "2019-03-08T08:55:37+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": []
}
<?php
namespace fehrlich\ScoutAPI;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;
use fehrlich\ScoutAPI\exceptions\AuthException;
use fehrlich\ScoutAPI\exceptions\InvalidResponse;
use fehrlich\ScoutAPI\exceptions\InvalidTokenException;
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 InvalidArgumentException;
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 base api url depending on the sandbox.
*
* @return string base url
*/
private function getBaseUrl()
{
return $this->isSandbox ? 'https://rest.sandbox-immobilienscout24.de/restapi/' : 'https://rest.immobilienscout24.de/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)
{
$url = $this->getBaseUrl();
$path = '/api/offer/v1.0/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 {
$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']['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];
}
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 = [])
{
$methodUri = $this->getUrl($methodUri);
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)
{
$data = [];
if ($jsonData && $useJson) {
$data = [
'json' => $jsonData,
];
} elseif ($jsonData) {
$data = $jsonData;
}
return $this->call($method, $methodUri, $data);
}
/**
* 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);
}
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)
{
return json_decode((string) $res->getBody(), true);
}
/**
* get a list of possible channels, to publish to.
*
* @return ResponseInterface
*/
public function getPublishChannels()
{
return $this->callMethod('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->callMethod('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->callMethod('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->callMethod('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->callMethod('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->callMethod('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->callMethod('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->callMethod('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'];
}
}
<?php
namespace fehrlich\ScoutAPI\exceptions;
class AuthException extends Exception
{
}
<?php
namespace fehrlich\ScoutAPI\exceptions;
class InvalidResponse extends Exception
{
}
<?php
namespace fehrlich\ScoutAPI\exceptions;
class InvalidTokenException extends Exception
{
}
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!