Edit file File name : Chat.php Content :<?php namespace App; use Illuminate\Database\Eloquent\Model; use Log; use File; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class Chat extends Model { protected $table = 'chat'; protected $fillable = [ 'instanceId', 'message_id', 'from', 'to', 'read', 'type', 'body', 'media', 'fromMe', 'time', 'message_id', 'assistent_id', 'customer_id' ]; // Base para conexão de API protected static function call_api($method, $endpoint, array $params = [], $secundario = 'auto', array $con = []){ // Caso esteja enviando os dados para conexão if($secundario === 3){ $wpp_api = $con['wpp_api']; $wpp_token = $con['wpp_token']; }elseif($secundario === true){ $wpp_api = config('app.wpp_api_c') ; $wpp_token = config('app.wpp_token_c'); }elseif($secundario === false){ $wpp_api = config('app.wpp_api'); $wpp_token = config('app.wpp_token'); // caso seja para testar todas as opções }elseif($secundario === "auto"){ $con_test = false; if($con != []){ $wpp_api = $con['wpp_api']; $wpp_token = $con['wpp_token']; $con_test = self::is_connected(3, $con); } if(!$con_test){ $wpp_api = config('app.wpp_api'); $wpp_token = config('app.wpp_token'); $con_test = self::is_connected(1); } if(!$con_test){ $wpp_api = config('app.wpp_api_c') ; $wpp_token = config('app.wpp_token_c'); $con_test = self::is_connected(2); } /* // Define os dados de conexão com o ultrachat $wpp_api = $secundario === true ? config('app.wpp_api_c') : config('app.wpp_api'); $wpp_token = $secundario === true ? config('app.wpp_token_c') : config('app.wpp_token'); if($secundario === 'auto' ? !self::is_connected(1) : false){ $wpp_api = config('app.wpp_api_c'); $wpp_token = config('app.wpp_token_c'); }*/ if(!$con_test) return false; } // echo "$wpp_api : $wpp_token -> $endpoint </br>"; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $wpp_api . $endpoint . ($method == "GET" ? "?" . http_build_query(array_merge(['token' => $wpp_token],$params)) : "" ), CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_POSTFIELDS => $method == "GET" ? NULL : http_build_query(array_merge(['token' => $wpp_token],$params)), CURLOPT_HTTPHEADER => array("content-type: application/x-www-form-urlencoded") ) ); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { $log = '[ERROR][SUCCESS][U:'.(Auth::user()?Auth::user()->id:"--").'] [' . date('Y-m-d H:i:s') . "] - $err " . PHP_EOL . PHP_EOL; File::append( storage_path('logs/whatsapp_error.log'), $log ); return false; } else { $log = '[SUCCESS][U:'.(Auth::user()?Auth::user()->id:"--").'] [' . date('Y-m-d H:i:s') . "] - " . print_r($response, true). PHP_EOL .'Endpoint: $endpoint'. PHP_EOL. 'Params:'.print_r($params, true). PHP_EOL . PHP_EOL; File::append( storage_path('logs/whatsapp_debug.log'), $log ); return $response; } } /* * $instancia = false retorna se uma das duas instancia estão connectadas * $instancia = 1 retorna o status da instancia princial * $instancia = 2 retorna o status da instancia de contingencia * $instancia = 3 retorna se a conexão passada em $con está conectada */ public static function is_connected($instancia = false, array $con = []){ // Testa conexão caso tenha sido enviado os dados $connection = ($con != []) ? self::status($con) : NULL; if(isset($connection->status) ? $connection->status->accountStatus->substatus === "connected" : false) return true; // Testa conexão princpal $connection = ($instancia != 2 AND $instancia != 3) ? self::status(false) : NULL; if(isset($connection->status) ? $connection->status->accountStatus->substatus === "connected" : false) return true; // Testa conexão de backup $connection = ($instancia != 1 AND $instancia != 3) ? self::status(true) : NULL; if(isset($connection->status) ? $connection->status->accountStatus->substatus === "connected" : false) return true; return false; } // Chamada para verificar se está conectado /* * $instancia = false retorna o status da instancia princial * $instancia = true retorna o status da instancia de contingencia * se receber array verifica da marca */ public static function status($secundario = false){ if(is_array($secundario)) return json_decode(self::call_api("GET", "instance/status", [], 3, $secundario)); else return json_decode(self::call_api("GET", "instance/status", [], $secundario)); } // Chamada para gerar QR Code public static function get_qr($secundario = false){ if(is_array($secundario)) return self::call_api("GET", "instance/qr", [], 3, $secundario); else return self::call_api("GET", "instance/qr", [], $secundario); } //Chamada para fazer logout do whatsapp public static function logout($secundario = false){ if(is_array($secundario)) return json_decode(self::call_api("POST", "instance/logout", [], 3, $secundario)); else return json_decode(self::call_api("POST", "instance/logout", [], $secundario)); } // Define id atraves do numero public static function get_id($number){ return $number."@c.us"; } // O reverso do get_id public static function get_whatapp_from_id($id){ return str_replace("@c.us", "", $id); } // Verifica se existe registro de mensagem vista no DB public static function verify_visto($message_id){ $message = self::where('message_id', $message_id)->first(); if(!$message) return false; if($message->read == true) return true; else return false; } // Obtem media de uma menssagem public static function get_media($message_id){ $message = self::where('message_id', $message_id)->first(); if(!$message) return false; $media = $message->media; return $media; } public static function prepare_url($url){ if( config('app.internal_url') == url('/')){ // Correção de bug $url = str_replace('http://', 'https://', $url); //Substitiu a url pública pela interna $url = str_replace( config('app.public_url'), config('app.internal_url').'/', $url); } return $url; } public static function url_to_send($url){ $url = str_replace( config('app.internal_url'), config('app.public_url') , $url); return $url; } // Retorna a imagem thumb do contato /* * Futuramente adaptar para enviar os dados da intancia que está sendo usada com esse contato * */ public static function get_image($number, $con = []){ return asset('img/default-user-image.png'); $contact = self::get_id($number); $response = json_decode(self::call_api("GET", "contacts/image", ['chatId' => $contact], 'auto', $con)); return isset($response->success) ? $response->success : asset('img/default-user-image.png'); } public static function get_messages($number, $con = [], $limit = 50){ $response = json_decode(self::call_api("GET", "chats/messages", ['chatId' => self::get_id($number), 'limit' => $limit], 'auto', $con)); if(count($response) == 0){ if(strlen($number) == 12){ $ini = substr($number, 0, 4); $number = $ini."9".substr($number, 4); $response = json_decode(self::call_api("GET", "chats/messages", ['chatId' => self::get_id($number), 'limit' => $limit], 'auto', $con)); // Tenta removendo o 9 caso a quantidade seja 13 caracteres }elseif(strlen($number) == 13){ $number = substr($number, 0, 4).substr($number, 5); $response = json_decode(self::call_api("GET", "chats/messages", ['chatId' => self::get_id($number), 'limit' => $limit], 'auto', $con)); } } return $response; } public static function send_msg($number, $msg, $con = []){ //echo $msg."----"; $response = json_decode(self::call_api("POST", "messages/chat", ['to' => self::get_id($number), 'body' => $msg, 'priority' => 10], 'auto', $con)); return $response; } // Obeter midia de uma mensagem enviada public static function get_media_from_id($message_id, $con = []){ $response = json_decode(self::call_api("GET", "messages", ['msgId' => $message_id], 'auto', $con)); /* $log = '[' . date('Y-m-d H:i:s') . "] - " . print_r($response, true) . PHP_EOL . PHP_EOL; File::append( storage_path('logs/whatsapp_debug.log'), $log ); */ if(isset($response->messages[0]->body)) return $response->messages[0]->body; else return ""; } public static function send_msg_doc($number, $doc, $con = []){ //echo $msg."----"; $response = json_decode(self::call_api("POST", "messages/document", ['to' => self::get_id($number), 'document' => self::url_to_send($doc), 'filename' => 'document.pdf'], 'auto', $con)); return $response; } public static function send_msg_aud($number, $aud, $con = []){ //echo $msg."----"; $response = json_decode(self::call_api("POST", "messages/voice", ['to' => self::get_id($number), 'audio' => self::url_to_send($aud)], 'auto', $con)); return $response; } public static function send_msg_img($number, $img, $con = []){ //echo $msg."----"; $response = json_decode(self::call_api("POST", "messages/image", ['to' => self::get_id($number), 'image' => self::url_to_send($img)], 'auto', $con)); return $response; } public static function countUnread(){ $user = Auth::user()->id; //$unread = self::where([['assistent_id', '=', $user], ['fromMe', '=', '0'], ['read', '=', '0']]); $unread = DB::select('SELECT DISTINCT(chat.customer_id) from chat where chat.assistent_id = :user and chat.fromMe = "0" AND chat.read = "0"', ["user" => $user]); return $unread; } public function customer() { return $this->belongsTo('App\Customer', 'customer_id'); } public static function getList($text = false, $stage = false, $unread = false, $page = false) { $values = []; $where = ""; $limit_sql = ""; $limit = 10; if(Auth::user()->hasRole('Assistente')) $where = " AND customers.assistent_id = '".Auth::user()->id."'"; if(Auth::user()->hasRole('Gerente')) $where = " AND customers.team_id = '".Auth::user()->team_id."'"; if(Auth::user()->hasRole('Master')) $where = ""; if(!isset($where)) die('Erro, tipo de usuário não identificado'); if($text){ $where .= " AND informations.nome LIKE :text "; $values['text'] = '%'.$text.'%'; } if($stage){ $where .= " AND customers.stage_id LIKE :stage "; $values['stage'] = $stage; } if($unread) $where .= " AND customers.unread_chat > 0 "; if($page) $limit_sql .= " LIMIT ".($page*$limit)." "; //$list = Customer::fromQuery("SELECT customers.*, informations.whatsapp_confirm, informations.nome FROM customers INNER JOIN informations ON informations.customer_id = customers.customer_id WHERE informations.whatsapp_confirm IS NOT NULL AND informations.whatsapp_confirm <> '' ".$where." ORDER BY time_last_message DESC ", $values); $list = DB::select(" SELECT customers.*, informations.whatsapp_confirm, informations.nome, teams.team, users.name as assistent FROM customers INNER JOIN informations ON informations.customer_id = customers.customer_id INNER JOIN teams ON teams.team_id = customers.team_id INNER JOIN users ON users.id = customers.assistent_id WHERE informations.whatsapp_confirm IS NOT NULL AND informations.whatsapp_confirm <> '' ".$where." ORDER BY time_last_message DESC ".$limit_sql, $values); return $list; } } Save