Search by

hefeus / asaas-sdk

tal_de_yuri

This is my package asaas-sdk

Package info

github.com/hefeus/asaas-sdk

pkg:composer/hefeus/asaas-sdk

Fund package maintenance!

hefeus

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0 2026-09-21 01:08 UTC

This package is auto-updated.

Last update: 2026-09-21 01:31:14 UTC


README

Latest Version on Packagist Total Downloads

SDK Laravel não oficial para a API do Asaas, com uma fluent facade, DTOs tipados para request/response e paginação nativa.

Instalação

composer require hefeus/asaas-sdk

Publique o arquivo de configuração:

php artisan vendor:publish --tag="asaas-sdk-config"

Isso cria config/asaas.php:

return [
    'api_key' => env('ASAAS_API_KEY'),
    'environment' => env('ASAAS_ENVIRONMENT', 'sandbox'),
    'webhook_token' => env('ASAAS_WEBHOOK_TOKEN'),
    'api_urls' => [
        'sandbox' => 'https://sandbox.asaas.com/api/v3',
        'production' => 'https://www.asaas.com/api/v3',
    ],
];

Adicione as variáveis no .env:

ASAAS_API_KEY=sua_chave_de_api
ASAAS_ENVIRONMENT=sandbox
ASAAS_WEBHOOK_TOKEN=

Uso básico

Via facade:

use Hefeus\Asaas\Facades\Asaas;

$customer = Asaas::customers()->create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);

Ou instanciando diretamente (útil para usar múltiplas contas/ambientes):

use Hefeus\Asaas\Asaas;

$asaas = new Asaas(apiKey: 'sua_chave', environment: 'production');

$asaas->payments()->find('pay_000000000001');

Cada recurso (customers(), payments()) devolve um Resource com métodos que mapeiam diretamente para os endpoints da API. Métodos de criação/atualização recebem um array de atributos, validam/normalizam via um DataObject interno e retornam um objeto de resposta tipado (Entity).

Erros de API (respostas com falha HTTP) lançam Hefeus\Asaas\Exceptions\AsaasApiException.

Endpoints mapeados

Clientes — Asaas::customers()

Método SDK HTTP Endpoint Asaas Retorno Referência
create(array $attributes) POST /customers CustomerResponse Criar novo cliente
find(string $id) GET /customers/{id} CustomerResponse Recuperar um único cliente
update(string $id, array $attributes) PUT /customers/{id} CustomerResponse Atualizar cliente existente
delete(string $id) DELETE /customers/{id} bool Remover cliente
list(array $filters = []) GET /customers AsaasPaginator<CustomerResponse> Listar clientes
restore(string $id) POST /customers/{id}/restore CustomerResponse Restaurar cliente removido
notifications(string $id) GET /customers/{id}/notifications AsaasPaginator<NotificationResponse> Recuperar notificações de um cliente

Exemplos:

// Criar
$customer = Asaas::customers()->create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'cpfCnpj' => '24971563792',
]);

// Buscar
$customer = Asaas::customers()->find('cus_000005113026');

// Atualizar
$customer = Asaas::customers()->update('cus_000005113026', [
    'name' => 'John Doe Updated',
]);

// Remover
$deleted = Asaas::customers()->delete('cus_000005113026'); // bool

// Listar (paginado)
$page = Asaas::customers()->list(['limit' => 50, 'offset' => 0]);
foreach ($page as $customer) {
    // $customer é um CustomerResponse
}
$page->hasMore;     // bool
$page->totalCount;  // int
$page->nextOffset(); // int|null

// Restaurar
$customer = Asaas::customers()->restore('cus_000005113026');

// Notificações do cliente
$notifications = Asaas::customers()->notifications('cus_000005113026');

Cobranças (Payments) — Asaas::payments()

