2022-07-02

【PHP】LINE 回覆影片訊息

參考資料 ----
Video 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" => "video",
                                    "originalContentUrl" => "https://完整網址/原始影片檔檔名.mp4",    // 大小不可超過 200M
                                    "previewImageUrl" => "https://完整網址/預覽圖檔檔名.png",   // 限 jpg 或 png, 大小不可超過 1M
                                    "trackingId" => "myid"  // 選擇性參數, 只可輸入 英數字 及 .=,+*()%$&;:@{}!?<>[] 這幾個符號
                                                            // 官網是說當回覆有帶這個參數時, 客戶端看完影片時會通知 webhook
                                ]
                            ]
            ];
            
    // 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);
}
?>
 


user 看完影片時, server 這邊收到的通知內容如下
 
"destination":"bla1bla1bla1bla1bla1bla1bla1bla1bla1bla1",
"events":[{ "type":"videoPlayComplete",
            "videoPlayComplete":{"trackingId":"myid"},
            "webhookEventId":"bla2bla2bla2bla2bla2bla2bla2bla2bla2bla2",
            "deliveryContext":{"isRedelivery":false},
            "timestamp":1656748409328,
            "source":{"type":"user",
                     "userId":"bla3bla3bla3bla3bla3bla3bla3bla3bla3bla3"
                    },
            "replyToken":"bla4bla4bla4bla4bla4bla4bla4bla4bla4bla4",
            "mode":"active"
        }]
        
至於能做什麼用途, 就自行發揮想像力吧
 

沒有留言:

張貼留言