PHPackages                             filipecacique/webpag-php - 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. [API Development](/categories/api)
4. /
5. filipecacique/webpag-php

ActiveLibrary[API Development](/categories/api)

filipecacique/webpag-php
========================

SDK PHP/Laravel para integração com a API WebPag

v1.1.3(1mo ago)0137MITPHPPHP &gt;=7.2CI passing

Since Jun 23Pushed 1mo agoCompare

[ Source](https://github.com/CaciqueFilipe/webpag-php)[ Packagist](https://packagist.org/packages/filipecacique/webpag-php)[ RSS](/packages/filipecacique-webpag-php/feed)WikiDiscussions main Synced 2w ago

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

WebPag PHP SDK
==============

[](#webpag-php-sdk)

SDK PHP para integração com a [API WebPag](https://api.webpag.com.br/docs). Compatível com **PHP puro (7.2+)** e **Laravel (5.8+)** — o Laravel é opcional.

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

[](#instalação)

```
composer require webpag/webpag-php
```

A dependência principal é apenas o **Guzzle**. O suporte a Laravel (`Service Provider` e `Facade`) é carregado automaticamente só quando o pacote é instalado em um projeto Laravel — em PHP puro, nada disso é necessário.

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

[](#configuração)

Obtenha sua chave API (`auth-token`) com o suporte WebPag.

### Configuração via variáveis de ambiente (recomendado)

[](#configuração-via-variáveis-de-ambiente-recomendado)

Defina as variáveis no seu ambiente ou arquivo `.env`:

```
WEBPAG_API_TOKEN=seu-token-aqui
WEBPAG_BASE_URL=https://api.webpag.com.br
WEBPAG_TIMEOUT=30
```

Depois é só usar:

```
use WebPag\WebPag;

$webpag = WebPag::env();
```

### Configuração via Environment (PHP puro)

[](#configuração-via-environment-php-puro)

```
use WebPag\WebPag;
use WebPag\Environment;

// A partir de um array
$webpag = WebPag::fromEnvironment(
    Environment::fromArray([
        'api_token' => 'seu-token-aqui',
        'base_url' => 'https://api.webpag.com.br',
        'timeout' => 30,
    ])
);

// Ou programaticamente
$env = new Environment();
$env->setApiToken('seu-token-aqui')
    ->setBaseUrl('https://api.webpag.com.br')
    ->setTimeout(30);

$webpag = WebPag::fromEnvironment($env);
```

### Configuração direta

[](#configuração-direta)

```
use WebPag\WebPag;

$webpag = WebPag::create('seu-token-aqui');
// ou com URL personalizada
$webpag = WebPag::create('seu-token-aqui', 'https://api.webpag.com.br');
```

### Uso em Laravel

[](#uso-em-laravel)

1. Publique a configuração:

```
php artisan vendor:publish --tag=webpag-config
```

2. Configure no `.env`:

```
WEBPAG_API_TOKEN=sua-chave-api
WEBPAG_BASE_URL=https://api.webpag.com.br
```

3. Use via Facade ou injeção de dependência:

```
use WebPag\Laravel\Facades\WebPag;

Route::get('/pagadores', function () {
    // O método list() retorna um array de DTOs `Payer`.
    // O Laravel se encarrega de serializar para JSON.
    $payers = WebPag::payers->list();
    return response()->json($payers);
});
```

```
use WebPag\WebPag;

class PaymentController extends Controller
{
    /** @var WebPag */
    private $webpag;

    public function __construct(WebPag $webpag)
    {
        $this->webpag = $webpag;
    }
}
```

Recursos disponíveis
--------------------

[](#recursos-disponíveis)

RecursoPropriedadeEndpointsCrediário`$webpag->installments`list, create, find, cancelEmpresa`$webpag->business`authenticate, me, cardTokenPublicKey, createFranchiseLinks de pagamento`$webpag->paymentLinks`list, createPagadores`$webpag->payers`list, find, create, update, inactivate, saveCreditCard, removeCreditCardPagamentos`$webpag->payments`list, process, find, cancel, refund, findRefund, markAsPaidDevRecorrência`$webpag->recurrency`create, list, update, cancelTransferências`$webpag->transfers`list, create, find, cancel, changeStatusDevWebhooks`$webpag->webhooks`parseExemplos de uso
---------------

[](#exemplos-de-uso)

### Processar pagamento via PIX

[](#processar-pagamento-via-pix)

```
use WebPag\WebPag;
use WebPag\Enums\PaymentMethod;

$webpag = WebPag::env();

// O retorno já é um DTO de resposta, pronto para uso.
$payment = $webpag->payments->process([
    'payer_id' => 15,
    'name' => 'Pedido #1234',
    'amount' => 1500, // R$ 15,00 em centavos
    'method' => PaymentMethod::PIX,
]);

// $payment é um objeto WebPag\Responses\Payments\Payment
echo "Pagamento criado com ID: " . $payment->id . PHP_EOL;
echo "Status: " . $payment->statusLabel . PHP_EOL;
echo "PIX Copia e Cola: " . $payment->pix['qr_code_text'] . PHP_EOL;
```

### Usando DTOs tipados

[](#usando-dtos-tipados)

```
use WebPag\Requests\Payments\ProcessPaymentRequest;
use WebPag\Enums\PaymentMethod;

$request = new ProcessPaymentRequest();
$request->payerId = 15;
$request->name = 'Pedido #1234';
$request->amount = 1500;
$request->method = PaymentMethod::PIX;

$response = $webpag->payments->process($request);
```

DTOs de requisição
------------------

[](#dtos-de-requisição)

Classes tipadas em `WebPag\Requests\*` implementam `RequestPayload` e possuem método `toArray()`:

- `WebPag\Requests\Installments\CreateInstallmentRequest`
- `WebPag\Requests\Business\AuthenticateRequest`
- `WebPag\Requests\Business\CreateFranchiseRequest`
- `WebPag\Requests\PaymentLinks\CreatePaymentLinkRequest`
- `WebPag\Requests\Payers\CreatePayerRequest`
- `WebPag\Requests\Payers\UpdatePayerRequest`
- `WebPag\Requests\Payers\SaveCreditCardRequest`
- `WebPag\Requests\Payers\Address`
- `WebPag\Requests\Payments\ProcessPaymentRequest`
- `WebPag\Requests\Payments\RefundPaymentRequest`
- `WebPag\Requests\Payments\ListPaymentsRequest`
- `WebPag\Requests\Recurrency\CreateRecurrencyRequest`
- `WebPag\Requests\Transfers\CreateTransferRequest`
- e outros...

Constantes
----------

[](#constantes)

Enums disponíveis em `WebPag\Enums\`:

- `PaymentMethod` — `credit_card`, `pix`, `bank_slip`
- `RecurrencyFrequency` — `monthly`, `bimonthly`, `quarterly`, `semiannual`, `yearly`
- `PaymentStatus` — status numéricos de pagamento (10 a 90)
- `TransferDestinationType`, `TransferType`, `PixKeyType`, etc.

DTOs de Resposta
----------------

[](#dtos-de-resposta)

Assim como as requisições, as respostas dos endpoints também são encapsuladas em DTOs tipados, localizados em `WebPag\Responses\*`. Todas implementam `ResponsePayload` e são criadas a partir do método estático `fromArray()`.

As propriedades são públicas para fácil acesso aos dados:

```
$payment = $webpag->payments->find(123);

echo $payment->id;
echo $payment->statusLabel;
echo $payment->amount; // em centavos
```

Alguns dos principais DTOs de resposta são:

- `WebPag\Responses\Business\Business`
- `WebPag\Responses\Business\CardTokenPublicKey`
- `WebPag\Responses\Installments\Installment`
- `WebPag\Responses\PaymentLinks\PaymentLink`
- `WebPag\Responses\Payers\Payer`
- `WebPag\Responses\Payers\SavedCreditCard`
- `WebPag\Responses\Payments\Payment`
- `WebPag\Responses\Payments\Refund`
- `WebPag\Responses\Recurrency\Recurrency`
- `WebPag\Responses\Transfers\Transfer`
- e outros...

Webhooks
--------

[](#webhooks)

Para processar notificações recebidas da WebPag, é crucial primeiro **validar a assinatura** para garantir a autenticidade da requisição.

```
// 1. Obtenha os dados brutos e a assinatura do header
$rawPayload = $request->getContent();
$signature = $request->header('X-Webpag-Signature');
$apiToken = config('webpag.api_token'); // ou getenv('WEBPAG_API_TOKEN')

// 2. Valide a assinatura
if (!\WebPag\Webhooks\WebhookParser::verifySignature($rawPayload, $signature, $apiToken)) {
    abort(403, 'Invalid signature.');
}

// 3. Interprete o evento
$event = $webpag->webhooks->parse($rawPayload);

if ($event->isPayment() && $event->getStatus() === 40) {
    // Pagamento confirmado
    $paymentId = $event->get('id');
}

// Valide o business.id para garantir autenticidade
$businessId = $event->getBusinessId();
```

Tratamento de erros
-------------------

[](#tratamento-de-erros)

```
use WebPag\Exceptions\ApiException;

try {
    $webpag->payments->find(99999);
} catch (ApiException $e) {
    echo $e->getStatusCode();      // 404
    echo $e->getErrorMessage();    // Mensagem da API
    print_r($e->getResponseBody()); // Corpo completo
}
```

Resposta da API
---------------

[](#resposta-da-api)

Os métodos dos recursos (ex: `$webpag->payments->find(123)`) retornam **DTOs de resposta** (como `WebPag\Responses\Payments\Payment`), que encapsulam os dados da API de forma tipada. Veja a seção "DTOs de Resposta" para uma lista.

Para casos onde você precise de acesso ao objeto de resposta HTTP completo (status, headers), você pode interagir diretamente com o `HttpClient`. A maioria dos usuários, no entanto, irá preferir a simplicidade dos DTOs.

O `HttpClient` interno retorna um objeto `WebPag\Http\ApiResponse` que oferece métodos como `getStatusCode()`, `getData()`, `toArray()`, e acesso `ArrayAccess` ao corpo da resposta.

Licença
-------

[](#licença)

MIT

Outras Informações
------------------

[](#outras-informações)

> "Este é um SDK independente. Para suporte customizado ou implementações complexas, entre em contato comigo."

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance93

Actively maintained with recent releases

Popularity15

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity30

Early-stage or recently created project

 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 ~3 days

Total

3

Last Release

35d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/41116603?v=4)[Filipe Cacique](/maintainers/CaciqueFilipe)[@CaciqueFilipe](https://github.com/CaciqueFilipe)

---

Top Contributors

[![CaciqueFilipe](https://avatars.githubusercontent.com/u/41116603?v=4)](https://github.com/CaciqueFilipe "CaciqueFilipe (26 commits)")

---

Tags

laravelsdkboletopagamentospixwebpag

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/filipecacique-webpag-php/health.svg)

```
[![Health](https://phpackages.com/badges/filipecacique-webpag-php/health.svg)](https://phpackages.com/packages/filipecacique-webpag-php)
```

###  Alternatives

[laravel/framework

The Laravel Framework.

34.8k556.2M21.0k](/packages/laravel-framework)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.5k6.0M763](/packages/sylius-sylius)[tempest/framework

The PHP framework that gets out of your way.

2.3k37.6k19](/packages/tempest-framework)[avalara/avataxclient

Client library for Avalara's AvaTax suite of business tax calculation and processing services. Uses the REST v2 API.

528.7M7](/packages/avalara-avataxclient)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

293.1k](/packages/eslazarev-wildberries-sdk)[nutgram/nutgram

The Telegram bot library that doesn't drive you nuts

740315.8k8](/packages/nutgram-nutgram)

PHPackages © 2026

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