Envía imágenes y documentos de WhatsApp usando Base64

Podemos enviar imágenes, documentos y medios convirtiendo los archivos a base64.

convertir archivo a Base64 usando ultramsg UI

puede convertir cualquier archivo utilizando File to Base64 Tools desde el menú Ultramsg después de iniciar sesión en su cuenta en Ultramsg.

paso 1: convertir la imagen a Base64:

base64
enviar un mensaje de imagen de WhatsApp como base64 – ultramsg

paso 2: Enviar imágenes de WhatsApp como Base64:

Simplemente podemos poner Base64 en lugar del enlace HTTP como se muestra en la siguiente imagen:

send base64 image
Longitud máxima de Base64: 2,000,000 ~ 1.5 MB

Ejemplo para enviar imágenes de WhatsApp como base64 usando PHP

$instance='instance1150';
$token='Token_123456';
$to='14155552671';
/////////// 
$path="1.jpg";
$data = file_get_contents($path);
// you can convert File to Base64  using ultramsg UI
// https://user.ultramsg.com/app/base64/base64.php 

//Encodes data base64
$img_base64 =  base64_encode($data);  
//urlencode — URL-encodes string  
$img_base64 =urlencode($img_base64 );
////////////
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.ultramsg.com/$instance/messages/image",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_SSL_VERIFYHOST =>0,
  CURLOPT_SSL_VERIFYPEER =>0,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "token=$token&to=$to&image=$img_base64&caption=image Caption",
  CURLOPT_HTTPHEADER => array(
    "content-type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Ejemplo para enviar un documento pdf de WhatsApp como base64 usando PHP

$instance='instance1150';
$token='Token_123456';
$to='14155552671';
/////////// 
$path="ultramsg.pdf";
$data = file_get_contents($path);
// you can convert File to Base64  using ultramsg UI
// https://user.ultramsg.com/app/base64/base64.php 

//Encodes data base64
$img_base64 =  base64_encode($data);  
//urlencode — URL-encodes string  
$img_base64 =urlencode($img_base64 );
////////////
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.ultramsg.com/$instance/messages/document",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_SSL_VERIFYHOST =>0,
  CURLOPT_SSL_VERIFYPEER =>0,
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "token=$token&to=$to&document=$img_base64&filename=ultramsg.pdf",
  CURLOPT_HTTPHEADER => array(
    "content-type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

 

Ejemplo para enviar audio de WhatsApp como Base64 usando Java

package com.mycompany.mavenproject1;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Ultramsg team
 */
public class newJavaFile {

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String args[]) throws IOException {
  //////////////////////////////////////
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
byte[] fileContent = FileUtils.readFileToByteArray(new File("/Users/demo/1.mp3"));
String sound = Base64.getEncoder().encodeToString(fileContent);
sound=URLEncoder.encode(sound, StandardCharsets.UTF_8.toString());
RequestBody body = RequestBody.create(mediaType, "token=123456789&to=14155552671&audio=" + sound);
Request request = new Request.Builder()
  .url("https://api.ultramsg.com/instance1150/messages/audio")
  .post(body)
  .addHeader("content-type", "application/x-www-form-urlencoded")
  .build();

Response response = client.newCall(request).execute();

//////////////////////////////////////
     System.out.println("===================");
     System.out.println(response.body().string());
    }
}

Ejemplo para enviar un documento pdf de WhatsApp como Base64 usando Java

package com.mycompany.mavenproject1;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Ultramsg team
 */
public class newJavaFile {

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String args[]) throws IOException {
  //////////////////////////////////////
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
byte[] fileContent = FileUtils.readFileToByteArray(new File("/Users/demo/ultramsg.pdf"));
String pdf = Base64.getEncoder().encodeToString(fileContent);
pdf=URLEncoder.encode(pdf, StandardCharsets.UTF_8.toString());
RequestBody body = RequestBody.create(mediaType, "token=123456789&to=14155552671&document=" + pdf+"&filename=ultramsg.pdf");
Request request = new Request.Builder()
  .url("https://api.ultramsg.com/instance1150/messages/document")
  .post(body)
  .addHeader("content-type", "application/x-www-form-urlencoded")
  .build();

Response response = client.newCall(request).execute();

//////////////////////////////////////
     System.out.println("===================");
     System.out.println(response.body().string());
    }
}

Ejemplo para enviar una imagen de WhatsApp como Base64 usando c#

using System;
using RestSharp;
using System.IO;

