Search by

fabianobn / laravel-asaas-api-v3

fabianobn

Pacote de integração Asaas API v3 para Laravel 9+

Package info

github.com/fabianobn/laravel-asaas-api-v3

pkg:composer/fabianobn/laravel-asaas-api-v3

Statistics

Installs: 7

Dependents: 0

Suggesters: 0

Stars: 0

v2.0.0 2026-09-09 18:14 UTC

This package is auto-updated.

Last update: 2026-09-09 18:38:43 UTC


README

Pacote de integração com a API Asaas v3 para Laravel 9+.

Requisitos

  • PHP 8.1+
  • Laravel 9, 10, 11 ou 12
  • Guzzle 7

Instalação

composer require fabianobn/laravel-asaas-api-v3

Testes

# Unitários (mock, sem rede) — padrão
composer test

# Integração com sandbox Asaas
cp .env.example .env
# edite ASAAS_API_KEY=$aact_hmlg_...

composer test:integration

# Ou sem .env:
ASAAS_API_KEY='$aact_hmlg_...' ASAAS_ENVIRONMENT=sandbox composer test:integration

Publique o config (opcional):

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

Configuração

No .env:

ASAAS_ENVIRONMENT=sandbox
ASAAS_API_KEY=$aact_hmlg_xxxxxxxx
ASAAS_USER_AGENT="MeuApp/1.0 (Laravel; sandbox)"
Ambiente Base URL Prefixo da chave
sandbox https://api-sandbox.asaas.com/v3 $aact_hmlg_
production https://api.asaas.com/v3 $aact_prod_

Autenticação via header access_token (não use Authorization: Bearer).
Contas criadas após 13/06/2024 exigem User-Agent.

Uso

Facade

use Asaas\Api\Facades\Asaas;

$cliente = Asaas::customers()->create([
    'name' => 'John Doe',
    'cpfCnpj' => '24971563792',
    'email' => 'john.doe@asaas.com.br',
]);

$cobranca = Asaas::payments()->create([
    'customer' => $cliente['id'],
    'billingType' => 'PIX', // BOLETO | CREDIT_CARD | PIX | UNDEFINED
    'value' => 100.00,
    'dueDate' => now()->addDays(3)->format('Y-m-d'),
    'description' => 'Pedido 123',
]);

$pix = Asaas::payments()->pixQrCode($cobranca['id']);
// $pix['encodedImage'], $pix['payload']

Injeção de dependência

use Asaas\Api\Asaas;

public function __construct(private Asaas $asaas)
{
}

public function store()
{
    return $this->asaas->customers()->create([...]);
}

Aliases 1.x (compatibilidade)

$asaas = app(Asaas::class);
$asaas->cliente->create([...]);   // = customers()
$asaas->cobranca->create([...]);  // = payments()

Métodos antigos como index() / get($id) mudaram para list() / getById($id).
A resposta agora é um array JSON (não mais stream Guzzle).

Recursos

Customers (/v3/customers)

list, getById, create, update, deleteById, restore, notifications

Payments (/v3/payments)

list, getById, create, createWithCreditCard, update, deleteById, restore,
status, refund, identificationField, pixQrCode, billingInfo, viewingInfo,
receiveInCash, undoReceivedInCash, payWithCreditCard, captureAuthorizedPayment,
simulate, limits

Subscriptions (/v3/subscriptions)

list, getById, create, createWithCreditCard, update, deleteById,
updateCreditCard, payments, paymentBook,
createInvoiceSettings, getInvoiceSettings, updateInvoiceSettings, deleteInvoiceSettings, invoices

Notifications (/v3/notifications)

update, updateBatch

Pix (/v3/pix/...)

Chaves: listAddressKeys, getAddressKey, createAddressKey, deleteAddressKey, checkExternalAddressKey, addressKeyTokenBucket
QR Codes: createStaticQrCode, deleteStaticQrCode, decodeQrCode, payQrCode
Transações: listTransactions, getTransaction, cancelTransaction
Automático: listAuthorizations, getAuthorization, createAuthorization, cancelAuthorization, listPaymentInstructions, getPaymentInstruction, retryPaymentInstruction
Recorrências: listRecurrings, getRecurring, cancelRecurring, listRecurringItems, cancelRecurringItem

