linecorp/line-bot-sdk

PHP的LINE Bot API SDK

9.11.0 2024-09-05 02:54 UTC

README

Build Status

介绍

PHP的LINE消息API SDK使您能够轻松开发使用LINE消息API的机器人,您可以在几分钟内创建一个示例机器人。

文档

有关更多信息,请参阅官方API文档。

要求

  • PHP 8.1或更高版本

安装

使用Composer安装LINE消息API SDK。

$ composer require linecorp/line-bot-sdk

入门

创建机器人客户端实例

机器人客户端实例是消息API的处理程序。

$client = new \GuzzleHttp\Client();
$config = new \LINE\Clients\MessagingApi\Configuration();
$config->setAccessToken('<channel access token>');
$messagingApi = new \LINE\Clients\MessagingApi\Api\MessagingApiApi(
  client: $client,
  config: $config,
);

您必须使用具有GuzzleHttp\ClientInterface实现的Client。

调用API

您可以通过消息Api实例调用API。

一个非常简单的示例

$message = new TextMessage(['type' => 'text','text' => 'hello!']);
$request = new ReplyMessageRequest([
    'replyToken' => '<reply token>',
    'messages' => [$message],
]);
$response = $messagingApi->replyMessage($request);

此过程向与<reply token>关联的目标发送消息。

我们也支持setter样式。

$message = (new TextMessage())
  ->setType(\LINE\Constants\MessageType::TEXT)
  ->setText('hello!');
$request = (new ReplyMessageRequest)
  ->setReplyToken('<reply token>')
  ->setMessages([$message]);
try {
  $messagingApi->replyMessage($request);
  // Success
} catch (\LINE\Clients\MessagingApi\ApiException $e) {
  // Failed
  echo $e->getCode() . ' ' . $e->getResponseBody();
}

如何获取x-line-request-id头和错误信息

您可能需要存储从多个API获取的响应中的x-line-request-id头。在这种情况下,请使用~WithHttpInfo函数。您可以获取头和状态代码。同样,您还可以以相同的方式获取x-line-accepted-request-idcontent-type头。

$request = new ReplyMessageRequest([
    'replyToken' => $replyToken,
    'messages' => [$textMessage = (new TextMessage(['text' => 'reply with http info', 'type' => MessageType::TEXT]))],
]);
$response = $messagingApi->replyMessageWithHttpInfo($request);
$this->logger->info('body:' . $response[0]);
$this->logger->info('http status code:' . $response[1]);
$this->logger->info('headers(x-line-request-id):' . $response[2]['x-line-request-id'][0]);

当您使用MessagingApiApi时,您可以从\LINE\Clients\MessagingApi\ApiException中获取错误信息。每个客户端定义其自己的异常类。

try {
    $profile = $messagingApi->getProfile("invalid-userId");
} catch (\LINE\Clients\MessagingApi\ApiException $e) {
    $headers = $e->getResponseHeaders();
    $lineRequestId = isset($headers['x-line-request-id']) ? $headers['x-line-request-id'][0] : 'Not Available';
    $httpStatusCode = $e->getCode();
    $errorMessage = $e->getResponseBody();

    $this->logger->info("x-line-request-id: $lineRequestId");
    $this->logger->info("http status code: $httpStatusCode");
    $this->logger->info("error response: $errorMessage");
}

当您需要从错误响应中获取x-line-accepted-request-id头时,您可以获取它:$headers['x-line-accepted-request-id'][0]

组件

Webhook

LINE的服务器将用户操作(如消息、图像或位置)发送到您的机器人服务器。该请求包含事件(用户操作)。

以下显示如何处理webhook

  1. 从LINE的服务器接收webhook。
  2. 通过EventRequestParser#parseEventRequest($body, $channelSecret, $signature)解析请求负载。
  3. 遍历解析的事件,并根据需要做出反应。

以下示例显示如何处理webhooks

更多信息

有关更多信息,请参阅官方API文档和PHPDoc。如果您是第一次使用此库,我们建议您查看examples\LINE的PHPDoc。

提示

示例

此存储库包含两个使用LINE消息API的示例。

EchoBot

一个简单的示例实现。此应用程序会对用户发送的文本消息做出反应。

KitchenSink

一个全栈(稍复杂)的示例实现。此应用程序展示了LINE消息API的实际应用。

PHPDoc

https://line.github.io/line-bot-sdk-php/

此库提供PHPDoc来描述如何使用方法。您可以使用以下命令使用phpDocumenter生成文档。

使用wget下载https://github.com/phpDocumentor/phpDocumentor/releases/download/v3.3.1/phpDocumentor.phar $ php phpDocumentor.phar run -d src -t docs HTML文件将在docs/目录下生成。

官方API文档

官方API文档展示了消息API的详细信息和SDK的基本用法。

另请参阅

Laravel支持

从Laravel使用起来非常简单。安装后,将LINE_BOT_CHANNEL_ACCESS_TOKEN添加到.env

LINE_BOT_CHANNEL_ACCESS_TOKEN=<Channel Access Token>

然后你可以使用以下类似的面具。

$profile = \LINEMessagingApi::pushMessage(....);

默认情况下,外观使用\GuzzleHttp\Client。如果你想更改配置,请运行

$ php artisan vendor:publish --provider="LINE\Laravel\LINEBotServiceProvider" --tag=config

然后line-bot.php将被发布到config/目录。如果你想配置自定义头,请执行以下操作。

return [
    'channel_access_token' => env('LINE_BOT_CHANNEL_ACCESS_TOKEN'),
    'channel_id' => env('LINE_BOT_CHANNEL_ID'),
    'channel_secret' => env('LINE_BOT_CHANNEL_SECRET'),
    'client' => [
        'config' => [
          'headers' => ['X-Foo' => 'Bar'],
        ],
    ],
];

帮助和媒体

常见问题解答:https://developers.line.biz/en/faq/

新闻:https://developers.line.biz/en/news/

版本控制

本项目遵循语义版本控制。

请参阅http://semver.org/

贡献

在做出贡献之前,请查看CONTRIBUTING

有关黑客攻击说明,请参阅HACKING.md

许可证

Copyright 2016 LINE Corporation

Licensed under the Apache License, version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  https://apache.ac.cn/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.