_access_token = ""; $this->_from = ""; $this->_to = ""; $this->template_name = ""; $this->components = []; } public function set_access_token($token) { $this->_access_token = $token; return $this; } public function msg_from($number = "") { if (trim($number) == "") { throw new Exception("From is required"); } $this->_from = $number; return $this; } public function msg_to($number = "") { if (trim($number) == "") { throw new Exception("To is required"); } $this->_to = $number; return $this; } public function template($name) { if (trim($name) == "") { // throw error return; } $this->template_name = $name; return $this; } public function add_component($type, $params = []) { $this->components[$type] = $params; return $this; } public function add_body_param($text, $type = "text") { if (!isset($this->components["body"])) { $this->components["body"] = []; } $dict = [ "type" => $type, "text" => $text ]; $this->components["body"][] = $dict; return $this; } public function send_template_message() { if (!$this->_to) { throw new Exception("To is not defined"); } if (!$this->_from) { throw new Exception("From is not defined"); } if (!$this->template_name) { throw new Exception("Template Name is not defined"); } $url = sprintf($this->base_url, $this->version, $this->_from, "messages"); $headers = [ 'Authorization: Bearer ' . $this->_access_token, 'Content-Type: application/json' ]; $components = []; if (isset($this->components['header'])) { $components[] = [ "type" => "header", "parameters" => $this->components["header"] ]; } if (isset($this->components['body'])) { $components[] = [ "type" => "body", "parameters" => $this->components["body"] ]; } if (isset($this->components['footer'])) { $components[] = [ "type" => "footer", "parameters" => $this->components["footer"] ]; } $body = [ "messaging_product" => $this->message_product, "to" => $this->_to, "type" => "template", "template" => [ "name" => $this->template_name, "language" => [ "code" => $this->language_code ], "components" => $components ] ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $resultado = curl_exec($ch); curl_close($ch); try { $json = json_decode($resultado); return $json; } catch(Exception $e) { return null; } } }