Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Line Bot Sdk Laravel Package

linecorp/line-bot-sdk

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require linecorp/line-bot-sdk
  1. Configure credentials in .env:
    LINE_BOT_CHANNEL_ACCESS_TOKEN=your_channel_access_token
    LINE_BOT_CHANNEL_SECRET=your_channel_secret
    
  2. Publish Laravel config (optional, for customization):
    php artisan vendor:publish --provider="LINE\Laravel\LINEBotServiceProvider" --tag=config
    
  3. First use case: Reply to a user message via webhook:
    use LINE\LINEBot;
    use LINE\Messages\TextMessage;
    
    // In your webhook route/controller
    $replyToken = $event->getReplyToken();
    $message = new TextMessage(['text' => 'Hello from Laravel!']);
    LINEBot::replyMessage($replyToken, [$message]);
    

Implementation Patterns

Webhook Handling

  1. Route webhook endpoint in routes/web.php:
    Route::post('/line-webhook', [LineWebhookController::class, 'handle']);
    
  2. Parse events in controller:
    use LINE\LINEBot;
    use LINE\LINEBot\Event\Events\MessageEvent;
    
    public function handle(Request $request) {
        $events = LINEBot::parseEvent($request->getContent());
        foreach ($events as $event) {
            if ($event instanceof MessageEvent) {
                $this->handleMessage($event);
            }
        }
    }
    
  3. Event-driven responses:
    protected function handleMessage(MessageEvent $event) {
        $replyToken = $event->getReplyToken();
        $text = $event->getMessage()->getText();
    
        if (strpos($text, 'help') !== false) {
            LINEBot::replyMessage($replyToken, [
                new TextMessage(['text' => 'Available commands: help, status'])
            ]);
        }
    }
    

Proactive Messaging

  1. Push messages to users:
    LINEBot::pushMessage('user_id', [
        new TextMessage(['text' => 'Proactive message']),
        new ImageMessage(['originalContentUrl' => 'https://example.com/image.jpg'])
    ]);
    
  2. Rich messages (e.g., carousel):
    $columns = [
        new CarouselColumn([
            new ImageMessage(['originalContentUrl' => 'url1', 'previewImageUrl' => 'preview1']),
            new TextMessage(['text' => 'Item 1'])
        ]),
        // Add more columns...
    ];
    LINEBot::pushMessage('user_id', [new CarouselTemplateMessage(['columns' => $columns])]);
    

Middleware Integration

  1. Validate webhook signatures:
    use LINE\LINEBot\Middleware\ValidateSignature;
    
    $middleware = app()->make(ValidateSignature::class);
    $isValid = $middleware->handle($request, function () {
        return response('Invalid signature', 401);
    });
    

Batch Processing

  1. Process multiple events:
    $events = LINEBot::parseEvent($request->getContent());
    $batch = LINEBot::batch();
    foreach ($events as $event) {
        $batch->reply($event->getReplyToken(), [new TextMessage(['text' => 'Processed'])]);
    }
    $batch->send();
    

Gotchas and Tips

Common Pitfalls

  1. Webhook Signature Mismatch:

    • Ensure LINE_BOT_CHANNEL_SECRET matches the one in LINE Developer Console.
    • Debug with:
      $signature = $request->header('X-Line-Signature');
      $isValid = LINEBot::validateSignature($request->getContent(), $signature);
      
  2. Rate Limits:

    • LINE API enforces rate limits.
    • Use sleep() or queues for high-frequency operations:
      sleep(1); // 1-second delay between requests
      
  3. Reply Token Expiry:

    • Reply tokens expire after 24 hours. Cache them if needed for delayed responses.
  4. Message Size Limits:

    • Text messages: 2,000 characters (including emojis).
    • Media messages: 1MB (original content), 512KB (preview).

Debugging Tips

  1. Log HTTP Headers:

    • Use withHttpInfo() for API calls to inspect headers:
      [$response, $status, $headers] = LINEBot::replyMessageWithHttpInfo($replyToken, [$message]);
      logger()->info('Request ID:', $headers['x-line-request-id'][0]);
      
  2. Handle API Exceptions:

    • Catch LINE\Clients\MessagingApi\ApiException for errors:
      try {
          LINEBot::getProfile('invalid_user_id');
      } catch (ApiException $e) {
          logger()->error('LINE API Error:', [
              'code' => $e->getCode(),
              'body' => $e->getResponseBody(),
              'request_id' => $e->getResponseHeaders()['x-line-request-id'][0] ?? 'N/A'
          ]);
      }
      
  3. Stateless Tokens:

    • For serverless environments, use stateless tokens:
      $token = LINEBot::issueStatelessChannelTokenByJWTAssertion($jwtAssertion);
      

Extension Points

  1. Custom Message Types:

    • Extend LINE\Messages\MessageInterface for custom messages:
      class CustomMessage extends AbstractMessage {
          public function __construct(array $data) {
              $this->data = $data;
          }
          public function getType(): string { return 'custom'; }
      }
      
  2. Middleware Stack:

    • Add custom middleware to the Laravel service provider:
      public function boot() {
          LINEBot::getMiddleware()->prepend(MyCustomMiddleware::class);
      }
      
  3. Event Subscribers:

    • Listen to specific events in a subscriber:
      use LINE\LINEBot\Event\EventInterface;
      
      class LineEventSubscriber implements ShouldBroadcast {
          public function handle(EventInterface $event) {
              if ($event instanceof MessageEvent) {
                  // Broadcast or process the event
              }
          }
      }
      

Performance Optimization

  1. Batch API Calls:

    • Use LINEBot::batch() to reduce HTTP overhead:
      $batch = LINEBot::batch();
      $batch->pushMessage('user1', [$msg1]);
      $batch->pushMessage('user2', [$msg2]);
      $batch->send();
      
  2. Lazy-Loading:

    • Defer message construction until needed:
      $messageFactory = function ($text) {
          return new TextMessage(['text' => $text]);
      };
      LINEBot::replyMessage($replyToken, [$messageFactory('Lazy-loaded')]);
      
  3. Caching:

    • Cache user profiles or frequent responses:
      $profile = Cache::remember("line_profile_{$userId}", now()->addHours(1), function () use ($userId) {
          return LINEBot::getProfile($userId);
      });
      

Laravel-Specific Tips

  1. Service Provider Binding:

    • Override default Guzzle client:
      $this->app->bind(\GuzzleHttp\ClientInterface::class, function () {
          return new \GuzzleHttp\Client(['timeout' => 10]);
      });
      
  2. Queue Jobs:

    • Offload heavy operations to queues:
      LineMessageJob::dispatch($replyToken, $messages)->onQueue('line');
      
      class LineMessageJob implements ShouldQueue {
          public function handle() {
              LINEBot::replyMessage($this->replyToken, $this->messages);
          }
      }
      
  3. Testing:

    • Mock the LINEBot facade in tests:
      LINEBot::shouldReceive('replyMessage')
          ->once()
          ->with($replyToken, [$message]);
      

---
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui