PHP code example of am2tec / payment-api-sdk

1. Go to this page and download the library: Download am2tec/payment-api-sdk 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/ */

    

am2tec / payment-api-sdk example snippets


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' => '[email protected]',
        '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']);

// 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' => '[email protected]', 'cpf' => '123.456.789-00'],
]);

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

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

// 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');

// 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' => '[email protected]',
        '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' => '[email protected]', '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

// 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, ...]

use App\Http\Controllers\PaymentWebhookController;

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

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
        }
    }
}

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

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();
}
bash
php artisan vendor:publish --tag=payment-api-config