PHP code example of greenter / consulta-cpe

1. Go to this page and download the library: Download greenter/consulta-cpe library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

greenter / consulta-cpe example snippets




$apiInstance = new \Greenter\Sunat\ConsultaCpe\Api\AuthApi(
    new \GuzzleHttp\Client()
);

$grant_type = 'client_credentials'; // Constante
$scope = 'https://api.sunat.gob.pe/v1/contribuyente/contribuyentes'; // Constante
$client_id = 'client_id_example'; // client_id generado en menú sol
$client_secret = 'client_secret_example'; // client_secret generado en menú sol

try {
    $result = $apiInstance->getToken($grant_type, $scope, $client_id, $client_secret);
        
    echo 'Token: '.$result->getAccessToken().PHP_EOL;
    echo 'Expira: '.$result->getExpiresIn().' segundos'.PHP_EOL;
} catch (Exception $e) {
    echo 'Excepcion cuando invocaba AuthApi->getToken: ', $e->getMessage(), PHP_EOL;
}



// Token generado en el ejemplo anterior
$token = 'xxxxxxxx';

$config = \Greenter\Sunat\ConsultaCpe\Configuration::getDefaultConfiguration()->setAccessToken($token);

$apiInstance = new \Greenter\Sunat\ConsultaCpe\Api\ConsultaApi(
    new GuzzleHttp\Client(),
    $config->setHost($config->getHostFromSettings(1))
);
$ruc = '20000000001'; // RUC de quién realiza la consulta

$cpeFilter = (new \Greenter\Sunat\ConsultaCpe\Model\CpeFilter())
            ->setNumRuc('20000000001') // RUC del emisor
            ->setCodComp('01') // Tipo de comprobante
            ->setNumeroSerie('F001')
            ->setNumero('1')
            ->setFechaEmision('20/10/2020')
            ->setMonto('100.00');

try {
    $result = $apiInstance->consultarCpe($ruc, $cpeFilter);
    if (!$result->getSuccess()) {
        echo $result->getMessage();
        return;
    }

    $data = $result->getData();
    switch ($data->getEstadoCp()) {
        case '0': echo 'NO EXISTE'; break;
        case '1': echo 'ACEPTADO'; break;
        case '2': echo 'ANULADO'; break;
        case '3': echo 'AUTORIZADO'; break;
        case '4': echo 'NO AUTORIZADO'; break;
    }

    echo PHP_EOL.'Estado RUC: '.$data->getEstadoRuc();
    echo PHP_EOL.'Condicion RUC: '.$data->getCondDomiRuc();

} catch (Exception $e) {
    echo 'Excepcion cuando invocaba ConsultaApi->consultarCpe: ', $e->getMessage(), PHP_EOL;
}