public class Program
{
    public static void Main()
    {
    byte[] AsBytes = File.ReadAllBytes("1.jpg");
    String AsBase64String = Convert.ToBase64String(AsBytes);
        ///////////
        var client =
            new RestClient("https://api.ultramsg.com/instance1150/messages/image");
        var request = new RestRequest(Method.POST);
        request.AddHeader("content-type", "application/x-www-form-urlencoded");
        request.AddParameter("token","123456789",ParameterType.GetOrPost);
        request.AddParameter("to","14155552671",ParameterType.GetOrPost);
        request.AddParameter("image",AsBase64String,ParameterType.GetOrPost);
        request.AddParameter("caption","Hello",ParameterType.GetOrPost);

       
        IRestResponse response = client.Execute(request);

        ///////////
        Console.WriteLine(response.Content);
    }
}

Ejemplo para enviar un documento pdf de WhatsApp como Base64 usando vb.net

Imports System 
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web

Module base64  
    Sub Main()  
        ''''' send documenct as base64
        Dim WebRequest As HttpWebRequest
        Dim bytes As Byte() = IO.File.ReadAllBytes("ultramsg.pdf")
        Dim file As String = Convert.ToBase64String(bytes)
        WebRequest = HttpWebRequest.Create("https://api.ultramsg.com/instance1150/messages/document")
        Dim postdata As String = "token=123456789&to=14155552671" & "&document=" & HttpUtility.UrlEncode(file) & "&filename=test.pdf"
        Dim enc As UTF8Encoding = New System.Text.UTF8Encoding()
        Dim postdatabytes As Byte()  = enc.GetBytes(postdata)
        WebRequest.Method = "POST"
        WebRequest.ContentType = "application/x-www-form-urlencoded"
        WebRequest.GetRequestStream().Write(postdatabytes)
       
       ' print return 
        Dim ret As New System.IO.StreamReader(WebRequest.GetResponse().GetResponseStream())
        console.writeline(ret.ReadToEnd())
        

  
    End Sub  
  
End Module  

Ejemplo para enviar una imagen de WhatsApp como Base64 usando vb.net

Imports System 
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web

Module base64  
    Sub Main()  
      ''''' send image as base64
        Dim WebRequest As HttpWebRequest
        Dim bytes As Byte() = IO.File.ReadAllBytes("test.jpeg")
        Dim file As String = Convert.ToBase64String(bytes)

        WebRequest = HttpWebRequest.Create("https://api.ultramsg.com/instance1150/messages/image")
        Dim postdata As String = "token=123456789&to=14155552671" & "&image=" & HttpUtility.UrlEncode(file) & "&caption=Hi"
        Dim enc As UTF8Encoding = New System.Text.UTF8Encoding()
        Dim postdatabytes As Byte()  = enc.GetBytes(postdata)
        WebRequest.Method = "POST"
        WebRequest.ContentType = "application/x-www-form-urlencoded"
        WebRequest.GetRequestStream().Write(postdatabytes)
        Dim ret As New System.IO.StreamReader(WebRequest.GetResponse().GetResponseStream())
        console.writeline(ret.ReadToEnd())
        
  
    End Sub  
  
End Module  

Ejemplo para enviar una imagen de WhatsApp como Base64 usando python 3

import http.client
import base64
import urllib.parse
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

conn = http.client.HTTPSConnection("api.ultramsg.com")

with open("1.jpeg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

img_bas64=urllib.parse.quote_plus(encoded_string)
payload = "token=token&to=mobile&image="+ img_bas64 + "&caption=image Caption"
headers = { 'content-type': "application/x-www-form-urlencoded" }
conn.request("POST", "/instance_id/messages/image", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

Ejemplo para enviar un documento pdf de WhatsApp como Base64 usando Python

import http.client
import base64
import urllib.parse
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
conn = http.client.HTTPSConnection("api.ultramsg.com")
with open("test.pdf", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

img_bas64=urllib.parse.quote_plus(encoded_string)
payload = "token=token&to=mobile&document="+ img_bas64 + "&filename=test.pdf"
headers = { 'content-type': "application/x-www-form-urlencoded" }
conn.request("POST", "/instance_id/messages/document", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

Ejemplo para enviar imagen de WhatsApp como Base64 usando Ruby

require 'uri'
require 'net/http'
require 'openssl'
require 'base64'
require 'cgi'

url = URI("https://api.ultramsg.com/instance_id/messages/image")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
img=Base64.strict_encode64(File.open("a.png", "rb").read)
img=CGI.escape(img)

request.body = "token=instance_token&to=14155552671&image="+ img + "&caption=image Caption"
response = http.request(request)
puts response.read_body

Puede ver la documentación completa de la API de Whatsapp y las preguntas frecuentes .