Método SDK HTTP Endpoint Asaas Retorno Referência
create(array $attributes) POST /payments PaymentResponse Criar nova cobrança
createWithCreditCard(array $attributes) POST /payments PaymentResponse Criar cobrança com cartão de crédito
list(array $filters = []) GET /payments AsaasPaginator<PaymentResponse> Listar cobranças
find(string $id) GET /payments/{id} PaymentResponse Recuperar uma única cobrança
update(string $id, array $attributes) POST /payments/{id} PaymentResponse Atualizar cobrança existente
delete(string $id) DELETE /payments/{id} PaymentDeletedResponse Excluir cobrança
restore(string $id) POST /payments/{id}/restore PaymentResponse Restaurar cobrança removida
status(string $id) GET* /payments/{id}/status PaymentStatusResponse Recuperar status de uma cobrança
billingInfo(string $id) GET /payments/{id}/billingInfo BillingInfoResponse Recuperar informações de pagamento de uma cobrança
viewingInfo(string $id) GET /payments/{id}/viewingInfo ViewingInfoResponse Informações sobre visualização da cobrança
identificationField(string $id) GET* /payments/{id}/identificationField IdentificationFieldResponse Obter linha digitável do boleto
pixQrCode(string $id) GET /payments/{id}/pixQrCode Pix Obter QR Code para pagamentos via Pix
receiveInCash(array $attributes, string $id) POST /payments/{id}/receiveInCash PaymentResponse Confirmar recebimento em dinheiro
undoReceivedInCash(string $id) POST /payments/{id}/undoReceivedInCash PaymentResponse Desfazer confirmação de recebimento em dinheiro
payWithCard(array $attributes, string $id) POST /payments/{id}/payWithCard PaymentResponse Pagar uma cobrança com cartão

Exemplos:

// Criar cobrança (boleto/pix/undefined)
$payment = Asaas::payments()->create([
    'customer' => 'cus_000005113026',
    'billingType' => 'BOLETO',
    'value' => 100.00,
    'dueDate' => '2025-12-30',
]);

// Criar cobrança já pagando com cartão de crédito
$payment = Asaas::payments()->createWithCreditCard([
    'customer' => 'cus_000005113026',
    'billingType' => 'CREDIT_CARD',
    'value' => 100.00,
    'dueDate' => '2025-12-30',
    'creditCard' => [
        'holderName' => 'John Doe',
        'number' => '5162306219378829',
        'expiryMonth' => '05',
        'expiryYear' => '2030',
        'ccv' => '318',
    ],
    'creditCardHolderInfo' => [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'cpfCnpj' => '24971563792',
        'postalCode' => '01310-000',
        'addressNumber' => '100',
        'phone' => '4738010919',
    ],
]);

// Listar
$page = Asaas::payments()->list(['customer' => 'cus_000005113026']);

// Buscar
$payment = Asaas::payments()->find('pay_000000000001');

// Atualizar
$payment = Asaas::payments()->update('pay_000000000001', [
    'value' => 150.00,
]);

// Excluir / restaurar
$deleted = Asaas::payments()->delete('pay_000000000001');   // PaymentDeletedResponse
$payment = Asaas::payments()->restore('pay_000000000001');

// Status e linha digitável
$status = Asaas::payments()->status('pay_000000000001');
$field = Asaas::payments()->identificationField('pay_000000000001');

// Informações de pagamento e visualização
$billingInfo = Asaas::payments()->billingInfo('pay_000000000001');
$viewingInfo = Asaas::payments()->viewingInfo('pay_000000000001');

// QR Code Pix
$pix = Asaas::payments()->pixQrCode('pay_000000000001');

// Recebimento em dinheiro
$payment = Asaas::payments()->receiveInCash([
    'paymentDate' => '2025-12-30',
    'value' => 100.00,
    'notifyCustomer' => true,
], 'pay_000000000001');

$payment = Asaas::payments()->undoReceivedInCash('pay_000000000001');

// Pagar cobrança existente com cartão
$payment = Asaas::payments()->payWithCard([
    'cardType' => 'CREDIT',
    'card' => [
        'holderName' => 'John Doe',
        'number' => '5162306219378829',
        'expiryMonth' => '05',
        'expiryYear' => '2030',
        'ccv' => '318',
    ],
], 'pay_000000000001');

Assinaturas (Subscriptions) — Asaas::subscriptions()

Método SDK HTTP Endpoint Asaas Retorno Referência
create(array $attributes) POST /subscriptions SubscriptionResponse Criar nova assinatura
createWithCreditCard(array $attributes) POST /subscriptions SubscriptionResponse Criar assinatura com cartão de crédito
find(string $id) GET /subscriptions/{id} SubscriptionResponse Recuperar uma única assinatura
update(string $id, array $attributes) PUT /subscriptions/{id} SubscriptionResponse Atualizar assinatura existente
delete(string $id) DELETE /subscriptions/{id} DeletedResponse Remover assinatura
list(array $filters = []) GET /subscriptions AsaasPaginator<SubscriptionResponse> Listar assinaturas
listPayments(string $id, array $filters = []) GET /subscriptions/{id}/payments AsaasPaginator<PaymentResponse> Listar cobranças de uma assinatura
updateCreditCard(string $id, array $attributes) PUT /subscriptions/{id}/creditCard SubscriptionResponse Atualizar cartão de crédito da assinatura

