2022-07-05

【PHP】LINE 回覆地理位置訊息

參考資料 ----
Location message

 
<?php
// 因為網站是寄放在虛擬主機商那, 所以要指定時區
date_default_timezone_set('Asia/Taipei');
$channelAccessToken = '{從 LINE 官方帳號後台取得的 token}';
 
// 客戶端傳來的訊息
$bodyMsg = file_get_contents('php://input');

// 寫 log, 檔案在目前目錄下的 log 目錄內
// 檔名為 log_西元年月日.log, 一天一個檔
$sLogfile = './log/log_'.date('Ymd').'.log';
$fp = fopen($sLogfile, "a+");
fwrite($fp , print_r(date('Y-m-d H:i:s').', Recive: '.$bodyMsg."\n", true));
fclose($fp);

$obj = json_decode($bodyMsg, true);

foreach ($obj['events'] as &$event) 
{
   $userId = $event['source']['userId'];
   
    // 取得 使用者傳來的訊息
    $msgUser = $event['message']['text'];

    // 回傳 地址位置訊息
    $payload = [ 'replyToken' => $event['replyToken'],
                'messages' => [ 
                                [
                                    "type" => "location",
                                    "title" => "高捷紅線美麗島站",
                                    "address" => "高雄市新興區中正四路3號",
                                    "latitude" => 22.631392,
                                    "longitude" => 120.301803
                                ]
                            ]
            ];
            
    // Send reply API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/bot/message/reply');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [  'Content-Type: application/json',
                                            'Authorization: Bearer ' . $channelAccessToken
                                        ]);
    $result = curl_exec($ch);
    curl_close($ch);
}
?>
 

 
相關筆記 ----

沒有留言:

張貼留言