| name | line-messaging-api |
| description | LINE Messaging API + linecorp/line-bot-sdk PHP SDK (v12.x) 完整技術參考。
涵蓋 MessagingApiApi 所有方法、訊息型別、Flex Message、Template Message、
Rich Menu、Webhook 事件解析、簽章驗證,以及在此 Power Funnel WordPress 專案中的實際用法模式。
當需要:發送 LINE 訊息(push/reply/multicast/broadcast/narrowcast)、處理 LINE Webhook 事件、
建立 Flex Message 或 Template Message、操作 Rich Menu、取得用戶資料時,必須使用此 SKILL。
|
LINE Messaging API — PHP SDK v12.x 技術參考
SDK 版本與 Namespace
linecorp/line-bot-sdk: ^12.3 | PHP: 8.1+
| 用途 | Namespace |
|---|
| Messaging API 主類別 | LINE\Clients\MessagingApi\Api\MessagingApiApi |
| Messaging API 模型 | LINE\Clients\MessagingApi\Model\* |
| Messaging API 例外 | LINE\Clients\MessagingApi\ApiException |
| Messaging API 設定 | LINE\Clients\MessagingApi\Configuration |
| Webhook 事件 | LINE\Webhook\Model\* |
| Webhook 解析 | LINE\Parser\EventRequestParser |
| Webhook 驗證 | LINE\Parser\SignatureValidator |
| HTTP Header 常數 | LINE\Constants\HTTPHeader |
初始化
use GuzzleHttp\Client;
use LINE\Clients\MessagingApi\Api\MessagingApiApi;
use LINE\Clients\MessagingApi\Configuration;
$config = new Configuration();
$config->setAccessToken($channelAccessToken);
$api = new MessagingApiApi(client: new Client(), config: $config);
Power Funnel 專案用法
$api = MessagingApiFactory::create();
$service = MessageService::instance();
$service->send_text_message($userId, '文字');
$service->send_template_message($userId, $templateMessage);
$service->reply($replyToken, $messages);
$service->multicast($userIds, $messages);
$service->broadcast($messages);
$service->get_profile($userId);
訊息發送 API
pushMessage
$api->pushMessage(new PushMessageRequest([
'to' => $userId,
'messages' => [$textMessage],
]), $retryKey);
replyMessage
$api->replyMessage(new ReplyMessageRequest([
'replyToken' => $event->getReplyToken(),
'messages' => [$message],
]));
multicast(max 500 人)
$api->multicast(new MulticastRequest([
'to' => ['U111...', 'U222...'],
'messages' => [$message],
]), $retryKey);
broadcast
$api->broadcast(new BroadcastRequest(['messages' => [$message]]), $retryKey);
narrowcast
$api->narrowcast(new NarrowcastRequest([
'messages' => [$message],
'recipient' => $recipient, // 選填
'filter' => $filter, // 選填
'limit' => $limit, // 選填
]));
$api->getNarrowcastProgress($requestId);
其他發送
$api->markMessagesAsRead($request);
$api->markMessagesAsReadByToken($request);
$api->showLoadingAnimation($request);
訊息型別
所有訊息繼承 LINE\Clients\MessagingApi\Model\Message。
Message 基礎屬性: type (string), quickReply (QuickReply), sender (Sender)
TextMessage
new TextMessage(['type' => 'text', 'text' => '文字',
'emojis' => [$emoji], 'quoteToken' => $token]);
ImageMessage
new ImageMessage(['type' => 'image',
'originalContentUrl' => 'https://...',
'previewImageUrl' => 'https://...',
]);
VideoMessage
new VideoMessage(['type' => 'video',
'originalContentUrl' => 'https://...',
'previewImageUrl' => 'https://...',
'trackingId' => 'id123',
]);
AudioMessage
new AudioMessage(['type' => 'audio',
'originalContentUrl' => 'https://...',
'duration' => 60000,
]);
LocationMessage
new LocationMessage(['type' => 'location',
'title' => '名稱', 'address' => '地址',
'latitude' => 25.0478, 'longitude' => 121.5319,
]);
StickerMessage
new StickerMessage(['type' => 'sticker',
'packageId' => '1', 'stickerId' => '1',
]);
TemplateMessage
new TemplateMessage(['type' => 'template',
'altText' => '替代文字',
'template' => $template,
]);
Template 型別(選填屬性見 references/flex-message.md):
| class | type | 必填 | 最多 |
|---|
ButtonsTemplate | buttons | text, actions | 4 actions |
ConfirmTemplate | confirm | text, actions | 2 actions |
CarouselTemplate | carousel | columns (CarouselColumn[]) | 10 cols, 3 actions/col |
ImageCarouselTemplate | image_carousel | columns | 10 cols |
FlexMessage
new FlexMessage(['type' => 'flex',
'altText' => '替代文字',
'contents' => $container,
]);
詳細 Flex Message 元件: references/flex-message.md
Actions
| class | type | 關鍵屬性 |
|---|
URIAction | uri | uri (必填), label, altUri |
PostbackAction | postback | data (必填), label, displayText, inputOption, fillInText |
MessageAction | message | text (必填, max 300), label |
DatetimePickerAction | datetimepicker | data (必填), mode (必填: date/time/datetime), initial/max/min |
ClipboardAction | clipboard | clipboardText (必填), label |
RichMenuSwitchAction | richmenuswitch | richMenuAliasId (必填), data |
CameraAction | camera | label |
CameraRollAction | cameraRoll | label |
LocationAction | location | label |
Webhook 處理
簽章驗證與事件解析
use LINE\Constants\HTTPHeader;
use LINE\Parser\EventRequestParser;
$signature = $request->get_header(HTTPHeader::LINE_SIGNATURE);
$body = $request->get_body();
$parsed = EventRequestParser::parseEventRequest($body, $channelSecret, $signature);
foreach ($parsed->getEvents() as $event) {
$type = $event->getType();
$source = $event->getSource();
$userId = $source->getUserId();
}
Event 型別對照
| type | Class | 關鍵方法 |
|---|
message | MessageEvent | getReplyToken(), getMessage() |
follow | FollowEvent | getReplyToken(), getFollow() |
unfollow | UnfollowEvent | (無 replyToken) |
postback | PostbackEvent | getReplyToken(), getPostback() |
join | JoinEvent | getReplyToken() |
leave | LeaveEvent | (無 replyToken) |
memberJoined | MemberJoinedEvent | getJoined() |
memberLeft | MemberLeftEvent | getLeft() |
beacon | BeaconEvent | getBeacon() |
accountLink | AccountLinkEvent | getLink() |
videoPlayComplete | VideoPlayCompleteEvent | getVideoPlayComplete() |
Event 基礎屬性
$event->getType()
$event->getSource()
$event->getTimestamp()
$event->getMode()
$event->getWebhookEventId()
Source 判斷
$source->getType();
if ($source instanceof \LINE\Webhook\Model\UserSource) {
$userId = $source->getUserId();
}
if ($source instanceof \LINE\Webhook\Model\GroupSource) {
$groupId = $source->getGroupId();
$userId = $source->getUserId();
}
MessageEvent 訊息類型
$message = $event->getMessage();
if ($message instanceof \LINE\Webhook\Model\TextMessageContent) {
$text = $message->getText();
$quoteToken = $message->getQuoteToken();
}
if ($message instanceof \LINE\Webhook\Model\ImageMessageContent) {
$provider = $message->getContentProvider();
}
if ($message instanceof \LINE\Webhook\Model\LocationMessageContent) {
$lat = $message->getLatitude(); $lng = $message->getLongitude();
}
if ($message instanceof \LINE\Webhook\Model\StickerMessageContent) {
$packageId = $message->getPackageId(); $stickerId = $message->getStickerId();
}
PostbackEvent
$postback = $event->getPostback();
$data = $postback->getData();
用戶資料 API
$profile = $api->getProfile($userId);
$profile->getDisplayName();
$profile->getUserId();
$profile->getPictureUrl();
$profile->getStatusMessage();
$botInfo = $api->getBotInfo();
$botInfo->getChatMode();
$botInfo->getMarkAsReadMode();
$api->getFollowers($start, $limit);
Rich Menu API
詳細操作: references/rich-menu.md
$result = $api->createRichMenu(new RichMenuRequest([
'size' => new RichMenuSize(['width' => 2500, 'height' => 1686]),
'selected' => true,
'name' => '選單名稱',
'chatBarText' => '選單',
'areas' => [
new RichMenuArea([
'bounds' => new RichMenuBounds(['x' => 0, 'y' => 0, 'width' => 2500, 'height' => 1686]),
'action' => $action,
]),
],
]));
$richMenuId = $result->getRichMenuId();
$blobApi = new \LINE\Clients\MessagingApi\Api\MessagingApiBlobApi(client: $client, config: $config);
$blobApi->setRichMenuImage($richMenuId, $imageData);
$api->setDefaultRichMenu($richMenuId);
$api->linkRichMenuIdToUser($userId, $richMenuId);
$api->unlinkRichMenuIdFromUser($userId);
$api->cancelDefaultRichMenu();
$api->deleteRichMenu($richMenuId);
$api->getRichMenuList();
$api->getRichMenuIdOfUser($userId);
$api->createRichMenuAlias($createRichMenuAliasRequest);
$api->getRichMenuAliasList();
$api->deleteRichMenuAlias($richMenuAliasId);
$api->setWebhookEndpoint(new \LINE\Clients\MessagingApi\Model\SetWebhookEndpointRequest([
'webhookEndpoint' => 'https://example.com/wp-json/power-funnel/v1/line-callback',
]));
$api->testWebhookEndpoint();
配額 API
$quota = $api->getMessageQuota();
$quota->getType();
$quota->getValue();
$consumption = $api->getMessageQuotaConsumption();
$consumption->getTotalUsage();
$api->getNumberOfSentPushMessages('20240101');
$api->getNumberOfSentReplyMessages('20240101');
$api->getNumberOfSentMulticastMessages('20240101');
$api->getNumberOfSentBroadcastMessages('20240101');
QuickReply / Sender
$msg->setQuickReply(new QuickReply([
'items' => [
new QuickReplyItem([
'type' => 'action',
'action' => new MessageAction(['type' => 'message', 'label' => '是', 'text' => 'yes']),
]),
],
]));
$msg->setSender(new Sender(['name' => '自訂名稱', 'iconUrl' => 'https://...']));
例外處理
use LINE\Clients\MessagingApi\ApiException;
try {
$api->pushMessage($request);
} catch (ApiException $e) {
$e->getCode();
$e->getMessage();
$e->getResponseBody();
}
常數
HTTPHeader::LINE_SIGNATURE
HTTPHeader::LINE_RETRY_KEY
MessageType::TEXT / TEMPLATE / IMAGEMAP / STICKER / LOCATION / IMAGE / AUDIO / VIDEO / FLEX
TemplateType::CONFIRM / BUTTONS / CAROUSEL / IMAGE_CAROUSEL
ActionType::MESSAGE / POSTBACK / URI / DATETIME_PICKER / CAMERA / CAMERA_ROLL / LOCATION / RICH_MENU_SWITCH
PostbackInputOption::CLOSE_RICH_MENU / OPEN_RICH_MENU / OPEN_KEYBOARD / OPEN_VOICE
Power Funnel 整合模式
Carousel 報名訊息範例
use LINE\Clients\MessagingApi\Model\{TemplateMessage, CarouselTemplate, CarouselColumn, PostbackAction};
$templateMsg = new TemplateMessage([
'type' => 'template',
'altText' => '活動報名通知',
'template'=> new CarouselTemplate([
'columns' => [
new CarouselColumn([
'thumbnailImageUrl' => $imageUrl,
'title' => $activityTitle,
'text' => $description,
'actions' => [
new PostbackAction([
'type' => 'postback',
'label' => '立即報名',
'data' => json_encode([
'action' => 'register',
'activity_id' => $activityId,
'promo_link_id' => $promoLinkId,
]),
'displayText' => '我要報名!',
]),
],
]),
],
]),
]);
MessageService::instance()->send_template_message($userId, $templateMsg);
EventWebhookHelper 用法(Power Funnel 封裝)
$helper = new EventWebhookHelper($event);
$payload = $helper->get_payload();
$action = $helper->get_action();
$userId = $helper->get_identity_id();
$actId = $helper->get_activity_id();
$promoId = $helper->get_promo_link_id();
Webhook 端點(Power Funnel)
POST /wp-json/power-funnel/v1/line-callback
觸發: power_funnel/line/webhook/{type}/{action}
power_funnel/line/webhook/{type}
延伸參考
references/flex-message.md — Flex Message 所有元件完整屬性(FlexBox, FlexText, FlexImage, FlexButton...)
references/rich-menu.md — Rich Menu 批次操作、別名、常見版型