2023-12-07

【LINE Messaging API】主動傳送訊息給指定使用者

 
<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, 管道有很多, 此處不贅述
$sUserId = ...;

$payload = [ 'to' => $sUserId,
             '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_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);
}
?>
 

沒有留言:

張貼留言