简单的推送通知
一、首先 需要前端获取一下 每个用户的登录之后的 registration_id
二、就是后端的推送问题了
<?php
namespace app\api\service;
use JPush\Client;
require_once('../vendor/JPush/autoload.php');//引入你的 autoload 文件
//极光 通知
class JpushService
{
protected $AppKey;
protected $MasterSecret;
function __construct()
{
$this->AppKey = '你的key';
$this->MasterSecret = '你的Secret';
}
//极光推送 单用户
public function push($data,$user){
$andoreArray=[];
foreach($user as $k=>$v){
if($v['registration_id']){
$andoreArray[]=$v['registration_id'];
}
}
if(count($andoreArray)>0){
$this->push_one($data,$andoreArray);
}
}
//简单的 极光 通知推送
public function push_one($data,$andoreArray){
$client = new \JPush\Client($this->AppKey, $this->MasterSecret);
$push_payload = $client->push()
->setPlatform('all') //推送平台设置 当前支持 Android, iOS, Windows Phone 三个平台的推送。其关键字分别为:"android", "ios", "winphone"。 推送到所有平台:使用 all
->addRegistrationId($andoreArray)//设备标识 多个注册 ID 之间是 OR 关系,即取并集。
// 通知内容体。是被推送到客户端的内容
// ->addAlias('alias') //别名推送 用别名来标识一个用户
// ->addTag(array('tag1', 'tag2')) //标签推送 多个标签之间是 AND 关系,即取交集 。 一次推送最多 20 个。
->setNotificationAlert($data['title'])
->iosNotification($data['title'], array(
'sound' => 'sound.caf',//ios 语音播放地址配置
// 'badge' => '+1',
// 'content-available' => true,
// 'mutable-content' => true,
'category' => 'jiguang',
'extras' => array(
'key' => 'value',
'jiguang'
),
))
->androidNotification($data['content'], array(
'title' => $data['title'],//标题
// 'builder_id' => 2,
'extras' => array(
'key' => 'value',
'jiguang'
),
))
// 可选参数 下面参数都是选填 根据自己的需要 进行选择 可去掉
->options(array(
'sendno'=> '123456'//推送序号 纯粹用来作为 API 调用标识
'time_to_live'=>'60'//离线消息保留时长(秒) 默认 86400 (1 天),最长 10 天。设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到。
// apns_production: 表示APNs是否生产环境,
// True 表示推送生产环境,False 表示要推送开发环境;如果不指定则默认为推送开发环境
'apns_production' => false,
// big_push_duration: 表示定速推送时长(分钟),又名缓慢推送,把原本尽可能快的推送速度,降低下来,
// 给定的 n 分钟内,均匀地向这次推送的目标用户推送。最大值为1400.未设置则不是定速推送
// 这里设置为 1 仅作为示例
'big_push_duration' => 1000
));
try{
$response = $push_payload->send();
}catch(\JPush\Exceptions\APIConnectionException $e) {
// try something here
print $e;
} catch (\JPush\Exceptions\APIRequestException $e) {
// try something here
print $e;
}
}
}
控制器方法
$data = [
'title'=>'标题',
'content'=>'内容'
];
$result = Db('user')->where(['id'=>1])->field('registration_id')->select();
$JpushService = new JpushService();
$result = $JpushService->push($data,$result);
附录
极光推送官方文档 https://docs.jiguang.cn/jpush/guideline/intro/
php php_sdk下载地址: https://github.com/jpush/jpush-api-php-client/archive/master.zip
补充:
如果你引入了 autoload.php 之后还不能找到class类的话
那就只能采取以下方法了
一、更改你的 文件目录 使得你的项目目录与 下面保持一直
二、更改你的 autoload.php
<?php
function classLoader($class)
{
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
$file = __DIR__ . '/src/' . $path . '.php';//路径与你的引入路径一直
if (file_exists($file)) {
require_once $file;
}
}
spl_autoload_register('classLoader');