
Recibir WhatsApp y crear una respuesta con ChatGPT para WooCommerce
Ya nos conectamos a ChatGPT y hemos obtenido respuestas a nuestras preguntas, ahora vamos a Recibir WhatsApp y crear una respuesta con ChatGPT para WooCommerce. Recordemos que WhatsApp fue comprado por Meta y debemos conectarnos a Meta para poder recibir mensajes desde WhatsApp siguiendo estos pasos:
Creamos una app en Facebook

O podemos aceder a este link Todas las apps – Meta for Developers (facebook.com)





Configuramos el Api de WhatsApp






Código Recibir WhatsApp y crear una respuesta con ChatGPT para WooCommerce
Código

<?php //Codigo para Recibir WhatsApp y crear una respuesta con ChatGPT para WooCommerce /* * VERIFICACION DEL WEBHOOK */ //TOQUEN QUE QUERRAMOS PONER $token = 'HolaNovato'; //RETO QUE RECIBIREMOS DE FACEBOOK $palabraReto = $_GET['hub_challenge']; //TOQUEN DE VERIFICACION QUE RECIBIREMOS DE FACEBOOK $tokenVerificacion = $_GET['hub_verify_token']; //SI EL TOKEN QUE GENERAMOS ES EL MISMO QUE NOS ENVIA FACEBOOK RETORNAMOS EL RETO PARA VALIDAR QUE SOMOS NOSOTROS if ($token === $tokenVerificacion) { echo $palabraReto; exit; } /* * RECEPCION DE MENSAJES */ //LEEMOS LOS DATOS ENVIADOS POR WHATSAPP $respuesta = file_get_contents("php://input"); //CONVERTIMOS EL JSON EN ARRAY DE PHP $respuesta = json_decode($respuesta, true); //EXTRAEMOS EL MENSAJE DEL ARRAY $mensaje=$respuesta['entry'][0]['changes'][0]['value']['messages'][0]['text']['body']; //EXTRAEMOS EL TELEFONO DEL ARRAY $telefonoCliente=$respuesta['entry'][0]['changes'][0]['value']['messages'][0]['from']; //EXTRAEMOS EL ID DE WHATSAPP DEL ARRAY $id=$respuesta['entry'][0]['changes'][0]['value']['messages'][0]['id']; //EXTRAEMOS EL TIEMPO DE WHATSAPP DEL ARRAY $timestamp=$respuesta['entry'][0]['changes'][0]['value']['messages'][0]['timestamp']; //SI HAY UN MENSAJE if($mensaje!=null){ $query = " SELECT CONCAT('Nombre: ', p.post_title) as product_name, CONCAT('Categoría: ', t.name) as category_name, CONCAT('Precio: ', MAX(CASE WHEN pm1.meta_key = '_price' THEN pm1.meta_value END)) as price, CONCAT('Existencia: ', MAX(CASE WHEN pm2.meta_key = '_stock' THEN pm2.meta_value END)) as stock, CONCAT('ID de miniatura: ', MAX(CASE WHEN pm3.meta_key = '_thumbnail_id' THEN pm3.meta_value END)) as thumbnail_id, CONCAT('Descripción: ', p.post_excerpt) as description, CONCAT('URL del producto: ', (SELECT option_value FROM wp_options WHERE option_name = 'siteurl'), '/producto/', p.post_name, '/') as product_url FROM wp_posts p JOIN wp_term_relationships tr ON p.ID = tr.object_id JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id JOIN wp_terms t ON tt.term_id = t.term_id JOIN wp_postmeta pm1 ON p.ID = pm1.post_id JOIN wp_postmeta pm2 ON p.ID = pm2.post_id LEFT JOIN wp_postmeta pm3 ON p.ID = pm3.post_id LEFT JOIN wp_posts img ON img.ID = pm3.meta_value WHERE p.post_type = 'product' AND tt.taxonomy = 'product_cat' AND (pm1.meta_key = '_price' OR pm2.meta_key = '_stock' OR pm3.meta_key = '_thumbnail_id') AND p.post_status = 'publish' GROUP BY p.post_title, t.name, img.guid, p.post_excerpt, p.post_name HAVING thumbnail_id IS NOT NULL AND thumbnail_id <> '' ORDER BY p.post_title ASC; "; // Incluir el entorno de WordPress require_once( '../wp-load.php' ); // Verificar si WooCommerce está activo if ( ! class_exists( 'WooCommerce' ) ) { die( 'WooCommerce no está activo.' ); } // Obtener la dirección, el teléfono y el correo electrónico de la tienda $store_address = get_option( 'woocommerce_store_address' ); $store_address_2 = get_option( 'woocommerce_store_address_2' ); $store_city = get_option( 'woocommerce_store_city' ); $store_postcode = get_option( 'woocommerce_store_postcode' ); $store_country = get_option( 'woocommerce_default_country' ); $store_state = get_option( 'woocommerce_default_state' ); $store_email = get_option( 'woocommerce_email_from_address' ); $site_url = get_site_url(); // Instancia de la clase wpdb global $wpdb; // Ejecutar la consulta $results = $wpdb->get_results( $query ); $pregunta="Eres un woocommerce de nombre ".$site_url.", tus horarios son de lunes a viernes de 8am a 6pm , nuestro telefono es 712321321 , estas ubicado en ". $store_address . ", " . $store_address_2 . ", " . $store_city . ", " . $store_postcode . ", " . $store_country . ", " . $store_state . " y cuentas con estos productos (Saluda al cliente mostrando la información de la tienda pero no los productos). "; // Imprimir los resultados foreach( $results as $result ) { $pregunta=$pregunta. 'Nombre: ' . $result->product_name . ' , '; $pregunta=$pregunta. 'Categoría: ' . $result->category_name . ' , '; $pregunta=$pregunta. 'Precio: ' . $result->price . ' , '; $pregunta=$pregunta. 'Existencia: ' . $result->stock . ' , '; $pregunta=$pregunta. 'Descripción: ' . $result->description . ' , '; $pregunta=$pregunta. 'URL del producto: ' . $result->product_url . ' , '; //$pregunta=$pregunta. '\n'; } $pregunta=$pregunta.". El cliente dice: ".$mensaje; require_once "chatgpt.php"; $respuesta=preguntaChatgpt($pregunta); //ESCRIBIMOS LA RESPUESTA file_put_contents("text.txt", $respuesta); //hola //que horarios tienes //abren el lunes //hola abren los domingos? //cual es tu telefono? //estan en acapulco? //estan en Ciudad de mexico? //tienes blusas? //A como las blusas? //como puedo comprar una blusa? //muestrame todos tus pantalones }
Activamos un servidor ngrok





