Mejora codigo smsgateway.

se añade llamado de parametro configuracion
parent c1e7004a
<?php <?php
namespace BackendBundle\Controller; namespace BackendBundle\Controller;
//use FOS\RestBundle\Controller\Annotations as Rest; use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\FOSRestController; use AppBundle\Lib\Utiles;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Lib\Utiles; use AppBundle\Model\NotificaQuery;
use Symfony\Component\HttpFoundation\Response; use AppBundle\Model\Notifica;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Model\NotificaQuery; require_once __DIR__ . '/../../../vendor/autoload.php';
use AppBundle\Model\Notifica;
//use Aws\CloudWatchLogs\CloudWatchLogsClient; use FOS\RestBundle\View\View;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
require_once __DIR__.'/../../../vendor/autoload.php';
class EnvioSmsController extends FOSRestController {
use FOS\RestBundle\View\View; /**
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; * @Route("/usuario/{id}", requirements={"id" = "\d+"}, defaults={"id" = 1})
* @Method({"GET"})
*/
public function indexAction($id) {
class EnvioSmsController extends FOSRestController $view = View::create();
{ $view->setData(array("id" => $id, "nombre" => "Usuario no autorizado"));
return $this->handleView($view);
/** }
* @Route("/usuario/{id}", requirements={"id" = "\d+"}, defaults={"id" = 1})
* @Method({"GET"}) /**
*/ * @Route("/enviar")
public function indexAction($id){ * @Method({"POST"})
$view = View::create(); */
$view->setData(array("id"=>$id,"nombre"=>"Usuario no autorizado")); public function enviarSmsAction() {
return $this->handleView($view);
} $campana = $_POST['campana'];
$telefono = $_POST['telefono'];
/** $mensaje = $_POST['mensaje'];
* @Route("/enviar") $idmetodo = $_POST['idmetodo'];
* @Method({"POST"})
*/
public function enviarSmsAction(){ $log = Utiles::setLog('BackendBundle', 'backend/backend');
/* $resp = array( $log->debug(count(NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($telefono)->find()));
'success' => true, $notifica = NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($telefono)->find();
'content' => array(0, 'main_content' => $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url)
)
); $usuario = "";
$password = "";
$url = "";
$finalResponse = json_encode($resp);
if ($idmetodo == 1) { //nrsgateway
$response = new Response($finalResponse); $usuario = Utiles::getParametroConfiguracion('nrsgateway_user');
$response->headers->set('Content-Type', 'application/json'); $password = Utiles::getParametroConfiguracion('nrsgateway_pws');
$url = Utiles::getParametroConfiguracion('nrsgateway_url');
return $response;*/ return $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url);
} else { //teltech
$campana = $_POST['campana']; if ($idmetodo == 2) {
$telefono = $_POST['telefono']; $usuario = Utiles::getParametroConfiguracion('teltech_user');
$mensaje = $_POST['mensaje']; $password = Utiles::getParametroConfiguracion('teltech_pws');
$idmetodo = $_POST['idmetodo']; $url = Utiles::getParametroConfiguracion('teltech_url');
return $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url);
} else { //Amazon
return $this->enviarMensajeAmazon($telefono, $mensaje);
}
}
$log = Utiles::setLog('BackendBundle', 'backend/backend'); }
$log->debug(count(NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($telefono)->find()));
$notifica = NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($telefono)->find(); private function enviarMensaje($campana, $movil, $mensaje, $usuario, $password, $url) {
try {
$usuario = ""; $post['to'] = array($movil);
$password = ""; $post['text'] = $mensaje;
$url = ""; $post['from'] = $movil;
$post['dlr-url'] = Utiles::getParametroConfiguracion("url_base")."/apirestsms/notifica/" . $campana . "/%P/%d";
if ($idmetodo==1){ //nrsgateway $user = $usuario;
$usuario = $this->container->getParameter('nrsgateway_user'); $password = $password;
$password = $this->container->getParameter('nrsgateway_pws'); $ch = curl_init();
$url = $this->container->getParameter('nrsgateway_url'); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $view = View::create(); curl_setopt($ch, CURLOPT_POST, 1);
// $view->setData($this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url)); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
//return $this->handleView($view); curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
return $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url); "Authorization: Basic " . base64_encode($user . ":" . $password)
} ));
else{ //teltech $result = curl_exec($ch);
if($idmetodo==2){
$usuario = $this->container->getParameter('teltech_user'); $array = json_decode($result, true);
$password = $this->container->getParameter('teltech_pws');
$url = $this->container->getParameter('teltech_url'); $resp = "";
//$view = View::create(); if (isset($array['error']['code'])) {
//$view->setData($this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url)); $resp = array(
//return $this->handleView($view); 'success' => false,
return $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url); 'statusCode' => $array['error']['code']
} );
else{ //Amazon return $resp;
return $this->enviarMensajeAmazon($telefono, $mensaje); } else {
} $log = Utiles::setLog('BackendBundle', 'backend/backend');
$log->debug('entra: ' . count($notifica));
} $notifica = NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($movil)->find();
$resp = "";
$estado = "";
if (count($notifica) > 0) {
/*$view = View::create(); foreach ($notifica as $noti) {
$view->setData($this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url)); $estado = $noti->getEstado();
return $this->handleView($view);*/ }
} $resp = array(
'success' => false,
private function enviarMensaje($campana, $movil, $mensaje, $usuario, $password, $url) { 'statusCode' => $estado
try{ );
$post['to'] = array($movil); return $resp;
$post['text'] = $mensaje; } else {
$post['from'] = $movil; $resp = array(
$post['dlr-url'] ="http://localhost/apirestsms/notifica/". $campana . "/%P/%d"; 'success' => false,
$user = $usuario; 'statusCode' => $array['error']['code']
$password = $password; );
$ch = curl_init(); return $resp;
curl_setopt($ch, CURLOPT_URL, $url); }
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); }
curl_setopt($ch, CURLOPT_POST, 1); } catch (\Exception $e) {
// curl_setopt($ch, CURLOPT_HEADER, array('Accept: application/json')); $log = Utiles::setLog('exception');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post)); $log->debug('exception: ' . $e);
// curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false); }
curl_setopt($ch, CURLOPT_HTTPHEADER, array( }
"Content-Type: application/json",
"Authorization: Basic " . base64_encode($user.":".$password) private function enviarMensajeAmazon($telefono, $mensaje) {
));
$result = curl_exec($ch); $sdk = new \Aws\Sns\SnsClient([
'region' => Utiles::getParametroConfiguracion('region'),
$array = json_decode($result, true); 'version' => Utiles::getParametroConfiguracion('version'),
'credentials' => ['key' => Utiles::getParametroConfiguracion('amazonkey'), 'secret' => Utiles::getParametroConfiguracion('amazonsecret')
$resp=""; ]]);
if (isset($array['error']['code'])) { $result = $sdk->publish([
$resp = array( 'Message' => $mensaje,
'success' => false, 'PhoneNumber' => $telefono,
'statusCode' => $array['error']['code'] 'MessageAttributes' => ['AWS.SNS.SMS.SenderID' => [
); 'DataType' => 'String',
return $resp; 'StringValue' => 'Mcafee'
} ]
else{ ]]);
$log = Utiles::setLog('BackendBundle', 'backend/backend');
$log->debug('entra: ' . count($notifica)); $messageId = $result['MessageId'];
$notifica=NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($movil)->find(); return $messageId;
}
$resp="";
$estado = ""; /**
if(count($notifica)>0){ * @Route("/buscarstatus")
foreach ($notifica as $noti) { * @Method({"POST"})
$estado=$noti->getEstado(); */
} public function buscarStatusAction() {
$resp = array( $time = intVal(strVal(time() - 3600 + 6) . "000");
'success' => false, $messageId = $_POST['messageid'];
'statusCode' => $estado
); $cloud = new \Aws\CloudWatchLogs\CloudWatchLogsClient([
'region' => 'us-east-1',
return $resp; 'version' => 'latest',
} 'credentials' => ['key' => $this->container->getParameter('amazonkey'), 'secret' => $this->container->getParameter('amazonsecret')
else{ ]]);
$resp = array(
'success' => false, $loggroup = $cloud->describeLogGroups(['logGroupNamePrefix' => 'sns', 'limit' => 10]);
'statusCode' => $array['error']['code'] $arrayGroup = json_decode($loggroup, true);
);
return $resp; $g = $loggroup['logGroups'];
}
}
$val = strVal($messageId);
}
catch(\Exception $e){ $cloud2 = new \Aws\CloudWatchLogs\CloudWatchLogsClient([
$log = Utiles::setLog('exception'); 'region' => 'us-east-1',
$log->debug('exception: ' .$e); 'version' => 'latest',
} 'credentials' => ['key' => $this->container->getParameter('amazonkey'), 'secret' => $this->container->getParameter('amazonsecret')
} ]]);
$result = $cloud2->filterLogEvents([
private function enviarMensajeAmazon($telefono, $mensaje){ 'filterPattern' => '{ $.notification.messageId = ' . $val . ' }',
'logGroupName' => $g[0]['logGroupName'], // REQUIRED
$sdk = new \Aws\Sns\SnsClient([ 'startTime' => $time,
'region' => 'us-east-1', ]);
'version' => 'latest',
'credentials' => ['key' => $this->container->getParameter('amazonkey'), 'secret' => $this->container->getParameter('amazonsecret')
]]); if ($result['events']) {
$result = $sdk->publish([ return $result;
'Message' => $mensaje, } else {
'PhoneNumber' => $telefono, $result = $cloud2->filterLogEvents([
'MessageAttributes' => ['AWS.SNS.SMS.SenderID' => [ 'filterPattern' => '{ $.notification.messageId = ' . $val . ' }',
'DataType' => 'String', 'logGroupName' => $g[1]['logGroupName'], // REQUIRED
'StringValue' => 'Mcafee' 'startTime' => $time,
] ]);
]]);
if ($result['events']) {
$messageId = $result['MessageId']; return $result;
return $messageId; } else {
} $resp = array(
'success' => true,
/** 'statusCode' => '-1'
* @Route("/buscarstatus") );
* @Method({"POST"})
*/ return $resp;
public function buscarStatusAction(){ }
$time = intVal(strVal(time() - 3600 + 6) . "000"); }
$messageId = $_POST['messageid']; }
$cloud = new \Aws\CloudWatchLogs\CloudWatchLogsClient([ /**
'region' => 'us-east-1', * @Route("/notifica/{idenvio}/{tel}/{estado}")
'version' => 'latest', */
'credentials' => ['key' => $this->container->getParameter('amazonkey'), 'secret' => $this->container->getParameter('amazonsecret') public function notificaAction($idenvio, $tel, $estado) {
]]); $notifica = new Notifica();
$notifica->setCampana($idenvio);
$loggroup = $cloud->describeLogGroups([ 'logGroupNamePrefix' => 'sns','limit' => 10 ]); $notifica->setTelefono($tel);
$arrayGroup = json_decode($loggroup, true); $notifica->setEstado($estado);
$g= $loggroup['logGroups']; $notifica->save();
}
$val=strVal($messageId); }
$cloud2 = new \Aws\CloudWatchLogs\CloudWatchLogsClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => ['key' => $this->container->getParameter('amazonkey'), 'secret' => $this->container->getParameter('amazonsecret')
]]);
$result = $cloud2->filterLogEvents([
'filterPattern' => '{ $.notification.messageId = '. $val . ' }',
'logGroupName' => $g[0]['logGroupName'], // REQUIRED
//'logStreamName' => '9a6f5bec-731e-4150-abd1-87f9a94ce3ee', // REQUIRED
// 'logStreamNamePrefix' => '<string>',
// 'logStreamNames' => ['<string>', ...],
// 'nextToken' => '<string>',
'startTime' => $time,
]);
if($result['events']){
return $result;
}
else{
$result = $cloud2->filterLogEvents([
'filterPattern' => '{ $.notification.messageId = '. $val . ' }',
'logGroupName' => $g[1]['logGroupName'], // REQUIRED
'startTime' => $time,
]);
if($result['events']){
return $result;
}
else{
$resp = array(
'success' => true,
'statusCode' => '-1'
);
return $resp;
}
}
}
/**
* @Route("/notifica/{idenvio}/{tel}/{estado}")
*/
public function notificaAction($idenvio, $tel,$estado){
$notifica = new Notifica();
$notifica->setCampana($idenvio);
$notifica->setTelefono($tel);
$notifica->setEstado($estado);
$notifica->save();
}
}
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment