Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Created by JetBrains PhpStorm.
- * User: unklefedor
- * Date: 20.02.16
- * Time: 17:11
- * To change this template use File | Settings | File Templates.
- */
- namespace app\components\breadhead\calls;
- use app\components\breadhead\service\SiteSettings;
- use yii\base\Exception;
- class TelphinApi {
- private $token;
- private $appName = "Navazy_service_app";
- private $appId = "R_U96VN5XW~bDyRyWc9~SM0byV72.DRU";
- private $secretKey = "9_Y5mCFRY4-5T5ETywH_RcdgvmIr_qrK";
- private $salt = "c3b85a57fd17864bf9754a861637f468";
- private $ftp_user = "SEU130168";
- private $ftp_password = "passrxa73vTF";
- private $redirectUri = "https://nasvazy.ru/";
- private $appUrl = "https://gate.telphin.ru/";
- private $queue;
- private $prefix = '11027*';
- private $apiMethods = array(
- 'auth' => 'oauth/token.php',
- 'calls' => 'uapi/phoneCalls/',
- 'records' => 'uapiext/getrecordinfo/',
- 'queue' => 'uapi/extensions/'
- );
- public function getPrefix()
- {
- return $this->prefix;
- }
- public function __construct($params = [])
- {
- $this->init($params);
- }
- private function init( $params )
- {
- if ( isset($params['queue']) ) $this->queue = $params['queue'];
- if ( strstr($_SERVER['SERVER_NAME'],'developer.nasvazy.ru') ) $this->queue = '11027*601';
- }
- private function getStateMarker()
- {
- return md5($this->appId.$this->secretKey.$this->salt);
- }
- private function getAuthParams()
- {
- return [
- 'grant_type' => 'client_credentials',
- 'redirect_uri' => $this->redirectUri,
- 'client_id' => $this->appId,
- 'client_secret' => $this->secretKey,
- 'state' => $this->getStateMarker()
- ];
- }
- private function buildQuery($params)
- {
- return http_build_query($params);
- }
- /**
- * @param $url
- * @param string $method
- * @param string $content_type
- * @param array $data
- * @return mixed
- */
- private function curlQuery($url,$auth = false,$method = "GET",$content_type = "application/json",$data = array())
- {
- $headers = array ();
- $headers[] = "Content-type: ".$content_type;
- if ($auth) $headers[] = "Authorization: Bearer ".$this->getToken();
- $ch = curl_init($url);
- if ( $data ) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
- $response = curl_exec($ch);
- curl_close($ch);
- return $response;
- }
- /**
- * Запрос токена у api
- * @return mixed
- * @throws Exception
- */
- private function requestToken()
- {
- $response = json_decode(
- $this->curlQuery(
- $this->appUrl.$this->apiMethods['auth'],
- false,
- null,
- "application/x-www-form-urlencoded",
- $this->buildQuery($this->getAuthParams())
- ),
- true);
- if ( isset($response['access_token']) ){
- return $response;
- }else{
- throw new Exception('Авторизация на АТС завершилась неудачей');
- }
- }
- /**
- * Обновление токена
- */
- private function refreshToken()
- {
- $tokenData = $this->requestToken();
- //Токен имет срок годности, после которого перестает валидироваться, запишем его с поправкой в 100 секунд
- $expires = time()+$tokenData['expires_in']-100;
- file_put_contents(__DIR__.'/token',$tokenData['access_token'].';'.$expires);
- $this->getExistingToken();
- }
- /**
- * Проверка наличия токена и его времени жизни
- */
- private function getExistingToken()
- {
- $this->token = false;
- if ( is_file(__DIR__.'/token') ) {
- $token = explode(';',file_get_contents(__DIR__ . '/token'));
- //Проверим срок годности токена
- if ( $token[1] > time() ){
- $this->token = $token[0];
- }
- }
- }
- /**
- * Получаем токен для объекта
- *
- * @return mixed
- */
- private function getToken()
- {
- $this->getExistingToken();
- if ( !$this->token ){
- $this->refreshToken();
- }
- return $this->token;
- }
- /**
- * Разрыв звонка
- *
- * @param $call_id
- * @param $caller_num
- */
- public function dropCall($call_id,$caller_num)
- {
- $response = $this->curlQuery(
- $this->appUrl.$this->apiMethods['calls'].'@me/@self/'.$call_id.'?phoneNumber='.$caller_num,
- true,
- "DELETE",
- "application/json"
- );
- }
- /**
- * Получение записи звонка
- *
- * @param $call_id
- * @param $num_ext
- */
- public function getRecord($call_id,$num_ext)
- {
- $response = json_decode(
- $this->curlQuery(
- $this->appUrl.$this->apiMethods['records'].'?extension='.$num_ext.'&id='.$call_id,
- true
- ),
- true
- );
- if ( isset($response['entry']) ){
- $folder = explode('*',$num_ext)[1];
- if ( isset($response['entry'][0]) ) {
- $result = $response['entry'][0];
- $result['url'] = "ftp://" . $this->ftp_user . ":" . $this->ftp_password . "@ftp.telphin.ru/$folder/{$response['entry'][0]['filename']}.WAV";
- return $result;
- }
- }
- return false;
- }
- /**
- * Получение текущего звонка на линии
- *
- * @param $ext_num
- * @return mixed
- */
- public function getCallData($ext_num)
- {
- $response = json_decode(
- $this->curlQuery(
- $this->appUrl.$this->apiMethods['calls'].'@me/'.$ext_num,
- true,
- null,
- "application/json"
- ),
- true
- );
- return $response;
- }
- /**
- * Сброс звонка, ответ
- */
- public function getHangupAction()
- {
- return '<?xml version="1.0" encoding="UTF-8"?>
- <Response>
- <Hangup/>
- </Response>';
- }
- /**
- * Получение состояния агентов в очереди
- *
- * @return mixed
- */
- public function getQueue($ext_num = '')
- {
- if ($ext_num) $ext_num = $this->prefix.$ext_num;
- $response = json_decode(
- $this->curlQuery(
- $this->appUrl.$this->apiMethods['queue'].'@me/'.$this->queue.'/queue/agents/'.$ext_num,
- true,
- null,
- "application/json"
- ),
- true
- );
- return $response;
- }
- public function agentStatusUpdate($num,$status)
- {
- if ( (int)$num >= 0 && (int)$status >= 0 ){
- $response = json_decode(
- $this->curlQuery(
- $this->appUrl.$this->apiMethods['queue'].'@me/'.$this->queue.'/queue/agents/'.$this->prefix.$num,
- true,
- 'PUT',
- "application/json",
- json_encode(['status' => $status])
- ),
- true
- );
- return !isset($response['error']);
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement