Install the Bundle
composer require baidu-bundle/baidu-push-bundle
Add to config/bundles.php:
return [
// ...
BaiduBundle\BaiduPushBundle::class => ['all' => true],
];
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
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();
}
Sending Push Notifications
$this->baiduPush->sendPush(
userId: 'user123',
message: 'Your order is confirmed!',
title: 'Order Update',
type: 'message'
);
userIdList.
$this->baiduPush->sendPush(
userIdList: ['user1', 'user2', 'user3'],
message: 'Weekly newsletter',
title: 'Newsletter',
type: 'message'
);
customContent).
$this->baiduPush->sendPush(
userId: 'user123',
message: 'New feature available',
title: 'App Update',
type: 'message',
customContent: json_encode(['feature' => 'dark_mode'])
);
Handling Responses
$response = $this->baiduPush->sendPush(...);
if ($response->isSuccess()) {
$jobId = $response->getJobId(); // Track push job
} else {
$error = $response->getError(); // Debug issues
}
retry helper).Integration with Laravel Features
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'
);
});
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(...);
}
}
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']);
});
Logging and Monitoring
$response = $this->baiduPush->sendPush(...);
\Log::info('Baidu Push Response', [
'success' => $response->isSuccess(),
'job_id' => $response->getJobId(),
'error' => $response->getError(),
]);
statsd or a custom table.API Key/Secret Mismanagement
.env and env() helper. Never commit .env to Git.Rate Limiting
throttle middleware or spatie/laravel-rate-limiter).User ID Mismatch
userId in the SDK must match the userId registered in Baidu Push Console.userId (e.g., via a baidu_user_id column).getError() to check for INVALID_USER_ID errors.Payload Size Limits
$payload = json_encode(['message' => $message, 'custom' => $data]);
if (strlen($payload) > 4000) {
throw new \RuntimeException('Payload too large');
}
Timezone Sync
$scheduledTime = now()->setTimezone('UTC')->toDateTimeString();
$this->baiduPush->sendPush(..., scheduledTime: $scheduledTime);
Deprecated Methods
$this->baiduPush->getClient()->setApiUrl('https://new-api-endpoint.com');
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:
401 Unauthorized).Test with Sandbox Use Baidu's sandbox environment for testing:
baidu_push:
api_key: 'sandbox_api_key'
secret_key: 'sandbox_secret_key'
sandbox: true
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 |
BaiduPushResponse class to add domain-specific logic:
namespace App\Services;
use BaiduBundle\Baidu
How can I help you explore Laravel packages today?