類似主動傳訊息給 user,不過在傳訊類型定義為 multicast。要傳訊的目標對象是多位 user,所以 UserId 要存在陣列中。
- <php?
- date_default_timezone_set('Asia/Taipei');
- $sRootDir = $_SERVER['DOCUMENT_ROOT'];
- $channelAccessToken = '您的 channel Access Token';
- $bodyMsg = file_get_contents('php://input');
- // LINE 不會幫我們記錄, 所以要自己寫 log
- // 這段不是必要, 只是方便自己除錯
- $sLogfile = 'log_'.date('Ymd').'.log'; // 指定 log 檔名, 一天一個檔, 檔名格式為: log_yyyymmdd.log
- $fp = fopen($sLogfile, "a+");
- fwrite($fp , print_r(date('Y-m-d H:i:s').', Recive: '.$bodyMsg."\n", true));
- fclose($fp);
- ...
- ...
- // 取得 user id, 管道有很多, 此處不贅述
- $arrUserId = ['...','...', ...]; ← 要推播的目標 UserId 存入陣列
- $payload = [ 'to' => $arrUserId,
- 'messages' => [
- ['type' => 'text',
- 'text' => '恭喜! 您中了特獎!',
- ]
- ]
- ];
- SendMsg($payload);
- // 傳送訊息給指定使用者
- function SendMsg($payload) {
- $ch = curl_init();
- // curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/bot/message/push');
- curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/bot/message/multicast'); ← 注意這裡要改成 multicast
- 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 ' . $GLOBALS['channelAccessToken']
- ]);
- $result = curl_exec($ch);
- curl_close($ch);
- // 寫 log
- $sLogfile = 'log_'.date('Ymd').'.log';
- $fp = fopen($sLogfile, "a+");
- fwrite($fp , print_r(date('Y-m-d H:i:s').', send message result: '.$result."\n", true));
- fclose($fp);
- }
- ?>
相關筆記 ----
沒有留言:
張貼留言