<?php
namespace App\Controller;
use App\Entity\Client;
use App\Entity\Config;
use Prophecy\Call\Call;
use App\Services\CallApiTab;
use Psr\Log\LoggerInterface;
use App\Services\webhooksMollie;
use App\Services\CallApiServices;
use PhpParser\Node\Expr\Instanceof_;
use App\Services\QuestionMailService;
use DateTime;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
class TarifsController extends AbstractController
{
private $logger;
private $paypalClientID;
private $paypalSecret;
public function __construct(CallApiTab $callApiTab, LoggerInterface $logger, $paypalClientID, $paypalSecret)
{
$this->logger = $logger;
$this->endpoint = $callApiTab->endpoint();
$this->paypalClientID = $paypalClientID;
$this->paypalSecret = $paypalSecret;
}
/**
* @Route("/tarifs", name="app_tarifs")
*/
public function index(CallApiServices $callApiServices, Request $request): Response
{
$user = $this->getUser();
$serviceId = $this->getParameter('app.serviceId');
if ($user) {
$client = $callApiServices->clientProfileCheck($serviceId, $user->getClientId());
$user->setSolde($client['solde']);
}
$serviceId = $this->getParameter('app.serviceId');
$accountId = $this->getParameter('app.accountId');
$session = $request->getSession();
$config = $callApiServices->configuratationPlateforme($accountId, $serviceId);
$configPlateforme = new Config();
$configPlateforme->setKindOfCredit($config['kindOfCredit']);
$configPlateforme->setItemsPerPage($config['itemsPerPage']);
$configPlateforme->setItemsPerRow($config['itemsPerRow']);
$configPlateforme->setWelcomeCredit($config['welcomeCredit']);
$configPlateforme->setRecaptchaTab($config['recaptchaTab']);
$configPlateforme->setPaymentInfos($config['paymentInfos']);
$configPlateforme->setMail($config['mail']);
$configPlateforme->setServiceId($serviceId);
$configPlateforme->setAccountId($accountId);
$configPlateforme->setMarchand($config['marchand']);
$payementInfo = $configPlateforme->getPaymentInfos();
if (isset($payementInfo['oonex']) && ($payementInfo['oonex']['activer'] == 1)) {
$activeOonex = true;
} else {
$activeOonex = false;
}
if (isset($payementInfo['mollie']) && ($payementInfo['mollie']['activer'] == 1)) {
$activeMollie = true;
} else {
$activeMollie = false;
}
if (isset($payementInfo['paypal']) && ($payementInfo['paypal']['activer'] == 1)) {
$activePaypal = true;
} else {
$activePaypal = false;
}
if (isset($payementInfo['mobiyo']) && ($payementInfo['mobiyo']['activer'] == 1)) {
$activeMobiyo = true;
} else {
$activeMobiyo = false;
}
$session->set('activeOonex', $activeOonex);
$session->set('activeMollie', $activeMollie);
$session->set('activePaypal', $activePaypal);
$session->set('activeMobiyo', $activeMobiyo);
$tarifsPlateforme = $callApiServices->tarifsPlateforme($serviceId);
return $this->render('tarifs/index.html.twig', [
'tarifsPlateforme' => $tarifsPlateforme,
'activeOonex' => $activeOonex,
'activeMollie' => $activeMollie,
'activePaypal' => $activePaypal,
'activeMobiyo' => $activeMobiyo,
]);
}
/**
* @Route("/payment/{id}", name="app_payment")
*/
public function payment(CallApiServices $callApiServices, $id, Request $request): Response
{
$user = $this->getUser();
if ($user instanceof Client) {
$serviceId = $user->getServiceId();
$code = $user->getCode();
$email = $user->getEmail();
$clientId = $user->getClientId();
$firstName = $user->getFirstName();
$lastName = $user->getLastName();
}
$tarifsPlateforme = $callApiServices->tarifsPlateforme($serviceId);
$prix = $tarifsPlateforme[$id]['prix'];
$data = array('act' => 'emspay', 'mnt' => number_format($prix, 2), 'devise' => '978', 'ref' => 'REF_' . $clientId . '_' . time());
$serviceId = $this->getParameter('app.serviceId');
$accountId = $this->getParameter('app.accountId');
$table = [
'amount' => $prix,
'reference' => $data['ref'],
'accountId' => $accountId,
'serviceId' => $serviceId,
'stamp' => time() + 2 * 60,
'idClient' => $clientId,
'code' => $code,
'customREF' => $data['ref']
];
$customTable = json_encode($table);
$table = base64_encode($customTable);
$time = new \DateTime();
$time = $time->format('d/m/Y');
$session = $request->getSession();
$config = $session->get('configPlateforme');
return $this->render('tarifs/payment.html.twig', [
'query' => $table,
'tarif' => $tarifsPlateforme[$id],
'config' => $config,
]);
}
/**
* @Route("/achat", name="app_achat")
*/
public function achat(CallApiServices $callApiServices, Request $request): Response
{
return $this->redirectToRoute("app_tarifs");
}
/**
* @Route("/achat/{id}", name="app_parrain")
*/
public function achatParrain(CallApiServices $callApiServices, $id, Request $request): Response
{
$session = $request->getSession();
$session->set('parrainId', $id);
return $this->redirectToRoute("app_tarifs");
}
/**
* @Route("/confirm-transaction/{id}", name="app_confirmTransaction")
*/
public function confirmTransaction(CallApiServices $callApiServices, $id, Request $request): Response
{
$user = $this->getUser();
$serviceId = $this->getParameter('app.serviceId');
if ($user) {
$clientId = $user->getClientId();
$client = $callApiServices->clientProfileCheck($serviceId, $clientId);
if (isset($client['responseCode'])) {
return $this->redirectToRoute('app_logout');
}
$user->setSolde($client['solde']);
}
$session = $request->getSession();
$config = $session->get('configPlateforme');
// $payementInfo = $config->getPaymentInfos();
$clientId = $user->getClientId();
$paypalClientID = $this->paypalClientID;
$paypalSecret = $this->paypalSecret;
$activeOonex = $session->get('activeOonex');
$activePaypal = $session->get('activePaypal');
$activeMollie = $session->get('activeMollie');
$activeMobiyo = $session->get('activeMobiyo');
$serviceId = $config->getServiceId();
$tarifsPlateforme = $callApiServices->tarifsPlateforme($serviceId);
$session->set('tarif', $tarifsPlateforme[$id]);
return $this->render('tarifs/confirmTransaction.html.twig', [
'tarifsPlateforme' => $tarifsPlateforme,
'tarif' => $tarifsPlateforme[$id],
'activeOonex' => $activeOonex,
'activeMollie' => $activeMollie,
'activePaypal' => $activePaypal,
'activeMobiyo' => $activeMobiyo,
'paypalClientID' => $paypalClientID,
'paypalSecret' => $paypalSecret,
'clientId' => $clientId,
'key' => $id,
]);
}
/**
* @Route("/paymentMollie/{id}", name="app_mollie_payment")
*/
public function mollieApi(CallApiServices $callApiServices, Request $request, $id)
{
$client = $this->getUser();
$serviceId = $this->getParameter('app.serviceId');
$accountId = $this->getParameter('app.accountId');
$http_host = $request->server->get('HTTP_HOST');
$config = $callApiServices->configuratationPlateforme($accountId, $serviceId);
$apikey = $config['paymentInfos']['mollie']['apiKey'];
$tarifsPlateforme = $callApiServices->tarifsPlateforme($serviceId);
$montant = $tarifsPlateforme[$id]['prix'];
/** @var Client $client */
$amount = number_format($montant, 2, '.', '');
$orderId = 'REF-' . $client->getClientId() . '_' . time();
$retour = "https://" . $http_host . "/userOperation";
$webhooks = "https://" . $http_host . "/mollieWebhook";
$profileArray = [
'firstName' => $client->getFirstName(),
'lastName' => $client->getLastName(),
'emailId' => $client->getEmail(),
'mobileNo' => $client->getPhoneNumber(),
'IP' => $client->getAddressIp()
];
$customProfile = json_encode($profileArray);
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setApiKey($apikey);
try {
$payment = $mollie->payments->create([
"amount" => [
"currency" => "EUR",
"value" => "$amount"
],
"description" => "Achat d'unitées sur le site " . $http_host,
"metadata" => ["order_id" => $orderId, "client_id" => $client->getClientId(), "customProfile" => $customProfile],
"redirectUrl" => $retour,
"webhookUrl" => $webhooks
]);
header("Location: " . $payment->getCheckoutUrl(), true, 303);
die;
} catch (\Mollie\Api\Exceptions\ApiException $e) {
$error_message = "API call failed: " . \htmlspecialchars($e->getMessage());
$this->_helper->FlashMessenger(array('error' => 'Mollie: error validate' . $error_message));
$this->_redirect('/client/crediter');
return;
}
return $payment;
}
/**
* @Route("/mollieWebhook", name="app_mollie", methods={"POST" })
*/
public function mollieWebhook(CallApiServices $callApiServices, Request $request, QuestionMailService $questionMailService,): Response
{
$sendEmail = false;
// cette fonction n'est pas appelée via le navigateur.
// donc la session précedente n'est plus valide
// il faut obtenir les infos via les parametre "metadata" de la transaction
// on ne peut pas utiliser le token obtenu par la connexion, donc il faut prendre le token figé (idem allo-carte)
// on utilisera donc ce token : ad2762c0071ab6fdbfe9b3591d3822a28ac1373181fa255b650db4561048
$httpMethod = $request->getMethod();
// retrieves JSON or POST variables respectively
if ($request->isMethod('POST') || ('json' === $request->getContentType())) {
$params = $request->request->all();
} else {
// retrieves GET variables
//$params = $request->attributes->get('_route_params');
$params = $request->query->all();
}
$FixedToken = "ad2762c0071ab6fdbfe9b3591d3822a28ac1373181fa255b650db4561048";
$session = $request->getSession();
$session->set('apiToken', $FixedToken);
$serviceId = $this->getParameter('app.serviceId');
$accountId = $this->getParameter('app.accountId');
$config = $callApiServices->configuratationPlateforme($accountId, $serviceId);
$apikey = $config['paymentInfos']['mollie']['apiKey'];
if (($httpMethod=='POST')||($httpMethod=='GET')) {
// Initialize the Mollie API library with your API key.
$mollie = new \Mollie\Api\MollieApiClient();
//'test_CBCbFx5drdcj8FWc6MhfTGFBuAKP7g'
$mollie->setApiKey($apikey);
// Retrieve the payment's current state.
$payment = $mollie->payments->get($params['id']);
$dateTrans = new DateTime($payment->createdAt);
$result_tab = [
"accountId" => $accountId,
"serviceId" => $serviceId,
"clientId" => $payment->metadata->client_id,
"operation" => "payment",
"statusCode" => $payment->status,
"responseCode" => $payment->status,
"paymentSystem" => 'MOLLIE',
"paymentSystem_info" => "Recharge par CB",
"transactionID" => $payment->id,
"transactionDate" => $dateTrans->format("Y-m-d H:i:s"),
"transactionAmount" => number_format($payment->amount->value, 2),
"refClient" => $payment->metadata->order_id,
"etat" => ""
];
// database_write($orderId, $payment->status);
if ($payment->isPaid() && !$payment->hasRefunds() && !$payment->hasChargebacks()) {
$result_tab['etat'] = 'ok';
$sendEmail = true;
$subject = "Confirmation d'une transaction";
$__REGLEMENT_STATUS__ = ">>> REGLEMENT ACCEPTÉ <<<";
} elseif ($payment->isOpen()) {
//$result_tab['etat'] = 'ouvert';
} elseif ($payment->isPending()) {
$result_tab['etat'] = 'attente';
} elseif ($payment->isFailed()) {
$result_tab['etat'] = 'ko';
$sendEmail = false;
$subject = "Echec d'une transaction";
$__REGLEMENT_STATUS__ = ">>> REGLEMENT REFUSÉ <<<";
//$stat_str = " - ". $alloCarte->Description;
} elseif ($payment->isExpired()) {
$result_tab['etat'] = 'expired';
} elseif ($payment->isCanceled()) {
//$result_tab['etat'] = 'annulé';
}
//On vérifie la présence et la validité de tous les paramètres obligatoires
if ( $result_tab['clientId'] && $result_tab['transactionID'] &&
$result_tab['transactionAmount'] && $result_tab['transactionDate'] && ($result_tab['etat'] != "") )
{
$this->logger->debug("result_tab : ". print_r($result_tab,1));
// process transaction
$ret = $callApiServices->cbTransaction($result_tab);
if (isset($ret['responseCode']) && ($ret['responseCode']!=200)) {
$sendEmail = false;
$this->logger->debug("transaction CB retour, responseCode: ". $ret['responseCode']. '- message:'. $ret['message']);
} else {
$this->logger->debug("transaction CB retour: ". print_r($ret,1));
}
if ($ret['sendEmail']==0){
$sendEmail = false;
}
} else {
// debug('Params manquants ou invalides');
}
if ($sendEmail == true) {
$result_tab['subject'] = $subject;
$result_tab['baseURL'] = $this->getParameter('baseURL');
/** @var Client $client */
$clientArray = $callApiServices->clientProfile($result_tab['serviceId'], $result_tab['clientId']);
if (isset($clientArray['responseCode']) && ($clientArray['responseCode']!=200)) {
$this->logger->debug("clientArray, responseCode: ". $ret['responseCode']. '- message:'. $ret['message']);
} else {
$questionMailService->sendMollieEmail($callApiServices, $request, $clientArray, $result_tab);
}
}
}
header("HTTP/1.0 200 OK");
die;
}
/**
* @Route("/api/paypal/", name="paypal_api")
*/
public function paypalApi(CallApiServices $callApiService, CallApiTab $callApiTab, SerializerInterface $serializer, Request $request,): JsonResponse
{
$client = $this->getUser();
$serviceId = $this->getParameter('app.serviceId');
$accountId = $this->getParameter('app.accountId');
$clientId = $client->getClientId();
$apiToken = $client->getApiToken();
$session = $request->getSession();
$tarif = $session->get('tarif');
$data = \json_decode($request->getContent(), true); // On récupère les data postées et on les déserialize
if (empty($content = $data)) {
throw new AccessDeniedHttpException('No data sent');
}
$message = $content;
if ($tarif['kindOfCredit'] == 0) {
$value = $tarif['minutes'];
} else {
$value = $content['purchase_units'][0]['amount']['value'];
}
$operationData = [
"accountId" => $accountId,
"serviceId" => $serviceId,
"clientId" => $clientId,
"description" => "Credit via Paypal",
"typeOperation" => "credit",
"montant" => $value
];
$this->logger->debug('message=', array($message));
if ($content['status'] == 'COMPLETED') {
$this->logger->debug('operationData=', array($operationData));
$webOperatonEndPoint = $this->endpoint['clientsWebOperationAjouter'];
$webOperatonTab = $callApiTab->tab($apiToken, $operationData);
$webOperaton = $callApiService->postApi($webOperatonEndPoint, $webOperatonTab);
$this->logger->debug('webOperaton=', array($webOperaton));
}
$jsonMessage = $serializer->serialize($message, 'json', [
'groups' => ['message'] // On serialize la réponse avant de la renvoyer
]);
return new JsonResponse( // Enfin, on retourne la réponse
$jsonMessage,
Response::HTTP_OK,
[],
true
);
}
/**
* @Route("/api/mobiyo/", name="mobiyo_api")
*/
public function mobiyoApi(CallApiServices $callApiServices, CallApiTab $callApiTab, SerializerInterface $serializer, Request $request,): JsonResponse
{
$client = $this->getUser();
$serviceId = $this->getParameter('app.serviceId');
$accountId = $this->getParameter('app.accountId');
$clientId = $client->getClientId();
$apiToken = $client->getApiToken();
$session = $request->getSession();
$tarif = $session->get('tarif');
$config = $callApiServices->configuratationPlateforme($accountId, $serviceId);
if (isset($config["paymentInfos"]["mobiyo"])){
$mobiyoActiver = $config["paymentInfos"]["mobiyo"]["activer"];
if ($config["paymentInfos"]["mobiyo"]["envKey"] == "DEV"){
$mobiyoEnvKey = 'PROD';
}
$mobiyoApiKey = $config["paymentInfos"]["mobiyo"]["apiKey"];
$mobiyoApiKeySecret = $config["paymentInfos"]["mobiyo"]["apiKeySecret"];
$mobiyoIdSite = $config["paymentInfos"]["mobiyo"]["idSite"];
$mobiyoIdProduit = $config["paymentInfos"]["mobiyo"]["idProduit"];
$mobiyoUrlTransaction = $config["paymentInfos"]["mobiyo"]["urlTransaction"];
$mobiyoUrlPayment = $config["paymentInfos"]["mobiyo"]["urlPayment"];
$mobiyoUrlSuccess = $config["paymentInfos"]["mobiyo"]["urlSuccess"];
$mobiyoUrlFail = $config["paymentInfos"]["mobiyo"]["urlFail"];
$mobiyoUrlCancel = $config["paymentInfos"]["mobiyo"]["urlCancel"];
}
$amount = $tarif['prix'];
if ($mobiyoActiver) {
$amount = number_format($amount, 2, '.', '');
if (isset($mobiyoUrlPayment)) {
$table = [
"amount" => $amount,
"reference" => 'REF_'.$client->getClientId().'_'. time(),
"serviceId" => $serviceId,
"accountId" => $accountId,
"stamp" => time() + 2*60,
"idClient" => $clientId,
"code" => $client->getCode(),
"customREF" => 'REF_'.$client->getClientId().'_'. time(),
];
$customTable = json_encode($table);
$QUERY = base64_encode($customTable);
$url_payment = $mobiyoUrlPayment . "?tr=". $QUERY;
header("Location: ". $url_payment );
die;
}
}
}
}