PHP code example of carecapay / sdk-php

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

    

carecapay / sdk-php example snippets


use CarecaPay\CarecaPay;

$carecapay = new CarecaPay($_ENV['CARECAPAY_SECRET_KEY']);

$carecapay = new CarecaPay($key, ['base_url' => 'http://localhost:8080']);

$charge = $carecapay->charges->create([
    'amount_cents' => 1990,             // R$ 19,90 — sempre em centavos, obrigatório
    'description' => 'Assinatura',      // opcional
    'external_reference' => 'order_42', // opcional — seu id do pedido, só guardamos e devolvemos
    'customer' => [
        'name' => 'Fulano de Tal',
        'email' => '[email protected]',
        'phone' => '11999999999',
        'document' => ['type' => 'CPF', 'value' => '111.444.777-35'],
    ],
]);
echo $charge['qr_code'];             // copia e cola do Pix
echo $charge['qr_code_base64'];      // PNG já renderizado (base64), pronto pra exibir

$carecapay->charges->get('txn_...');
$carecapay->charges->list(['status' => 'paid', 'limit' => 10]);
$carecapay->balance->get();          // ['available_cents' => ..., 'pending_cents' => ...]

// só no sandbox: baixa fake (dispara o webhook também)
$carecapay->charges->simulatePayment($charge['id']);

// cliente já cadastrado (precisa já ter name/email/phone salvos)
$carecapay->charges->create(['amount_cents' => 1990, 'customer_id' => 'cust_...']);

// gerenciar clientes diretamente — aqui só o documento é obrigatório
// (o restante pode ser completado depois, ou já na criação da cobrança)
$customer = $carecapay->customers->create([
    'document' => '11144477735',
    'name' => 'Fulano de Tal',
    'email' => '[email protected]',
    'phone' => '11999999999',
]);
$carecapay->customers->get($customer['id']);
$carecapay->customers->list();

use CarecaPay\Webhooks;
use CarecaPay\CarecaPayWebhookException;

try {
    $event = Webhooks::constructEvent(
        payload: file_get_contents('php://input'),          // corpo cru!
        header: $_SERVER['HTTP_X_CARECAPAY_SIGNATURE'] ?? '',
        secret: $_ENV['CARECAPAY_WEBHOOK_SECRET'],          // ccp_whsec_...
    );
} catch (CarecaPayWebhookException) {
    http_response_code(400);
    exit;
}

if ($event['type'] === 'charge.paid') {
    liberarPedido($event['data']['id']); // deduplique pelo $event['id']
}
http_response_code(200);

if (($_SERVER['HTTP_X_CARECAPAY_TOKEN'] ?? '') !== $_ENV['CARECAPAY_WEBHOOK_SECRET']) {
    http_response_code(401);  // não veio da CarecaPay
    exit;
}

use CarecaPay\CarecaPayException;

try {
    $carecapay->charges->create(['amount_cents' => 0]);
} catch (CarecaPayException $err) {
    $err->code;    // "invalid_amount" (estável — programe contra ele)
    $err->status;  // 400 (0 em falha de rede, code "network_error")
}
bash
composer