resq/src/Controller/PayMongoController.php

105 lines
2.8 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\GatewayTransaction;
use App\Ramcar\TransactionStatus;
use App\Service\PayMongoConnector;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PayMongoController extends Controller
{
protected $pm;
protected $em;
public function __construct(PayMongoConnector $pm, EntityManagerInterface $em)
{
$this->pm = $pm;
$this->em = $em;
}
public function listen(Request $req)
{
$payload = json_decode($req->getContent(), true);
// log this callback
$this->pm->log('CALLBACK', "[]", $req->getContent(), 'callback');
// if no event type given, silently fail
if (empty($payload['data'])) {
error_log("Invalid paymongo callback received: " . print_r($payload, true));
return $this->json([
'success' => true,
]);
}
// get event type and process accordingly
$attr = $payload['data']['attributes'];
$event = $attr['data'];
$event_name = $attr['type'];
switch ($event_name) {
case "payment.paid":
return $this->handlePaymentPaid($event);
break;
case "payment.failed":
return $this->handlePaymentPaid($event);
break;
case "payment.refunded": // TODO: handle refunds
case "payment.refund.updated":
case "checkout_session.payment.paid":
default:
break;
}
return $this->json([
'success' => true,
]);
}
protected function handlePaymentPaid($event)
{
$metadata = $event['attributes']['metadata'];
$obj = $this->getTransaction($metadata['transaction_id']);
if (!empty($obj)) {
// mark as paid
$obj->setStatus(TransactionStatus::PAID);
$this->em->flush();
}
return $this->json([
'success' => true,
]);
}
protected function handlePaymentFailed(Request $req)
{
// TODO: do something about failed payments?
return $this->json([
'success' => true,
]);
}
protected function getTransaction($id)
{
//$class_name = 'App\\Entity\\' . $type;
//$instance = new $class_name;
return $this->em->getRepository(GatewayTransaction::class)->find($id);
}
public function paymentSuccess(Request $req)
{
return $this->render('paymongo/success.html.twig');
}
public function paymentCancelled(Request $req)
{
return $this->render('paymongo/cancelled.html.twig');
}
}