Payment Links (/v3/paymentLinks)

list, getById, create, update, deleteById, restore,
listImages, getImage, addImage, deleteImage, setMainImage

Webhooks (/v3/webhooks)

list, getById, create, update, deleteById, removeBackoff, validateAccessToken

Webhook authToken (receber eventos)

Ao criar/atualizar o webhook, envie authToken (32–255 chars). O Asaas devolve o valor só na criação — guarde em ASAAS_WEBHOOK_TOKEN.

Em cada POST para o seu endpoint, o Asaas envia:

asaas-access-token: whsec_...

Validação manual

use Asaas\Api\Facades\Asaas;
use Asaas\Api\Webhooks\AccessToken;

Route::post('/webhooks/asaas', function (Request $request) {
    AccessToken::assertValid($request->header(AccessToken::HEADER));

    // ou:
    // if (! Asaas::webhooks()->validateAccessToken($request->header('asaas-access-token'))) {
    //     abort(401);
    // }

    // persista $request->input('id') (idempotência) e responda 200 rápido
    return response()->json(['received' => true]);
});

Middleware Laravel

use Asaas\Api\Http\Middleware\VerifyAsaasWebhookToken;

Route::post('/webhooks/asaas', WebhookController::class)
    ->middleware(VerifyAsaasWebhookToken::class);
ASAAS_WEBHOOK_TOKEN=whsec_seu_token_salvo_na_criacao

Exceções

use Asaas\Api\Exceptions\AsaasException;
use Asaas\Api\Exceptions\AuthenticationException;
use Asaas\Api\Exceptions\ValidationException;

try {
    Asaas::payments()->create($payload);
} catch (ValidationException $e) {
    // HTTP 400 — $e->getErrors()
} catch (AuthenticationException $e) {
    // HTTP 401 ou API key ausente
} catch (AsaasException $e) {
    // demais erros da API
}

Exemplo: assinatura

Asaas::subscriptions()->create([
    'customer' => 'cus_xxx',
    'billingType' => 'BOLETO',
    'value' => 49.90,
    'nextDueDate' => now()->format('Y-m-d'),
    'cycle' => 'MONTHLY', // WEEKLY, BIWEEKLY, MONTHLY, BIMONTHLY, QUARTERLY, SEMIANNUALLY, YEARLY
    'description' => 'Plano Pro',
]);

Exemplo: Pix

// Chave aleatória (EVP)
$chave = Asaas::pix()->createAddressKey(['type' => 'EVP']);

// QR Code estático
$qr = Asaas::pix()->createStaticQrCode([
    'addressKey' => $chave['key'],
    'description' => 'Doação',
    'value' => 50,
    'format' => 'ALL',
]);

// Decodificar / pagar QR Code
$decoded = Asaas::pix()->decodeQrCode(['payload' => $qr['payload']]);
Asaas::pix()->payQrCode([
    'qrCode' => ['payload' => $qr['payload']],
    'value' => 50,
]);

Exemplo: Payment Link

$link = Asaas::paymentLinks()->create([
    'name' => 'Venda de livros',
    'description' => 'Qualquer livro por R$ 50',
    'billingType' => 'UNDEFINED', // UNDEFINED | BOLETO | CREDIT_CARD | PIX
    'chargeType' => 'DETACHED',   // DETACHED | RECURRENT | INSTALLMENT
    'value' => 50,
]);

Asaas::paymentLinks()->addImage($link['id'], storage_path('app/cover.png'), true);
// $link['url']

Upgrade da 1.x

  1. PHP 8.1+ e Laravel 9+
  2. Configure ASAAS_ENVIRONMENT + ASAAS_API_KEY (URLs antigas www.asaas.com/api/v3 foram removidas)
  3. Troque form_params mentalmente por JSON — o pacote já envia application/json
  4. Troque decode manual do body por uso direto do array retornado
  5. Prefira customers() / payments() em vez de cliente / cobranca

Créditos

Baseado no trabalho original de Rafael Xavier.
API alinhada à documentação oficial Asaas.