### Open Finance Full Flow Example Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/open-finance.md This comprehensive example demonstrates a complete Open Finance flow using the EfiPay SDK. It covers configuring callbacks, initiating immediate, scheduled, and recurring payments, and handling biometric enrollments and payments. ```php 'seu_client_id', 'clientSecret' => 'seu_client_secret', 'certificate' => '/caminho/para/certificado.p12', 'sandbox' => true ]; $efi = new EfiPay($options); try { // 1. Configurar URLs de callback $efi->ofConfigUpdate( [], [ 'redirect_url' => 'https://seu-app.com/callback/openfinance', 'notifications_url' => 'https://seu-app.com/webhooks/openfinance' ] ); // 2. Iniciar pagamento imediato $payment = $efi->ofStartPixPayment( [], [ 'valor' => 50000, 'chaveDestino' => 'empresa@example.com' ] ); echo "Redirecionar para: " . $payment['autorizationUrl'] . "\n"; // 3. Agendar pagamento para futuro $scheduled = $efi->ofStartSchedulePixPayment( [], [ 'valor' => 10050, 'chaveDestino' => 'empresa@example.com', 'dataAgendamento' => '2024-02-15' ] ); // 4. Criar pagamento recorrente $recurrent = $efi->ofStartRecurrencyPixPayment( [], [ 'valor' => 2990, 'chaveDestino' => 'empresa@example.com', 'frequencia' => 'MENSAL', 'dataInicio' => '2024-02-01' ] ); // 5. Registrar biometria $enrollment = $efi->ofCreateBiometricEnrollment( [], [ 'cpf' => '12345678901', 'phoneNumber' => '+5511999999999', 'email' => 'usuario@example.com' ] ); // 6. Pagar com biometria $bioPay = $efi->ofCreateBiometricPixPayment( [], [ 'enrollmentId' => $enrollment['enrollmentId'], 'valor' => 15000, 'chaveDestino' => 'empresa@example.com' ] ); } catch (OpenFinanceException $e) { echo "Erro Open Finance: " . $e->errorDescription . "\n"; } ``` -------------------------------- ### StaticPix QR Code Generation Example Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/REFERENCIA_TECNICA.md Example demonstrating how to create a static Pix QR Code payload using the StaticPix class and echo the resulting payload. ```php use Efi\StaticPix; $pix = new StaticPix(); $qrCode = $pix->create([ 'chave' => 'usuario@example.com', 'nomeRecebedor' => 'Joao Silva', 'cidade' => 'Sao Paulo', 'valor' => '150.00', 'txid' => 'ABC123', 'descricao' => 'Pagamento de fatura' ]); echo $qrCode; // Payload do QR Code para ser convertido em imagem ``` -------------------------------- ### EVP Creation Response Example Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/pix.md Example of the response structure when successfully creating a dynamic EVP. ```json { "chave": "12345678-1234-5678-1234-567812345678" } ``` -------------------------------- ### Account Balance Response Example Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/pix.md An example of the JSON response when successfully retrieving account balance information. It includes available balance, balance to block, and account limit. ```json { "saldoDisponivel": 50000000, "saldoABloquear": 0, "limiteConta": 100000000 } ``` -------------------------------- ### getInstallments Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Retrieves available installment options for a given amount. ```APIDOC ## GET /v1/installments ### Description Retrieves available installment options for a given amount. ### Method GET ### Endpoint /v1/installments ### Parameters #### Query Parameters - **amount** (integer) - Required - The amount in cents for which to get installment options ### Response #### Success Response (200) - **installments** (array) - List of available installment options - **installments** (integer) - Number of installments - **installment_value** (integer) - Value of each installment in cents - **total_amount** (integer) - Total amount for the installments in cents - **interest_percent** (integer) - Interest percentage applied ### Response Example ```json { "installments": [ { "installments": 1, "installment_value": 10050, "total_amount": 10050, "interest_percent": 0 }, { "installments": 3, "installment_value": 3450, "total_amount": 10350, "interest_percent": 3 } ] } ``` ``` -------------------------------- ### Configuration with Base64 Certificate Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/configuracao.md This example shows how to configure the SDK using a certificate encoded in Base64, which can be more efficient for repeated use as it avoids file reading on each instantiation. ```php 'seu_client_id', 'clientSecret' => 'seu_client_secret', 'certificate' => $certificadoBase64, // String base64 'pwdCertificate' => 'senha', 'sandbox' => false, ]; $efi = new EfiPay($options); ``` -------------------------------- ### Configure Pix/Open Finance in Sandbox with Certificate Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/configuracao.md When using Pix or Open Finance in a sandbox environment, a correct certificate must be provided. This example shows the correct way to configure the options with a certificate path. ```php // ❌ Errado - Pix em sandbox sem certificado $options = [ 'clientId' => 'id', 'clientSecret' => 'secret', 'sandbox' => true, // Sem 'certificate' ]; // ✅ Correto $options = [ 'clientId' => 'id', 'clientSecret' => 'secret', 'certificate' => realpath(__DIR__ . '/efi_homolog.p12'), 'sandbox' => true, ]; ``` -------------------------------- ### Complete Charge Flow Example in PHP Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md This snippet demonstrates a full workflow for managing charges and subscriptions using the EfiPay PHP SDK. It covers creating a generic charge, listing charges with filters, retrieving charge details, creating a subscription plan, and creating a subscription. Ensure your EfiPay client ID and secret are correctly configured, and consider using the sandbox environment for testing. ```php 'seu_client_id', 'clientSecret' => 'seu_client_secret', 'sandbox' => true ]; $efi = new EfiPay($options); try { // 1. Criar cobrança genérica $charge = $efi->createCharge( [], [ 'email' => 'cliente@example.com', 'paymentMethod' => 'all', 'items' => [ [ 'name' => 'Produto A', 'value' => 10050, 'amount' => 1 ] ] ] ); echo "Cobrança criada: " . $charge['code'] . "\n"; // 2. Listar cobranças $chargeList = $efi->listCharges([ 'status' => 'open', 'limit' => 10 ]); // 3. Obter detalhes $details = $efi->detailCharge(['id' => $charge['code']]); echo "Status: " . $details['status'] . "\n"; // 4. Criar assinatura $plan = $efi->createPlan( [], [ 'name' => 'Plano Mensal', 'interval' => ['frequency' => 'monthly'], 'items' => [ [ 'name' => 'Acesso', 'value' => 2900 ] ] ] ); $subscription = $efi->createSubscription( ['id' => $plan['id']], [ 'email' => 'assinante@example.com' ] ); echo "Assinatura criada: " . $subscription['id'] . "\n"; } catch (ChargesException $e) { echo "Erro: " . $e->errorDescription . "\n"; } ``` -------------------------------- ### Complete Pix Flow Example (PHP) Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/pix.md Demonstrates a full Pix transaction flow, including creating an immediate charge, setting up a webhook, listing charges, and sending a Pix transfer. Ensure your SDK is configured with correct credentials and paths. ```php 'seu_client_id', 'clientSecret' => 'seu_client_secret', 'certificate' => '/caminho/para/certificado.p12', 'pwdCertificate' => 'senha', 'sandbox' => true, 'cache' => true ]; $efi = new EfiPay($options); try { // 1. Criar cobrança Pix imediata $chargeResponse = $efi->pixCreateImmediateCharge( [], [ 'valor' => 10050, 'chave' => 'usuario@example.com', 'solicitacaoPagador' => 'Pagamento de fatura #123' ] ); echo "TxID: " . $chargeResponse['txid'] . "\n"; echo "QR Code: " . $chargeResponse['qrCode'] . "\n"; // 2. Configurar webhook para receber notificações $efi->pixConfigWebhook( ['chave' => 'usuario@example.com'], ['url' => 'https://seu-servidor.com/webhooks/pix'] ); // 3. Listar cobranças criadas $charges = $efi->pixListCharges([ 'inicio' => '2024-01-01T00:00:00Z', 'fim' => '2024-01-31T23:59:59Z' ]); foreach ($charges['cobs'] as $cob) { echo $cob['txid'] . " - Status: " . $cob['status'] . "\n"; } // 4. Enviar Pix (transferência) $sendResponse = $efi->pixSend( ['idEnvio' => 'ENV' . time()], [ 'valor' => 20000, 'chaveDestino' => 'destino@example.com' ] ); echo "Pix enviado com ID: " . $sendResponse['id'] . "\n"; } catch (PixException $e) { echo "Erro Pix: " . $e->errorDescription . "\n"; echo "Tipo: " . $e->error . "\n"; echo "Código HTTP: " . $e->code . "\n"; } ``` -------------------------------- ### Instantiate EfiPay and Create Pix Immediate Charge Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/REFERENCIA_TECNICA.md Instantiate the EfiPay class with configuration options and use its dynamic methods to interact with the API. This example shows how to create an immediate Pix charge. ```php 'seu_client_id', 'clientSecret' => 'seu_client_secret', 'certificate' => '/caminho/para/certificado.p12', 'pwdCertificate' => 'senha_do_certificado', 'sandbox' => true, 'cache' => true, 'timeout' => 30 ]; $efi = new EfiPay($options); // Usando método dinâmico para criar um Pix imediato $params = []; $body = [ 'valor' => 100.50, 'chave' => 'seu@email.com' ]; try { $response = $efi->pixCreateImmediateCharge($params, $body); echo $response['qrCode']; } catch (EfiException $e) { echo "Erro: " . $e->errorDescription; } ``` -------------------------------- ### Start Pix Payment / Start Scheduled Pix Payment Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/tipos.md Initiates a single Pix payment or a scheduled Pix payment. Requires payment amount, destination Pix key, and optionally additional information and an idempotency key. ```APIDOC ## POST /payments/open-finance/pix ### Description Initiates a Pix payment or a scheduled Pix payment via Open Finance. ### Method POST ### Endpoint /payments/open-finance/pix ### Parameters #### Request Body - **valor** (integer) - Required - Payment amount in cents. - **chaveDestino** (string) - Required - Destination Pix key. - **infoAdicional** (string) - Optional - Additional information for the payment. - **idempotencyKey** (string) - Optional - Idempotency key for the transaction. - **dataAgendamento** (string) - Optional - Date for scheduling the payment in YYYY-MM-DD format. ### Request Example ```json { "valor": 10050, "chaveDestino": "recebedor@example.com", "infoAdicional": "Pagamento", "idempotencyKey": "ABC123", "dataAgendamento": "2024-02-15" } ``` ### Response #### Success Response (200) - **id** (string) - ID of the payment. - **status** (string) - Status of the payment (e.g., 'WAITING_PAYMENT'). - **valor** (integer) - Payment amount in cents. - **chaveDestino** (string) - Destination Pix key. - **autorizationUrl** (string) - URL for payment authorization. - **dataCriacao** (string) - Date and time of payment creation. - **dataAgendamento** (string) - Scheduled date for the payment (if applicable). #### Response Example ```json { "id": "PAY123", "status": "WAITING_PAYMENT", "valor": 10050, "chaveDestino": "recebedor@example.com", "autorizationUrl": "https://...", "dataCriacao": "2024-01-15T10:30:00Z", "dataAgendamento": "2024-02-15" } ``` ``` -------------------------------- ### Integrate Payments, Accounts, and Statements with PHP SDK Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/payments-statements-accounts.md This comprehensive example shows how to use the EfiPay PHP SDK to interact with Payments, Opening Accounts, and Statements APIs. It covers requesting a barcode, configuring a payment webhook, creating a new account, generating a certificate, setting up monthly statements, listing statement files, and creating an SFTP key. Includes basic error handling. ```php 'seu_client_id', 'clientSecret' => 'seu_client_secret', 'certificate' => '/caminho/para/certificado.p12', 'sandbox' => true ]; $efi = new EfiPay($options); try { // ===== API PAYMENTS ===== // Solicitar código de barras $barcode = $efi->payRequestBarCode( [], [ 'nome' => 'Cliente ABC', 'cpf' => '12345678901', 'valor' => 50000 ] ); echo "Código: " . $barcode['barcode'] . "\n"; // Configurar webhook de pagamento $efi->payConfigWebhook( [], [ 'url' => 'https://seu-app.com/webhooks/payment', 'events' => ['PAYMENT_CONFIRMED'] ] ); // ===== API OPENING ACCOUNTS ===== // Criar nova conta $account = $efi->createAccount( [], [ 'nome' => 'Nova Empresa', 'cpf_cnpj' => '12345678901234', 'email' => 'novo@empresa.com', 'telefone' => '1133334444', 'endereco' => [ 'logradouro' => 'Rua X', 'numero' => '100', 'bairro' => 'Centro', 'cidade' => 'Sao Paulo', 'estado' => 'SP', 'cep' => '01234567' ] ] ); echo "Conta criada: " . $account['accountId'] . "\n"; // Gerar certificado da conta $cert = $efi->createAccountCertificate(['accountId' => $account['accountId']]); echo "Certificado: " . $cert['certificateUrl'] . "\n"; // ===== API STATEMENTS ===== // Configurar extrato automático mensal $recurrence = $efi->createStatementRecurrency( [], [ 'frequency' => 'MONTHLY', 'dayOfMonth' => 1, 'enabled' => true ] ); // Listar extratos existentes $statements = $efi->listStatementFiles(); foreach ($statements['statements'] as $stmt) { echo "Extrato: " . $stmt['fileName'] . "\n"; } // Criar chave SFTP $sftpKey = $efi->createSftpKey(); } catch (EfiException $e) { echo "Erro: " . $e->errorDescription . "\n"; echo "Tipo: " . $e->error . "\n"; echo "Código: " . $e->code . "\n"; } ``` -------------------------------- ### Get Open Finance Configuration Details Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/open-finance.md Retrieves the current configuration details for the Open Finance integration. ```APIDOC ## GET /v1/openfinance/config ### Description Retrieves the current configuration details for the Open Finance integration. ### Method GET ### Endpoint /v1/openfinance/config ``` -------------------------------- ### Instalar SDK PHP Efí Bank com Composer Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/README.md Instale o SDK PHP para as APIs Efí Bank usando o Composer. Inclua a dependência em seu arquivo composer.json ou baixe o pacote diretamente. ```bash git clone https://github.com/efipay/sdk-php-apis-efi.git composer install ``` ```json ... "require": { "efipay/sdk-php-apis-efi": "^1" }, ... ``` ```bash composer require efipay/sdk-php-apis-efi ``` -------------------------------- ### Get Endpoints Instance and Detail Charge Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/REFERENCIA_TECNICA.md Obtain an instance of the Endpoints class using static method `getInstance` and then use it to call API methods like `detailCharge`. Ensure credentials are set in options. ```php $endpoints = Endpoints::getInstance($options); $charge = $endpoints->detailCharge(['id' => '123456']); ``` -------------------------------- ### Response Object Example Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/REFERENCIA_TECNICA.md Illustrates accessing the body and headers of an API response object, typically available when responseHeaders is enabled. ```php // Disponível quando responseHeaders = true na configuração $response = $efi->pixCreateImmediateCharge($params, $body); echo $response->body['qrCode']; echo $response->headers['Content-Type']; // Array de valores de header ``` -------------------------------- ### Initiate Immediate Pix Payment Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/open-finance.md Starts an immediate Pix payment transaction. Requires the payment amount, destination Pix key, and optionally an additional info and idempotency key. ```APIDOC ## POST /v1/openfinance/pix/immediate ### Description Initiates an immediate Pix payment. This endpoint requires the payment amount, the recipient's Pix key, and can optionally include additional information and an idempotency key for transaction uniqueness. ### Method POST ### Endpoint /v1/openfinance/pix/immediate ### Parameters #### Request Body - **valor** (integer) - Required - The payment amount in cents. - **chaveDestino** (string) - Required - The Pix key of the recipient. - **infoAdicional** (string) - Optional - Additional information for the payment. - **idempotencyKey** (string) - Optional - An idempotency key to ensure the request is processed only once. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the payment. - **status** (string) - The current status of the payment (e.g., WAITING_PAYMENT). - **valor** (integer) - The payment amount in cents. - **chaveDestino** (string) - The Pix key of the recipient. - **autorizationUrl** (string) - The URL the user must be redirected to for authorization. - **dataCriacao** (string) - The timestamp when the payment was created in ISO 8601 format. ``` -------------------------------- ### OpenFinanceException Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/erros.md Specific exceptions for the Open Finance API. This example demonstrates catching `OpenFinanceException` and accessing error details like `error` and `errorDescription` for invalid inputs. ```APIDOC ## OpenFinanceException **Location:** `src/Efi/Exception/OpenFinanceException.php` Specific to errors from the Open Finance API. **Example:** ```php use Efi\Exception\OpenFinanceException; try { $payment = $efi->ofStartPixPayment([], [ 'valor' => -100, // Invalid value 'chaveDestino' => 'invalido' ]); } catch (OpenFinanceException $e) { echo "Erro Open Finance: " . $e->errorDescription . "\n"; echo "Tipo: " . $e->error . "\n"; } ``` ``` -------------------------------- ### Create Carnê with EFI SDK Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Use this method to create a new carnê (installment plan). Ensure all required fields in the request body, including payer details, items, and parcel configuration, are correctly provided. ```php $response = $efi->createCarnet( [], [ 'email' => 'cliente@example.com', 'cpf' => '12345678901', 'items' => [ [ 'name' => 'Produto Parcelado', 'value' => 30000, 'amount' => 1 ] ], 'parcels' => [ 'quantity' => 12, 'frequency' => 'monthly', 'first_expire_at' => '2024-02-15' ] ] ); echo "Carnê ID: " . $response['id']; ``` -------------------------------- ### Get Installment Options Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Retrieve available installment options for a given amount. The amount should be provided in cents. ```json { "installments": [ { "installments": 1, "installment_value": 10050, "total_amount": 10050, "interest_percent": 0 }, { "installments": 3, "installment_value": 3450, "total_amount": 10350, "interest_percent": 3 } ] } ``` -------------------------------- ### Initialize SDK and Handle Exceptions Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/README.md Include necessary modules and namespaces, then initialize the SDK within a try-catch block to manage API and general exceptions. ```php require __DIR__ . '/vendor/autoload.php'; use Efi\Exception\EfiException; use Efi\EfiPay; ``` ```php try { $api = new EfiPay($options); /* chamada da função desejada */ } catch(EfiException $e) { /* Os erros da API virão aqui */ print_r($e->code . "
"); print_r($e->error . "
"); print_r($e->errorDescription . "
"); } catch(Exception $e) { /* Outros erros virão aqui */ print_r($e->getMessage()); } ``` -------------------------------- ### Handle Certificate File Paths in PHP Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/configuracao.md When specifying the certificate path, it's recommended to use an absolute path and verify the file's existence to prevent 'Certificate not found' errors. This example shows how to use `realpath` and `file_exists` for robust certificate handling. ```php // ❌ Caminho relativo pode falhar $options = ['certificate' => './efi.p12']; // ✅ Usar caminho absoluto $options = ['certificate' => realpath(__DIR__ . '/efi.p12')]; // ✅ Verificar se arquivo existe $certPath = realpath(__DIR__ . '/efi.p12'); if (!file_exists($certPath)) { throw new Exception("Certificado não encontrado: $certPath"); } $options = ['certificate' => $certPath]; ``` -------------------------------- ### Start Recurring Pix Payment Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/tipos.md Initiates a recurring Pix payment setup. Allows for fixed or variable amounts, specifies frequency, start and end dates, and an optional description. ```APIDOC ## POST /payments/open-finance/pix/recurrent ### Description Initiates a recurring Pix payment setup via Open Finance. ### Method POST ### Endpoint /payments/open-finance/pix/recurrent ### Parameters #### Request Body - **valor** (integer | object) - Required - Fixed amount in cents (integer) OR an object with `minima` and `maxima` for variable amounts. - **minima** (integer) - Minimum amount in cents. - **maxima** (integer) - Maximum amount in cents. - **chaveDestino** (string) - Required - Destination Pix key. - **frequencia** (string) - Required - Payment frequency (e.g., 'MENSAL', 'TRIMESTRAL', 'SEMESTRAL', 'ANUAL'). - **dataInicio** (string) - Required - Start date for the recurrence in YYYY-MM-DD format. - **dataFim** (string) - Optional - End date for the recurrence in YYYY-MM-DD format. - **descricao** (string) - Optional - Description for the recurring payment. ### Request Example ```json { "valor": { "minima": 1000, "maxima": 100000 }, "chaveDestino": "recebedor@example.com", "frequencia": "MENSAL", "dataInicio": "2024-02-01", "dataFim": "2025-01-31", "descricao": "Assinatura" } ``` ### Response #### Success Response (200) - **id** (string) - ID of the recurring payment setup. - **status** (string) - Status of the recurring payment setup. - **valor** (object) - Details of the payment amount (fixed or variable range). - **chaveDestino** (string) - Destination Pix key. - **frequencia** (string) - Frequency of the recurrence. - **dataInicio** (string) - Start date of the recurrence. - **dataFim** (string) - End date of the recurrence (if set). - **descricao** (string) - Description of the recurring payment. #### Response Example ```json { "id": "REC123", "status": "ACTIVE", "valor": { "minima": 1000, "maxima": 100000 }, "chaveDestino": "recebedor@example.com", "frequencia": "MENSAL", "dataInicio": "2024-02-01", "dataFim": "2025-01-31", "descricao": "Assinatura" } ``` ``` -------------------------------- ### Catching EfiException in PHP Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/erros.md This example demonstrates how to catch EfiException and access its properties like HTTP status code, error type, and detailed description. It also shows how to get a string representation of the exception. ```php use Efi\EfiPay; use Efi\Exception\EfiException; $efi = new EfiPay($options); try { $response = $efi->pixCreateImmediateCharge([], [...]); } catch (EfiException $e) { // Propriedades disponíveis echo "Código HTTP: " . $e->code; echo "Tipo de erro: " . $e->error; echo "Descrição: " . $e->errorDescription; echo "Headers: " . json_encode($e->headers); echo "Mensagem: " . $e->message; // String representation echo (string)$e; } ``` -------------------------------- ### Devolve Recurring Pix Payment Installment Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/open-finance.md Initiates the devolution of a specific installment for a recurring Pix payment. ```php public function ofDevolutionRecurrencyPix(array $params, array $body): mixed ``` -------------------------------- ### Complete Configuration (Production) Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/configuracao.md This comprehensive configuration is for production environments and includes all necessary credentials, digital certificate, custom headers, and partner token. It also demonstrates error handling with a try-catch block. ```php 'seu_client_id_producao', 'clientSecret' => 'seu_client_secret_producao', // Certificado digital 'certificate' => realpath(__DIR__ . '/certificados/efi_producao.p12'), 'pwdCertificate' => 'senha_certificado', // Ambiente 'sandbox' => false, // Produção! // Cache e performance 'cache' => true, 'timeout' => 45, // Debug e monitoramento 'debug' => false, 'responseHeaders' => true, // Headers customizados 'headers' => [ 'X-App-ID' => 'meu_app', 'X-Timestamp' => date('c'), ], // Parceiro (opcional) 'partnerToken' => 'token_parceiro', ]; $efi = new EfiPay($options); try { $response = $efi->pixCreateImmediateCharge([], [ 'valor' => 10050, 'chave' => 'empresa@example.com' ]); echo "TXID: " . $response->body['txid'] . "\n"; echo "Status Code: " . $response->headers['Content-Type'][0] . "\n"; } catch (Exception $e) { echo "Erro: " . $e->getMessage(); } ``` -------------------------------- ### settleCarnetParcel Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Settles a specific parcel of a 'carnet' (installment plan). ```APIDOC ## PUT /v1/carnet/:id/parcel/:parcel/settle ### Description Settles a parcel of a carnet. ### Method PUT ### Endpoint /v1/carnet/:id/parcel/:parcel/settle ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the carnet. - **parcel** (string) - Required - The specific parcel number to settle. ### Response (Success and error response details are not specified in the source.) ``` -------------------------------- ### Cancel Carnet Parcel Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Cancels a specific installment of a Carnet. ```APIDOC ## PUT /v1/carnet/:id/parcel/:parcel/cancel ### Description Cancels a specific installment of a Carnet. ### Method PUT ### Endpoint /v1/carnet/:id/parcel/:parcel/cancel ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the Carnet - **parcel** (integer) - Required - The number of the installment to cancel. ``` -------------------------------- ### Update Carnet Parcels Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Updates multiple installments of a Carnet. ```APIDOC ## PUT /v1/carnet/:id/parcels ### Description Updates multiple installments of a Carnet. ### Method PUT ### Endpoint /v1/carnet/:id/parcels ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the Carnet #### Request Body [Details of the fields that can be updated for multiple parcels] ``` -------------------------------- ### Include SDK and Instantiate EfiPay Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/README-en.md Require the SDK's autoloader and use the necessary namespaces. Instantiate the EfiPay class with your configured options within a try-catch block to handle exceptions. ```php require __DIR__ . '/vendor/autoload.php'; use Efi\Exception\EfiException; use Efi\EfiPay; ``` ```php try { $api = new EfiPay($options); /* call the desired function */ } catch(EfiException $e) { /* API errors will come here */ print_r($e->code . "
"); print_r($e->error . "
"); print_r($e->errorDescription . "
"); } catch(Exception $e) { /* Other errors will come here */ print_r($e->getMessage()); } ``` -------------------------------- ### Update Carnet Parcel Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Updates a specific installment of a Carnet. ```APIDOC ## PUT /v1/carnet/:id/parcel/:parcel ### Description Updates a specific installment of a Carnet. ### Method PUT ### Endpoint /v1/carnet/:id/parcel/:parcel ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the Carnet - **parcel** (integer) - Required - The installment number #### Request Body [Details of the fields that can be updated in the parcel] ``` -------------------------------- ### Configure SDK Credentials Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/README.md Set up authentication credentials and environment options for the Efí SDK. Ensure the certificate path is absolute if required for the API. ```php $options = [ "clientId" => "Client_Id...", "clientSecret" => "Client_Secret...", "certificate" => realpath(__DIR__ . "/arquivoCertificado.p12"), // Obrigatório, com exceção da API Cobranças | Caminho absoluto para o certificado no formato .p12 ou .pem, ou o certificado PEM convertido em base64 "pwdCertificate" => "", // Opcional | Padrão = "" | Senha de criptografia do certificado "sandbox" => false, // Opcional | Padrão = false | Define o ambiente de desenvolvimento entre Produção e Homologação "debug" => false, // Opcional | Padrão = false | Ativa/desativa os logs de requisições do Guzzle "cache" => true, // Opcional | Padrão = true | Ativa/desativa o cache da autenticação e de certificados base64, otimizando e reduzindo o número de requisições "timeout" => 30, // Opcional | Padrão = 30 | Define o tempo máximo de resposta das requisições "responseHeaders" => false, // Optional | Default = false || Ativa/desativa o retorno do header das requisições ]; ``` -------------------------------- ### Create Carnet Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Creates a new Carnet, which is a set of installments. ```APIDOC ## POST /v1/carnet ### Description Creates a new Carnet (set of installments). ### Method POST ### Endpoint /v1/carnet ### Parameters #### Request Body - **email** (string) - Required - Payer's email - **cpf** (string) - Optional - Payer's CPF - **items** (array) - Required - Items to be charged - **name** (string) - Required - Item name - **value** (integer) - Required - Item value - **amount** (integer) - Required - Item amount - **parcels** (object) - Required - Installment configuration - **quantity** (integer) - Required - Number of installments - **frequency** (string) - Required - Frequency: "monthly" - **first_expire_at** (string) - Required - Date of the first installment ### Request Example ```php $response = $efi->createCarnet( [], [ 'email' => 'cliente@example.com', 'cpf' => '12345678901', 'items' => [ [ 'name' => 'Produto Parcelado', 'value' => 30000, 'amount' => 1 ] ], 'parcels' => [ 'quantity' => 12, 'frequency' => 'monthly', 'first_expire_at' => '2024-02-15' ] ] ); echo "Carnê ID: " . $response['id']; ``` ### Response #### Success Response (200) - **id** (string) - The ID of the created Carnet. ``` -------------------------------- ### Configure EfiPay SDK Credentials Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/README-en.md Instantiate the SDK with your credentials. Ensure the `certificate` path is absolute if required for the API. Set `sandbox` to `true` for the development environment. ```php $options = [ "clientId" => "Client_Id...", "clientSecret" => "Client_Secret...", "certificate" => realpath(__DIR__ . "/certificateFile.p12"), // Mandatory, except for the Charges API | Absolute path to the certificate in .p12 or .pem format, or the certificate in PEM converted to base64. "pwdCertificate" => "", // Optional | Default = "" | Certificate encryption password "sandbox" => false, // Optional | Default = false | Sets the development environment between Production and Sandbox "debug" => false, // Optional | Default = false | Enables/disables Guzzle request logs "cache" => true, // Optional | Default = true | Enables/disables authentication caching, optimizing and reducing the number of requests "timeout" => 30, // Optional | Default = 30 | Sets the maximum response time for requests "responseHeaders" => false, // Optional | Default = false || Enables/disables the return of request headers ]; ``` -------------------------------- ### Atualizar Configuração Open Finance Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/open-finance.md Use este método para atualizar as URLs de redirecionamento e notificação para a integração Open Finance. Certifique-se de que os escopos `openfinance.config.write` estejam configurados. ```php $config = $efi->ofConfigUpdate( [], [ 'redirect_url' => 'https://seu-app.com/callback', 'notifications_url' => 'https://seu-app.com/webhooks/openfinance' ] ); ``` -------------------------------- ### Get Webhook Details Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/payments-statements-accounts.md Retrieves the details of a specific webhook configuration. ```APIDOC ## GET /v1/accounts/webhook/:id ### Description Obtains details of a specific webhook. ### Method GET ### Endpoint /v1/accounts/webhook/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the webhook to retrieve details for ### Response #### Success Response (200) - **url** (string) - The configured URL for the webhook - **id** (string) - The unique identifier of the webhook - **createdAt** (string) - The timestamp when the webhook was created #### Response Example ```json { "url": "https://example.com/webhook", "id": "whk_abc123", "createdAt": "2024-01-15T10:30:00Z" } ``` ``` -------------------------------- ### Get Carnê Details Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Retrieve detailed information about a specific carnê using its ID. ```php public function detailCarnet(array $params): mixed ``` -------------------------------- ### Initialize Security with Encryption Key Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/REFERENCIA_TECNICA.md Instantiate the Security class by providing an encryption key for AES-256-CBC. ```php public function __construct(string $encryptionKey) ``` -------------------------------- ### Send Carnet Parcel Email Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Sends a specific installment of the Carnet to the payer via email. ```APIDOC ## POST /v1/carnet/:id/parcel/:parcel/email ### Description Sends a specific installment of the Carnet to the payer via email. ### Method POST ### Endpoint /v1/carnet/:id/parcel/:parcel/email ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the Carnet - **parcel** (integer) - Required - The number of the installment to send via email #### Request Body [Details of any fields required for sending the email, e.g., subject, body content] ``` -------------------------------- ### Get Notification Details - PHP Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Retrieves detailed information about a specific notification using its unique token. ```php public function getNotification(array $params): mixed ``` -------------------------------- ### Configurar Ambiente de Homologação (Sandbox) Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/configuracao.md Ativa o ambiente de homologação (sandbox) definindo a opção 'sandbox' como `true`. Isso direciona as requisições para as URLs de homologação (`*-h.api.efipay.com.br`) e pode exigir um certificado diferente do ambiente de produção. ```php // Homologação $options = [ 'sandbox' => true, 'certificate' => realpath(__DIR__ . '/certificado_homolog.p12'), ]; ``` -------------------------------- ### Get Configuration Property Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/REFERENCIA_TECNICA.md Retrieve a specific configuration property using the `Config::get` static method. ```php public static function get(string $property): mixed ``` -------------------------------- ### createOneStepCharge Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Cria uma cobrança e processa o pagamento em uma única etapa, seja por boleto ou cartão de crédito. Requer os mesmos parâmetros de `createCharge` mais os dados específicos de pagamento. ```APIDOC ## POST /v1/charge/one-step ### Description Cria cobrança e pagamento em uma única etapa. ### Method POST ### Endpoint /v1/charge/one-step ### Parameters #### Request Body Mesma estrutura de `createCharge` + dados de pagamento (cartão ou boleto) ``` -------------------------------- ### Configurar Ambiente de Produção Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/configuracao.md Configura a SDK para o ambiente de produção definindo a opção 'sandbox' como `false`. As requisições serão enviadas para as URLs de produção (`*.api.efipay.com.br`). ```php // Produção $options = [ 'sandbox' => false, 'certificate' => realpath(__DIR__ . '/certificado_producao.p12'), ]; ``` -------------------------------- ### Get Account Credentials Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/payments-statements-accounts.md Retrieves the authentication credentials (Client ID and Client Secret) for a specific account. ```APIDOC ## GET /v1/accounts/:accountId/credentials ### Description Obtains the authentication credentials for the account. ### Method GET ### Endpoint /v1/accounts/:accountId/credentials ### Parameters #### Path Parameters - **accountId** (string) - Required - The ID of the account whose credentials are to be retrieved ### Response #### Success Response (200) - **clientId** (string) - The client ID for authentication - **clientSecret** (string) - The client secret for authentication #### Response Example ```json { "clientId": "CLIENT123", "clientSecret": "SECRET123" } ``` ``` -------------------------------- ### Get Account Webhook Details Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/payments-statements-accounts.md Retrieve the details of a specific account webhook configuration using its ID. ```php $efi->accountDetailWebhook(['id' => 'WEBHOOK_ID']); ``` -------------------------------- ### Create Plan - PHP Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/charges.md Use this method to create a new subscription plan. It requires a name, interval details (frequency like 'monthly' or 'yearly'), and a list of items with their names and values. Custom metadata can also be included. ```php $plan = $efi->createPlan( [], [ 'name' => 'Plano Premium', 'interval' => [ 'frequency' => 'monthly' ], 'items' => [ [ 'name' => 'Acesso Premium', 'value' => 9900 ] ] ] ); echo "Plano ID: " . $plan['id']; ``` -------------------------------- ### pixDetailWebhook Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/pix.md Retrieves the details of a specific Pix webhook. Use this method to get information about a particular webhook configuration. ```APIDOC ## GET /v2/webhook/:chave ### Description Gets details of a webhook. ### Method GET ### Endpoint /v2/webhook/:chave ### Parameters #### Path Parameters - **chave** (string) - Required - Pix key for the webhook details ``` -------------------------------- ### Iniciar Pagamento Pix Imediato Open Finance Source: https://github.com/efipay/sdk-php-apis-efi/blob/main/_autodocs/api-reference/open-finance.md Inicia um pagamento Pix imediato via Open Finance. Forneça o valor em centavos, a chave Pix do recebedor e, opcionalmente, informações adicionais e uma chave de idempotência. O escopo `openfinance.pix.write` é necessário. O retorno inclui uma URL de autorização para redirecionamento do usuário. ```php $payment = $efi->ofStartPixPayment( [], [ 'valor' => 50000, 'chaveDestino' => 'recebedor@example.com', 'infoAdicional' => 'Pagamento via Open Finance' ] ); // Redirecionar usuário para autorizar header('Location: ' . $payment['autorizationUrl']); ```