PHPackages                             toreti/cobrefacil-php-client - 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. toreti/cobrefacil-php-client

ActiveLibrary[API Development](/categories/api)

toreti/cobrefacil-php-client
============================

Cobre Fácil SDK

v1.0.0(2y ago)010MITPHPPHP ^8.0

Since Nov 15Pushed 2y agoCompare

[ Source](https://github.com/toreti/cobrefacil-php-client)[ Packagist](https://packagist.org/packages/toreti/cobrefacil-php-client)[ Docs](https://cobrefacil.com.br)[ RSS](/packages/toreti-cobrefacil-php-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (6)Versions (3)Used By (0)

Cobre Fácil - PHP SDK
=====================

[](#cobre-fácil---php-sdk)

SDK oficial de integração à API da Cobre Fácil.
Para ler a documentação da API acesse:

Pré requisitos
--------------

[](#pré-requisitos)

1. PHP &gt;= 8.2.8
2. cURL
3. [Composer](http://getcomposer.org/)

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

[](#instalação)

A instalação é realizada via Composer através do comando:

```
composer require cobrefacil/sdk-php

```

Autenticação
------------

[](#autenticação)

Para realizar a autenticação é necessário informar no construtor da classe `CobreFacil` o `app_id` e `secret` disponíveis no painel de sua conta.

```
use CobreFacil\CobreFacil;

$cobrefacil = new CobreFacil($appId, $secret);
```

Essa classe é a responsável por gerar o token que será utilizado nas requisições e facilitar o acesso aos recursos disponíveis.

Por padrão a classe utiliza o ambiente de `produção`, caso deseje utilizar o ambiente de `sandbox` basta chamar o método `setProduction` e passar o valor `false`.

```
$cobrefacil = new CobreFacil($appId, $secret);
$cobrefacil->setProduction(false);
```

Recursos Disponíveis
--------------------

[](#recursos-disponíveis)

Atualmente nosso SDK disponibiliza métodos para facilitar a manipulação de `Clientes`, `Cartões de Crédito` e `Cobranças`. Para saber quais dados devem ser enviados e recebidos consulte a [documentação da API](https://developers.cobrefacil.com.br).

Os dados devem ser enviados em forma de array associativo:

```
$params = [
    'customer_id' => 'Y73MNPGJ18Y18V5KQODX',
    'payable_with' => 'bankslip',
    //...
];
$response = $cobrefacil->invoice->create($params);
```

E as respostas também são no formato de array associativo, exemplo usando a variável `$response` do exemplo anterior:

```
[
    'id' => '2KD9LGERW897NZ6JM5V4',
    'customer_id' => 'Y73MNPGJ18Y18V5KQODX',
    'payable_with' => 'bankslip',
    //...
];
```

### Clientes

[](#clientes)

```
// POST /customers
$cobrefacil->customer->create($params);

// PUT /customers/{id}
$cobrefacil->customer->update($id, $params);

// GET /customers
$cobrefacil->customer->search();

// GET /customers?email=exemplo@mail.com
$cobrefacil->customer->search(['email' => 'exemplo@mail.com']);

// GET /customers/{id}
$cobrefacil->customer->getById($id);

// DELETE /customers/{id}
$cobrefacil->customer->remove($id);
```

### Cartões de Crédito

[](#cartões-de-crédito)

```
// POST /cards
$cobrefacil->card->create($params);

// POST /cards/{id}/default
$cobrefacil->card->setDefault($id);

// GET /cards/{id}
$cobrefacil->card->getById($id);

// GET /cards
$cobrefacil->card->search();

// GET /cards?customer_id=Z8J53ROD2JK1PQ47WG0E
$cobrefacil->card->search(['customer_id' => 'Z8J53ROD2JK1PQ47WG0E']);

// DELETE /cards/{id}
$cobrefacil->card->remove($id);
```

### Cobranças

[](#cobranças)

```
// POST /invoices
$cobrefacil->invoice->create($params);

// POST /invoices/{id}/capture
$cobrefacil->invoice->capture($id, $amount);

// GET /invoices
$cobrefacil->invoice->search();

// GET /invoices?status=paid
$cobrefacil->invoice->search(['status' => 'paid']);

// POST /invoices/{id}/refund
$cobrefacil->invoice->refund($id, $amount);

// DELETE /invoices/{id}
$cobrefacil->invoice->cancel($id);
```

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

[](#tratamento-de-erros)

Caso aconteça algum erro durante uma requisição, será retornada uma `exception`.

E para facilitar o tratamento dos erros disponibilizamos 3 exceptions que facilitam identificar qual foi o tipo de erro.

Erro na autenticação:

```
use CobreFacil\Exceptions\InvalidCredentialsException;

try {
    $cobrefacil = new CobreFacil($appId, $secret);
} catch (InvalidCredentialsException $e) {
    // 401 Unauthorized: As credenciais são inválidas
}
```

Erro na requisição:

```
use CobreFacil\Exceptions\InvalidParamsException;
use CobreFacil\Exceptions\ResourceNotFoundException;

try {
    $cobrefacil->customer->create($params);
} catch (InvalidParamsException $e) {
    // 400 Bad Request: Algum parâmetro obrigatório não foi enviado ou é inválido
    $e->getErrors();// retorna um array contendo os erros
} catch (ResourceNotFoundException $e) {
    // 404 Not Found: O registro solicitado não existe
}
```

Webhooks
--------

[](#webhooks)

Para facilitar o tratamento dos eventos de webhook recebidos, disponibilizamos a classe `WebhookEvent`.

```
$receivedEvent = WebhookEvent::createFromJson($json);
```

Com ela é possível utilizar métodos para auxiliar na leitura dos dados:

```
$receivedEvent->getEvent();// nome do evento recebido, exemplo: invoice.created
$receivedEvent->getData();// dados da cobrança em forma de array associativo
```

E também métodos para fazer algumas verificações:

```
$receivedEvent->isInvoiceCreated();// invoice.created
$receivedEvent->isInvoiceViewed();// invoice.viewed
$receivedEvent->isInvoiceReversed();// invoice.reversed
$receivedEvent->isInvoiceDeclined();// invoice.declined
$receivedEvent->isInvoicePreAuthorized();// invoice.pre_authorized
$receivedEvent->isInvoicePaid();// invoice.paid
$receivedEvent->isInvoiceRefunded();// invoice.refunded
$receivedEvent->isInvoiceCanceled();// invoice.canceled
$receivedEvent->isInvoiceDispute();// invoice.dispute
$receivedEvent->isInvoiceDisputeSucceeded();// invoice.dispute_succeeded
$receivedEvent->isInvoiceDisputeChargedBack();// invoice.charged_back
```

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

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

Unknown

Total

1

Last Release

906d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a42da7beab3d6701fbdeafd9699265bd3d20b152161c51b950fda676b4c9e928?d=identicon)[toreti](/maintainers/toreti)

---

Top Contributors

[![toreti](https://avatars.githubusercontent.com/u/1796597?v=4)](https://github.com/toreti "toreti (7 commits)")

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/toreti-cobrefacil-php-client/health.svg)

```
[![Health](https://phpackages.com/badges/toreti-cobrefacil-php-client/health.svg)](https://phpackages.com/packages/toreti-cobrefacil-php-client)
```

###  Alternatives

[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3731.2M42](/packages/tencentcloud-tencentcloud-sdk-php)[convertkit/convertkitapi

Kit PHP SDK for the Kit API

2167.1k1](/packages/convertkit-convertkitapi)[mapado/rest-client-sdk

Rest Client SDK for hydra API

1125.9k2](/packages/mapado-rest-client-sdk)

PHPackages © 2026

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