File: /var/www/vhost/disk-apps/demo.sports-crowd.com/app/Core/Payment/Methods/Stripe/StripeStrategy.php
<?php
declare(strict_types=1);
namespace App\Core\Payment\Methods\Stripe;
use App\Core\Payment\Entities\Payment;
use App\Core\Payment\Entities\PaymentIntentResponse;
use App\Core\Payment\Entities\PaymentRetrieveResponse;
use App\Core\Payment\PaymentMethodInterface;
use App\Core\Payment\PaymentStatusEnum;
use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\StripeClient;
class StripeStrategy implements PaymentMethodInterface
{
const PAYMENT_STATUS = [
"succeeded" => PaymentStatusEnum::CONFIRMED,
"payment_failed" => PaymentStatusEnum::DECLINED,
"requires_payment_method" => PaymentStatusEnum::PENDING
];
private $parameters;
public function __construct(
$parameters
) {
$this->parameters = $parameters;
}
public function pay(Payment $payment): PaymentIntentResponse
{
$paymentIntent = $this->createPaymentIntent($payment);
$paymentIntentResponse = new PaymentIntentResponse(
PaymentIntentResponse::ACTION_SHOW,
$paymentIntent->id
);
$returnUrl = $this->buildReturnUrl($paymentIntent);
$data = [
"clientSecret" => $paymentIntent->client_secret,
"description" => $paymentIntent->description,
"amount" => $paymentIntent->amount,
"currency" => $paymentIntent->currency,
"reference" => $paymentIntent->metadata->reference,
"pubKey" => $this->parameters->client_public,
"returnUrl" => $returnUrl
];
$paymentIntentResponse->setView("stripe.webcheckout");
$paymentIntentResponse->setData($data);
return $paymentIntentResponse;
}
public function retrieve(Payment $payment): PaymentRetrieveResponse
{
try {
$stripe = new StripeClient([
'api_key' => $this->parameters->client_secret
]);
$paymentIntent = $stripe->paymentIntents->retrieve($payment->paymentGatewayTxId());
return new PaymentRetrieveResponse(
$paymentIntent->id,
self::PAYMENT_STATUS[$paymentIntent->status],
$paymentIntent->status
);
} catch (\Throwable $th) {
return new PaymentRetrieveResponse(
$payment->paymentGatewayTxId(),
PaymentStatusEnum::PENDING,
$th->getMessage()
);
}
}
private function createPaymentIntent(Payment $payment)
{
Stripe::setApiKey($this->parameters->client_secret);
$amount = (int)($payment->amount()->total() * 100);
return \Stripe\PaymentIntent::create([
'amount' => $amount,
'currency' => $this->parameters->currency,
'payment_method_types' => [
"card"
],
"metadata" => [
"reference" => $payment->reference()
]
]);
}
private function buildReturnUrl($paymentIntent)
{
$url = config('app.url') . '/store/payment';
$queryString = [
'paymentGatewayId' => $this->parameters->id,
'reference' => $paymentIntent->metadata->reference
];
$queryString = array_merge($queryString, $this->parameters->extraConfirmUrlData);
return Request::create($url)->fullUrlWithQuery($queryString);
}
}