<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Message;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use App\Form\MessageType;
use App\Repository\MessageRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use App\Entity\Client;
use App\Entity\RechercheAppuisConseil;
use Symfony\Component\HttpFoundation\JsonResponse;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use App\Repository\ClientRepository;
use App\Entity\Session;
use App\Repository\RechercheAgroMeteoRepository;
use App\Repository\RechercheAppuisConseilRepository;
use App\Entity\RechercheAgroMeteo;
use App\Repository\RecherchePrixRepository;
use App\Entity\RecherchePrix;
use App\Repository\SessionRepository;
use App\Fonctions\Fonctions;
use App\Repository\UserRepository;
use DateTimeImmutable;
class MessageController extends AbstractController
{
private $client;
public function __construct(SessionInterface $session,HttpClientInterface $client,Fonctions $fonct)
{
$this->client = $client;
$this->fonct = $fonct;
$this->session = $session;
}
// try {
// $accessToken = "JCSDIUVHDJFVBEUDYVBDFJHKBVCSDFJHBVCJDYHS";
// $token = $request->query->get('hub_verify_token');
// $challenge = $request->query->get('hub_challenge');
// // dd($token,$challenge);
// if ($challenge !== null && $token !== null && $token === $accessToken) {
// return new Response($challenge);
// } else {
// return new Response(null, 400);
// }
// } catch (\Exception $e) {
// return new Response(null, 400);
// }
#[Route('/message/communication', name: 'app_message_communication', methods: ['GET', 'POST'])]
public function MessageCommunication(Request $request, SessionRepository $SessionRepository, ClientRepository $ClientRepository, EntityManagerInterface $entityManager): Response
{
$json = $request->getContent();
$data = json_decode($json, true);
$messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
$name = $data['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name'];
// $userMessage = $data['entry'][0]['changes'][0]['value']['messages'][0]['text']['body'];
// $name = "djafara";
$number = $messages['from'];
// $number = "22792829789";
$typeMessage = $messages['type'];
// message texte
// $userMessage = $messages['text']['body'];
$client=$ClientRepository->findOneBy(['telephone' => $number, 'statut' => 1]);
if (!$client) {
//on cree le client
$client = new Client();
$client->setNomPrenom($name);
$client->setTelephone($number);
$client->setAdresse("");
$client->setCreatedAt(new DateTimeImmutable());
$client->setStatut(1);
$entityManager->persist($client);
$entityManager->flush();
}
$session = $SessionRepository->findOneBy(['idClient' => $client->getId(),'statut' => 1]);
if ($typeMessage=='text') {
if ($messages['text']['body']=="Merci" || $messages['text']['body']=="Au revoir")
{
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\n Merci d'avoir utilisé notre service. nous restons a votre disposition pour de futurs échanges \nA tres bientot.", $number);
}
# code...
}
if (!$session) {
// Con cree une nouvelle session
$session = new Session();
$session->setIdClient($client);
$session->setEtape(0); //etape 0 creation de la session
$session->setTempsConnexion(0);
$session->setCreatedAt(new DateTimeImmutable());
$session->setStatut(1);
$entityManager->persist($session);
$entityManager->flush();
$text = "Bonjour bienvenue *{$name}*\nje suis votre assistante de service *GARBAL*, c'est un plaisir de vous accueillir parmi nous. Je suis là pour vous accompagner à chaque étape.";
$this->MessageChoixService($text, $number);
}
// if ($messages['text']['body']=="Merci" || $messages['text']['body']=="Au revoir")
// {
// $session->setStatut(0);
// $session->setDeletedAt(new DateTimeImmutable());
// $entityManager->persist($session);
// $entityManager->flush();
// $this->envoyerSimpleMessage("*Session expirée*\n Merci d'avoir utilisé notre service. nous restons a votre disposition pour de futurs échanges \nA tres bientot.", $number);
// }
if ($session->getEtape()==0) {
$isInteractive = isset($messages['interactive']);
if (isset($messages['interactive'])) {
// si l'utilisateur fait un choix
$choix = $messages['interactive']['list_reply']['id'];
$session->setService($choix);
$session->setEtape(1); //etape 1 choix service
$entityManager->persist($session);
$entityManager->flush();
switch ($choix) {
case "Sc_001":
// agro méteo
// on enregistre dans la table recherche agro meteo
$agrometeo = new RechercheAgroMeteo();
$agrometeo->setIdSession($session);
$agrometeo->setEtape(0); //etape 0 creation
$agrometeo->setCreatedAt(new DateTimeImmutable());
$agrometeo->setStatut(1);
$entityManager->persist($agrometeo);
$entityManager->flush();
// $text = "👉 Tapez 1 pour *Dates de semis*\n👉 Tapez 2 pour *Poches de sècheresse*\n👉 Tapez 3 pour *Début et fin de saison*\n👉 Tapez 4 pour *Alertes acridiennes et aviaires*\nVeuillez choisir le type d'information souhaité.";
$text = "Veuillez choisir le type d'information souhaité.";
$this->ChoixInformation($text,$number);
break;
case "Sc_002":
$apuisconseil = new RechercheAppuisConseil();
$apuisconseil->setIdSession($session);
$apuisconseil->setEtape(0); // étape domaine
$apuisconseil->setCreatedAt(new DateTimeImmutable());
$apuisconseil->setStatut(1);
$entityManager->persist($apuisconseil);
$entityManager->flush();
// On envoie la liste des domaines en interactive
$this->ChoixDomaine($number);
// Ne change pas encore $session->etape, on reste à 1 global
break;
// si appuis conseil
// on enregistre dans la table recherche appuis conseil
// $apuisconseil = new RechercheAppuisConseil();
// $apuisconseil->setIdSession($session);
// $apuisconseil->setEtape(0); //etape 0 creation de l' apuisconseil
// $apuisconseil->setCreatedAt(new DateTimeImmutable());
// $apuisconseil->setStatut(1);
// $entityManager->persist($apuisconseil);
// $entityManager->flush();
// // $text = "Très bien ! Vous avez choisi *APPuis*.\nVeuillez entrer la localité souhaitée.";
// $this->ChoixDomaine($number);
// break;
case "Sc_003":
// si prix
// on enregistre dans la table rechercheprix
$rechercheprix = new RecherchePrix();
$rechercheprix->setIdSession($session);
$rechercheprix->setEtape(0); //etape 0 creation
$rechercheprix->setCreatedAt(new DateTimeImmutable());
$rechercheprix->setStatut(1);
$entityManager->persist($rechercheprix);
$entityManager->flush();
$text = "Veuillez choisir le type d'information souhaité.";
$this->EnvoyerListeCategories($text,$number);
break;
default:
$this->envoyerSimpleMessage("Désolé je n'ai pas reconnu ce choix.", $number);
}
}
// else {
// $this->envoyerSimpleMessage("Veuillez faire votre choix.", $number);
// }
}else {
$choix = $session->getService();
switch ($choix) {
case "Sc_001":
// agro méteo
$this->TraiterAgroMeteo($data,$session,$entityManager);
break;
case "Sc_002":
// $apuisconseil = $entityManager->getRepository(RechercheAppuisConseil::class)->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
// if ($apuisconseil && $session->getEtape()==2) {
// si appuis conseil
$this->TraiterAppuisConseil($data,$session,$entityManager);
break;
// }
case "Sc_003":
// si prix
$this->TraiterPrix($data, $session, $entityManager);
break;
default:
$this->envoyerSimpleMessage("Veuillez recommencer je n'ai pas reconnu ce choix.", $number);
}
}
}
public function TraiterPrix($data, $session, $entityManager)
{
$messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
$number = $messages['from'];
$typeMessage = $messages['type'];
if ($typeMessage === "text") {
$texte = trim($messages['text']['body']);
if ($texte === "Merci" || $texte === "Au revoir") {
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage(
"*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
$number
);
return;
}
}
$prixSession = $entityManager->getRepository(RecherchePrix::class)
->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
if (!$prixSession) {
$this->envoyerSimpleMessage("Aucune session.", $number);
return;
// $prixSession = new RecherchePrix();
// $prixSession->setIdSession($session);
// $prixSession->setEtape(0); //etape 0 creation
// $prixSession->setCreatedAt(new DateTimeImmutable());
// $prixSession->setStatut(1);
// $entityManager->persist($prixSession);
// $entityManager->flush();
// $this->EnvoyerListeCategories("Veuillez choisir une catégorie :", $number);
// return;
}
/* ÉTAPE 0 : CHOIX CATÉGORIE */
if ($prixSession->getEtape() == 0) {
if (isset($messages['interactive']['list_reply']['id'])) {
$choix = $messages['interactive']['list_reply']['id'];
if ($choix === "Pc_001") {
$prixSession->setType("AGRICULTURE");
$prixSession->setEtape(1);
$entityManager->flush();
$this->envoyerSimpleMessage(
"Vous avez choisi *AGRO ALIMENTAIRE*.\n\nVeuillez saisir le nom d'une commune :",
$number
);
return;
}
if ($choix === "Pc_002") {
$prixSession->setType("BETAIL");
$prixSession->setEtape(1);
$entityManager->flush();
$this->envoyerSimpleMessage(
"Vous avez choisi *ANIMAUX / BÉTAIL*.\n\nVeuillez saisir le nom d'une commune :",
$number
);
return;
}
$this->envoyerSimpleMessage("Choix invalide, veuillez réessayer.", $number);
return;
}
// Si aucun choix reçu, envoyer la liste de catégories
$this->EnvoyerListeCategories("Veuillez choisir une catégorie :", $number);
return;
}
/* ÉTAPE 1 : RECHERCHE DE COMMUNE */
if ($prixSession->getEtape() == 1 ) {
if ($typeMessage !== "text") {
$this->envoyerSimpleMessage(
"Veuillez saisir un nom de commune sous forme de texte.",
$number
);
return;
}
$texteRecu = trim($messages['text']['body']);
$listeCommunes = $this->AppelApiRechercheCommunes($texteRecu);
if (empty($listeCommunes)) {
$this->envoyerSimpleMessage(
"Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
$number
);
return;
}
// Stocker la liste pour sélection
$prixSession->setListeResultat(json_encode($listeCommunes));
$prixSession->setEtape(2);
$entityManager->flush();
$this->EnvoyerListeCommunes($listeCommunes, $number);
return;
}
/* ÉTAPE 2 : CHOIX D'UNE COMMUNE */
if ($prixSession->getEtape() == 2 && $typeMessage === "text") {
$choix = trim($messages['text']['body']);
if (!ctype_digit($choix)) {
$this->envoyerSimpleMessage("Veuillez saisir un numéro valide.", $number);
return;
}
$listeCommunes = json_decode($prixSession->getListeResultat(), true);
$index = intval($choix) - 1;
if (!isset($listeCommunes[$index])) {
$this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer.", $number);
return;
}
$commune = $listeCommunes[$index];
$prixSession->setCommune($commune['id']);
$prixSession->setListeResultat(null);
$prixSession->setEtape(3);
$entityManager->flush();
/* les prix selon la catégorie */
if ($prixSession->getType() === "AGRICULTURE") {
$listePrix = $this->AppelApiPrixProduitsAgricoles($commune['id']);
$this->EnvoyerPrixProduitsAgricoles($listePrix, $number);
$prixSession->setStatut(0);
$prixSession->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
if ($prixSession->getType() === "BETAIL") {
$listePrix = $this->AppelApiPrixBetail($commune['id']);
$this->EnvoyerPrixBetail($listePrix, $number);
$prixSession->setStatut(0);
$prixSession->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
return;
}
/* ERREUR PAR DÉFAUT */
$this->envoyerSimpleMessage("Désolé, je n'ai pas reconnu votre choix.", $number);
}
public function EnvoyerListeCommunes(array $listeCommunes, string $number)
{
if (empty($listeCommunes)) {
$this->envoyerSimpleMessage("Aucune commune trouvée. Veuillez réessayer.", $number);
return;
}
$message = "*Communes trouvées :*\n\n";
$i = 1;
foreach ($listeCommunes as $commune) {
$message .= "👉 Tapez *".$i."* pour *".$commune['libelle']."*\n";
$i++;
}
$message .= "\n*Tapez le numéro* correspondant à votre commune.";
// CORRECTION : utiliser $number et NON $numero
$this->envoyerSimpleMessage($message, $number);
}
public function AppelApiRechercheCommunes(string $texte): array
{
//Authentification API
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email" => "djafarasakinatou@gmail.com",
"password" => "l2323"
]));
//Appel API de recherche des communes
$response = $this->fonct->execPost( $auth['data']['token'], 'api/communes/recherche', json_encode([ "commune" => $texte ]) );
//Vérification réponse
if (!isset($response['status']) || $response['status'] != 200)
{
return [];
}
//Retourne la liste des résultats
return $response['results'] ?? [];
}
public function AppelApiPrixBetail(string $idCommune): array
{
// Authentification API
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email" => "djafarasakinatou@gmail.com",
"password" => "l2323"
]));
// Appel API Prix Bétail
$response = $this->fonct->execPost( $auth['data']['token'], 'api/prix/animaux', json_encode([ "id_commune" => $idCommune ]) );
if (!isset($response['status']) || $response['status'] != 200)
{
return [];
}
return $response['data'] ?? [];
}
public function AppelApiPrixProduitsAgricoles(string $idCommune): array
{
// Authentification API
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email" => "djafarasakinatou@gmail.com",
"password" => "l2323"
]));
// Appel API Prix Produits Agricoles
$response = $this->fonct->execPost(
$auth['data']['token'],
'api/prix/produit/agricole',
json_encode([
"id_commune" => $idCommune,
"id_semaine" => "" // ton API prend automatiquement la semaine active
])
);
// Vérification du status
if (!isset($response['status']) || $response['status'] != 200) {
return [];
}
// Retour des données
return $response['data'] ?? [];
}
public function EnvoyerListeCategories(string $text, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "interactive",
"interactive" => [
"type" => "list",
"body" => [
"text" => $text
],
"footer" => [
"text" => "Pour arrêter le processus tapez merci ou au revoir"
],
"action" => [
"button" => "Catégories",
"sections" => [
[
"title" => "Catégories disponibles",
"rows" => [
[
"id" => "Pc_001",
"title" => "AGRO ALIMENT",
"description" => "Prix des aliments d'une localité du Niger"
],
[
"id" => "Pc_002",
"title" => "ANIMAUX",
"description" => "Prix du bétail d'une localité du Niger"
]
]
]
]
]
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
$result = $response->toArray(false);
return $result;
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function EnvoyerPrixBetail(array $prix, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
// Construction du message
if (empty($prix)) {
$texte = " *Aucun prix de bétail trouvé pour cette commune.*";
} else {
$texte = " *Prix du Bétail*\n\n";
foreach ($prix as $item) {
$texte .= " *" . $item["animal"] . "*\n";
$texte .= " Prix : " . $item["prix"] . " FCFA\n";
$texte .= "-------------------------\n";
}
}
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "text",
"text" => [
"body" => $texte
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function EnvoyerPrixProduitsAgricoles(array $prix, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
// Construction du message
if (empty($prix))
{
$texte = " *Aucun prix de produit agricole trouvé pour cette commune.*";
} else
{
$texte = " *Prix des produits agricoles*\n\n";
foreach ($prix as $item)
{
$texte .= " *" . $item["produit"] . "*\n";
$texte .= " Prix : " . $item["prix"] . " FCFA\n";
$texte .= "-------------------------\n";
}
}
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "text",
"text" => [
"body" => $texte
]
];
try
{
$response = $this->client->request('POST', $apiUrl, [ 'headers' => [ 'Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', ], 'json' => $payload, ]);
return $response->toArray();
} catch (\Exception $e)
{
return ['error' => $e->getMessage()];
}
}
public function TraiterAgroMeteo($data,$session,$entityManager)
{
$messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
$number = $messages['from'];
$typeMessage = $messages['type'];
if ($typeMessage === "text") {
$texte = trim($messages['text']['body']);
if ($texte === "Merci" || $texte === "Au revoir") {
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage(
"*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
$number
);
return;
}
}
$agrometeo = $entityManager->getRepository(RechercheAgroMeteo::class)->findOneBy(['idSession' => $session->getId(),'statut' => 1]);
// Fin de session
// if ($agrometeo->getEtape()==3)
// {
// $session->setStatut(0);
// $session->setDeletedAt(new DateTimeImmutable());
// $entityManager->flush();
// $this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
// return;
// }
if (!$agrometeo) {
$this->envoyerSimpleMessage("Aucune session.", $number);
return;
// $agrometeo = new RechercheAgroMeteo();
// $agrometeo->setIdSession($session);
// $agrometeo->setEtape(0); //etape 0 creation
// $agrometeo->setCreatedAt(new DateTimeImmutable());
// $agrometeo->setStatut(1);
// $entityManager->persist($agrometeo);
// $entityManager->flush();
// // $text = "👉 Tapez 1 pour *Dates de semis*\n👉 Tapez 2 pour *Poches de sècheresse*\n👉 Tapez 3 pour *Début et fin de saison*\n👉 Tapez 4 pour *Alertes acridiennes et aviaires*\nVeuillez choisir le type d'information souhaité.";
// $text = "Veuillez choisir le type d'information souhaité.";
// $this->ChoixInformation($text,$number);
// return;
}
if ($agrometeo->getEtape()==0) {
if (isset($messages['interactive']['list_reply']['id'])) {
$choix = $messages['interactive']['list_reply']['id'];
} else {
$this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste.", $number);
return;
}
$agrometeo->setType($choix);
$agrometeo->setEtape(1); // choix type info
$entityManager->persist($agrometeo);
$entityManager->flush();
// $text = "Veuillez saissir la localité souhaitée.";
// $this->envoyerSimpleMessage($text, $number);
}
if ($agrometeo->getEtape()==1 && $agrometeo->getType()!=null) {// si etape 1 choix commune fait
if ($typeMessage !== "text") {
$this->envoyerSimpleMessage("Veuillez saisir un nom de commune sous forme de texte.",$number);
return;
}
$texteRecu = trim($messages['text']['body']);
$listeCommunes = $this->AppelApiRechercheCommunes($texteRecu);
if (empty($listeCommunes)) {
$this->envoyerSimpleMessage(
"Aucune commune trouvée pour *$texteRecu*.\nVeuillez saisir un autre nom.",
$number
);
return;
}
$agrometeo->setResultat(json_encode($listeCommunes));
$agrometeo->setEtape(2); //saissi commune
$entityManager->persist($agrometeo);
$entityManager->flush();
$this->EnvoyerListeCommunes($listeCommunes, $number);
return;
}
if ($agrometeo->getEtape() == 2) {
// $this->envoyerSimpleMessage("ok", $number);
$userMessage = trim($messages['text']['body']);
if ($typeMessage !== "text") {
$this->envoyerSimpleMessage("Veuillez saisir un numéro.", $number);
return;
}
if (!ctype_digit($messages['text']['body'])) {
$this->envoyerSimpleMessage("Numéro invalide.", $number);
return;
}
$listeCommunes = json_decode($agrometeo->getResultat(), true);
$index = intval($messages['text']['body']) - 1;
if (!isset($listeCommunes[$index])) {
$this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer.", $number);
return;
}
$commune = $listeCommunes[$index];
$idCommune=$commune['id'];
// Enregistrer dans la base
$agrometeo->setCommune($idCommune);
$agrometeo->setEtape(3);
$entityManager->flush();
// Continue selon type
if ($agrometeo->getType() == "In_01") {
$this->EnvoyerDateSemis($idCommune, $number);
$agrometeo->setStatut(0);
$agrometeo->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
if ($agrometeo->getType() == "In_02") {
$this->EnvoyerPocheSecheresse($idCommune, $number);
$agrometeo->setStatut(0);
$agrometeo->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
if ($agrometeo->getType() == "In_03") {
$this->EnvoyerDateSaison($idCommune, $number);
$agrometeo->setStatut(0);
$agrometeo->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
if ($agrometeo->getType() == "In_04") {
$this->EnvoyerAlerte($idCommune, $number);
$agrometeo->setStatut(0);
$agrometeo->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
return;
}
}
public function EnvoyerDateSemis($idCommune, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responsesemis = $this->fonct->execPost($auth['data']['token'],'api/date/semis',json_encode(["id_commune" => $idCommune]));
// $this->envoyerSimpleMessage("ok", $number);
if (!isset($responsesemis['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $number);
return;
}
$msg = "Information disponible:\n";
foreach ($responsesemis['data'] as $semis) {
$msg .= "*{$semis['information']}*\n\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function EnvoyerPocheSecheresse($idCommune, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responsesemis = $this->fonct->execPost($auth['data']['token'],'api/poche/secheresse',json_encode(["id_commune" => $idCommune]));
// $this->envoyerSimpleMessage("ok", $number);
// 🔍 DEBUG : voir ce que retourne l'API
//$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsesemis), $number);
if (!isset($responsesemis['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $number);
return;
}
$msg = "Information disponible:\n";
foreach ($responsesemis['data'] as $semis) {
$msg .= "*{$semis['information']}*\n\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function EnvoyerDateSaison($idCommune, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responsesemis = $this->fonct->execPost($auth['data']['token'],'api/date/saison',json_encode(["id_commune" => $idCommune]));
// $this->envoyerSimpleMessage("ok", $number);
if (!isset($responsesemis['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $number);
return;
}
$msg = "Information disponible:\n";
foreach ($responsesemis['data'] as $semis) {
$msg .= "*{$semis['information']}*\n\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function EnvoyerAlerte($idCommune, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responsesemis = $this->fonct->execPost($auth['data']['token'],'api/alerte',json_encode(["id_commune" => $idCommune]));
// $this->envoyerSimpleMessage("ok", $number);
if (!isset($responsesemis['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $number);
return;
}
$msg = "Information disponible:\n";
foreach ($responsesemis['data'] as $semis) {
$msg .= "*{$semis['information']}*\n\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function TraiterAppuisConseil($data, $session, $entityManager)
{
$messages = $data['entry'][0]['changes'][0]['value']['messages'][0];
$number = $messages['from'];
$typeMessage = $messages['type'];
if ($typeMessage === "text") {
$texte = trim($messages['text']['body']);
if ($texte === "Merci" || $texte === "Au revoir") {
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->persist($session);
$entityManager->flush();
$this->envoyerSimpleMessage(
"*Session expirée*\nMerci d'avoir utilisé notre service prix.\nÀ très bientôt.",
$number
);
return;
}
}
$apuisconseil = $entityManager->getRepository(RechercheAppuisConseil::class)->findOneBy(['idSession' => $session->getId(), 'statut' => 1]);
if (!$apuisconseil) {
$this->envoyerSimpleMessage("Aucune session.", $number);
return;
// $apuisconseil = new RechercheAppuisConseil();
// $apuisconseil->setIdSession($session);
// $apuisconseil->setEtape(0); // étape domaine
// $apuisconseil->setCreatedAt(new DateTimeImmutable());
// $apuisconseil->setStatut(1);
// $entityManager->persist($apuisconseil);
// $entityManager->flush();
// // On envoie la liste des domaines en interactive
// $this->ChoixDomaine($number);
// return;
}
if ($apuisconseil->getEtape() == 0) {
// $this->envoyerSimpleMessage("❌ Session Appuis Conseil introuvable.", $number);
// return;
// Récupère le choix domaine depuis interactive ou texte
if (isset($messages['interactive']['list_reply']['id'])) {
$choix = $messages['interactive']['list_reply']['id'];
} else {
$this->envoyerSimpleMessage("Veuillez sélectionner un type d'information dans la liste.", $number);
return;
}
$theme = $this->thematiqueTrouver($choix);
if (empty($theme)) {
$this->envoyerSimpleMessage(
"Aucun thème trouvé.",
$number
);
return;
}
$apuisconseil->setResultat(json_encode($theme));
$apuisconseil->setDomaine($choix);
$apuisconseil->setEtape(1); // étape thématique
$entityManager->flush();
$this->EnvoyerListeThematique($choix, $number);
return;
}
if ($apuisconseil->getEtape() == 1 && $typeMessage == "text") {
$choixThematique = trim($messages['text']['body']);
// Vérifie que le choix est un ID numérique ou valide
if (!ctype_digit($choixThematique)) {
$this->envoyerSimpleMessage("Veuillez saisir un numéro valide.", $number);
return;
}
$listetheme = json_decode($apuisconseil->getResultat(), true);
$index = intval($choixThematique) - 1;
if (!isset($listetheme[$index])) {
$this->envoyerSimpleMessage("Numéro invalide. Veuillez réessayer.", $number);
return;
}
$theme = $listetheme[$index];
$idTheme=$theme['id'];
$apuisconseil->setThematique($idTheme);
$apuisconseil->setEtape(2); // fin
$entityManager->flush();
$this->envoyerFichierTheme($number, $idTheme);
$apuisconseil->setStatut(0);
$apuisconseil->setDeletedAt(new DateTimeImmutable());
$session->setStatut(0);
$session->setDeletedAt(new DateTimeImmutable());
$entityManager->flush();
$this->envoyerSimpleMessage("*Session expirée*\nMerci d'avoir utilisé notre service.\nÀ bientôt !", $number);
return;
}
}
#[Route('/communication', name: 'app_communication', methods: ['GET', 'POST'])]
public function index(Request $request, MessageRepository $messageRepository): Response
{
$message = new Message();
$form = $this->createForm(MessageType::class, $message);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$imageFiles = $form->get('image')->getData();
$telephone = $form->get('telephone')->getData();
$contenus = $form->get('contenus')->getData();
$titre = $form->get('titre')->getData();
if ($imageFiles) {
foreach ($imageFiles as $imageFile) {
$newFilename = uniqid().'.'.$imageFile->guessExtension();
try {
$imageFile->move(
$this->getParameter('messages_images_directory'),
$newFilename
);
} catch (FileException $e) {
$this->addFlash('error', 'Impossible de télécharger une image.');
continue;
}
$message->addImage($newFilename);
}
}
$message->setCreatedAt(new \DateTimeImmutable());
$message->setStatus(1);
$message->setIdUser($this->getUser());
$messageRepository->add($message, true);
$resultat = $this->envoyerMessage("227". $telephone, $titre, $contenus);
if ($imageFiles) {
$resultat = $this->envoyerMessagePlusDocument("227". $telephone, "1" );
}
return $this->redirectToRoute('app_communication', [], Response::HTTP_SEE_OTHER);
}
$messages = $messageRepository->findBy(
['status' => 1],
['createdAt' => 'DESC']
);
$this->addFlash('success', 'Message envoyé avec succès !');
return $this->render('message/index.html.twig', [
'messages' => $messages,
'form' => $form->createView(),
]);
}
#[Route('/message/{id}', name: 'app_message_show', methods: ['GET', 'POST'])]
public function show(Message $message, MessageRepository $messageRepository): Response
{
return $this->render('message/detail.html.twig', [
'messages' => $messageRepository->findBy(
['status' => 1],
['createdAt' => 'DESC']
),
'message' => $message,
]);
}
public function envoyerSimpleMessage(string $contenus,string $numero)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$data = [
"messaging_product" => "whatsapp",
"recipient_type" => "individual",
"to" => "$numero", // numéro du destinataire
"type" => "text",
"text" => [
"preview_url" => false,
"body" => $contenus
]
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $token",
"Content-Type: application/json"
],
CURLOPT_POSTFIELDS => json_encode($data)
]);
$response = curl_exec($ch);
curl_close($ch);
}
public function ChoixInformation(string $text, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "interactive",
"interactive" => [
"type" => "list",
"body" => [
"text" => $text
],
"footer" => [
"text" => "Pour arrêter le processus tapez merci ou au revoir"
],
"action" => [
"button" => "Choisir un type",
"sections" => [
[
"title" => "Type information",
"rows" => [
[
"id" => "In_01",
"title" => "SEMIS",
"description" => "Dates de semis"
],
[
"id" => "In_02",
"title" => "SECHERESSE",
"description" => "Poches de sècheresse"
],
[
"id" => "In_03",
"title" => "SAISON",
"description" => "Début et fin de la saison"
],
[
"id" => "In_04",
"title" => "ALERTE",
"description" => "Alerte sur l’invasion acridienne et aviaire"
]
]
]
]
]
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function MessageChoixService(string $text, string $number)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "interactive",
"interactive" => [
"type" => "list",
"body" => [
"text" => $text
],
"footer" => [
"text" => "Pour arrêter le processus tapez merci ou au revoir"
],
"action" => [
"button" => "Choisir un service",
"sections" => [
[
"title" => "Services disponibles",
"rows" => [
[
"id" => "Sc_001",
"title" => "AGRO METEO",
"description" => "Prévisions météorologiques d'une localité du Niger"
],
[
"id" => "Sc_002",
"title" => "APPUIS CONSEIL",
"description" => "Conseils et assistance dans divers domaines"
],
[
"id" => "Sc_003",
"title" => "PRIX",
"description" => "Prix des animaux et produits agricoles dans les marchés du Niger"
]
]
]
]
]
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function ChoixDomaine(string $number)
{
//on recupere la connection
$all=[
"email"=> "djafarasakinatou@gmail.com",
"password"=> "l2323"
];
$dataPost=json_encode($all);
$chemin='api/authentification';
$response=$this->fonct->execPost('',$chemin,$dataPost);
//on recupere les domaines
$cheminDomaine='api/appuis/conseil/domaine';
$responseDomaine=$this->fonct->execGet($response['data']['token'],$cheminDomaine);
$messageListe = array();
$text="Veuillez choisir un domaine";
foreach ($responseDomaine['data'] as $domaine) {
$messageListe[] = [
"id" => $domaine['id'],
"title" => $domaine['libelle']
];
}
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
$payload = [
"messaging_product" => "whatsapp",
"to" => $number,
"type" => "interactive",
"interactive" => [
"type" => "list",
"body" => [
"text" => $text
],
"footer" => [
"text" => "Pour arrêter le processus tapez merci ou au revoir"
],
"action" => [
"button" => "Choisir un domaine",
"sections" => [
[
"title" => "domaine disponibles",
"rows" => $messageListe
]
]
]
]
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
public function EnvoyerListeThematique($choix, $number)
{
// Authentification
$auth = $this->fonct->execPost('', 'api/authentification', json_encode(["email"=> "djafarasakinatou@gmail.com","password"=> "l2323"]));
//thématiques
$responseThematique = $this->fonct->execPost($auth['data']['token'],'api/appuis/conseil/theme',json_encode(["id_domaine" => $choix]));
//$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responseThematique), $number);
if (!isset($responseThematique['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune.", $number);
return;
}
// texte
$msg = "📚 *Veuillez choisir une thématique :*\n\n";
foreach ($responseThematique['data'] as $theme) {
$msg .= "👉 Tapez *{$theme['N°']}* pour *{$theme['libelle']}*\n";
}
$msg .= "\nPour arrêter tapez *merci* ou *au revoir*.";
// Envoyer
$this->envoyerSimpleMessage($msg, $number);
}
public function thematiqueTrouver($domaine): array
{
// Authentification
$auth = $this->fonct->execPost('','api/authentification',json_encode([
"email"=> "djafarasakinatou@gmail.com",
"password"=> "l2323"
])
);
// Vérification authentification
if (!isset($auth['data']['token'])) {
return [];
}
$token = $auth['data']['token'];
// Récupération thématiques
$response = $this->fonct->execPost($token,'api/appuis/conseil/theme',json_encode(["id_domaine" => $domaine]));
// Vérification statuts
if (!isset($response['status']) || $response['status'] !== 200) {
return [];
}
// Retour du tableau des thématiques
return $response['data'] ?? [];
}
#[Route('/envoyer/fichier', name: 'app_envoyer_fichier', methods: ['POST'])]
public function envoyerFichier(Request $request, EntityManagerInterface $entityManager, UserRepository $UserRepository): Response
{
$data = json_decode($request->getContent(), true);
$obligatoire = ['id_theme','numero'];
foreach ($obligatoire as $champs) {
if (empty($data[$champs])) {
return $this->json([
'status' => 400,
'message' => 'failed',
'data' => ['error_message' => "Le champ $champs est obligatoire."],
]);
}
}
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
// Authentification interne
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email"=> "djafarasakinatou@gmail.com",
"password"=> "l2323"
]));
// Récupération des fichiers
$responsefichiers = $this->fonct->execPost(
$auth['data']['token'],
'api/appuis/conseil/fichier',
json_encode(["id_theme"=> $data['id_theme']])
);
if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
return $this->json(['status' => 400, 'message' => 'Aucun fichier trouvé']);
}
//dd($responsefichiers);
$dataFichier = [];
// $i=0;
foreach ($responsefichiers['data'] as $item) {
$dataFichier[] = [
'conseil'=>$item['conseil'],
'fichier'=>$item['fichier'],
'semaine'=>$item['semaine'],
'date_ajout'=>$item['date_ajout'],
];
$extension = pathinfo($item['fichier'], PATHINFO_EXTENSION);
// dd($extension);
$payload = [
"to" => $data['numero'],
"type" => "template",
"messaging_product" => "whatsapp",
"template" => [
"name" => "model_garbal_format_document",
"language" => ["code" => "fr"],
"components" => [
[
"type" => "header",
"parameters" => [
[
"type" => "document",
"document" => [
"link" => $item['fichier'],
"filename" => $item['conseil']
]
]
]
],
[
"type" => "body",
"parameters" => [
[
"type" => "text",
"text" => $item['conseil']
]
]
]
]
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer '.$token,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
file_put_contents("whatsapp_response.log", "RESPONSE: ".$response." | ERROR: ".$error.PHP_EOL, FILE_APPEND);
// usleep(300000); // pause 0.3s pour ne pas se faire bloquer
}
return $this->json([
'status' => 200,
'message' => 'Fichiers envoyés avec succès'
// 'data' => $dataFichier
]);
}
public function envoyerFichierTheme($numero, $id_theme)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcSAqZBt7z2WMmS00uip8oMydyvrmdrLNALaPzqAMBNCrrVixicUwZAWcEtf0JXYZB4nWn15WTbGVHShFN4CgMCayNZCCcAZDZD';
// Authentification interne
$auth = $this->fonct->execPost('', 'api/authentification', json_encode([
"email"=> "djafarasakinatou@gmail.com",
"password"=> "l2323"
]));
//$this->envoyerSimpleMessage("Aucune donnée trouvée pour cette commune.", $numero);
// Récupération des fichiers
$responsefichiers = $this->fonct->execPost(
$auth['data']['token'],
'api/appuis/conseil/fichier',
json_encode(["id_theme"=> $id_theme])
);
//$this->envoyerSimpleMessage("DEBUG : \n" . json_encode($responsefichiers), $numero);
if (!isset($responsefichiers['data']) || empty($responsefichiers['data'])) {
$this->envoyerSimpleMessage("Aucune donnée trouvée .", $numero);
return;
}
//dd($responsefichiers);
$dataFichier = [];
// $i=0;
foreach ($responsefichiers['data'] as $item) {
$dataFichier[] = [
'conseil'=>$item['conseil'],
'fichier'=>$item['fichier'],
'semaine'=>$item['semaine'],
'date_ajout'=>$item['date_ajout'],
];
$extension = pathinfo($item['fichier'], PATHINFO_EXTENSION);
// dd($extension);
$payload = [
"to" => $numero,
"type" => "template",
"messaging_product" => "whatsapp",
"template" => [
"name" => "model_garbal_format_document",
"language" => ["code" => "fr"],
"components" => [
[
"type" => "header",
"parameters" => [
[
"type" => "document",
"document" => [
"link" => $item['fichier'],
"filename" => $item['conseil']
]
]
]
],
[
"type" => "body",
"parameters" => [
[
"type" => "text",
"text" => $item['conseil']
]
]
]
]
]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer '.$token,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
file_put_contents("whatsapp_response.log", "RESPONSE: ".$response." | ERROR: ".$error.PHP_EOL, FILE_APPEND);
// usleep(300000); // pause 0.3s pour ne pas se faire bloquer
}
}
public function envoyerMessagePlusDocument(string $numero, string $nombre)
{
$apiUrl = 'https://graph.facebook.com/v22.0/870067449513702/messages';
$token = 'EAALq1IZALeIMBPvptNRWvGz44tBfwXLgFYTejW6OleBlldvwKvAZBIwOzNQpcSELEZAvZCREVWuLz045ZB9BXUPT3bO5GX3okJGOZBBgHEcS';
$payload = [
"messaging_product" => "whatsapp",
"to" => "$numero",
"type" => "template",
"template" => [
"name" => "model_garbal_format_document ",
"language" => ["code" => "FR"],
"components" => [
[
"type" => "body",
"parameters" => [
["type" => "text", "text" => $nombre],
],
],
],
],
];
try {
$response = $this->client->request('POST', $apiUrl, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
'json' => $payload,
]);
return $response->toArray();
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
private function validateToken(Request $request, JWTEncoderInterface $JWTDecodeManager, EntityManagerInterface $entityManager, UserRepository $UserRepository)
{
$authorizationHeader = $request->headers->get('Authorization');
if (!$authorizationHeader) {
return new JsonResponse(['status' => 401, 'message' => 'Token non fourni'], 401);
}
$tokenParts = explode(' ', $authorizationHeader);
if (count($tokenParts) !== 2 || $tokenParts[0] !== 'Bearer') {
return new JsonResponse(['status' => 401, 'message' => 'Format du token invalide'], 401);
}
$token = $tokenParts[1];
try {
$userData = $JWTDecodeManager->decode($token);
} catch (\Exception $e) {
return new JsonResponse(['status' => 401, 'message' => 'Token invalide'], 401);
}
if (!isset($userData['username'])) {
return new JsonResponse(['status' => 401, 'message' => 'Token mal formé (username manquant)'], 401);
}
// dd($userData);
$user = $UserRepository->findOneBy(['email' => $userData['username']]);
if (!$user) {
return new JsonResponse(['status' => 401, 'message' => 'Utilisateur non trouvé'], 401);
}
if ($user->getStatut() != 1) {
return new JsonResponse(['status' => 401, 'message' => 'Compte inactif'], 401);
}
if (isset($userData['exp']) && $userData['exp'] < time()) {
return new JsonResponse(['status' => 401, 'message' => 'Token expiré'], 401);
}
// Tout est bon, on retourne les infos de l'utilisateur
return [
'id' => $user->getId(),
'role' => $user->getRoles(),
'email' => $user->getEmail()
];
}
}