以下是一个使用PHP和Google Cloud Messaging(GCM)发送消息到Android设备的实例。在这个例子中,我们将使用Google API PHP Client Library来简化GCM API的调用。
1. 准备工作
确保你已经:
- 在Google Cloud Console中创建了一个项目,并启用了GCM API。
- 获取了API密钥。
- 安装了Google API PHP Client Library。
2. 安装Google API PHP Client Library
```bash
composer require google/apiclient
```
3. 创建PHP脚本
创建一个名为 `gcm.php` 的文件,并添加以下代码:
```php
require 'vendor/autoload.php';
use Google""CloudMessaging""Gcm;
// 初始化GCM客户端
$gcm = new Gcm('YOUR_API_KEY');
// 设备注册ID列表
$registration_ids = [
'YOUR_REGISTRATION_ID_1',
'YOUR_REGISTRATION_ID_2',
// ... 添加更多设备注册ID
];
// 构建消息
$message = array(
'registration_ids' => $registration_ids,
'data' => array(
'message' => 'Hello, this is a test message!'
)
);
// 发送消息
try {
$response = $gcm->send($message);
echo "