<?php
namespace App\Controller;
use App\Entity\Client;
use App\Entity\Config;
use App\Services\CallApiServices;
use App\Services\QuestionMailService;
use App\Services\webhooksMollie;
use PhpParser\Node\Expr\Instanceof_;
use Prophecy\Call\Call;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Psr\Log\LoggerInterface;
use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
class TarifsController extends AbstractController
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @Route("/tarifs", name="app_tarifs")
*/
public function index(CallApiServices $callApiServices): Response
{
$config = new Config();
$serviceId = $config->getServiceId();
$tarifsPlateforme = $callApiServices->tarifsPlateforme($serviceId);
return $this->render('tarifs/index.html.twig', [
'tarifsPlateforme' => $tarifsPlateforme,
]);
}
/**
* @Route("/payment/{id}", name="app_payment")
*/
public function payment(CallApiServices $callApiServices, $id): Response
{
$accountId = $this->getParameter('app.accountId');
$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());
$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');
$config = new Config();
return $this->render('tarifs/payment.html.twig', [
'query' => $table,
'tarif' => $tarifsPlateforme[$id],
'config' => $config,
]);
}
/**
* @Route("/tarifs/{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): Response
{
$serviceId = $this->getParameter('app.serviceId');
$accountId = $this->getParameter('app.accountId');
$tarifsPlateforme = $callApiServices->tarifsPlateforme($serviceId);
return $this->render('tarifs/confirmTransaction.html.twig', [
'tarifsPlateforme' => $tarifsPlateforme,
'tarif' => $tarifsPlateforme[$id],
'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');
$tarifsPlateforme = $callApiServices->tarifsPlateforme($serviceId);
$montant = $tarifsPlateforme[$id]['prix'];
$amount = number_format($montant, 2, '.', '');
$orderId = 'REF-' . $client->getClientId() . '_' . time();
$retour = "https://" . $http_host . "/userOperation";
$webhooks = "https://" . $http_host . "/mollieWebhook";
$config = $callApiServices->configuratationPlateforme($accountId, $serviceId);
$apikey = $config['paymentInfos']['mollie']['apiKey'];
$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" => "Order #12345",
"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
{
$client = $this->getUser();
$serviceId = $this->getParameter('app.serviceId');
$accountId = $this->getParameter('app.accountId');
$config = $callApiServices->configuratationPlateforme($accountId, $serviceId);
$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');
}
//
$apikey = $config['paymentInfos']['mollie']['apiKey'];
if ($httpMethod=='POST') {
// 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']);
$result_tab = [
"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" => strftime("%Y-%m-%d %H:%M:%S", strtotime($payment->createdAt)),
"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é';
}
// Le flux a été traité
// Le marchand peut ici mettre à jour sa base de données de commandes et effectuer d'autres traitements.
//
// debug('getStatus :'. $stat_str. ' - etat:'. $result_tab['etat'] );
// // enregistrement data base
// $dg_result= str_replace(array("\r\n", "\n", "\r"), '', print_r($result_tab, 1) );
// debug('PARAMS :'. $dg_result);
//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'] != "") )
{
// process transaction
$ret = $callApiServices->cbTransaction($result_tab);
$this->logger->debug("tableau : ".print_r($result_tab,1));
$this->logger->debug("transaction CB retour: ".print_r($ret,1));
if ($ret['sendEmail']==0){
$sendEmail = false;
}elseif ($sendEmail == true){
$questionMailService->sendMollieEmail($client, $callApiServices, $result_tab);
}
} else {
// debug('Params manquants ou invalides');
}
}
header("HTTP/1.0 200 OK");
die;
}
}