PHP code example of linecorp / line-bot-sdk

1. Go to this page and download the library: Download linecorp/line-bot-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

linecorp / line-bot-sdk example snippets


$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,
);

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

$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();
}

$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]);

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");
}

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'],
        ],
    ],
];