Documentation

ANAFAPIClient
in package

Tags
license

MIT Client for ANAF APIs:

  • TVA Status
  • RO EFactura

Table of Contents

Properties

$Timeout  : float
$AccessToken  : AccessToken|null
$AuthenticatedAPIClient  : Client
$ErrorCallback  : callable|null
$LockToken  : bool
$OAuthConfig  : array<string|int, mixed>
$Production  : bool
$PublicAPIClient  : Client
$TokenFilePath  : string

Methods

__construct()  : mixed
CheckTVAStatus()  : TVAResponse
Check if a company is registered for TVA
DoEntityFetch()  : EntityResponse
Base method for fetching company/institution data from ANAF
DownloadAndExtractAnswer()  : ExtractedAnswer
Uses DownloadAnswer to get the zip file and then extracts it to check for errors, optionally verifies the signature of the answer)
GetAccessToken()  : AccessToken|null
Gets the current access token (if it exists), tries to load it from the file if necessary
GetAnswerPage()  : InternalPagedAnswersResponse
Call the paged answer list endpoint with a speicifc page number
GetEntity()  : EntityResponse
Get company/institution data from ANAF
GetLoginURL()  : string
Helper method for the initial OAuth2 login
HasAccessToken()  : bool
Check if the client has a valid access token.
HasSuggestedExtensionSupport()  : bool
Check if the client has support for answer extraction (libxml, openssl, dom)
IsProduction()  : bool
ListAnswers()  : ANAFAnswerListResponse
Get answer list for a company (authenticated user must have access to the company!)
ListAnswersWithPagination()  : PagedAnswerListResponse
Get answer list for a company (authenticated user must have access to the company!) Uses the paged API end point Answers will be returned in a unified list
LoadAccessToken()  : AccessToken|null
Loads the access token from the file specified in TokenFilePath
ProcessOAuthCallback()  : AccessToken|null
Gets the access token from ANAF, should be called from the OAuth callback script
RefreshAccessToken()  : bool
Refresh the access token using the refresh token
RemoveSchemaLocationAttribute()  : string
Removes the xsi:schemaLocation attribute from the root element of the UBL XML
TokenWillExpireSoon()  : bool|null
Checks if the current access token will expire soon
UBL2PDF()  : string|false
Convert UBL XML to PDF using the ANAF API
UploadEFactura()  : UBLUploadResponse
ValidateCIF()  : bool
Verifies a CUI given the official checksum algorithm
VerifyXML()  : ANAFVerifyResponse
ATTENTION DOES NOT FUNCTION RELIABLY. The API randomly returns "nok" for valid invoices.
CallErrorCallback()  : void
Calls ErrorCallback with given params.
DownloadAnswer()  : string
Download Answer from ANAF To obtain the ID, use ListAnswers
GetOAuthProvider()  : GenericProvider
Creates a new instance of the OAuth2 provider based on the configuration specified in the constructor
SanitizeCUI()  : string|false
Sanitize CUI input for most requests. Requests to the API should not contain the "RO" prefix and should be numeric. This method is case-insensitive.
SaveAccessToken()  : void
Saves access token to TokenFilePath
SendANAFRequest()  : ResponseInterface
All requests to ANAF are made through this method

Properties

$Timeout

public float $Timeout = 5

Outgoing request timeout in seconds

$AuthenticatedAPIClient

private Client $AuthenticatedAPIClient

Guzzle Client for authenticated API requests

$LockToken

private bool $LockToken = false

Used to make sure test suit does not mutate the token

$Production

private bool $Production

If true, the client will use the production API otherwise will use testing API endpoints

$PublicAPIClient

private Client $PublicAPIClient

Guzzle Client for public API requests

$TokenFilePath

private string $TokenFilePath

Path to the file where the access token will be saved/loaded from Specified in @see ANAFAPIClient::__construct()

Methods

__construct()

