<?php
namespace App\Helper;
use App\Exception\BusinessException;
use App\Constants\ErrorCode;
class XiaomiMessage
{
/**
* 推送URL
*/
const URL = 'https://api.xmpush.xiaomi.com/v2/message/regid';
/**
* 推送消息
* @param $package 包名
* @param $setting 消息配置
* @param $message 消息体
* @param $regId 用户regId 多个用逗号隔开
*/
public function send($package, $setting, $message, $regId)
{
$appSecret = $setting->app_secret;
$url = $this->getUrl($package, $message, $regId);
$options = [
'headers' => [
'Content-type' => 'application/x-www-form-urlencoded',
'Authorization' => sprintf('key=%s', $appSecret),
],
];
try {
$result = make(Client::class)
->request('POST', $url, [], $options)
->getResult();
if ($result['result'] !== 'ok' && $result['code'] !== 0) {
throw new BusinessException(ErrorCode::BIZ_ERROR, $result['description']);
}
} catch (\Exception $exception) {
throw new BusinessException(ErrorCode::BIZ_ERROR, $exception->getMessage());
}
}
/**
* 构建URL
*/
public function getUrl($package, $message, $regId)
{
$params = $this->getParams($package, $message, $regId);
return self::URL . '?' . http_build_query($params);
}
/**
* 构建请求参数
*/
public function getParams($package, $message, $regId)
{
$extra = [
'push_server_action' => 'hybrid_message',
'hybrid_pn' => $message['url'],
'notify_foreground' => 1,
'notify_effect' => 2,
];
if ($message['params']) {
$extra['book_id'] = $message['params']['book_id'];
$extra['chapter'] = $message['params']['chapter'];
};
return [
'restricted_package_name' => $package,
'restricted_package_name' => $package,
'title' => $message['title'],
'description' => $message['content'],
'notify_type' => -1,
'registration_id' => $regId,
'notify_id' => 2,
'extra' => $extra,
];
}
}
PHP实现小米推送
最新推荐文章于 2024-06-28 16:52:52 发布