Advertisement
Guest User

Untitled

a guest
Jul 8th, 2016
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.96 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Created by JetBrains PhpStorm.
  4.  * User: unklefedor
  5.  * Date: 20.02.16
  6.  * Time: 17:11
  7.  * To change this template use File | Settings | File Templates.
  8.  */
  9.  
  10. namespace app\components\breadhead\calls;
  11.  
  12. use app\components\breadhead\service\SiteSettings;
  13. use yii\base\Exception;
  14.  
  15. class TelphinApi {
  16.     private $token;
  17.  
  18.     private $appName = "Navazy_service_app";
  19.     private $appId = "R_U96VN5XW~bDyRyWc9~SM0byV72.DRU";
  20.     private $secretKey = "9_Y5mCFRY4-5T5ETywH_RcdgvmIr_qrK";
  21.     private $salt = "c3b85a57fd17864bf9754a861637f468";
  22.  
  23.     private $ftp_user = "SEU130168";
  24.     private $ftp_password = "passrxa73vTF";
  25.  
  26.     private $redirectUri = "https://nasvazy.ru/";
  27.     private $appUrl = "https://gate.telphin.ru/";
  28.     private $queue;
  29.     private $prefix = '11027*';
  30.     private $apiMethods = array(
  31.         'auth' => 'oauth/token.php',
  32.         'calls' => 'uapi/phoneCalls/',
  33.         'records' => 'uapiext/getrecordinfo/',
  34.         'queue' => 'uapi/extensions/'
  35.     );
  36.  
  37.     public function getPrefix()
  38.     {
  39.         return $this->prefix;
  40.     }
  41.  
  42.     public function __construct($params = [])
  43.     {
  44.         $this->init($params);
  45.     }
  46.  
  47.     private function init( $params )
  48.     {
  49.         if ( isset($params['queue']) ) $this->queue = $params['queue'];
  50.         if ( strstr($_SERVER['SERVER_NAME'],'developer.nasvazy.ru') ) $this->queue = '11027*601';
  51.     }
  52.  
  53.     private function getStateMarker()
  54.     {
  55.         return md5($this->appId.$this->secretKey.$this->salt);
  56.     }
  57.  
  58.     private function getAuthParams()
  59.     {
  60.         return [
  61.             'grant_type' => 'client_credentials',
  62.             'redirect_uri' => $this->redirectUri,
  63.             'client_id' => $this->appId,
  64.             'client_secret' => $this->secretKey,
  65.             'state' => $this->getStateMarker()
  66.         ];
  67.     }
  68.  
  69.     private function buildQuery($params)
  70.     {
  71.         return http_build_query($params);
  72.     }
  73.  
  74.     /**
  75.      * @param $url
  76.      * @param string $method
  77.      * @param string $content_type
  78.      * @param array $data
  79.      * @return mixed
  80.      */
  81.     private function curlQuery($url,$auth = false,$method = "GET",$content_type = "application/json",$data = array())
  82.     {
  83.         $headers = array ();
  84.         $headers[] = "Content-type: ".$content_type;
  85.         if ($auth) $headers[] = "Authorization: Bearer ".$this->getToken();
  86.  
  87.         $ch = curl_init($url);
  88.         if ( $data ) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  89.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  90.         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
  91.         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  92.  
  93.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  94.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  95.  
  96.         $response = curl_exec($ch);
  97.         curl_close($ch);
  98.  
  99.         return $response;
  100.     }
  101.  
  102.     /**
  103.      * Запрос токена у api
  104.      * @return mixed
  105.      * @throws Exception
  106.      */
  107.     private function requestToken()
  108.     {
  109.         $response = json_decode(
  110.             $this->curlQuery(
  111.                 $this->appUrl.$this->apiMethods['auth'],
  112.                 false,
  113.                 null,
  114.                 "application/x-www-form-urlencoded",
  115.                 $this->buildQuery($this->getAuthParams())
  116.             ),
  117.         true);
  118.  
  119.         if ( isset($response['access_token']) ){
  120.             return $response;
  121.         }else{
  122.             throw new Exception('Авторизация на АТС завершилась неудачей');
  123.         }
  124.     }
  125.  
  126.     /**
  127.      * Обновление токена
  128.      */
  129.     private function refreshToken()
  130.     {
  131.         $tokenData = $this->requestToken();
  132.  
  133.         //Токен имет срок годности, после которого перестает валидироваться, запишем его с поправкой в 100 секунд
  134.         $expires = time()+$tokenData['expires_in']-100;
  135.         file_put_contents(__DIR__.'/token',$tokenData['access_token'].';'.$expires);
  136.  
  137.         $this->getExistingToken();
  138.     }
  139.  
  140.     /**
  141.      * Проверка наличия токена и его времени жизни
  142.      */
  143.     private function getExistingToken()
  144.     {
  145.         $this->token = false;
  146.         if ( is_file(__DIR__.'/token') ) {
  147.             $token = explode(';',file_get_contents(__DIR__ . '/token'));
  148.  
  149.             //Проверим срок годности токена
  150.             if ( $token[1] > time() ){
  151.                 $this->token = $token[0];
  152.             }
  153.         }
  154.     }
  155.  
  156.     /**
  157.      * Получаем токен для объекта
  158.      *
  159.      * @return mixed
  160.      */
  161.     private function getToken()
  162.     {
  163.         $this->getExistingToken();
  164.         if ( !$this->token ){
  165.             $this->refreshToken();
  166.         }
  167.  
  168.         return $this->token;
  169.     }
  170.  
  171.     /**
  172.      * Разрыв звонка
  173.      *
  174.      * @param $call_id
  175.      * @param $caller_num
  176.      */
  177.     public function dropCall($call_id,$caller_num)
  178.     {
  179.         $response = $this->curlQuery(
  180.             $this->appUrl.$this->apiMethods['calls'].'@me/@self/'.$call_id.'?phoneNumber='.$caller_num,
  181.             true,
  182.             "DELETE",
  183.             "application/json"
  184.         );
  185.     }
  186.  
  187.     /**
  188.      * Получение записи звонка
  189.      *
  190.      * @param $call_id
  191.      * @param $num_ext
  192.      */
  193.     public function getRecord($call_id,$num_ext)
  194.     {
  195.         $response = json_decode(
  196.             $this->curlQuery(
  197.                 $this->appUrl.$this->apiMethods['records'].'?extension='.$num_ext.'&id='.$call_id,
  198.                 true
  199.             ),
  200.             true
  201.         );
  202.  
  203.         if ( isset($response['entry']) ){
  204.             $folder = explode('*',$num_ext)[1];
  205.  
  206.             if ( isset($response['entry'][0]) ) {
  207.                 $result = $response['entry'][0];
  208.                 $result['url'] = "ftp://" . $this->ftp_user . ":" . $this->ftp_password . "@ftp.telphin.ru/$folder/{$response['entry'][0]['filename']}.WAV";
  209.  
  210.                 return $result;
  211.             }
  212.         }
  213.  
  214.         return false;
  215.     }
  216.  
  217.     /**
  218.      * Получение текущего звонка на линии
  219.      *
  220.      * @param $ext_num
  221.      * @return mixed
  222.      */
  223.     public function getCallData($ext_num)
  224.     {
  225.         $response = json_decode(
  226.             $this->curlQuery(
  227.                 $this->appUrl.$this->apiMethods['calls'].'@me/'.$ext_num,
  228.                 true,
  229.                 null,
  230.                 "application/json"
  231.             ),
  232.             true
  233.         );
  234.  
  235.         return $response;
  236.     }
  237.  
  238.     /**
  239.      * Сброс звонка, ответ
  240.      */
  241.     public function getHangupAction()
  242.     {
  243.         return '<?xml version="1.0" encoding="UTF-8"?>
  244.                <Response>
  245.                    <Hangup/>
  246.                </Response>';
  247.     }
  248.  
  249.     /**
  250.      * Получение состояния агентов в очереди
  251.      *
  252.      * @return mixed
  253.      */
  254.     public function getQueue($ext_num = '')
  255.     {
  256.         if ($ext_num) $ext_num = $this->prefix.$ext_num;
  257.  
  258.         $response = json_decode(
  259.             $this->curlQuery(
  260.                 $this->appUrl.$this->apiMethods['queue'].'@me/'.$this->queue.'/queue/agents/'.$ext_num,
  261.                 true,
  262.                 null,
  263.                 "application/json"
  264.             ),
  265.             true
  266.         );
  267.  
  268.         return $response;
  269.     }
  270.  
  271.     public function agentStatusUpdate($num,$status)
  272.     {
  273.         if ( (int)$num >= 0 && (int)$status >= 0 ){
  274.             $response = json_decode(
  275.                 $this->curlQuery(
  276.                     $this->appUrl.$this->apiMethods['queue'].'@me/'.$this->queue.'/queue/agents/'.$this->prefix.$num,
  277.                     true,
  278.                     'PUT',
  279.                     "application/json",
  280.                     json_encode(['status' => $status])
  281.                 ),
  282.                 true
  283.             );
  284.  
  285.             return !isset($response['error']);
  286.         }
  287.  
  288.         return false;
  289.     }
  290.  
  291. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement