
Enviar mensajes con Api Oficial de WhatsApp en JAVA
En este tutorial aprenderemos a enviar mensajes con Api Oficial de WhatsApp en Java, solo debemos seguir 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
Enviar mensajes con Api Oficial de WhatsApp en Java
Instalamos y configuramos un servidor Tomcat
Creamos un proyecto en Netbeans
Subimos este código a nuestro servidor con https
<%@page import="java.util.Scanner"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.net.URL"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
//TOKEN QUE NOS DA FACEBOOK
String token = "EAATRygN1uhcBADBaSw72VgZBXyYkW2zP0iyraTKov8v2OARZBGAdiq1mjOZCcMV3VUAqbMumCyBJ3oNe6ZAfNsoZCsnSILw31aEAlIyySARoKCRrcK5Aev34ik1dIZCDRla37TpBDuCZB9Vrd71PvAqlSP5agixIuOlytuVLGocRo526fdY6voejIFVyn8jRXHMw1RKP79VkgZDZD";
//NUESTRO TELEFONO
String telefono = "527121122441";
//IDENTIFICADOR DE NÚMERO DE TELÉFONO
String idNumero = "116907067953774";
//COLOCAMOS LA URL PARA ENVIAR EL MENSAJE
URL url = new URL("https://graph.facebook.com/v15.0/" + idNumero + "/messages");
//INICIALIZAMOS EL CONTENEDOR DEL ENVIO
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//EL TIPO DE ENVIO DE DATOS VA A SER VIA POST
httpConn.setRequestMethod("POST");
//CODIGO DE AUTORIZACION DE JAVA
httpConn.setRequestProperty("Authorization", "Bearer " + token);
//DEFINIMOS QUE LOS DATOS SERAN TRATADOS COMO JSON
httpConn.setRequestProperty("Content-Type", "application/json; application/x-www-form-urlencoded; charset=UTF-8");
//PREPARAMOS Y ENVIAMOS EL JSON
httpConn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
writer.write("{ "
+ "\"messaging_product\": \"whatsapp\", "
+ "\"to\": \"" + telefono + "\", "
+ "\"type\": \"template\", "
+ "\"template\": "
+ " { \"name\": \"hello_world\", "
+ " \"language\": { \"code\": \"en_US\" } "
+ " } "
+ "}");
//LIMPIAMOS LOS DATOS
writer.flush();
//CERRAMOS LOS DATOS
writer.close();
//CERRAMOS LA CONEXION
httpConn.getOutputStream().close();
//RECIBIMOS EL RESULTADO DEL ENVIO
InputStream responseStream = httpConn.getResponseCode() / 100 == 2
? httpConn.getInputStream()
: httpConn.getErrorStream();
Scanner s = new Scanner(responseStream).useDelimiter("\\A");
//OBTENEMOS LOS RESULTADOS
String respuesta = s.hasNext() ? s.next() : "";
System.out.println(respuesta);
%>
</body>
</html>
Ave que vuela, a la cazuela.