การส่ง message
การส่ง Message ก็คือการส่งข้อความไปยัง web service ของ facebook ด้วยข้อความที่เราต้องการ
ในตัวอย่างนี้จะเป็นการคืนข้อความที่ผู้ใช้งานส่งมากลับไป
เพิ่ม code ในไฟล์ bot.php
<?php
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php.log");
$challange = $_REQUEST['hub_challenge'];
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
error_log($challange);
error_log($sender);
error_log($message);
$access_token = "EAAEF6Rg2mWEBAAnqU0FhYYlb3s0a7kiVuKMUja9umtC50i25bTZAOBBVvDf9BX0hixiqYryCMVLVnhZBZCkJZBl5AZAQTMvAoIZCj5W268DOurt2FLIGb2GL2fGWMwY6RtN7nuFe3K13B9tXxNPfonHvDZCGyTldpbFvdipzJD3QQZDZD";
if(!empty($input['entry'][0]['messaging'][0]['message']))
{
reply($access_token, $sender, $message);
}
echo $challange;
function reply($access_token, $sender, $message)
{
//API Url
$url = 'https://graph.facebook.com/v2.6/me/messages?'.http_build_query(array(
'access_token' => $access_token));
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array (
'recipient' =>
array (
'id' => $sender,
),
'message' =>
array (
'text' => $message,
),
);
error_log($jsonData);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
error_log($jsonDataEncoded);
error_log($url);
error_log($result);
error_log($httpcode);
error_log($error);
}
พิมพ์ข้อความใน Messenger จะได้รับข้อความตอบกลับ