add all controllers logic
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
namespace App\Services\Payments;
|
||||
|
||||
use App\Models\Payment;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class PaypalPaymentService
|
||||
@@ -55,12 +56,13 @@ class PaypalPaymentService
|
||||
$paypalPayment->setRedirectUrls($redirectUrls);
|
||||
$paypalPayment->create($apiContext);
|
||||
|
||||
session()->put('paypalPaymentId', $paypalPayment->getId());
|
||||
session()->put('paymentId', $paymentId);
|
||||
Cache::put($this->cacheKey((string) $paypalPayment->getId()), $paymentId, now()->addHours(2));
|
||||
|
||||
return [
|
||||
'redirect_url' => $paypalPayment->getApprovalLink(),
|
||||
'mode' => 'sdk',
|
||||
'paypal_payment_id' => $paypalPayment->getId(),
|
||||
'payment_id' => $paymentId,
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('PayPal create payment failed: ' . $e->getMessage());
|
||||
@@ -68,27 +70,33 @@ class PaypalPaymentService
|
||||
}
|
||||
}
|
||||
|
||||
public function executePayment(string $payerId, ?string $paypalPaymentId = null): void
|
||||
public function executePayment(string $payerId, ?string $paypalPaymentId = null, ?int $paymentId = null): void
|
||||
{
|
||||
if (!$this->sdkAvailable()) {
|
||||
throw new \RuntimeException('PayPal SDK not installed.');
|
||||
}
|
||||
|
||||
$paymentId = $paypalPaymentId ?: (string) session()->get('paypalPaymentId');
|
||||
if (!$paymentId) {
|
||||
$paypalId = $paypalPaymentId ?: '';
|
||||
if ($paypalId === '') {
|
||||
throw new \RuntimeException('Missing PayPal payment ID.');
|
||||
}
|
||||
|
||||
$apiContext = $this->buildApiContext();
|
||||
$payment = \PayPal\Api\Payment::get($paymentId, $apiContext);
|
||||
$payment = \PayPal\Api\Payment::get($paypalId, $apiContext);
|
||||
$execution = new \PayPal\Api\PaymentExecution();
|
||||
$execution->setPayerId($payerId);
|
||||
|
||||
$payment->execute($execution, $apiContext);
|
||||
|
||||
$internalPaymentId = (int) session()->get('paymentId');
|
||||
$internalPaymentId = $paymentId;
|
||||
if (!$internalPaymentId && $paypalId !== '') {
|
||||
$internalPaymentId = (int) Cache::get($this->cacheKey($paypalId));
|
||||
}
|
||||
if ($internalPaymentId) {
|
||||
Payment::query()->whereKey($internalPaymentId)->update(['status' => 'Completed']);
|
||||
if ($paypalId !== '') {
|
||||
Cache::forget($this->cacheKey($paypalId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,4 +128,9 @@ class PaypalPaymentService
|
||||
|
||||
return $apiContext;
|
||||
}
|
||||
|
||||
private function cacheKey(string $paypalPaymentId): string
|
||||
{
|
||||
return 'paypal_payment:' . $paypalPaymentId;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user