<?php
namespace App\Http\Controllers;
use App\Models\Plan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class AsaasController extends Controller
{
private $apiKey;
private $baseUrl;
public function __construct()
{
$this->apiKey = env('ASAAS_API_KEY');
$this->baseUrl = env('ASAAS_BASE_URL', 'https://api.asaas.com/v3');
}
public function showCheckout($planId)
{
$plan = Plan::with('currency')->findOrFail($planId);
abort_unless($plan->currency->currency_code === 'BRL', 403);
return view('asaas.checkout', compact('plan'));
}
public function processPayment(Request $request, $planId)
{
$request->validate([
'cpf_cnpj' => ['required','string','min:11','max:18'],
'name' => ['required','string'],
'email' => ['required','email'],
]);
$plan = Plan::with('currency')->findOrFail($planId);
$cpf = preg_replace('/[^0-9]/', '', $request->cpf_cnpj);
$customer = $this->createOrFindCustomer($cpf, $request->name, $request->email);
if (!$customer || isset($customer['errors'])) {
return back()->withErrors(['asaas' => 'Erro cliente: '.json_encode($customer['errors'] ?? [])]);
}
$userId = Auth::id();
$charge = $this->createPixCharge($customer['id'], $plan->price, 'Plano '.$plan->name, $planId, $userId);
if (!$charge || isset($charge['errors'])) {
return back()->withErrors(['asaas' => 'Erro cobranca: '.json_encode($charge['errors'] ?? [])]);
}
$pixData = $this->getPixQrCode($charge['id']);
return view('asaas.pix', compact('plan', 'charge', 'pixData'));
}
private function createOrFindCustomer($cpfCnpj, $name, $email)
{
$search = Http::withHeaders(['access_token' => $this->apiKey])
->get($this->baseUrl.'/customers', ['cpfCnpj' => $cpfCnpj]);
if ($search->ok() && $search->json('totalCount') > 0) {
return $search->json('data')[0];
}
return Http::withHeaders(['access_token' => $this->apiKey])
->post($this->baseUrl.'/customers', ['name' => $name, 'email' => $email, 'cpfCnpj' => $cpfCnpj])
->json();
}
private function createPixCharge($customerId, $value, $description, $planId, $userId)
{
return Http::withHeaders(['access_token' => $this->apiKey])
->post($this->baseUrl.'/payments', [
'customer' => $customerId,
'billingType' => 'PIX',
'value' => $value,
'dueDate' => date('Y-m-d', strtotime('+1 day')),
'description' => $description,
'externalReference' => 'plan_'.$planId.'_user_'.$userId,
])->json();
}
private function getPixQrCode($chargeId)
{
return Http::withHeaders(['access_token' => $this->apiKey])
->get($this->baseUrl.'/payments/'.$chargeId.'/pixQrCode')
->json();
}
}
|