Переглянути джерело

Ejemplo de cómo enviar mensaje de whatsapp

Hugo Quijada 2 роки тому
батько
коміт
65dc2eb6b9
3 змінених файлів з 203 додано та 0 видалено
  1. 51 0
      commands/ComandoController.php
  2. 148 0
      components/Whatsapp.php
  3. 4 0
      config/params.php

+ 51 - 0
commands/ComandoController.php

@@ -0,0 +1,51 @@
+<?php
+
+namespace app\commands;
+
+use app\components\Whatsapp;
+use yii\console\Controller;
+
+class ComandoController extends Controller {
+
+  public function actionEnviarMensaje() {
+
+    $params = \Yii::$app->params;
+    $wab = null;
+    if(isset($params["wab"])) {
+      $wab = $params["wab"];
+    }
+
+    if($wab === null) {
+      $this->stdout("No existe la configuración\n");
+    }
+
+    $msgTo = "526621115643";
+    $template = "laud_resumen_eventos";
+    $template = "informe_de_eventos";
+
+    $eventos = "5/5 eventos";
+    $mensaje = "gracias por tu ";
+
+    try {
+      $wa = (new Whatsapp())
+        ->set_access_token($wab["access-token"])
+        ->msg_from($wab["phone-id"])
+        ->msg_to($msgTo)
+        ->template($template)
+        ->add_body_param($eventos)
+        ->add_body_param($mensaje)
+        ->send_template_message();
+      
+      if($wa === null) {
+        $this->stdout("Ocurrió un error al enviar el mensaje\n");
+        return;
+      }
+
+      $this->stdout("Proceso terminado\n");
+    } catch (\Exception $e) {
+      $this->stdout("Error al enviar el mensaje: {$e->getMessage()}\n");
+    }
+
+  }
+
+}

+ 148 - 0
components/Whatsapp.php

@@ -0,0 +1,148 @@
+<?php
+
+namespace app\components;
+
+use Exception;
+
+class Whatsapp {
+
+  private $_access_token = "";
+  public $base_url = "https://graph.facebook.com/%s/%s/%s";
+  public $components = [];
+  public $language_code = "es_MX";
+  public $message_product = "whatsapp";
+  public $_from = "";
+  public $_to = "";
+  public $version = "v14.0";
+  public $template_name = "";
+
+  public function __construct() {
+    $this->_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;
+    }
+  }
+}

+ 4 - 0
config/params.php

@@ -3,4 +3,8 @@
 return [
   'jwt.key' => 'XQky31fheBkkB5T4cYnD',
   'firebaseKey' => __DIR__ . '/firebase-key.json',
+  'wab' => [ // WhatsAppBusiness
+    "access-token" => "EABRcl7XEGR8BAOuo807qQQNHMXQojPkNndwiCFWXwKZBKqgf0eUrzYTx8vkAFWBB6JUZCcdFTtwLqZAW6YtgmH43s4LHm3ztHaSx6ZCFDZC5D7cHY67L4t49GrxmyrIHRlbykZAmzYLRvXvADf5rSdBVZAZCKmXAPEFf5R1Oy3RzwwTWCiZADgJHi",
+    "phone-id" => "111886161708348",
+  ]
 ];