public __construct(array<string|int, mixed> $OAuthConfig, bool $production[, callable|null $errorCallback = null ][, string|null $tokenFilePath = null ]) : mixed
Parameters
$OAuthConfig : array<string|int, mixed>

O Auth config for authenticated requests see README.md

$production : bool

If true, the client will use the production API otherwise will use testing API endpoints

$errorCallback : callable|null = null

The callable should have the following signature: function (string $message, ?Throwable $ex = null): void

$tokenFilePath : string|null = null

Path to the file where the access token will be saved/loaded from, if null the file will be called ANAFAccessToken.json in the same folder as this script

DownloadAndExtractAnswer()

Uses DownloadAnswer to get the zip file and then extracts it to check for errors, optionally verifies the signature of the answer)

public DownloadAndExtractAnswer(string $id, bool $verifySignature) : ExtractedAnswer
Parameters
$id : string
$verifySignature : bool
Return values
ExtractedAnswer

GetAccessToken()

Gets the current access token (if it exists), tries to load it from the file if necessary

public GetAccessToken() : AccessToken|null
Return values
AccessToken|null

GetLoginURL()

Helper method for the initial OAuth2 login

public GetLoginURL() : string
Return values
string

HasAccessToken()

Check if the client has a valid access token.

public HasAccessToken() : bool
Return values
bool

HasSuggestedExtensionSupport()

Check if the client has support for answer extraction (libxml, openssl, dom)

public static HasSuggestedExtensionSupport() : bool
Return values
bool

ListAnswers()

Get answer list for a company (authenticated user must have access to the company!)

public ListAnswers(int $cif[, int $days = 60 ][, AnswerFilter|null $filter = null ][, bool $usePaginationIfNeeded = false ][, float|int $endDateOffsetForPagination = 5 * 60 ]) : ANAFAnswerListResponse
Parameters
$cif : int
$days : int = 60

Number of days to look back

$filter : AnswerFilter|null = null
$usePaginationIfNeeded : bool = false

If true and the answer has LastError code ANAFException::MESSAGE_LIST_TOO_LONG, the method will try to fetch the answers using pagination

$endDateOffsetForPagination : float|int = 5 * 60

ANAF API gives an error if the end date is "in the future" based on their internal clock, so end date will be currentTime-$endDateOffsetForPagination. Default is 5 minutes

Tags
see
ANAFAPIClient::ListAnswersWithPagination()
Return values
ANAFAnswerListResponse

ListAnswersWithPagination()

Get answer list for a company (authenticated user must have access to the company!) Uses the paged API end point Answers will be returned in a unified list

public ListAnswersWithPagination(int $startTime, int $endTime, int $cif[, int|null $specificPage = null ][, AnswerFilter|null $filter = null ]) : PagedAnswerListResponse
Parameters
$startTime : int
$endTime : int
$cif : int
$specificPage : int|null = null
$filter : AnswerFilter|null = null
Return values
PagedAnswerListResponse

LoadAccessToken()

Loads the access token from the file specified in TokenFilePath

public LoadAccessToken([bool $autoRefresh = true ]) : AccessToken|null
Parameters
$autoRefresh : bool = true

if true, the token will be refreshed if it has expired

Tags
see
ANAFAPIClient::$TokenFilePath

Note: This will be called automatically by @see ANAFAPIClient::SendANAFRequest() if the token is not already loaded and the request requires it.

Return values
AccessToken|null

ProcessOAuthCallback()

Gets the access token from ANAF, should be called from the OAuth callback script

public ProcessOAuthCallback(string $authCode) : AccessToken|null
Parameters
$authCode : string
Tags
throws
IdentityProviderException
Return values
AccessToken|null

RefreshAccessToken()

Refresh the access token using the refresh token

public RefreshAccessToken([AccessToken|null $token = null ]) : bool
Parameters
$token : AccessToken|null = null

if null the current access token @see ANAFAPIClient::$AccessToken will be used.

Return values
bool

RemoveSchemaLocationAttribute()

Removes the xsi:schemaLocation attribute from the root element of the UBL XML

