Finser API 0.5

Przykładowy klient w PHP 5

<?php

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                             SAMPLE API CLIENT                             //
//                         Bartlomiej Tadych, b4rtaz                         //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////


$_config = array(
	'username' => "[USERNAME]",
	'password' => "[PASSWORD]"
);


///////////////////////////////////////////////////////////////////////////////


/**
* /brief   Curl pod Finser API.
*/
function curl($action,$post = array(),$session = FALSE)
{
	$c = curl_init(sprintf('http://api.finser.pl/%s/',$action));

	curl_setopt($c,CURLOPT_HEADER,TRUE);
	curl_setopt($c,CURLOPT_HTTPHEADER,array(

		'X-Finser-API: 0.5',
		'Accept: application/xml'
	));
	curl_setopt($c,CURLOPT_USERAGENT,'Sample API Client');

	curl_setopt($c,CURLOPT_POST,TRUE);
	curl_setopt($c,CURLOPT_POSTFIELDS,http_build_query($post,'','&'));

	if($session !== FALSE) {
		curl_setopt($c,CURLOPT_COOKIE,sprintf("n_session=%s; ",$session));

	}

	curl_setopt($c,CURLOPT_RETURNTRANSFER,TRUE);
	return curl_exec($c);

}


///////////////////////////////////////////////////////////////////////////////


header("Content-type: text");

#
# Logujemy.
#
$trylogin = curl('login',array(

	'username' => $_config['username'],
	'password' => $_config['password']

));

if(intval(substr($trylogin,9,12)) !== 200) {

	die("Nie zalogowano.\r\n\r\n" . $trylogin);
}

#
# Pobieramy identyfikator sesji.
#
$session_key = NULL;
preg_match("/Set-Cookie.*n_session=([a-zA-Z0-9]+)\;/",$trylogin,$session_key);
$session_key = $session_key[1];

#
# Pobieramy operacje.
#
$operations = curl('get',array(
	'query' => '!last'
),$session_key);

if(intval(substr($operations,9,12)) !== 200) {

	die("Nie pobrano operacji.\r\n\r\n" . $trylogin);
}

$length = NULL;
preg_match("/Content-Length: (\d+)/",$operations,$length);
$length = (int) $length[1];

$operations = substr($operations,-$length);
$operations = json_decode($operations);

#
# Wyswietlamy pobrane operacje.
#
print_r($operations);

#
# Wylogowujemy.
#
$trylogout = curl('logout',array(),$session_key);

if(intval(substr($trylogout,9,12)) !== 200) {

	die("Nie wylogowano.\r\n\r\n" . $trylogin);
}

exit;