How to send a message using messengers Api, 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.
The text content is set in the "body" parameter.
All data should be in the JSON.
$data = json_encode(
array(
'chatId'=>$phone.'@c.us',
'body'=>$message
)
);
Specify the valid URL to API. It contains the APIurl, a method and the token in a GET-parameter.
$url = $apiURL.'message?token='.$token;
Now we can send a request to the API.
$options = stream_context_create(
array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $data
)
)
);
$response = file_get_contents($apiURL.'message?token='.$token,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['text']) or !isset($_GET['phone'])){ die('Not enough data');}
$apiURL = 'https://api.chat-api.com/instanceYYYYY/';
$token = 'abcdefgh12345678';
$message = $_GET['text'];
$phone = $_GET['phone'];
$data = json_encode(
array(
'chatId'=>$phone.'@c.us',
'body'=>$message
)
);
$url = $apiURL.'message?token='.$token;
$options = stream_context_create(
array('http' =>
array(
'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.