UnknownSec Bypass
403
:
/
mnt
/
lmsestudio-instance-vol002
/
lms_ea1addfbb834
/
app
/
Services
/ [
drwxr-xr-x
]
Menu
Upload
Mass depes
Mass delete
Terminal
Info server
About
name :
PagarMeService.php
<?php namespace EstudioLMS\Services; use Carbon\Carbon; use EstudioLMS\Cart\Cart; use EstudioLMS\Repositories\Auth\UserRepository; use EstudioLMS\Repositories\Config\PagarmeRecipientInterface; use EstudioLMS\Repositories\Environment\HiredCourseRepository; use EstudioLMS\Repositories\Financial\HireSubscriptionInterface; use EstudioLMS\Repositories\Financial\PayableInterface; use EstudioLMS\Repositories\Financial\PostbackInterface; use EstudioLMS\Repositories\Financial\RecurringInterface; use EstudioLMS\Repositories\Subscription\PeriodicityInterface; use EstudioLMS\Services\Hires\HiringServices; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Session; use PagarMe\Sdk\ClientException; use PagarMe\Sdk\Customer\Address as pgmAddress; use PagarMe\Sdk\Customer\Phone as pgmPhone; use PagarMe\Sdk\PagarMe; use PagarMe\Sdk\SplitRule\SplitRuleCollection; /** * Class PagarMeService * @package EstudioLMS\Services */ class PagarMeService { /** * @var PagarmeRecipientInterface */ private $pagarmeRecipient; /** * @var UserRepository */ private $userRepository; /** * @var PostbackInterface */ private $postback; /** * @var PayableInterface */ private $payable; /** * @var HireSubscriptionInterface */ private $hireSubscription; /** * @var RecurringInterface */ private $recurring; /** * @var PeriodicityInterface */ private $periodicity; /** * @var HiringServices */ private $hiringServices; /** * @var HiredCourseRepository */ private $hiredCourse; /** * PagarMeService constructor. * @param PagarmeRecipientInterface $pagarmeRecipient * @param UserRepository $userRepository * @param PostbackInterface $postback * @param PayableInterface $payable * @param HireSubscriptionInterface $hireSubscription * @param RecurringInterface $recurring * @param PeriodicityInterface $periodicity * @param HiringServices $hiringServices * @param HiredCourseRepository $hiredCourse */ public function __construct( PagarmeRecipientInterface $pagarmeRecipient, UserRepository $userRepository, PostbackInterface $postback, PayableInterface $payable, HireSubscriptionInterface $hireSubscription, RecurringInterface $recurring, PeriodicityInterface $periodicity, HiringServices $hiringServices, HiredCourseRepository $hiredCourse ) { $this->pagarmeRecipient = $pagarmeRecipient; $this->userRepository = $userRepository; $this->postback = $postback; $this->payable = $payable; $this->hireSubscription = $hireSubscription; $this->recurring = $recurring; $this->periodicity = $periodicity; $this->hiringServices = $hiringServices; $this->hiredCourse = $hiredCourse; } /** * @param Request $request * @param string $transferInterval * @param int $transferDay * @return \PagarMe\Sdk\Recipient\Recipient | array */ public function registerRecipient(Request $request, $transferInterval = 'monthly', $transferDay = 15) { $data = $request->all(); $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); $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']; $documentNumber = $data['doc']; $legalName = strlen($data['full_name']) > 30 ? substr($data['full_name'], 0, 29) : $data['full_name']; $accountType = $data['account_type']; try { $bankAccount = $pagarMe->bankAccount()->create( $bankCode, $agenciaNumber, $accountNumber, $accountDigit, $documentNumber, $legalName, $agenciaDigit, $accountType ); } catch (\Exception $e) { \Log::critical($e->getMessage()); return [ 'error_code' => $e->getCode(), 'error_message' => $e->getMessage() ]; } $transferEnabled = true; $automaticAnticipationEnabled = false; $anticipatableVolumePercentage = 0; try { $recipient = $pagarMe->recipient()->create( $bankAccount, $transferInterval, $transferDay, $transferEnabled, $automaticAnticipationEnabled, $anticipatableVolumePercentage ); } catch (\Exception $e) { \Log::critical($e->getMessage()); return [ 'error_code' => $e->getCode(), 'error_message' => $e->getMessage() ]; } return $recipient; } /** * @param Request $request * @return array|\PagarMe\Sdk\Recipient\Recipient */ public function updateRecipient(Request $request) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); $data = $request->all(); $recipientId = isset($data['pagarme_recipient_id']) && !empty($data['pagarme_recipient_id']) ? $data['pagarme_recipient_id'] : null; if (empty($recipientId)) { $recipient = $this->registerRecipient($request); $recipientId = $recipient->getId(); } $recipient = $pagarMe->recipient()->get($recipientId); $bankAccount = null; $newAccountId = 0; $account = $recipient->getBankAccount(); $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']; $documentNumber = $data['doc']; $legalName = strlen($data['full_name']) > 30 ? substr($data['full_name'], 0, 29) : $data['full_name']; $accountType = $data['account_type']; if ($account->getBankCode() !== $bankCode || $account->getAgencia() !== $agenciaNumber || $account->getAgenciaDv() !== $agenciaDigit || $account->getConta() !== $accountNumber || $account->getContaDv() !== $accountDigit) { $bankAccount = $pagarMe->bankAccount()->create( $bankCode, $agenciaNumber, $accountNumber, $accountDigit, $documentNumber, $legalName, $agenciaDigit, $accountType ); $newAccountId = $bankAccount->getId(); } $recipient->setTransferInterval('monthly'); $recipient->setTransferDay(16); $recipient->setTransferEnabled(true); $recipient->setAutomaticAnticipationEnabled(false); $recipient->setAnticipatableVolumePercentage(0); if ($newAccountId > 0 && $newAccountId !== $data['pagarme_account_id']) { $recipient->setBankAccount($bankAccount); } $pagarMe->recipient()->update($recipient); $recipient = $pagarMe->recipient()->get($recipientId); return $recipient; } /** * @param $data * @return pgmAddress */ private function createAddress($data) { $address = new pgmAddress([ 'zipcode' => $data['zipcode'], 'street' => $data['street'], 'street_number' => $data['street_number'], 'complementary' => $data['complementary'], 'neighborhood' => $data['neighborhood'], 'city' => $data['city'], 'state' => $data['state'] ]); return $address; } /** * @param $data * @return pgmPhone */ private function createPhone($data) { $phone = new pgmPhone([ "ddd" => $data['ddd'], "number" => $data['number'] ]); return $phone; } /** * @param $user * @return \PagarMe\Sdk\Customer\Customer */ public function registerCustomer($user) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); $person = strlen($user->cpf) == 11 ? 'individual' : 'corporation'; $type = strlen($user->cpf) == 11 ? 'cpf' : 'cnpj'; $eId = '#' . (string)\Auth::user()->id; $dataAddress = [ 'street' => $user->address->street, 'street_number' => $user->address->number, 'complementary' => $user->address->complement, 'neighborhood' => $user->address->neighborhood, 'zipcode' => $user->address->zip_code, 'city' => $user->address->city, 'state' => $user->address->state ]; $dataPhone = [ "ddd" => substr($user->address->phone, 0, 2), "number" => substr($user->address->phone, 2) ]; $address = $this->createAddress($dataAddress); $phone = $this->createPhone($dataPhone); $customer = $pagarMe->customer()->create( $user->name, $user->email, $user->cpf, $address, $phone ); return $customer; } /** * @param $customerId * @return \PagarMe\Sdk\Customer\Customer */ public function getCustomerByID($customerId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); return $pagarMe->customer()->get($customerId); } /** * @param $customerId * @return \ArrayObject */ public function getCustomerByID_Curl($customerId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey ]; $params = http_build_query($data); $url = "https://api.pagar.me/1/customers/" . $customerId . '?'; $charSet = "UTF-8"; $headers = ["Content-Type: application/json"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url . $params); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); $json = json_decode($result, true); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $json; } /** * @param $cardHash * @param $customerId * @return mixed */ public function storeCardByHashCURL($cardHash, $customerId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey, 'customer_id' => $customerId, 'card_hash' => $cardHash ]; $data = json_encode($data); $url = "https://api.pagar.me/1/cards"; $charSet = "UTF-8"; $headers = ["Content-Type: application/json"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); $json = json_decode($result, true); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $json; } /** * @param $cardId * @return \PagarMe\Sdk\Card\Card */ public function getCardByID($cardId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); $card = $pagarMe->card()->get($cardId); return $card; } /** * @param $customerId * @return \ArrayObject */ public function getAllCustomerCards($customerId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey, 'customer_id' => $customerId, ]; $params = http_build_query($data); $url = "https://api.pagar.me/1/cards?"; $charSet = "UTF-8"; $headers = ["Content-Type: application/json"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url . $params); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); $json = json_decode($result, true); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $json; } /** * @param $cardHashId * @param Cart $cart * @param $subscriptionHash * @param null $userId * @param null $postbackUrl * @param string $softDescriptor * @return \PagarMe\Sdk\Transaction\BoletoTransaction|\PagarMe\Sdk\Transaction\CreditCardTransaction */ public function cardTransaction($cardHashId, Cart $cart, $subscriptionHash = null, $userId = null, $postbackUrl = null, $softDescriptor = '' ) { $userId = is_null($userId) ? \Auth::user()->id : $userId; $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); $recipient = $this->pagarmeRecipient->firstRecord(); $user = $this->userRepository->with([ 'customer' => function ($q) use ($cardHashId) { $q->where('card_id', '=', $cardHashId); } ])->find($userId); $cardCvv = Crypt::decrypt($user->customer[0]->hash); //$cardCvv = '658'; $card = $this->getCardByID($user->customer[0]->card_id); $customer = $this->getCustomerByID(intval($user->customer[0]->customer_id)); $recipientCli = $pagarMe->recipient()->get($recipient->pagarme_recipient_id); $recipientAdm = $pagarMe->recipient()->get(config('pagar_me.PAGAR_ME_RECIPIENT_ID')); $splitRules = new SplitRuleCollection(); $price = ($cart->getGrossAmount() - $cart->getDiscountAmount()) + $cart->getShippingAmount() + $cart->getInstallmentInterest(); $installments = $cart->get('installments'); $adminPerc = Session::get('planLimite.is_free') == true ? 2.4 : 1.4; $adminValue = round((($adminPerc * $price) / 100), 2); $adminValue += 0.5; $valueClient = $price - $adminValue; $adminValue = strval($adminValue * 100); $valueClient = strval($valueClient * 100); $ruleCli = $pagarMe->splitRule()->monetaryRule($valueClient, $recipientCli, true, true, true); $ruleAdm = $pagarMe->splitRule()->monetaryRule($adminValue, $recipientAdm, false, false, false); $splitRules[0] = $ruleCli; $splitRules[1] = $ruleAdm; $extraAttributes = [ 'split_rules' => $splitRules ]; $metaData = [ 'user_email' => $user->email, 'user_id' => $user->id, 'recipient_id' => $recipientCli->getId(), 'instance_email' => Session::get('planLimite.email'), 'product_id' => $cart->get('course_id'), 'plan_id' => $cart->get('plan_id') ]; $https = Session::get('planLimite.ssl_activated') == 1 ? 'https://' : 'http://'; $onlineUrl = $https . Session::get('planLimite.url') . '.' . Session::get('planLimite.domain'); if (!is_null($subscriptionHash)) { $metaData['subscription_hash'] = $subscriptionHash; $onlineUrl .= '/gateway/pagarme/postback'; } else { $onlineUrl .= '/gateway/pagarme/single/postback'; } $postbackUrl = is_null($postbackUrl) ? env('PAGAR_ME_POSTBACK_URL', $onlineUrl) : $postbackUrl; $amount = strval($price * 100); $transaction = $pagarMe->transaction()->creditCardTransaction( $amount, $card, $customer, $cardCvv, $installments, true, $postbackUrl, $metaData, $extraAttributes, $softDescriptor ); $result = null; $result = $this->getTransactionByID($transaction->getId()); while (!method_exists($result, 'getStatus')) { $result = $this->getTransactionByID($transaction->getId()); } while ($result->getStatus() == 'processing') { $result = $this->getTransactionByID($transaction->getId()); } return $result; } /** * @param Cart $cart * @param $subscriptionHash * @param null $userId * @param null $postbackUrl * @return \PagarMe\Sdk\Transaction\BoletoTransaction|\PagarMe\Sdk\Transaction\CreditCardTransaction */ public function boletoTransaction(Cart $cart, $subscriptionHash = null, $userId = null, $postbackUrl = null ) { $userId = is_null($userId) ? \Auth::user()->id : $userId; $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); $recipient = $this->pagarmeRecipient->firstRecord(); $user = $this->userRepository->with(['customer'])->find($userId); $customer = $this->getCustomerByID(intval($user->customer[0]->customer_id)); $recipient98 = $pagarMe->recipient()->get($recipient->pagarme_recipient_id); $recipient2 = $pagarMe->recipient()->get(config('pagar_me.PAGAR_ME_RECIPIENT_ID')); $splitRules = new SplitRuleCollection(); $adminPerc = Session::get('planLimite.is_free') == true ? 3 : 2; $price = ($cart->getGrossAmount() - $cart->getDiscountAmount()) + $cart->getShippingAmount(); $adminValue = round((($adminPerc * $price) / 100), 2); $valueClient = $price - $adminValue; $adminValue = strval($adminValue * 100); $valueClient = strval($valueClient * 100); $rule_98 = $pagarMe->splitRule()->monetaryRule($valueClient, $recipient98, true, true, true); $rule_2 = $pagarMe->splitRule()->monetaryRule($adminValue, $recipient2, false, false, false); $splitRules[0] = $rule_98; $splitRules[1] = $rule_2; $extraAttributes = [ 'split_rules' => $splitRules ]; $metaData = [ 'user_email' => $user->email, 'user_id' => $user->id, 'recipient_id' => $recipient98->getId(), 'instance_email' => Session::get('planLimite.email'), 'product_id' => $cart->get('course_id'), 'plan_id' => $cart->get('plan_id') ]; $https = Session::get('planLimite.ssl_activated') == 1 ? 'https://' : 'http://'; $onlineUrl = $https . Session::get('planLimite.url') . '.' . Session::get('planLimite.domain'); if (!is_null($subscriptionHash)) { $metaData['subscription_hash'] = $subscriptionHash; $onlineUrl .= '/gateway/pagarme/postback'; } else { $onlineUrl .= '/gateway/pagarme/single/postback'; } $postbackUrl = is_null($postbackUrl) ? env('PAGAR_ME_POSTBACK_URL', $onlineUrl) : $postbackUrl; $amount = strval((($cart->getGrossAmount() - $cart->getDiscountAmount()) + $cart->getShippingAmount()) * 100); $transaction = $pagarMe->transaction()->boletoTransaction( $amount, $customer, $postbackUrl, $metaData, $extraAttributes ); $result = null; $result = $this->getTransactionByID($transaction->getId()); while (!method_exists($result, 'getStatus')) { $result = $this->getTransactionByID($transaction->getId()); } while ($result->getStatus() == 'processing') { $result = $this->getTransactionByID($transaction->getId()); } return $result; } /** * @param $id * @return \PagarMe\Sdk\Transaction\BoletoTransaction|\PagarMe\Sdk\Transaction\CreditCardTransaction */ public function getTransactionByID($id) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); $transaction = null; try { $transaction = $pagarMe->transaction()->get($id); } catch (ClientException $e) { \Log::info($e->getMessage()); } return $transaction; } /** * @param $transactionId * @return mixed */ public function getTransactionPayableValues($transactionId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey, 'transaction_id' => $transactionId, 'count' => 1000, 'page' => 1 ]; $params = http_build_query($data); $url = "https://api.pagar.me/1/payables?"; $charSet = "UTF-8"; $headers = ["Content-Type: application/json"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url . $params); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); $json = json_decode($result, true); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $json; } /** * @param Request $request */ public function postback(Request $request) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $pagarMe = new PagarMe($apiKey); $signature = $request->headers->get('x-hub-signature'); $rawBody = $request->getContent(); if ($pagarMe->postback()->validateRequest($rawBody, $signature)) { $data = $request->all(); $json = json_encode($data); $postback = json_decode($json, true); $poId = $signature = $request->headers->get('x-pagarme-delivery'); $message = ''; $transactionId = $postback['id']; if (isset($postback['transaction']['metadata']['subscription_hash'])) { $message = 'Postback de assinatura gravado com sucesso!'; } else { $message = 'Postback de transação avulsa gravado com sucesso!'; } $fingerprint = $postback['fingerprint']; $received = Carbon::now(); $check = $this->postback ->findWhere([ ['payload', '=', $json] ]); if (count($check) == 0) { $this->postback->create([ 'gateway_id' => 1, 'subscription_id' => $transactionId, 'postback_id' => $poId, 'payload' => $json, 'processed' => false, 'received_at' => $received->toDateTimeString() ]); \Log::info($message); } } else { $fillName = uniqid() . '-invalid.txt'; $newFile = fopen($fillName, 'w'); fwrite($newFile, $rawBody); fwrite($newFile, $signature); fclose($newFile); } } /** * @param null $postBackId * Faz o processamento dos postbacks do pagar.me * Invocado pelo listener "created" do model Postback */ public function processPostbacks($postBackId = null) { $postback = $this->postback->findWhere([ ['processed', '=', 0], ['postback_id', '=', $postBackId] ])->first(); $today = Carbon::now()->format('Y-m-d'); $recipientESId = config('pagar_me.PAGAR_ME_RECIPIENT_ID'); $payload = json_decode($postback['payload'], true); if (isset($payload['transaction']['metadata']['subscription_hash'])) { $this->processSubscriptionPostback($payload); $postback->processed = 1; } else { $status = $this->processTrasactionPostback($payload); $postback->processed = $status; } $postback->save(); } /** * @param $payload * Verificar a possibilidade de trabalhar com transação de banco de dados; * Fazer com que esse método, retorne true ou false, e setar o processamento do postback, através desse * resultado; */ public function processSubscriptionPostback($payload) { $today = Carbon::now()->format('Y-m-d'); $tomorow = Carbon::now()->addDay(1)->format('Y-m-d'); if ($payload['event'] == 'transaction_status_changed' && ($payload['current_status'] == 'paid' || $payload['current_status'] == 'waiting_payment')) { $subscriptionHash = $payload['transaction']['metadata']['subscription_hash']; $userEmail = $payload['transaction']['metadata']['user_email']; $paymentMethod = $payload['transaction']['payment_method']; $cardId = $payload['transaction']['payment_method'] == 'credit_card' ? $payload['transaction']['card']['id'] : null; $user = $this->userRepository->findByField('email', $userEmail)->first(); $subscription = $this->hireSubscription->findByField('subscription_hash', $subscriptionHash)->first(); while (!$subscription) { $subscription = $this->hireSubscription->findByField('subscription_hash', $subscriptionHash)->first(); } $periodicityId = $subscription->periodicity_id; $periodicity = $this->periodicity->find($periodicityId); $sumFeeAmount = 0.0; $netAmount = 0.0; $payableStatus = 'waiting_funds'; $paymentDate = null; $payables = null; if ($payload['current_status'] == 'paid') { $hireSubscriptionData = [ 'user_id' => $user->id, 'subscription_id' => $subscription->subscription_id, 'subscription_hash' => $subscriptionHash, 'periodicity_id' => $subscription->periodicity_id, 'gateway_id' => 1, 'payment_code' => $payload['id'], 'payment_type' => $payload['transaction']['payment_method'], 'card_id' => $cardId, 'gross_amount' => $payload['transaction']['amount'] / 100, 'discount_amount' => 0, 'fee_amount' => $sumFeeAmount / 100, 'extra_amount' => 0, 'net_amount' => $netAmount / 100, 'status' => 1 ]; $subscription->fill($hireSubscriptionData); $subscription->save(); } $recurring = $this->recurring->getLatestRecurrence($subscriptionHash); $countRecurrences = $this->recurring->countSubscriptionRecurrences($subscriptionHash); $countRecurrences = $countRecurrences + 1; if ($recurring) { /* * Se a recorrência existe; * Se a recorencia não foi processada, ou * Se a recorrência está com falha no pagamento do cartão, ou * Se a recorrência é um boleto em aberto, E * O postback é um pagamento */ if (($recurring->status == 0 || $recurring->status == 2 || $recurring->status == 3) && $payload['current_status'] == 'paid') { if (Carbon::parse($recurring->next_attempt_date)->format('Y-m-d') >= $today) { $recurring->status = 1; $recurring->attempts = $recurring->attempts + 1; $recurring->payment_date = $today; $recurring->payment_code = $payload['id']; $recurring->fee_amount = $sumFeeAmount; $recurring->net_amount = $netAmount; $recurring->save(); $this->generateNextRecurrence($user, $payload, $recurring->due_date, 0, 0, 0, $cardId, $periodicityId, $countRecurrences); } else { \Log::useDailyFiles(storage_path() . '/logs/command.log'); \Log::info('Problemas na recorrência para a assinatura: ' . $subscription->subscription_hash . ' next_attempt_date < today'); } } elseif (($recurring->status == 0 || $recurring->status == 2 || $recurring->status == 3) && $payload['current_status'] !== 'paid') { \Log::info('Achou uma recorrência, com status não processado ou falha. não vai pagar, só atualizar!'); /* * Se a recorrência existe; * Se a recorencia não foi processada, ou * Se a recorrência está com falha no pagamento do cartão, ou * Se a recorrência é um boleto em aberto, E * O postback NÃO é um pagamento * * Só atualizar a recorrência, para ser cobrada/verificada no próximo dia */ $nextAttemptDate = Carbon::parse($recurring->next_attempt_date)->addDay()->format('Y-m-d'); $recurring->attempts = $recurring->attempts + 1; $recurring->next_attempt_date = $nextAttemptDate; $recurring->payment_code = $payload['id']; $recurring->status = $payload['transaction']['payment_method'] == 'credit_card' ? 2 : 3; $recurring->save(); } } else { /* * Não existe recorrência. * Criar a recorrência atual. * criar a próxima recorrência. * Se for boleto, criar apenas a recorrência atual, não paga, com boleto em processamento. */ if ($payload['transaction']['payment_method'] == 'credit_card') { $retroDate = Carbon::parse($subscription->created_at)->format('Y-m-d'); \Log::info('Não achou recorrência! Vaiu gerar as duas credit_card.'); $this->generateFirstRecurrence($user, $payload, $retroDate, 1, $sumFeeAmount, $netAmount, $cardId); sleep(1); $this->generateNextRecurrence($user, $payload, $retroDate, 0, 0, 0, $cardId, $periodicityId, 2); } else { $retroDate = Carbon::parse($subscription->created_at)->format('Y-m-d'); \Log::info('Não achou recorrência! Vaiu gerar só um boleto.'); $this->generateFirstRecurrence($user, $payload, $retroDate, 3); } } } } /** * @param $date * @param $periodicityId * @return Carbon */ private function getDueDate($date, $periodicityId) { $periodicity = $this->periodicity->find($periodicityId); switch ($periodicity->periodicity) { case 30: $nextDueDate = Carbon::parse($date)->addMonth(); break; case 90: $nextDueDate = Carbon::parse($date)->addMonth(3); break; case 180: $nextDueDate = Carbon::parse($date)->addMonth(6); break; case 365: $nextDueDate = Carbon::parse($date)->addYear(); break; } return $nextDueDate; } /** * @param $user * @param $payload * @param $today * @param $status * @param int $sumFeeAmount * @param int $netAmount * @param null $cardId */ private function generateFirstRecurrence($user, $payload, $today, $status, $sumFeeAmount = 0, $netAmount = 0, $cardId = null) { $tomorow = Carbon::now()->addDay()->format('Y-m-d'); $attempts = Carbon::parse($today)->diffInDays(Carbon::now()); //$attempts = $attempts > 0 ? $attempts - 1 : $attempts; $recurrence = $this->recurring->create([ 'user_id' => $user->id, 'subscription_hash' => $payload['transaction']['metadata']['subscription_hash'], 'gateway_id' => 1, 'due_date' => $today, 'next_attempt_date' => $payload['transaction']['payment_method'] == 'credit_card' ? $today : $tomorow, 'payment_code' => $payload['id'], 'payment_type' => $payload['transaction']['payment_method'], 'card_id' => $cardId, 'payment_date' => $payload['transaction']['payment_method'] == 'credit_card' ? $today : null, 'attempts' => $payload['transaction']['payment_method'] == 'credit_card' ? 1 : 0, 'gross_amount' => ($payload['transaction']['amount'] / 100), 'discount_amount' => null, 'fee_amount' => $sumFeeAmount / 100, 'extra_amount' => null, 'net_amount' => $netAmount / 100, 'charge_number' => 1, 'status' => $status ]); } /** * @param $user * @param $payload * @param $dueDate * @param int $status * @param int $sumFeeAmount * @param int $netAmount * @param null $cardId * @param int $periodicityId * @param int $chargeNumber */ private function generateNextRecurrence($user, $payload, $dueDate, $status = 0, $sumFeeAmount = 0, $netAmount = 0, $cardId = null, $periodicityId = 0, $chargeNumber = 1) { try { $recurrence = $this->recurring->create([ 'user_id' => $user->id, 'subscription_hash' => $payload['transaction']['metadata']['subscription_hash'], 'gateway_id' => 1, 'due_date' => $this->getDueDate($dueDate, $periodicityId), 'next_attempt_date' => $this->getDueDate($dueDate, $periodicityId), 'payment_type' => $payload['transaction']['payment_method'], 'card_id' => $cardId, 'payment_date' => null, 'attempts' => 0, 'gross_amount' => ($payload['transaction']['amount'] / 100), 'discount_amount' => null, 'fee_amount' => $sumFeeAmount / 100, 'extra_amount' => null, 'net_amount' => $netAmount / 100, 'charge_number' => $chargeNumber, 'status' => $status ]); } catch (\Exception $e) { \Log::error('Erro ao criar recorrência para assinatura ' . $payload['transaction']['metadata']['subscription_hash']); \Log::error($e->getTraceAsString()); } } /** * @param $payload * @return int */ public function processTrasactionPostback($payload) { $today = Carbon::now()->format('Y-m-d'); $tomorow = Carbon::now()->addDay(1)->format('Y-m-d'); $recipientESId = config('pagar_me.PAGAR_ME_RECIPIENT_ID'); if ($payload['event'] == 'transaction_status_changed' && ( $payload['current_status'] == 'paid' || $payload['current_status'] == 'waiting_payment' || $payload['current_status'] == 'refunded')) { $userEmail = $payload['transaction']['metadata']['user_email']; $paymentMethod = $payload['transaction']['payment_method']; $cardId = $payload['transaction']['payment_method'] == 'credit_card' ? $payload['transaction']['card']['id'] : null; $hiring = $this->hiringServices->getByPaymentCode($payload['id']); $counter = 0; while (!$hiring) { $hiring = $this->hiringServices->getByPaymentCode($payload['id']); $counter += 1; if ($counter > 20) { break; } } if ($hiring) { $payables = null; $totalFeeAmount = 0.00; if ($payload['current_status'] == 'paid') { while (count($payables) <= 1) { $payables = $this->getTransactionPayableValues($payload['id']); } for ($i = 0; $i <= count($payables) - 1; $i++) { if ($payables[$i]['recipient_id'] == $recipientESId) { $totalFeeAmount += $payables[$i]['amount']; } else { $totalFeeAmount += $payables[$i]['fee']; } } $totalFeeAmount = $totalFeeAmount / 100; } $hiringData = [ 'fee_amount' => $totalFeeAmount, 'net_amount' => ($hiring->gross_amount - ($hiring->discount_amount + $totalFeeAmount)) + $hiring->installment_interest, 'status' => \GatHelper::translateGatewayStatus( 'PagarMe', $payload['current_status'] ) ]; $hiring->fill($hiringData)->save(); $hiredCourse = [ 'user_id' => $hiring->user_id, 'course_id' => $hiring->course_id, 'plan_id' => $hiring->plan_id, 'hirings_id' => $hiring->id, 'status' => \GatHelper::translateGatewayStatus( 'PagarMe', $payload['current_status'] ), 'is_free' => false ]; $renew = $this->hiredCourse->findWhere([ ['user_id', '=', $hiring->user_id], ['course_id', '=', $hiring->course_id] ])->first(); $renew->fill($hiredCourse)->save(); if ($payload['current_status'] == 'paid') { $recipient = $this->pagarmeRecipient->firstRecord(); //Ordenando o array de payables por recipient_id e payment_date $recipId = array_column($payables, 'recipient_id'); $date = array_column($payables, 'payment_date'); array_multisort($recipId, SORT_ASC, $date, SORT_ASC, $payables); //Filtrando o array de payables, para pegar apenas os registros do recebedor principal $filterBy = $recipient->pagarme_recipient_id; $arrayRecipients = array_filter($payables, function ($arr) use ($filterBy) { return ($arr['recipient_id'] == $filterBy); }); foreach ($arrayRecipients as $index => $arrayRecipient) { $tempArray = array_filter($payables, function ($arr) use ($arrayRecipient, $recipientESId) { return $arr['recipient_id'] == $recipientESId && $arr['payment_date'] == $arrayRecipient['payment_date']; }); $index = array_keys($tempArray)[0]; $sumFeeAmount = $arrayRecipient['fee']; $netAmount = $arrayRecipient['amount'] - $arrayRecipient['fee']; $payableStatus = $arrayRecipient['status']; $paymentDate = Carbon::parse($arrayRecipient['payment_date'])->format('Y-m-d H:s:i'); $payableData = [ 'subscription_hash' => $payload['id'], 'payment_code' => $payload['id'], 'payment_type' => $payload['transaction']['payment_method'], 'payment_date' => $paymentDate, 'card_id' => $cardId, 'gross_amount' => $arrayRecipient['amount'] / 100, 'discount_amount' => 0, 'fee_amount' => $sumFeeAmount / 100, 'extra_amount' => 0, 'net_amount' => $netAmount / 100, 'payable_status_id' => $payableStatus == 'paid' ? 2 : 1 ]; $payable = $this->payable->findWhere([ ['subscription_hash', '=', $payload['id']], ['payment_code', '=', $payload['id']], ['payment_date', '=', $paymentDate], ['payable_status_id', '=', $payableData['payable_status_id']] ])->first(); if ($payable) { $payable->fill($payableData)->save(); } else { $payable = $this->payable->create($payableData); } } } if ($payload['current_status'] == 'refunded') { $hiringData = [ 'status' => \GatHelper::translateGatewayStatus( 'PagarMe', $payload['current_status'] ) ]; $hiring->fill($hiringData)->save(); $hiredCourse = [ 'status' => \GatHelper::translateGatewayStatus( 'PagarMe', $payload['current_status'] ), 'is_free' => false ]; $renew = $this->hiredCourse->findWhere([ ['user_id', '=', $hiring->user_id], ['course_id', '=', $hiring->course_id] ])->first(); $renew->fill($hiredCourse)->save(); } } else { return 5; } return 1; } return 1; } /** * @param string $email * @param int $transactionId * @return mixed */ public function collectPayment(string $email, int $transactionId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey, 'email' => $email ]; $data = json_encode($data); $url = "https://api.pagar.me/1/transactions/" . $transactionId . '/collect_payment'; $charSet = "UTF-8"; $headers = ["Content-Type: application/json"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); $json = json_decode($result, true); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $json; } /** * @return mixed */ public function balance() { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey ]; $params = http_build_query($data); $recipient = $this->pagarmeRecipient->firstRecord(); $recipientId = $recipient->pagarme_recipient_id; $url = "https://api.pagar.me/1/recipients/" . $recipientId . "/balance?"; $charSet = "UTF-8"; $headers = ["Content-Type: application/json"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url . $params); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); $json = json_decode($result, true); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $json; } /** * @return bool|mixed|string */ public function getBalanceOperations() { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $dataCurl = [ 'api_key' => $apiKey, 'count' => 1000, 'page' => 1 ]; $recipient = $this->pagarmeRecipient->firstRecord(); $recipientId = $recipient->pagarme_recipient_id; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.pagar.me/1/recipients/$recipientId/balance/operations", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30000, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS => json_encode($dataCurl), CURLOPT_HTTPHEADER => array( "content-type: application/json", ), )); $response = curl_exec($curl); $response = json_decode($response, true); return $response; } /** * @return bool|mixed|string */ public function getBalanceSpecificOperation($balanceId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $dataCurl = [ 'api_key' => $apiKey, 'count' => 1000, 'page' => 1 ]; $recipient = $this->pagarmeRecipient->firstRecord(); $recipientId = $recipient->pagarme_recipient_id; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://api.pagar.me/1/recipients/$recipientId/balance/operations/$balanceId", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30000, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS => json_encode($dataCurl), CURLOPT_HTTPHEADER => array( "content-type: application/json", ), )); $response = curl_exec($curl); $response = json_decode($response, true); return $response; } /** * @param $amount * @param $freeInstalments * @param $maxInstalments * @param $interestRate * @return mixed */ public function installments($amount, $freeInstalments, $maxInstalments, $interestRate) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey, 'amount' => $amount, 'free_installments' => $freeInstalments, 'max_installments' => $maxInstalments, 'interest_rate' => $interestRate ]; $url = "https://api.pagar.me/1/transactions/calculate_installments_amount/"; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30000, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => array( "content-type: application/json", ), )); $response = curl_exec($curl); $response = json_decode($response, true); $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); return $response; } /** * @param $transactionId * @param $bankAccount * @return mixed */ public function cancelTransaction($transactionId, $bankAccount = null) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey, ]; if (isset($bankAccount)) { $data['bank_account'] = [ 'bank_code' => $bankAccount['bank_id'], 'agencia' => $bankAccount['agency'], 'conta' => $bankAccount['account'], 'conta_dv' => $bankAccount['account_digit'], 'type' => $bankAccount['account_type'], 'document_number' => $bankAccount['document_number'], 'legal_name' => $bankAccount['legal_name'] ]; } $data = json_encode($data); $url = "https://api.pagar.me/1/transactions/" . $transactionId . '/refund'; $charSet = "UTF-8"; $headers = ["Content-Type: application/json"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch); $json = json_decode($result, true); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); return $json; } /** * @param $documentNumber * @return mixed */ public function getBankAccountByDocument($documentNumber) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey, 'count' => 1, 'document_number' => $documentNumber ]; $url = "https://api.pagar.me/1/bank_accounts"; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30000, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => array( "content-type: application/json", ), )); $response = curl_exec($curl); $response = json_decode($response, true); $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); return $response; } /** * @param $transactionId * @return mixed */ public function getRefundTransaction($transactionId) { $apiKey = config('pagar_me.PAGAR_ME_API_KEY'); $data = [ 'api_key' => $apiKey, 'transaction_id' => $transactionId ]; $url = "https://api.pagar.me/1/refunds"; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30000, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => array( "content-type: application/json", ), )); $response = curl_exec($curl); $response = json_decode($response, true); $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); return $response; } }
Copyright © 2026 - UnknownSec