إرسال الصور والملفات مع واتس اب API بإستخدام Base64

يمكننا إرسال الصور والمستندات والوسائط عن طريق تحويل الملفات إلى base64.

تحويل الملف إلى Base64 باستخدام ultramsg UI

يمكنك تحويل أي ملف باستخدام File to Base64 Tools من قائمة Ultramsg بعد تسجيل الدخول إلى حسابك في Ultramsg.

الخطوة 1: تحويل الصورة إلى Base64:

base64
إرسال رسالة صورة WhatsApp كـ base64 – ultramsg

الخطوة الثانية: إرسال صور WhatsApp كـ Base64:

يمكننا ببساطة وضع Base64 بدلاً من رابط HTTP كما هو موضح في الصورة التالية:

send base64 image
الحد الأقصى لطول Base64: 2،000،000 ~ 1.5 ميجابايت

مثال لإرسال صور WhatsApp كـ base64 باستخدام 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;
}

مثال لإرسال مستند WhatsApp pdf كـ base64 باستخدام 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;
}

 

مثال لإرسال WhatsApp Audio كـ Base64 باستخدام 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());
    }
}

مثال لإرسال مستند WhatsApp pdf كـ Base64 باستخدام 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());
    }
}

مثال لإرسال صورة WhatsApp كـ Base64 باستخدام 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);
    }
}

مثال لإرسال مستند WhatsApp pdf كـ Base64 باستخدام 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  

مثال لإرسال صورة WhatsApp كـ Base64 باستخدام 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  

مثال لإرسال صورة WhatsApp كـ Base64 باستخدام 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"))

مثال لإرسال مستند WhatsApp pdf كـ Base64 باستخدام 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"))

مثال لإرسال صورة WhatsApp كـ Base64 باستخدام 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

يمكنك الاطلاع على وثائق Whatsapp API الكاملة والأسئلة الشائعة .