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

Baidu Push Bundle Laravel Package

baidu-bundle/baidu-push-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require baidu-bundle/baidu-push-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        BaiduBundle\BaiduPushBundle::class => ['all' => true],
    ];
    
  2. Configure the Bundle Update config/packages/baidu_push.yaml (or create it):

    baidu_push:
        api_key: '%env(Baidu_PUSH_API_KEY)%'
        secret_key: '%env(Baidu_PUSH_SECRET_KEY)%'
        user_id: '%env(Baidu_PUSH_USER_ID)%'
    

    Ensure .env contains:

    Baidu_PUSH_API_KEY=your_api_key
    Baidu_PUSH_SECRET_KEY=your_secret_key
    Baidu_PUSH_USER_ID=your_user_id
    
  3. First Use Case: Sending a Push Notification Inject the BaiduPushClient service in a controller or command:

    use BaiduBundle\BaiduPushBundle\Service\BaiduPushClient;
    
    public function __construct(private BaiduPushClient $baiduPush)
    {
    }
    
    public function sendPush()
    {
        $result = $this->baiduPush->sendPush(
            userId: 'your_user_id',
            message: 'Hello from Laravel!',
            title: 'Notification Title',
            type: 'message' // or 'event'
        );
    
        return $result->isSuccess() ? 'Push sent!' : 'Failed: ' . $result->getError();
    }
    

Implementation Patterns

Common Workflows

  1. Sending Push Notifications

    • Single Push: Target a specific user or device.
      $this->baiduPush->sendPush(
          userId: 'user123',
          message: 'Your order is confirmed!',
          title: 'Order Update',
          type: 'message'
      );
      
    • Batch Push: Send to multiple users via userIdList.
      $this->baiduPush->sendPush(
          userIdList: ['user1', 'user2', 'user3'],
          message: 'Weekly newsletter',
          title: 'Newsletter',
          type: 'message'
      );
      
    • Custom Payload: Extend with additional fields (e.g., customContent).
      $this->baiduPush->sendPush(
          userId: 'user123',
          message: 'New feature available',
          title: 'App Update',
          type: 'message',
          customContent: json_encode(['feature' => 'dark_mode'])
      );
      
  2. Handling Responses

    • Check success/failure:
      $response = $this->baiduPush->sendPush(...);
      if ($response->isSuccess()) {
          $jobId = $response->getJobId(); // Track push job
      } else {
          $error = $response->getError(); // Debug issues
      }
      
    • Retry Logic: Implement exponential backoff for failed pushes (e.g., using Laravel's retry helper).
  3. Integration with Laravel Features

    • Events: Trigger pushes on user actions (e.g., user.registered).
      use Illuminate\Support\Facades\Event;
      
      Event::listen('user.registered', function ($user) {
          $this->baiduPush->sendPush(
              userId: $user->baidu_user_id,
              message: 'Welcome to our app!',
              title: 'Welcome'
          );
      });
      
    • Queues: Offload pushes to a queue (e.g., sendPush in a job).
      use Illuminate\Bus\Queueable;
      use Illuminate\Contracts\Queue\ShouldQueue;
      
      class SendPushJob implements ShouldQueue
      {
          use Queueable;
      
          public function handle(BaiduPushClient $baiduPush)
          {
              $baiduPush->sendPush(...);
          }
      }
      
    • Notifications: Extend Laravel's Notification class.
      use Illuminate\Notifications\Notification;
      
      class BaiduPushNotification extends Notification
      {
          public function via($notifiable)
          {
              return ['baidu_push'];
          }
      
          public function toBaiduPush($notifiable)
          {
              return (new BaiduPushMessage)
                  ->title('Hello!')
                  ->message('This is a test notification.');
          }
      }
      
      Register the channel in AppServiceProvider:
      Notification::extend('baidu_push', function ($app) {
          return new BaiduPushChannel($app['baidu_push.client']);
      });
      
  4. Logging and Monitoring

    • Log push attempts and responses:
      $response = $this->baiduPush->sendPush(...);
      \Log::info('Baidu Push Response', [
          'success' => $response->isSuccess(),
          'job_id' => $response->getJobId(),
          'error' => $response->getError(),
      ]);
      
    • Track metrics (e.g., push success rates) using Laravel's statsd or a custom table.

Gotchas and Tips

Pitfalls

  1. API Key/Secret Mismanagement

    • Issue: Hardcoding credentials in config or version control.
    • Fix: Use Laravel's .env and env() helper. Never commit .env to Git.
    • Tip: Rotate keys periodically and revoke old ones in the Baidu Push Console.
  2. Rate Limiting

    • Issue: Baidu Push has rate limits (e.g., 200 requests/minute).
    • Fix: Implement throttling in Laravel (e.g., throttle middleware or spatie/laravel-rate-limiter).
    • Tip: Batch pushes to minimize API calls.
  3. User ID Mismatch

    • Issue: userId in the SDK must match the userId registered in Baidu Push Console.
    • Fix: Ensure your Laravel user model maps to Baidu's userId (e.g., via a baidu_user_id column).
    • Debug: Use getError() to check for INVALID_USER_ID errors.
  4. Payload Size Limits

    • Issue: Messages > 4KB may fail silently.
    • Fix: Validate payload size before sending:
      $payload = json_encode(['message' => $message, 'custom' => $data]);
      if (strlen($payload) > 4000) {
          throw new \RuntimeException('Payload too large');
      }
      
  5. Timezone Sync

    • Issue: Baidu Push uses UTC for scheduled pushes.
    • Fix: Convert Laravel timestamps to UTC:
      $scheduledTime = now()->setTimezone('UTC')->toDateTimeString();
      $this->baiduPush->sendPush(..., scheduledTime: $scheduledTime);
      
  6. Deprecated Methods

    • Issue: The bundle is outdated (last release 2018). Some Baidu Push API methods may have changed.
    • Fix: Cross-reference with Baidu's PHP SDK docs and override methods if needed:
      $this->baiduPush->getClient()->setApiUrl('https://new-api-endpoint.com');
      

Debugging Tips

  1. Enable Verbose Logging Configure the SDK to log raw requests/responses:

    # config/packages/baidu_push.yaml
    baidu_push:
        debug: true
        log_file: /path/to/baidu_push.log
    

    Check logs for:

    • HTTP status codes (e.g., 401 Unauthorized).
    • Request payloads (validate against Baidu's API spec).
  2. Test with Sandbox Use Baidu's sandbox environment for testing:

    baidu_push:
        api_key: 'sandbox_api_key'
        secret_key: 'sandbox_secret_key'
        sandbox: true
    
  3. Common Error Codes

    Error Code Cause Solution
    10001 Invalid API Key Verify api_key in .env
    10002 Invalid User ID Check userId mapping in your DB
    10003 Signature Error Regenerate secret_key
    10004 Request Frequency Limit Implement rate limiting
    10005 Invalid Parameter Validate payload structure

Extension Points

  1. Custom Response Handling Extend the BaiduPushResponse class to add domain-specific logic:
    namespace App\Services;
    
    use BaiduBundle\Baidu
    
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin