Mejora codigo smsgateway.

se añade llamado de parametro configuracion
parent c1e7004a
<?php
namespace BackendBundle\Controller;
//use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use AppBundle\Lib\Utiles;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Model\NotificaQuery;
use AppBundle\Model\Notifica;
//use Aws\CloudWatchLogs\CloudWatchLogsClient;
require_once __DIR__.'/../../../vendor/autoload.php';
use FOS\RestBundle\View\View;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class EnvioSmsController extends FOSRestController
{
/**
* @Route("/usuario/{id}", requirements={"id" = "\d+"}, defaults={"id" = 1})
* @Method({"GET"})
*/
public function indexAction($id){
$view = View::create();
$view->setData(array("id"=>$id,"nombre"=>"Usuario no autorizado"));
return $this->handleView($view);
}
/**
* @Route("/enviar")
* @Method({"POST"})
*/
public function enviarSmsAction(){
/* $resp = array(
'success' => true,
'content' => array(0, 'main_content' => $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url)
)
);
$finalResponse = json_encode($resp);
$response = new Response($finalResponse);
$response->headers->set('Content-Type', 'application/json');
return $response;*/
$campana = $_POST['campana'];
$telefono = $_POST['telefono'];
$mensaje = $_POST['mensaje'];
$idmetodo = $_POST['idmetodo'];
$log = Utiles::setLog('BackendBundle', 'backend/backend');
$log->debug(count(NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($telefono)->find()));
$notifica = NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($telefono)->find();
$usuario = "";
$password = "";
$url = "";
if ($idmetodo==1){ //nrsgateway
$usuario = $this->container->getParameter('nrsgateway_user');
$password = $this->container->getParameter('nrsgateway_pws');
$url = $this->container->getParameter('nrsgateway_url');
// $view = View::create();
// $view->setData($this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url));
//return $this->handleView($view);
return $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url);
}
else{ //teltech
if($idmetodo==2){
$usuario = $this->container->getParameter('teltech_user');
$password = $this->container->getParameter('teltech_pws');
$url = $this->container->getParameter('teltech_url');
//$view = View::create();
//$view->setData($this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url));
//return $this->handleView($view);
return $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url);
}
else{ //Amazon
return $this->enviarMensajeAmazon($telefono, $mensaje);
}
}
/*$view = View::create();
$view->setData($this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url));
return $this->handleView($view);*/
}
private function enviarMensaje($campana, $movil, $mensaje, $usuario, $password, $url) {
try{
$post['to'] = array($movil);
$post['text'] = $mensaje;
$post['from'] = $movil;
$post['dlr-url'] ="http://localhost/apirestsms/notifica/". $campana . "/%P/%d";
$user = $usuario;
$password = $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// curl_setopt($ch, CURLOPT_HEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
// curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Authorization: Basic " . base64_encode($user.":".$password)
));
$result = curl_exec($ch);
$array = json_decode($result, true);
$resp="";
if (isset($array['error']['code'])) {
$resp = array(
'success' => false,
'statusCode' => $array['error']['code']
);
return $resp;
}
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){
foreach ($notifica as $noti) {
$estado=$noti->getEstado();
}
$resp = array(
'success' => false,
'statusCode' => $estado
);
return $resp;
}
else{
$resp = array(
'success' => false,
'statusCode' => $array['error']['code']
);
return $resp;
}
}
}
catch(\Exception $e){
$log = Utiles::setLog('exception');
$log->debug('exception: ' .$e);
}
}
private function enviarMensajeAmazon($telefono, $mensaje){
$sdk = new \Aws\Sns\SnsClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => ['key' => $this->container->getParameter('amazonkey'), 'secret' => $this->container->getParameter('amazonsecret')
]]);
$result = $sdk->publish([
'Message' => $mensaje,
'PhoneNumber' => $telefono,
'MessageAttributes' => ['AWS.SNS.SMS.SenderID' => [
'DataType' => 'String',
'StringValue' => 'Mcafee'
]
]]);
$messageId = $result['MessageId'];
return $messageId;
}
/**
* @Route("/buscarstatus")
* @Method({"POST"})
*/
public function buscarStatusAction(){
$time = intVal(strVal(time() - 3600 + 6) . "000");
$messageId = $_POST['messageid'];
$cloud = new \Aws\CloudWatchLogs\CloudWatchLogsClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => ['key' => $this->container->getParameter('amazonkey'), 'secret' => $this->container->getParameter('amazonsecret')
]]);
$loggroup = $cloud->describeLogGroups([ 'logGroupNamePrefix' => 'sns','limit' => 10 ]);
$arrayGroup = json_decode($loggroup, true);
$g= $loggroup['logGroups'];
$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
<?php
namespace BackendBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use AppBundle\Lib\Utiles;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Model\NotificaQuery;
use AppBundle\Model\Notifica;
require_once __DIR__ . '/../../../vendor/autoload.php';
use FOS\RestBundle\View\View;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class EnvioSmsController extends FOSRestController {
/**
* @Route("/usuario/{id}", requirements={"id" = "\d+"}, defaults={"id" = 1})
* @Method({"GET"})
*/
public function indexAction($id) {
$view = View::create();
$view->setData(array("id" => $id, "nombre" => "Usuario no autorizado"));
return $this->handleView($view);
}
/**
* @Route("/enviar")
* @Method({"POST"})
*/
public function enviarSmsAction() {
$campana = $_POST['campana'];
$telefono = $_POST['telefono'];
$mensaje = $_POST['mensaje'];
$idmetodo = $_POST['idmetodo'];
$log = Utiles::setLog('BackendBundle', 'backend/backend');
$log->debug(count(NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($telefono)->find()));
$notifica = NotificaQuery::create()->filterByCampana($campana)->filterByTelefono($telefono)->find();
$usuario = "";
$password = "";
$url = "";
if ($idmetodo == 1) { //nrsgateway
$usuario = Utiles::getParametroConfiguracion('nrsgateway_user');
$password = Utiles::getParametroConfiguracion('nrsgateway_pws');
$url = Utiles::getParametroConfiguracion('nrsgateway_url');
return $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url);
} else { //teltech
if ($idmetodo == 2) {
$usuario = Utiles::getParametroConfiguracion('teltech_user');
$password = Utiles::getParametroConfiguracion('teltech_pws');
$url = Utiles::getParametroConfiguracion('teltech_url');
return $this->enviarMensaje($campana, $telefono, $mensaje, $usuario, $password, $url);
} else { //Amazon
return $this->enviarMensajeAmazon($telefono, $mensaje);
}
}
}
private function enviarMensaje($campana, $movil, $mensaje, $usuario, $password, $url) {
try {
$post['to'] = array($movil);
$post['text'] = $mensaje;
$post['from'] = $movil;
$post['dlr-url'] = Utiles::getParametroConfiguracion("url_base")."/apirestsms/notifica/" . $campana . "/%P/%d";
$user = $usuario;
$password = $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Authorization: Basic " . base64_encode($user . ":" . $password)
));
$result = curl_exec($ch);
$array = json_decode($result, true);
$resp = "";
if (isset($array['error']['code'])) {
$resp = array(
'success' => false,
'statusCode' => $array['error']['code']
);
return $resp;
} 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) {
foreach ($notifica as $noti) {
$estado = $noti->getEstado();
}
$resp = array(
'success' => false,
'statusCode' => $estado
);
return $resp;
} else {
$resp = array(
'success' => false,
'statusCode' => $array['error']['code']
);
return $resp;
}
}
} catch (\Exception $e) {
$log = Utiles::setLog('exception');
$log->debug('exception: ' . $e);
}
}
private function enviarMensajeAmazon($telefono, $mensaje) {
$sdk = new \Aws\Sns\SnsClient([
'region' => Utiles::getParametroConfiguracion('region'),
'version' => Utiles::getParametroConfiguracion('version'),
'credentials' => ['key' => Utiles::getParametroConfiguracion('amazonkey'), 'secret' => Utiles::getParametroConfiguracion('amazonsecret')
]]);
$result = $sdk->publish([
'Message' => $mensaje,
'PhoneNumber' => $telefono,
'MessageAttributes' => ['AWS.SNS.SMS.SenderID' => [
'DataType' => 'String',
'StringValue' => 'Mcafee'
]
]]);
$messageId = $result['MessageId'];
return $messageId;
}
/**
* @Route("/buscarstatus")
* @Method({"POST"})
*/
public function buscarStatusAction() {
$time = intVal(strVal(time() - 3600 + 6) . "000");
$messageId = $_POST['messageid'];
$cloud = new \Aws\CloudWatchLogs\CloudWatchLogsClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => ['key' => $this->container->getParameter('amazonkey'), 'secret' => $this->container->getParameter('amazonsecret')
]]);
$loggroup = $cloud->describeLogGroups(['logGroupNamePrefix' => 'sns', 'limit' => 10]);
$arrayGroup = json_decode($loggroup, true);
$g = $loggroup['logGroups'];
$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
'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();
}
}
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