Exemplos:

// Criar assinatura (boleto/pix/undefined)
$subscription = Asaas::subscriptions()->create([
    'customer' => 'cus_000005113026',
    'billingType' => 'BOLETO',
    'value' => 100.00,
    'nextDueDate' => '2025-12-30',
    'cycle' => 'MONTHLY',
]);

// Criar assinatura já paga com cartão de crédito (tokenizado ou completo)
$subscription = Asaas::subscriptions()->createWithCreditCard([
    'customer' => 'cus_000005113026',
    'billingType' => 'CREDIT_CARD',
    'value' => 100.00,
    'nextDueDate' => '2025-12-30',
    'cycle' => 'MONTHLY',
    'creditCard' => [
        'holderName' => 'John Doe',
        'number' => '5162306219378829',
        'expiryMonth' => '05',
        'expiryYear' => '2030',
        'ccv' => '318',
    ],
    'creditCardHolderInfo' => [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'cpfCnpj' => '24971563792',
        'postalCode' => '01310-000',
        'addressNumber' => '100',
        'phone' => '4738010919',
    ],
]);

// Buscar
$subscription = Asaas::subscriptions()->find('sub_000000000001');

// Atualizar (apenas os campos enviados são alterados)
$subscription = Asaas::subscriptions()->update('sub_000000000001', [
    'value' => 150.00,
]);

// Remover
$deleted = Asaas::subscriptions()->delete('sub_000000000001'); // DeletedResponse

// Listar (paginado)
$page = Asaas::subscriptions()->list(['customer' => 'cus_000005113026', 'status' => 'ACTIVE']);

// Cobranças geradas pela assinatura (paginado)
$payments = Asaas::subscriptions()->listPayments('sub_000000000001', ['status' => 'RECEIVED']);

// Trocar o cartão de crédito da assinatura, sem gerar cobrança imediata
$subscription = Asaas::subscriptions()->updateCreditCard('sub_000000000001', [
    'creditCard' => [
        'holderName' => 'John Doe',
        'number' => '5162306219378829',
        'expiryMonth' => '05',
        'expiryYear' => '2030',
        'ccv' => '318',
    ],
    'creditCardHolderInfo' => [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'cpfCnpj' => '24971563792',
        'postalCode' => '01310-000',
        'addressNumber' => '100',
        'phone' => '4738010919',
    ],
]);

DTOs e Entities

  • Data\* — objetos de request, validam/normalizam o array de entrada antes de enviar à API (ex.: CreateSubscriptionData, UpdateCustomerData).
  • Entities\* — objetos de response, hidratados a partir do JSON retornado pela API (ex.: PaymentResponse, CustomerResponse).
  • AsaasPaginator — encapsula respostas paginadas (data, hasMore, totalCount, limit, offset), implementa Countable e IteratorAggregate (pode ser percorrido em foreach).

Objetos aninhados com tipo de classe único (ex.: ?CreditCard $creditCard) são hidratados automaticamente a partir de arrays. Campos de lista (ex.: split, refunds, refundedSplits) são marcados com o atributo #[CollectionOf(Split::class)] e também são hidratados individualmente — cada item do array vira uma instância da entidade correspondente, tanto na leitura (fromArray) quanto na serialização de volta (toArray).

Tratamento de erros

Qualquer resposta HTTP de falha (4xx/5xx) da API do Asaas lança Hefeus\Asaas\Exceptions\AsaasApiException, assim como a ausência da API key configurada.

use Hefeus\Asaas\Exceptions\AsaasApiException;

try {
    Asaas::payments()->find('pay_inexistente');
} catch (AsaasApiException $e) {
    // $e->getMessage(), erros da API, etc.
}

Problemas conhecidos (a verificar)

  • PaymentResource::status() e PaymentResource::identificationField() chamam a API via POST, mas a documentação oficial do Asaas define esses endpoints como GET. Validar contra a API antes de depender desses métodos em produção.

Testes

composer test

Changelog

Consulte o CHANGELOG para mais informações sobre o que mudou recentemente.

Licença

MIT. Veja o arquivo de licença para mais informações.