public static RemoveSchemaLocationAttribute(mixed $xmlString) : string
Parameters
$xmlString : mixed
Return values
string

TokenWillExpireSoon()

Checks if the current access token will expire soon

public TokenWillExpireSoon([int $soon = 3600 * 24 ]) : bool|null
Parameters
$soon : int = 3600 * 24

Time in seconds to consider "soon" Default value is 24 hours

Return values
bool|null

Null if the token is not set or does not have an expiration date

UBL2PDF()

Convert UBL XML to PDF using the ANAF API

public UBL2PDF(string $ubl, string $metadata[, bool $authenticated = true ][, float|null $timeoutOverride = null ]) : string|false
Parameters
$ubl : string
$metadata : string
$authenticated : bool = true

if true the request will use the OAuth2 API endpoint

$timeoutOverride : float|null = null

if set, will override the default timeout (ANAFAPIClient::$Timeout)

Return values
string|false

UploadEFactura()

public UploadEFactura(string $ubl, string $sellerCIF[, bool $extern = false ][, bool $autoFactura = false ]) : UBLUploadResponse
Parameters
$ubl : string

UBL XML content to upload

$sellerCIF : string

CUI of the company which issued the invoice

$extern : bool = false

If true, the invoice is marked as "extern" (not issued to a romanian company)

$autoFactura : bool = false

If true, the invoice is marked as "autofactura" (issued by the buyer in the sellers name)

Return values
UBLUploadResponse

ValidateCIF()

Verifies a CUI given the official checksum algorithm

public static ValidateCIF(string|false $cif) : bool
Parameters
$cif : string|false
Return values
bool

VerifyXML()

ATTENTION DOES NOT FUNCTION RELIABLY. The API randomly returns "nok" for valid invoices.

public VerifyXML(string $ubl[, bool $authenticated = true ]) : ANAFVerifyResponse

Use at your own risk. Read the comment above.

Parameters
$ubl : string
$authenticated : bool = true

If true, the request will use the OAuth2 API endpoint

Return values
ANAFVerifyResponse

CallErrorCallback()

Calls ErrorCallback with given params.

private CallErrorCallback(string $message[, Throwable|null $ex = null ]) : void
Parameters
$message : string
$ex : Throwable|null = null
Tags
see
ANAFAPIClient::$ErrorCallback

DownloadAnswer()

Download Answer from ANAF To obtain the ID, use ListAnswers

private DownloadAnswer(string $id) : string
Parameters
$id : string
Tags
see
ANAFAPIClient::ListAnswers()
Return values
string

either an error message (starts with "ERROR_") or zip file content

GetOAuthProvider()

Creates a new instance of the OAuth2 provider based on the configuration specified in the constructor

private GetOAuthProvider() : GenericProvider
Return values
GenericProvider

SanitizeCUI()

Sanitize CUI input for most requests. Requests to the API should not contain the "RO" prefix and should be numeric. This method is case-insensitive.

private SanitizeCUI(string $cui) : string|false
Parameters
$cui : string
Return values
string|false

Will return false if the input contains non-numeric other than the "RO" prefix

SendANAFRequest()

All requests to ANAF are made through this method

private SendANAFRequest(string $Method[, string|null $body = null ][, array<string|int, mixed>|null $queryParams = null ][, bool $hasAuth = false ][, string $contentType = "application/json" ][, float|null $timeoutOverride = null ]) : ResponseInterface
Parameters
$Method : string

The URL

$body : string|null = null

The request body (if this is different from null, the request will be a POST request)

$queryParams : array<string|int, mixed>|null = null

Query parameters (if teh value is ["ex1"=>"val"] ?ex1=val will be appended to the URL)

$hasAuth : bool = false

Should be true of the request requires authentication

$contentType : string = "application/json"

Content type header for the outgoing request

$timeoutOverride : float|null = null

if set, will override the default timeout (ANAFAPIClient::$Timeout)

Tags
throws
GuzzleException
Return values
ResponseInterface
On this page

Search results