iT邦幫忙

2021 iThome 鐵人賽

DAY 13
1
Software Development

Laravel 新手初見 API系列 第 13

Day13-Webhook 實作(二)LINEBot 之 Echo bot

大家好~
昨天我們已經將 LINEBot 安裝完成啦~
今天來做個 Echo bot 簡單認識一下 LINEBot 的實作過程吧~

Webhook 測試

首先來為我們的 Webhook 準備好 Route 與 Controller 吧!

php artisan make:controller LinebotController
routes/api.php
Route::post('/linebot-reply',[LinebotController::class,'reply']);
app/Http/Controllers/LinebotController.php
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use LINE\LINEBot\HTTPClient\CurlHTTPClient;
use LINE\LINEBot;
public function reply(Request $request)
{
    Log::info($request->all());
    return response('HTTP_OK',Response::HTTP_OK);
}

先來測試 Webhook 連線是否正常吧~
順便看看 Request body 長怎樣。
至於 URL 就先用 ngrok 協助我們測試吧!

在 Messaging API settings 的頁面下可以設定 Webhook URL,
按下 Verify 可以測試我們的 API 是否可以成功接收 Request。

然後記得要啟用 Webhook 喔。
下圖就是用 Line 傳送文字訊息給我們的 LINEBot 後所獲得的 Request body 格式。

Echo bot 實作

app/Http/Controllers/LinebotController.php
public function reply(Request $request)
{
    $httpClient = new CurlHTTPClient(env('LINE_BOT_CHANNEL_ACCESS_TOKEN'));
    $bot = new LINEBot($httpClient, ['channelSecret' => env('LINE_BOT_CHANNEL_SECRET')]);
    
    try {
        $bot->parseEventRequest($request->getContent(), $request->header('X-Line-Signature'));
    }catch (LINEBot\Exception\InvalidSignatureException $exception){
        return response('An exception class that is raised when signature is invalid.',Response::HTTP_FORBIDDEN);
    }catch (LINEBot\Exception\InvalidEventRequestException $exception){
        return response('An exception class that is raised when received invalid event request.',Response::HTTP_FORBIDDEN);
    }
    
    $text = $request['events'][0]['message']['text'];
    $replyToken = $request['events'][0]['replyToken'];
    $response = $bot->replyText($replyToken, $text);
    
    if ($response->isSucceeded()){
        return response('HTTP_OK', Response::HTTP_OK);
    }else{
        Log::debug($response->getHTTPStatus());
        Log::debug($response->getRawBody());
        return response('HTTP_UNPROCESSABLE_ENTITY', Response::HTTP_UNPROCESSABLE_ENTITY);
    }

要記得將 Channel access token 與 Channel secret 寫入 .env 喔~
成果如下圖。

LINEBot::parseEventRequest($body, $signature, $eventOnly = true)

這個 Function 可以幫我們驗證簽名與判斷 Event type。

LINEBot::replyText($replyToken, $text, $extraTexts = null)

LINEBot 有著多種的 MessageBuilder,
不過以我們目前的 Echo bot 來說,
使用 replyText() 就足夠應付了。

今天就先這樣啦~
大家明天見!
若文章有任何問題,
還請大家不吝賜教!

參考資料:


上一篇
Day12-Webhook 實作(一)LINEBot Channel 申請、SDK 安裝
下一篇
Day14-Webhook 實作(三)LINEBot 之 MessageBuilder(I)
系列文
Laravel 新手初見 API30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言