LINE Bot SDK for PHP

repository·master·Indexed 20 days ago

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

A PHP SDK for the LINE Messaging API that enables developers to build LINE bots. It provides high-level abstractions for sending messages, handling webhooks via EventRequestParser, and interacting with user profiles. The SDK supports PHP 8.2+, integrates with Laravel via facades and service providers, and includes sample implementations like Echo Bot and KitchenSink using the Slim framework.

Tokens
10.9K
Snippets
42
Records
52
Agent score
72%

What's inside line-bot-sdk-php

  1. Overview of KitchenSink application structure

    master

    The KitchenSink sample is organized into several key components:

    • Entry Point: public/index.php serves as the application entry point.
    • Core Logic: src/LINEBot/KitchenSink/Route.php contains the main application logic interacting with the LINE Messaging API.
    • Event Handlers: src/LINEBot/KitchenSink/EventHandler contains the specific logic for handling different types of LINE Messaging API events.
    • Multimedia Storage: Files are temporarily stored in ./public/static/tmpdir/.
  2. Handle LINE Webhooks

    master

    To process user actions (messages, images, etc.) sent by LINE's server, follow these steps:

    1. Receive the webhook request from LINE's server.
    2. Parse the request payload using EventRequestParser#parseEventRequest($body, $channelSecret, $signature).
    3. Iterate through the parsed events and implement your bot's logic.
  3. Create a Messaging API client

    master

    To interact with the LINE Messaging API, you need to instantiate a GuzzleHttp\ Client, a LINE\\Clients\\MessagingApi\\Configuration object with your channel access token, and a LINE\\Clients\\MessagingApi\\Api\\MessagingApiApi instance.

    use GuzzleHttp\Client;
    use LINE\Clients\MessagingApi\Configuration;
    use LINE\Clients\MessagingApi\Api\MessagingApiApi;
    
    $client = new Client();
    $config = new Configuration();
    $config->setAccessToken('<channel access token>');
    $messagingApi = new MessagingApiApi(
        client: $client,
        config: $config,
    );
  4. Set up the Echo Bot sample project

    master

    The Echo Bot is a sample implementation of the LINE Messaging API using the Slim framework. To run the sample locally, follow these steps:

    1. Install Composer: Ensure you have composer.phar available.
    2. Install Dependencies: Run composer install to pull in the required libraries (including the LINE Messaging API SDK and Slim).
    3. Configure Bot Credentials: Edit ./src/LINEBot/EchoBot/Setting.php to provide your specific LINE Bot channel information (such as Channel Access Token and Channel Secret).
    4. Start the Server: Use the PHP built-in web server to host the application.

    Note: The application entry point is public/index.php and the core logic resides in src/LINEBot/EchoBot/Route.php.

    # Install composer
    curl -sS https://getcomposer.org/installer | php
    
    # Install dependencies
    ./composer.phar install
    
    # Edit your bot information in the Setting file
    $EDITOR ./src/LINEBot/EchoBot/Setting.php
    
    # Start the local development server
    php -S 0.0.0.0:8080 -t public
  5. Access response headers and status codes using *WithHttpInfo methods

    master

    If you need to inspect the HTTP status code or response headers for a successful request, use the methods ending in WithHttpInfo (e.g., replyMessageWithHttpInfo). These methods return an array containing three elements: [$body, $statusCode, $headers]. You can then access specific headers like x-line-request-id from the $headers array.

    [$body, $statusCode, $headers] = $messagingApi->replyMessageWithHttpInfo($request);
    
    $requestId = $headers['x-line-request-id'][0];
  6. Customize LINE Bot configuration in Laravel

    master

    By default, the SDK uses environment variables for configuration. To customize settings such as the HTTP client configuration (e.g., adding custom headers), you must publish the configuration file to config/line-bot.php using the following command:

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

    The published config/line-bot.php file allows you to manage the following keys:

    • channel_access_token: The LINE Channel Access Token.
    • channel_id: The LINE Channel ID.
    • channel_secret: The LINE Channel Secret.
    • client.config.headers: An array of HTTP headers to include in requests.
  7. Configure the LINE SDK for Laravel

    master

    The SDK supports Laravel via facades.

    1. Add LINE_BOT_CHANNEL_ACCESS_TOKEN to your .env file.
    2. Use the \LINEMessagingApi facade for calls.

    To customize the configuration (e.g., adding custom headers), publish the config file:

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

    Then modify config/line-bot.php:

    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'],
            ],
        ],
    ];
  8. Install and run the KitchenSink sample application

    master

    The KitchenSink sample is a full-stack implementation of the LINE Messaging API using the Slim framework. To set it up locally, follow these steps:

    1. Install Composer if you haven't already.
    2. Install the project dependencies using Composer.
    3. Configure your bot credentials in src/LINEBot/KitchenSink/Setting.php.
    4. Run the application using the provided shell script.

    Note: The application uses a temporary directory for multimedia files which is cleared upon shutdown.

    $ curl -sS https://getcomposer.org/installer | php # Install composer.phar
    $ ./composer.phar install
    $ $EDITOR ./src/LINEBot/KitchenSink/Setting.php # <= edit your bot information
    $ ./run.sh 8080
  9. Handle LINE webhooks using EventRequestParser

    master

    To process user actions (messages, images, locations, etc.) sent by LINE's server, you must receive the webhook request and parse the body using the EventRequestParser.

    Follow these steps:

    1. Receive the webhook request from LINE.
    2. Use EventRequestParser::parseEventRequest() to validate the signature and parse the request body.
    3. Iterate through the parsed events using getEvents() to handle each specific event type.
    use LINE//Parser/EventRequestParser;
    
    $parsedEvents = EventRequestParser::parseEventRequest(
        $body,           // The raw request body
        $channelSecret,  // Your LINE Channel Secret
        $signature,      // The X-Line-Signature header value
    );
    
    foreach ($parsedEvents->getEvents() as $event) {
        // Handle event
    }
  10. Create a bot client instance

    master

    To interact with the Messaging API, you must instantiate a MessagingApiApi object. This requires a GuzzleHttp ClientInterface implementation (such as GuzzleHttp Client) and a Configuration object containing your channel access token.

    $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,
    );
  11. Handle API exceptions and retrieve error details

    master

    When an API call fails, it throws a \LINE\Clients\MessagingApi\ApiException. You can extract the HTTP status code, the error response body, and the x-line-request-id from the exception's response headers.

    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();
    
        // Use $lineRequestId, $httpStatusCode, and $errorMessage
    }