<?php
namespace App\Controller;
use App\Entity\ConsumerWebService;
use App\Entity\PaymentIntention;
use App\Repository\ConsumerWebServiceRepository;
use App\Repository\PaymentIntentionRepository;
use Doctrine\ORM\EntityManagerInterface;
use Nullix\CryptoJsAes\CryptoJsAesInterno;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Psr\Log\LoggerInterface;
class HomeController extends AbstractController
{
private $client;
private $logger;
public function __construct(HttpClientInterface $client, LoggerInterface $logger)
{
$this->client = $client;
$this->logger = $logger;
}
/**
* @Route("/", name="app_index_home",methods={"GET"})
*/
public function index_home(Request $request): Response
{
return $this->render('home/index.html.twig');
}
/**
* @Route("/get_link", name="app_home",methods={"POST"})
*/
public function index(Request $request, PaymentIntentionRepository $paymentIntentionRepository, EntityManagerInterface $entityManager): Response
{
$data_response = json_decode(
$request->getContent(),
true
);
$datos_ad = $data_response["datos_adicionales"];
$datos_adicionales = "<datos_adicionales>";
$count = 1;
foreach ($datos_ad as $item) {
$datos_adicionales .= '<data id="' . $count . '" display="true">
<label>' . $item["label"] . '</label>
<value>' . $item["value"] . '</value>
</data>';
}
$datos_adicionales .= "</datos_adicionales>";
$params = array(
'id_company' => $_ENV['ID_COMPANY_SANTANDER'],
'id_branch' => $_ENV['ID_BRANCH_SANTANDER'],
'user' => $_ENV['USER_SANTANDER'],
'passwd' => $_ENV['PASWORD_SANTANDER'],
'gen_url' => $_ENV['GEN_URL_SANTANDER'],
'key' => $_ENV['KEY_SANTANDER'],
'data0' => $_ENV['DATA0_SANTANDER']
);
$vigencia = "";
$vigencia_response = $data_response['fh_vigencia'] ?? null;
if ($vigencia_response !== null) {
$vigencia = '<fh_vigencia>'.$data_response["fh_vigencia"].'</fh_vigencia>';
}
$originalString = '<?xml version="1.0" encoding="UTF-8"?>
<P>
<business>
<id_company>'.$_ENV['ID_COMPANY_SANTANDER'].'</id_company>
<id_branch>'.$_ENV['ID_BRANCH_SANTANDER'].'</id_branch>
<user>'.$_ENV['USER_SANTANDER'].'</user>
<pwd>'.$_ENV['PASWORD_SANTANDER'].'</pwd>
</business>
<url>
<reference>'.$data_response["reference"].'</reference>
<amount>'.$data_response["amount"].'</amount>
<moneda>'.$data_response["moneda"].'</moneda>
<canal>W</canal>
<omitir_notif_default>0</omitir_notif_default>
<promociones>'.$data_response["promociones"].'</promociones>
<st_correo>1</st_correo>
' . $vigencia . '
<version>IntegraWPP</version>
' . $datos_adicionales . '
</url>
</P>';
$key = $_ENV['KEY_SANTANDER'];
$encrypted = \AESCrypto::encriptar($originalString, $key);
$result = $this->postWithFetch($encrypted, $params);
$decrypted = \AESCrypto::desencriptar($result, $key);
$array = json_decode(json_encode((array)simplexml_load_string($decrypted)), true);
// Obtén el repositorio de la entidad Producto
$webServiceRepository = $entityManager->getRepository(ConsumerWebService::class);
// Utiliza findOneBy para buscar un producto por nombre
$web_service = $webServiceRepository->findOneBy(['id' => $data_response["web_service"]]);
$paymentIntention = new PaymentIntention();
$paymentIntention->setConsumerWebService($web_service);
$paymentIntention->setPaymentStatus(0);
$paymentIntention->setXmlRequest($originalString);
$paymentIntention->setAmount($data_response["amount"]);
$paymentIntention->setMoneda($data_response["moneda"]);
$paymentIntention->setReference($data_response["reference"]);
$paymentIntention->setPromociones($data_response["promociones"]);
$paymentIntention->setFhVigencia(new \DateTime('now'));
$paymentIntention->setOriginalXmlRequest($decrypted);
$paymentIntention->setCreateAt(new \DateTime('now'));
$paymentIntention->setUpdateAt(new \DateTime('now'));
$paymentIntentionRepository->add($paymentIntention, true);
// error_log($decrypted);
$this->logger->info("decrypted" . $originalString);
return new JsonResponse(
[
'url' => $array["nb_url"],
],
JsonResponse::HTTP_ACCEPTED
);
}
/**
* @Route("/process_payment", name="app_pago", methods={"POST"})
*/
public function pago(Request $request, PaymentIntentionRepository $paymentIntentionRepository, EntityManagerInterface $entityManager, SerializerInterface $serializer)
{
$key = $_ENV['KEY_SANTANDER'];
$encryptedData = $request->request->get('strResponse');
$decrypted = \AESCrypto::desencriptar($encryptedData, $key);
$response_XML = json_decode(json_encode((array)simplexml_load_string($decrypted)), true);
// Obtén el repositorio de la entidad Producto
$paymentIntentionRepository = $entityManager->getRepository(PaymentIntention::class);
// Utiliza findOneBy para buscar un producto por nombre
$paymentIntention = $paymentIntentionRepository->findOneBy(['reference' => $response_XML["reference"]]);
$status = 0;
if ($response_XML["response"] == "approved") {
$status = 1;
} else if ($response_XML["response"] == "denied") {
$status = 2;
} else if ($response_XML["response"] == "error") {
$status = 3;
}
$paymentIntention->setPaymentStatus($status);
$paymentIntention->setOriginalXmlResponse($decrypted);
$paymentIntention->setResponseReceivedAt(new \DateTime('now'));
$paymentIntention->setUpdateAt(new \DateTime('now'));
$paymentIntentionRepository->add($paymentIntention, true);
$url = $paymentIntention->getConsumerWebService()->getWebhook();
$pago = (object)[
'id' => $paymentIntention->getId(),
'referencia' => $paymentIntention->getReference(),
'moneda' => $paymentIntention->getMoneda(),
'paymentStatus' => $paymentIntention->getPaymentStatus(),
'promociones' => $paymentIntention->getPromociones(),
'xmlRequest' => $paymentIntention->getXmlRequest(),
'originalXmlRequest' => $paymentIntention->getOriginalXmlRequest(),
'originalXmlResponse' => $paymentIntention->getOriginalXmlResponse(),
'responseReceivedAt' => $paymentIntention->getResponseReceivedAt(),
'createAt' => $paymentIntention->getCreateAt(),
'updateAt' => $paymentIntention->getUpdateAt(),
'amount' => $paymentIntention->getAmount(),
'costumerService' => $paymentIntention->getConsumerWebService()->getID(),
];
$objeto = (object) [
'referencia' => $response_XML["reference"],
'status' => $response_XML["response"],
'pago' => $pago,
'response' => (array)simplexml_load_string($decrypted)
];
$client = HttpClient::create();
$response = $client->request('POST', $url, [
'headers' => [
'Content-Type' => 'application/json',
],
'body' => json_encode($objeto), // Convierte el array en JSON automáticamente
]);
return new JsonResponse(
[
'data' => "ok",
],
JsonResponse::HTTP_ACCEPTED
);
}
function postWithFetch($encrypted, $params)
{
$body = http_build_query(array(
'xml' => "<pgs><data0>{$params['data0']}</data0><data>{$encrypted}</data></pgs>"
));
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => $body,
'timeout' => 10, // Tiempo máximo de espera
)
);
$context = stream_context_create($options);
$result = @file_get_contents($params['gen_url'], false, $context);
if ($result === FALSE) {
return ''; // Manejar el error como lo desees
}
return $result;
}
}