Hantar imej dan Dokumen WhatsApp menggunakan Base64

Kami boleh menghantar imej, dokumen dan media dengan menukar fail kepada base64.

tukar Fail ke Base64 menggunakan UI ultramsg

anda boleh menukar mana-mana Fail menggunakan Fail kepada Alat Base64 daripada menu Ultramsg selepas log masuk ke akaun anda dalam Ultramsg.

langkah 1 : tukar imej kepada Base64 :

base64
hantar mesej imej WhatsApp sebagai base64 – ultramsg

langkah 2 : Hantar imej WhatsApp sebagai Base64 :

Kita hanya boleh meletakkan Base64 dan bukannya pautan HTTP Seperti yang ditunjukkan dalam imej berikut:

send base64 image
Panjang Max Base64 : 2,000,000 ~1.5 MB

Contoh untuk menghantar imej WhatsApp sebagai base64 menggunakan 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;
}

Contoh untuk menghantar dokumen pdf WhatsApp sebagai base64 menggunakan 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;
}

 

Contoh untuk menghantar Audio WhatsApp sebagai Base64 menggunakan 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());
    }
}

Contoh untuk menghantar dokumen pdf WhatsApp sebagai Base64 menggunakan 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());
    }
}

Contoh untuk menghantar imej WhatsApp sebagai Base64 menggunakan 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);
    }
}

Contoh untuk menghantar dokumen pdf WhatsApp sebagai Base64 menggunakan 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  

Contoh untuk menghantar imej WhatsApp sebagai Base64 menggunakan 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  

Contoh untuk menghantar imej WhatsApp sebagai Base64 menggunakan 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"))

Contoh untuk menghantar dokumen pdf WhatsApp sebagai Base64 menggunakan 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"))

Contoh untuk menghantar imej WhatsApp sebagai Base64 menggunakan 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

anda boleh melihat Dokumentasi dan Soalan Lazim API Whatsapp Penuh.