PHPackages                             am2tec/payment-api-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. am2tec/payment-api-sdk

ActiveLibrary[Payment Processing](/categories/payments)

am2tec/payment-api-sdk
======================

Laravel SDK for the am2tec payment\_api centralized payment gateway.

1.4.1(1mo ago)010MITPHPPHP ^8.2

Since May 21Pushed 1mo agoCompare

[ Source](https://github.com/alberto-morais-oliveira-f/paymnet_api_sdk)[ Packagist](https://packagist.org/packages/am2tec/payment-api-sdk)[ RSS](/packages/am2tec-payment-api-sdk/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (10)Versions (4)Used By (0)

Payment API SDK
===============

[](#payment-api-sdk)

PHP SDK para integração com a Payment API (`am2tec/payment-api`).

Instalação
----------

[](#instalação)

```
composer require am2tec/payment-api-sdk
```

Publicar configuração:

```
php artisan vendor:publish --tag=payment-api-config
```

Configuração
------------

[](#configuração)

```
PAYMENT_API_URL=https://api.seudominio.com
PAYMENT_API_KEY=sk_live_seu_token_aqui
PAYMENT_API_WEBHOOK_SECRET=seu_webhook_secret
PAYMENT_API_TIMEOUT=30
PAYMENT_API_RETRY_TIMES=3
PAYMENT_API_RETRY_DELAY_MS=500
```

---

Uso
---

[](#uso)

### Cobranças únicas

[](#cobranças-únicas)

```
use Am2tec\PaymentApiSdk\Facades\PaymentApi;

// Criar cobrança
$charge = PaymentApi::charge()->create([
    'reference_id'  => 'pedido_123',
    'callback_url'  => 'https://app.com/webhooks/payment',
    'amount'        => 9900, // centavos
    'billing_type'  => 'PIX', // depende do provider — ver nota abaixo
    'customer'      => [
        'name'  => 'João Silva',
        'email' => 'joao@email.com',
        'cpf'   => '123.456.789-00',
    ],
]);

echo $charge->id;          // uuid
echo $charge->status;      // pending | confirmed | failed
echo $charge->checkoutUrl; // link de pagamento
echo $charge->pixCode;     // código PIX se billing_type=PIX

// Buscar
$charge = PaymentApi::charge()->find('uuid');

// Cancelar
$charge = PaymentApi::charge()->cancel('uuid');

// Reembolsar
PaymentApi::charge()->refund('uuid', ['amount' => 9900, 'reason' => 'Cancelamento']);

// Listar
$charges = PaymentApi::charge()->list(['status' => 'confirmed']);
```

> **`billing_type` varia por provider.** Use `provider()->capabilities($provider)`para descobrir o que cada gateway aceita:
>
> - **PIX** / **BOLETO**: Asaas, MercadoPago, Iugu, C6 Bank
> - **CREDIT\_CARD**: Asaas, MercadoPago, Iugu, Stripe (cartão transparente via `tokenization_js` do gateway)
> - **CARD**: C6 Bank (checkout transparente — ver seção abaixo)

### Cartão transparente (checkout transparente)

[](#cartão-transparente-checkout-transparente)

O cartão é criptografado no browser pelo SDK do gateway (PAN nunca chega ao servidor). Envie o hash/token em `billing_type=CARD`:

```
// Cobrança com cartão criptografado (hash do SDK) + salvar para reuso
$charge = PaymentApi::charge()->create([
    'provider'       => 'c6bank',
    'amount'         => 5000,
    'reference_id'   => 'pedido_card',
    'callback_url'   => 'https://app.com/webhooks/payment',
    'due_date'       => '2026-06-23',
    'billing_type'   => 'CARD',
    'encrypted_card' => $cardHashDoSdk, // OU 'card_token' => 'tok_salvo'
    'save_card'      => true,           // tokeniza p/ 1-clique / recorrência
    'authenticate'   => 'NOT_REQUIRED', // NOT_REQUIRED | OPTIONAL | REQUIRED
    'card_type'      => 'CREDIT',       // CREDIT | DEBIT
    'installments'   => 1,
    'customer'       => ['name' => 'João', 'email' => 'joao@email.com', 'cpf' => '123.456.789-00'],
]);

echo $charge->status;       // confirmed | failed | authorized
echo $charge->cardTokenId;  // uuid do cartão salvo (se save_card=true)
```

Para o checkout transparente do C6, busque a chave pública do SDK:

```
$session = PaymentApi::provider()->c6PublicKey(); // ['public_key' => ..., 'session_key' => ..., 'expires_in' => ...]
```

### Cartões salvos (tokenizados)

[](#cartões-salvos-tokenizados)

```
// Listar cartões salvos do tenant (nunca expõe o token cru)
$cards = PaymentApi::cardToken()->list();
foreach ($cards as $card) {
    echo "{$card->brand} •••• {$card->last4} ({$card->id})";
}

// Remover
PaymentApi::cardToken()->delete('ct_uuid');
```

### Assinaturas recorrentes

[](#assinaturas-recorrentes)

```
// Criar plano
$plan = PaymentApi::plan()->create([
    'name'     => 'Plano Mensal',
    'amount'   => 9900,
    'interval' => 'monthly', // monthly | yearly | weekly
    'provider' => 'asaas',
]);

// Criar assinatura
$sub = PaymentApi::subscription()->create([
    'plan_id'      => $plan->id,
    'reference_id' => 'cliente_456',
    'callback_url' => 'https://app.com/webhooks/payment',
    'customer'     => [
        'name'  => 'Maria Santos',
        'email' => 'maria@email.com',
        'cpf'   => '987.654.321-00',
    ],
]);

echo $sub->id;             // uuid
echo $sub->status;         // pending | active | trial | paused | cancelled
echo $sub->trialEndsAt;    // ISO8601 ou null
echo $sub->nextBillingDate;// YYYY-MM-DD ou null

// Assinatura cobrada por cartão salvo (gateways sem assinatura nativa, ex.: C6 —
// a recorrência é cobrada localmente reutilizando o cartão tokenizado)
$sub = PaymentApi::subscription()->create([
    'provider'      => 'c6bank',
    'amount_cents'  => 9900,
    'interval'      => 'monthly',
    'reference_id'  => 'aluno_789',
    'callback_url'  => 'https://app.com/webhooks/payment',
    'card_token_id' => $charge->cardTokenId, // OU 'card_token' => 'tok'
    'customer'      => ['name' => 'Maria', 'email' => 'maria@email.com', 'cpf' => '987.654.321-00'],
]);

// Buscar / cancelar / listar
$sub  = PaymentApi::subscription()->find('uuid');
$sub  = PaymentApi::subscription()->cancel('uuid');
$subs = PaymentApi::subscription()->list();

// Solicitar extensão de trial (enviado para fila de aprovação do admin)
$req = PaymentApi::subscription()->requestExtension(
    id: $sub->id,
    reason: 'Precisamos de mais tempo para avaliar o produto.' // opcional
);

echo $req->id;      // uuid do pedido
echo $req->status;  // pending
echo $req->message; // confirmação textual
```

### Gateways de pagamento

[](#gateways-de-pagamento)

```
// Configurar Asaas
PaymentApi::provider()->store('asaas', [
    'api_key'  => 'sua_chave_asaas',
    'base_url' => 'https://sandbox.asaas.com/api/v3',
]);

// Listar providers ativos
$providers = PaymentApi::provider()->list();

// Capabilities do gateway (renderizar o checkout correto no front)
$caps = PaymentApi::provider()->capabilities('c6bank');
// ['pix'=>true, 'transparent_card'=>true, 'tokenization_js'=>'c6', 'native_subscriptions'=>false, ...]
```

### Webhooks

[](#webhooks)

Configure a rota no seu `routes/web.php`:

```
use App\Http\Controllers\PaymentWebhookController;

Route::post('/webhooks/payment', PaymentWebhookController::class)
    ->middleware('payment-api.webhook'); // valida HMAC-SHA256
```

Crie o controller estendendo a base:

```
use Am2tec\PaymentApiSdk\Http\Controllers\PaymentApiWebhookController;
use Am2tec\PaymentApiSdk\Webhook\WebhookEvent;

class PaymentWebhookController extends PaymentApiWebhookController
{
    public function handle(WebhookEvent $event): void
    {
        if ($event->is('PAYMENT_RECEIVED')) {
            // cobrança confirmada
            $referenceId  = $event->referenceId;
            $amountCents  = $event->amountCents;
            $paidAt       = $event->paidAt;
        }

        if ($event->is('PAYMENT_OVERDUE')) {
            // cobrança vencida
        }
    }
}
```

Validação manual (sem middleware):

```
$event = PaymentApi::webhook()->validate(
    payload: $request->getContent(),
    signature: $request->header('X-Payment-Signature'),
);
```

---

Respostas
---------

[](#respostas)

### `ChargeResponse`

[](#chargeresponse)

CampoTipoDescrição`id``string`UUID da cobrança`status``string``pending` | `authorized` | `confirmed` | `failed``providerAlias``?string`Conta do gateway (multi-conta)`checkoutUrl``?string`Link de pagamento`pixCode``?string`Copia-e-cola PIX`amountCents``?int`Valor em centavos`cardTokenId``?string`UUID do cartão salvo (se `save_card=true`)### `CardTokenResponse`

[](#cardtokenresponse)

CampoTipoDescrição`id``string`UUID do cartão salvo`provider``string`Gateway de origem`brand``?string`Bandeira (VISA, ...)`last4``?string`Últimos 4 dígitos`expMonth` / `expYear``?string`Validade`isDefault``bool`Cartão padrão`lastUsedAt``?string`ISO8601### `SubscriptionResponse`

[](#subscriptionresponse)

CampoTipoDescrição`id``string`UUID da assinatura`status``string``pending` | `active` | `trial` | `paused` | `dunning` | `past_due` | `cancelled``providerSubscriptionId``?string`ID externo no gateway`referenceId``?string`Seu ID de referência`startedAt``?string`ISO8601`cancelledAt``?string`ISO8601`trialEndsAt``?string`ISO8601 — fim do trial`pausedAt``?string`ISO8601 — quando foi pausada`nextBillingDate``?string`YYYY-MM-DD — próxima cobrança### `ExtensionRequestResponse`

[](#extensionrequestresponse)

CampoTipoDescrição`id``string`UUID do pedido`status``string``pending` — aguarda análise admin`message``string`Confirmação textual> **Erro 422:** já existe pedido pendente para esta assinatura. Aguarde aprovação ou negação antes de criar novo.

---

Fluxo de Trial
--------------

[](#fluxo-de-trial)

```
SDK: subscription()->create()         → status = pending
API: webhook SUBSCRIPTION_ACTIVATED   → status = active ou trial
SDK: subscription()->requestExtension() → cria pedido na fila do admin
Admin: aprova → trial_ends_at += N dias
Admin: nega   → pedido.status = denied

```

---

Tratamento de Erros
-------------------

[](#tratamento-de-erros)

O SDK lança `Illuminate\Http\Client\RequestException` em respostas 4xx/5xx.

```
use Illuminate\Http\Client\RequestException;

try {
    $sub = PaymentApi::subscription()->cancel('uuid');
} catch (RequestException $e) {
    $status = $e->response->status(); // 404, 422, etc.
    $body   = $e->response->json();
}
```

---

Testes
------

[](#testes)

```
vendor/bin/phpunit
```

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance91

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~17 days

Total

3

Last Release

32d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9c73888302004cbc23517ec47f2891db5e61ad63f75c817c8c55a6b071bfa1c9?d=identicon)[Am2tec](/maintainers/Am2tec)

---

Top Contributors

[![alberto-morais-oliveira-f](https://avatars.githubusercontent.com/u/162183935?v=4)](https://github.com/alberto-morais-oliveira-f "alberto-morais-oliveira-f (6 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/am2tec-payment-api-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/am2tec-payment-api-sdk/health.svg)](https://phpackages.com/packages/am2tec-payment-api-sdk)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77922.3M186](/packages/laravel-mcp)[api-platform/laravel

API Platform support for Laravel

58174.6k17](/packages/api-platform-laravel)[fleetbase/core-api

Core Framework and Resources for Fleetbase API

1235.9k21](/packages/fleetbase-core-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
