2022-07-02

【PHP】LINE 回覆貼圖訊息

參考資料 ----
List of available stickers

也可回覆貼圖, 只不過限於 LINE 官方的貼圖
 
<?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' => [ // 一次最多可回覆 5 張貼圖, 若超過 5 張, 程式就掛了, 不會有任何回應
                                [ 'type' => 'sticker',
                                  'packageId' => '446',
                                  'stickerId' => '1988'
                                ],
                                [ 'type' => 'sticker',
                                  'packageId' => '789',
                                  'stickerId' => '10855'
                                ],
                                [ 'type' => 'sticker',
                                  'packageId' => '8525',
                                  'stickerId' => '16581290'
                                ],
                                [ 'type' => 'sticker',
                                  'packageId' => '6136',
                                  'stickerId' => '10551376'
                                ],
                                [ 'type' => 'sticker',
                                  'packageId' => '6325',
                                  'stickerId' => '10979904'
                                ]
                            ]
            ];
            
    // 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);
}
 
?>






沒有留言:

張貼留言