Receive Message
เป้าประสงค์ของบทนี้คือต้องการให้ท่านเห็นลักษณะของ message ที่ Facebook ส่งมาให้บอท เพื่อที่ท่านจะได้มีไอเดียว่าจะทำอะไรกับมันได้บ้าง ลักษณะ message จะเป็นดังนี้
{
"object": "page",
"entry": [
{
"id": "131138044270079",
"time": 1511408188526,
"messaging": [
{
"sender": {
"id": "1333624753415639"
},
"recipient": {
"id": "131138044270079"
},
"timestamp": 1511408188371,
"message": {
"mid": "mid.$cAAB3RLogr0pmGDgD01f5vK7bRAzt",
"seq": 158239,
"text": "Hi"
}
}
]
}
]
}
ข้อสังเกตุ
- entry เป็นอะเรย์
- messaging เป็นอะเรย์
ทำไมข้อสังเกตุนี้มันสำคัญ ก็คือ ถ้ามันเป็นอะเรย์แสดงว่าเป็นไปได้ที่ทาง Facebook จะส่งข้อมูลมาหลายชุดในครั้งเดียว ซึ่งเราจำเป็นต้องเขียนโค้ดอย่างระมัดระวัง
ทดลองเขียนโค้ด
<?php
$access_token = 'EAAFUz3HsNTEBAFZAeDiZA8ywOtEUZB52ZBLYziFtXjZCZAUZBmqlUtuemBnbbkN3M25NBKutMZCDzngjD0Uxz530fFmIiJHnFDHZBen9KRGvWZBjnti5awKG6a1g4XfaO8ZCKVfG2Cer5nu3W0uvubzk4wYfpsZCc9QfLGe2tiVZA5JGY6QZDZD';
/* validate verify token needed for setting up web hook */
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === $access_token) {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}
}
/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input['entry'][0]['messaging'][0]['sender']['id'])) {
$sender = $input['entry'][0]['messaging'][0]['sender']['id']; //sender facebook id
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='. $access_token;
/*initialize curl*/
$ch = curl_init($url);
/*prepare response*/
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text": "Your message is '. $input['entry'][0]['messaging'][0]['message']['text'] .'"
}
}';
/* curl setting to send a json post data */
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch); // user will get the message
}
อธิบายโค้ด
โค้ดนี้ไว้ใช้สำหรับให้ทาง Facebook ตรวจสอบเรื่อง callback URL ที่ผมเขียนไว้ในบท Facebook เรายังเก็บไว้ในหัวไฟล์โค้ดเราเสมอ
/* validate verify token needed for setting up web hook */
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === $access_token) {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}
}
แปลง JSON ที่ Facebook ส่งมาให้ไปเป็นอะเรย์ เพื่อง่ายต่อการเขียนโค้ด
/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);
ตรวจสอบว่า message ที่ส่งมานั้นมี id ของผู้ส่งหรือเปล่า อันนี้เป็นการตรวจสอบคร่าวๆว่ามีคนคุยกับบอท ไม่ใช่เรียก URL เว็บขึ้นมาตรงๆ ผมเขียนตรวจสอบไว้เพียงเล็กน้อยเท่านั้น เพื่อไม่ให้โค้ดมันดูยุ่งยากเกินไป เมื่อถึงตอนท่านเขียนโค้ดเพื่อใช้งานจริงๆ ก็อาจจะตรวจสอบให้รัดกุมขึ้นอีกหน่อย
if (isset($input['entry'][0]['messaging'][0]['sender']['id']))
URL นี้เป็น enpoint api ของ Facebook ที่เราสามารถ POST ข้อความไปให้ Facebook เพื่อให้ Facebook ส่งข้อความต่อไปให้บุคคลที่ระบุ
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='. $access_token;
เราจะใช้ cURL ยิง POST ไปหา Facebook
/*initialize curl*/
$ch = curl_init($url);
message ที่เราจะยิงไปให้ Facebook จะต้องอยู่ในรูปแบบของ JSON ระบุ id ของผู้รับและข้อความที่เราต้องการส่งไปให้
/*prepare response*/
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text": "Your message is '. $input['entry'][0]['messaging'][0]['message']['text'] .'"
}
}';
สั่ง cURL ยิง JSON ไปยัง endpoint api ของ Facebook ก็เป็นอันเรียบร้อยว่าบอทได้ตอบกลับไปหายูสเซอร์ที่ทักมา
/* curl setting to send a json post data */
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch); // user will get the message
หลังจาก commit changes โค้ดแล้วให้เข้าไปหน้า Facebook เพจที่เราเตรียมไว้ทำบอท แล้วลองส่งเมสเสจทักบอทไปดู ซึ่งบอทจะต้องตอบกลับมาว่า Your message is ตามด้วยข้อความที่คุณทักไป
การสร้าง JSON จากอะเรย์
โค้ดด้านบนจะเห็นว่าการสร้าง JSON เพื่อให้บอทส่งไปหา API ของ Facebook ผมใช้วิธีสร้าง JSON กันแบบโต้งๆ ถ้าใครถนัดอะเรย์มากกว่า JSON ดูตัวอย่างนี้ครับ
<?php
$access_token = 'EAAFUz3HsNTEBAFZAeDiZA8ywOtEUZB52ZBLYziFtXjZCZAUZBmqlUtuemBnbbkN3M25NBKutMZCDzngjD0Uxz530fFmIiJHnFDHZBen9KRGvWZBjnti5awKG6a1g4XfaO8ZCKVfG2Cer5nu3W0uvubzk4wYfpsZCc9QfLGe2tiVZA5JGY6QZDZD';
/* validate verify token needed for setting up web hook */
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === $access_token) {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}
}
/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input['entry'][0]['messaging'][0]['sender']['id'])) {
$sender = $input['entry'][0]['messaging'][0]['sender']['id']; //sender facebook id
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='. $access_token;
/*initialize curl*/
$ch = curl_init($url);
/*prepare response*/
$resp = array(
'recipient' => array(
'id' => $sender
),
'message' => array(
'text' => 'Your message is '. $input['entry'][0]['messaging'][0]['message']['text']
)
);
$jsonData = json_encode($resp);
/* curl setting to send a json post data */
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch); // user will get the message
}
ดูคำสั่งตรงนี้ ผมเก็บสิ่งที่ต้องส่งไปให้ Facebook API ด้วยโครงสร้างแบบอะเรย์ก่อน จากนั้นจึงใช้คำสั่ง json_encode แปลงจากอะเรย์ไปเป็น JSON
/*prepare response*/
$resp = array(
'recipient' => array(
'id' => $sender
),
'message' => array(
'text' => 'Your message is '. $input['entry'][0]['messaging'][0]['message']['text']
)
);
$jsonData = json_encode($resp);