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

Laravel Notification Channel Instagram Laravel Package

ka4ivan/laravel-notification-channel-instagram

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require ka4ivan/laravel-notification-channel-instagram
    

    Publish the config file:

    php artisan vendor:publish --provider="Ka4ivan\InstagramNotification\InstagramNotificationServiceProvider"
    
  2. Configure Instagram Bot

    • Register an Instagram Business account and set up a Meta Developer Account.
    • Create an app and get your Page Access Token and Instagram Business Account ID.
    • Update .env:
      INSTAGRAM_PAGE_ACCESS_TOKEN=your_page_access_token
      INSTAGRAM_BUSINESS_ACCOUNT_ID=your_business_account_id
      
  3. Get Profile ID Use the Graph API Explorer to fetch your Instagram Business Profile ID:

    GET /{instagram-business-account-id}?fields=id
    
  4. Update Config Edit config/instagram-notification.php:

    'profile_id' => 'your_instagram_profile_id',
    'page_access_token' => env('INSTAGRAM_PAGE_ACCESS_TOKEN'),
    'business_account_id' => env('INSTAGRAM_BUSINESS_ACCOUNT_ID'),
    
  5. First Notification Send a simple text notification to a user:

    use App\Models\User;
    use Ka4ivan\InstagramNotification\Channels\InstagramChannel;
    
    $user = User::find(1);
    $user->notify(new \App\Notifications\InstagramMessage(
        'Hello from Laravel!',
        'This is your first Instagram notification.'
    ));
    

Implementation Patterns

Core Workflows

  1. Define a Notification Class Extend Illuminate\Notifications\Notification and use the InstagramChannel:

    use Ka4ivan\InstagramNotification\Channels\InstagramChannel;
    
    class InstagramMessage extends Notification
    {
        protected $message;
        protected $buttons = [];
    
        public function __construct($message, $buttons = [])
        {
            $this->message = $message;
            $this->buttons = $buttons;
        }
    
        public function via($notifiable)
        {
            return [InstagramChannel::class];
        }
    
        public function toInstagram($notifiable)
        {
            return [
                'message' => $this->message,
                'buttons' => $this->buttons,
            ];
        }
    }
    
  2. Send Interactive Messages Use buttons for quick replies or actions:

    $buttons = [
        [
            'type' => 'reply',
            'title' => 'Yes',
            'payload' => 'USER_DEFINED_PAYLOAD_YES',
        ],
        [
            'type' => 'url',
            'title' => 'Visit Website',
            'url' => 'https://example.com',
        ],
    ];
    
    $user->notify(new InstagramMessage('Choose an option:', $buttons));
    
  3. Batch Notifications Use Laravel's Notification facade to send to multiple users:

    use Illuminate\Support\Facades\Notification;
    
    $users = User::where('is_active', true)->get();
    Notification::send($users, new InstagramMessage('Weekly Update!'));
    
  4. Integrate with Events Trigger notifications from events (e.g., OrderShipped):

    use Illuminate\Support\Facades\Event;
    
    Event::listen('order.shipped', function ($order) {
        $order->user->notify(new InstagramMessage(
            "Your order #{$order->id} is shipped!",
            [['type' => 'url', 'title' => 'Track', 'url' => $order->tracking_url]]
        ));
    });
    
  5. Conditional Notifications Use Laravel's when to send notifications based on logic:

    $user->notify(new InstagramMessage('Your account is verified.'))
         ->when($user->hasPremium, function ($notifiable) {
             return new InstagramMessage('Enjoy premium features!');
         });
    

Gotchas and Tips

Common Pitfalls

  1. Token Expiry

    • Instagram Page Access Tokens expire (typically 60 days). Use the Graph API to generate a long-lived token or implement token refresh logic.
    • Tip: Store the expiry time in your database and automate token refresh before expiry.
  2. Profile ID Mismatch

    • Ensure the profile_id in config/instagram-notification.php matches the Instagram Business Profile ID (not the user ID).
    • Debug: Use the Graph API Explorer to verify:
      GET /{instagram-business-account-id}?fields=id,name
      
  3. Rate Limits

    • Instagram API has strict rate limits (e.g., 200 calls/hour for sandbox accounts, 5000 for live). Avoid sending notifications in tight loops.
    • Tip: Implement exponential backoff for retries:
      try {
          $user->notify(new InstagramMessage('Hello!'));
      } catch (\Ka4ivan\InstagramNotification\Exceptions\InstagramException $e) {
          if ($e->getCode() === 429) { // Too Many Requests
              sleep(10); // Wait and retry
              retry();
          }
      }
      
  4. Button Payload Length

    • Instagram has a 2048-character limit for button payloads. Truncate long payloads:
      $payload = Str::limit($payload, 2040);
      
  5. Sandbox vs. Live Mode

    • Test in Instagram Sandbox Mode first. Live mode requires approval and a Business Verification.
    • Tip: Use config('instagram-notification.sandbox_mode', true) for testing.

Debugging

  1. Enable Logging Add to config/instagram-notification.php:

    'debug' => env('APP_DEBUG', false),
    

    Check storage/logs/laravel.log for API responses/errors.

  2. API Response Inspection Override the channel to log raw responses:

    use Ka4ivan\InstagramNotification\Channels\InstagramChannel;
    
    class CustomInstagramChannel extends InstagramChannel
    {
        protected function sendThroughInstagram($notifiable, $message)
        {
            $response = parent::sendThroughInstagram($notifiable, $message);
            \Log::info('Instagram API Response:', ['response' => $response]);
            return $response;
        }
    }
    

    Update the notification's via() to use CustomInstagramChannel::class.

  3. Webhook Verification If using webhooks for interactive messages, verify the hub.challenge and hub.mode in your endpoint:

    public function handle()
    {
        $hubChallenge = request()->input('hub.challenge');
        $hubMode = request()->input('hub.mode');
    
        if ($hubMode === 'subscribe' && $hubChallenge) {
            return response($hubChallenge);
        }
        // Handle message payload
    }
    

Extension Points

  1. Custom Message Types Extend the channel to support custom message templates (e.g., carousel, media):

    class CustomInstagramChannel extends InstagramChannel
    {
        public function sendMediaNotification($notifiable, $mediaUrl)
        {
            $response = $this->callInstagramApi('messages', [
                'recipient' => ['id' => $notifiable->instagram_id],
                'message' => [
                    'attachment' => [
                        'type' => 'image',
                        'payload' => [
                            'url' => $mediaUrl,
                        ],
                    ],
                ],
            ]);
            return $response;
        }
    }
    
  2. User Data Mapping Store Instagram-specific data (e.g., instagram_id) in a notifiable trait:

    trait HasInstagram
    {
        public function routeNotificationForInstagram()
        {
            return $this->instagram_id ?: $this->fallbackInstagramId();
        }
    }
    
  3. Queue Delay for High Volumes Use Laravel Queues to stagger notifications:

    $user->notify(new InstagramMessage('Hello!'))
         ->delay(now()->addMinutes(5)); // Delay by 5 minutes
    
  4. Fallback Channels Combine with other channels (e.g., SMS) for reliability:

    public function via($notifiable)
    {
        return [InstagramChannel::class, \Illuminate\Notifications\Channels\SmsChannel::class];
    }
    
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.
milito/query-filter
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