API messengers send file, php

How to send a file using messengers API in PHP

At the beginning, we immediately associate messenger with our script, so as we write the code, we check its operation. To do this, go to your personal account and get a QR code there. Next, open messengers on your mobile phone, go to Settings -> messengers Web -> Scan a QR code.

Here we specify APiURL and token.

var $APIurl = 'https://api.chat-api.com/instanceYYYYY/';
var $token = 'abcdefgh12345678';

We are going to use GET-parameters to set a destination and a message content.

$message = $_GET['text'];
$phone = $_GET['phone'];

The destination for personal messages is a phone number and the postfix "@c.us".
It should be in the "chatId" parameter.
Put your file to the server and insert the direct link to the file to the "body" parameter. The link should contain protocol and domain, don't send only the path. Remember, that you must install a SSL-certificate, because messengers refuses getting files due http-protocol, only https.

You can specify a name of the file in "filename" parameter and add a text-message to the file in the "caption" parameter. All data should be in the JSON.

$data = json_encode(array(
    'chatId'=>$phone.'@c.us',
    'body'=>'https://domain.com/PHP/picture.jpg',
    'filename'=>'picture.jpg',
    'caption'=>'Hey! There is a file!'
));

Specify the valid URL to API. It contains the APIurl, a method and the token in a GET-parameter.

$url = $apiURL.'sendFile?token='.$token;

Now we can send a request to the API.

$options = stream_context_create(['http' => [
    'method'  => 'POST',
    'header'  => 'Content-type: application/json',
    'content' => $data
]
]);
$response = file_get_contents($url,false,$options);
echo $response;

To prevent errors, add this line at the beginning of the script:
if(!isset($_GET['text']) or !isset($_GET['phone'])){ die('Not enough data');}

And here is the whole script:

if(!isset($_GET['phone'])){ die('Not enough data');}

$apiURL = 'https://api.chat-api.com/instanceXXXXX/';
$token = 'abcdefgABCDEFG';

$phone = $_GET['phone'];

$data = json_encode(array(
    'chatId'=>$phone.'@c.us',
    'body'=>'https://domain.com/PHP/picture.jpg',
    'filename'=>'picture.jpg',
    'caption'=>'Hey! There is a file!'
));

$url = $apiURL.'sendFile?token='.$token;
$options = stream_context_create(['http' => [
    'method'  => 'POST',
    'header'  => 'Content-type: application/json',
    'content' => $data
]
]);
$response = file_get_contents($url,false,$options);
echo $response; exit;

Usage:
https://yoursite.com/path/to/script/yourscript.php?text=Hello&phone=70123456789
Don't use brackets, hyphens and any other formatting symbols in the phone. Use only digits.

You will only need to substitute your token from your personal account into the $token variable and instance number
Get API key

Feel free to reach out and share your experiences or ask any questions.

To top