UnknownSec Bypass
403
:
/
mnt
/
lmsestudio-instance-vol002
/
lms_4c865a681939
/
app
/
Services
/ [
drwxr-xr-x
]
Menu
Upload
Mass depes
Mass delete
Terminal
Info server
About
name :
PagarMeServiceApi.php
<?php namespace EstudioLMS\Services; use Carbon\Carbon; use EstudioLMS\Exceptions\Handler; use EstudioLMS\Models\Config\SaasConfig; use Illuminate\Http\Request; use GuzzleHttp\Client; class PagarMeServiceApi { protected $httpClient; protected $apiKey; public function __construct() { $this->apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $this->httpClient = new Client([ 'base_uri' => 'https://api.pagar.me/core/v5/', 'timeout' => 30.0, // 30 segundos timeout total 'connect_timeout' => 10.0, // 10 segundos timeout de conexão 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Basic ' . base64_encode($this->apiKey . ":") ] ]); } // Método removido - Na API v5, conta bancária é criada junto com o recebedor public function createRecipient($bankAccountData, $transferInterval, $transferDay, $transferEnabled, $automaticAnticipationEnabled, $anticipatableVolumePercentage, $registerInformation, $registerInformationPj, $type, $metadata ) { $registerInformationType = ($type == "individual") ? $registerInformation : $registerInformationPj; $response = $this->httpClient->post('recipients', [ 'json' => [ 'name' => $registerInformationType['name'] ?? $registerInformationType['company_name'], 'email' => $registerInformationType['email'], 'description' => 'Recipient created via API', 'document' => $registerInformationType['document_number'], 'type' => $type, 'default_bank_account' => $bankAccountData, 'transfer_settings' => [ 'transfer_enabled' => $transferEnabled, 'transfer_interval' => $transferInterval, 'transfer_day' => $transferDay ], 'automatic_anticipation_settings' => [ 'enabled' => $automaticAnticipationEnabled, 'volume_percentage' => $anticipatableVolumePercentage ], 'metadata' => $metadata ] ]); return json_decode($response->getBody()->getContents(), true); } public function registerRecipient(Request $request, $transferInterval = 'monthly', $transferDay = 15) { $saasConfig = SaasConfig::get()->first(); $data = $request->all(); $bankCode = str_pad($data['bank_id'], 3, '0', STR_PAD_LEFT); $agenciaNumber = $data['agency']; $agenciaDigit = $data['agency_digit'] == '' ? null : $data['agency_digit']; $accountNumber = $data['account']; $accountDigit = $data['account_digit']; $cpf = preg_replace('/[^0-9]/is', '', $data['doc']); $cnpj = preg_replace('/[^0-9]/is', '', $data['cnpj']); $legalName = strlen($data['full_name']) > 30 ? substr($data['full_name'], 0, 29) : $data['full_name']; $accountType = $data['account_type']; // Converter tipo de conta para o formato da API v5 $accountTypeMap = [ 'conta_corrente' => 'checking', 'conta_poupanca' => 'savings' ]; $accountType = isset($accountTypeMap[$accountType]) ? $accountTypeMap[$accountType] : $accountType; $type = ($data['person_type'] == "fisica") ? "individual" : "company"; $documentNumber = ($data['person_type'] == "fisica") ? $cpf : $cnpj; // Na API v5, não criamos conta bancária separadamente $holderType = ($type == "individual") ? "individual" : "company"; $bankAccountData = [ 'bank' => $bankCode, 'branch_number' => $agenciaNumber, 'branch_check_digit' => $agenciaDigit, 'account_number' => $accountNumber, 'account_check_digit' => $accountDigit, 'holder_document' => $documentNumber, 'holder_name' => $legalName, 'holder_type' => $holderType, 'type' => $accountType ]; $birthdate = Carbon::parse($data['birthdate']); $transferEnabled = true; $automaticAnticipationEnabled = false; $anticipatableVolumePercentage = 0; $registerInformation = [ 'type' => 'individual', 'document_number' => $cpf, 'name' => $legalName, 'email' => $data['email'], 'birthdate' => $birthdate->format('Y-m-d'), 'monthly_income' => intval($data['monthly_income']), 'professional_occupation' => $data['professional_occupation'], 'address' => [ 'street' => $data['address_street'], 'complementary' => $data['address_complementary'], 'street_number' => $data['address_street_number'], 'neighborhood' => $data['address_neighborhood'], 'city' => $data['address_city'], 'state' => $data['address_state'], 'zipcode' => $data['address_zipcode'], 'reference_point' => $data['address_reference_point'], 'country' => 'BR' ], 'phone_numbers' => [ [ 'country_code' => '55', 'ddd' => $data['phone_ddd'], 'number' => $data['phone_number'], 'type' => 'mobile' ] ], ]; $metadata = [ 'tenant_id' => $saasConfig->tenant_id, ]; $registerInformationPj = [ 'type' => 'company', 'document_number' => $cnpj, 'company_name' => $data['company_name'], 'trading_name' => $data['trading_name'], 'annual_revenue' => intval($data['annual_revenue']), 'email' => $data['email_company'], 'site_url' => $data['site_url'], 'main_address' => [ 'street' => $data['address_street'], 'complementary' => $data['address_complementary'], 'street_number' => $data['address_street_number'], 'neighborhood' => $data['address_neighborhood'], 'city' => $data['address_city'], 'state' => $data['address_state'], 'zipcode' => $data['address_zipcode'], 'reference_point' => $data['address_reference_point'], 'country' => 'BR' ], 'phone_numbers' => [ [ 'country_code' => '55', 'ddd' => $data['phone_ddd'], 'number' => $data['phone_number'], 'type' => 'mobile' ] ], 'managing_partners' => [ $registerInformation ] ]; try { $recipient = $this->createRecipient( $bankAccountData, $transferInterval, $transferDay, $transferEnabled, $automaticAnticipationEnabled, $anticipatableVolumePercentage, $registerInformation, $registerInformationPj, $type, $metadata ); } catch (\Exception $e) { app(Handler::class)->report($e); return [ 'error_code' => $e->getCode(), 'error_message' => $e->getMessage() ]; } return $recipient; } public function updateRecipient(Request $request) { $data = $request->all(); $recipientId = $data['pagarme_recipient_id'] ?? null; \Illuminate\Support\Facades\Log::info('updateRecipient chamado', [ 'recipient_id' => $recipientId, 'is_new' => empty($recipientId) ]); if (empty($recipientId)) { $recipient = $this->registerRecipient($request); $recipientId = $recipient['id']; } try { // Obter recebedor atual $recipient = $this->getRecipient($recipientId); if (!$recipient) { return ['error' => 'Recebedor não encontrado']; } // APENAS configurações permitidas pela API v5 // Removido completamente o PUT do recebedor pois na v5 quase nada pode ser alterado // Apenas conta bancária pode ser atualizada via endpoint específico \Illuminate\Support\Facades\Log::info('API v5: Pulando atualização de configurações do recebedor (não permitido)', [ 'recipient_id' => $recipientId, 'method' => 'updateRecipient', 'action' => 'skip_recipient_update' ]); $updateResp = ['success' => true]; // Simulando sucesso para não quebrar o fluxo // Verificar se conta bancária mudou e atualizar separadamente if ($this->bankAccountChanged($recipient, $data)) { \Illuminate\Support\Facades\Log::info('Detectada alteração na conta bancária', [ 'recipient_id' => $recipientId ]); $bankAccountResult = $this->updateBankAccount($recipientId, $data); if (is_array($bankAccountResult) && isset($bankAccountResult['error'])) { if ($bankAccountResult['error'] === 'allow_list_required') { \Illuminate\Support\Facades\Log::warning('Allow List necessária para atualizar conta bancária', [ 'recipient_id' => $recipientId, 'message' => $bankAccountResult['message'] ]); // Retorna aviso mas não falha o processo return [ 'warning' => 'allow_list_required', 'message' => $bankAccountResult['message'], 'dashboard_url' => $bankAccountResult['dashboard_url'], 'recipient' => $recipient ]; } else { \Illuminate\Support\Facades\Log::error('Erro ao atualizar conta bancária do recebedor: ' . $recipientId); return ['error' => 'Erro ao atualizar conta bancária']; } } else { \Illuminate\Support\Facades\Log::info('Conta bancária atualizada com sucesso', [ 'recipient_id' => $recipientId ]); } } else { \Illuminate\Support\Facades\Log::info('Conta bancária não mudou, nenhuma atualização necessária', [ 'recipient_id' => $recipientId ]); } // Retornar recebedor atualizado return $this->getRecipient($recipientId); } catch (\Exception $e) { \Illuminate\Support\Facades\Log::error('Erro ao atualizar recebedor: ' . $e->getMessage()); return [ 'error_code' => $e->getCode(), 'error_message' => $e->getMessage() ]; } } /** * Verifica se os dados da conta bancária mudaram */ private function bankAccountChanged($recipient, $data) { if (!isset($recipient['default_bank_account'])) { return false; } $account = $recipient['default_bank_account']; $bankCode = str_pad($data['bank_id'], 3, '0', STR_PAD_LEFT); $agenciaNumber = $data['agency']; $agenciaDigit = $data['agency_digit'] == '' ? null : $data['agency_digit']; $accountNumber = $data['account']; $accountDigit = $data['account_digit']; return ($account['bank'] !== $bankCode || $account['branch_number'] !== $agenciaNumber || $account['branch_check_digit'] !== $agenciaDigit || $account['account_number'] !== $accountNumber || $account['account_check_digit'] !== $accountDigit); } /** * Atualiza apenas a conta bancária do recebedor * Endpoint separado conforme documentação API v5 * ATENÇÃO: Requer Allow List configurada no painel Pagar.me */ public function updateBankAccount($recipientId, $data) { // IMPORTANTE: A API v5 tem limitações severas para atualização de conta bancária // e requer Allow List configurada no painel Pagar.me \Illuminate\Support\Facades\Log::warning('Tentativa de atualizar conta bancária - Requer Allow List', [ 'recipient_id' => $recipientId, 'notice' => 'API v5 requer configuração de Allow List no painel Pagar.me para este endpoint' ]); // Por limitações da API v5 e necessidade de Allow List, // vamos apenas registrar a tentativa e retornar falso // O usuário deve atualizar manualmente no painel Pagar.me return [ 'error' => 'allow_list_required', 'message' => 'Atualização de conta bancária requer configuração de Allow List no painel Pagar.me. Atualize manualmente no dashboard.', 'dashboard_url' => 'https://dashboard.pagar.me/' ]; } public function qrcodeRender($recipientId) { try { $response = $this->httpClient->post("recipients/{$recipientId}/kyc_link", [ 'json' => [ 'type' => 'link' ] ]); if($response){ return json_decode($response->getBody()->getContents(), true); } else { return false; } } catch (\Exception $e) { // Log do erro para debug \Illuminate\Support\Facades\Log::error('Erro ao gerar QR Code KYC: ' . $e->getMessage()); return false; } } function getRecipient($recipientId){ try { $response = $this->httpClient->get("recipients/{$recipientId}"); if($response){ $recipient = json_decode($response->getBody()->getContents(), true); \Illuminate\Support\Facades\Log::info('Recebedor obtido com sucesso', [ 'recipient_id' => $recipientId, 'status' => $recipient['status'] ?? 'unknown', 'has_default_bank_account' => isset($recipient['default_bank_account']) ]); return $recipient; } else { return false; } } catch (\Exception $e) { // Log do erro para debug \Illuminate\Support\Facades\Log::error('Erro ao buscar recebedor: ' . $e->getMessage(), [ 'recipient_id' => $recipientId, 'error_code' => $e->getCode(), 'error_class' => get_class($e) ]); return false; } } }
Copyright © 2026 - UnknownSec