#yyds干货盘点#手机APP消息推送极光推送jpush-php实例

2022年01月16日 阅读数:4
这篇文章主要向大家介绍#yyds干货盘点#手机APP消息推送极光推送jpush-php实例,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

> 本文环境 ThinkPHP5.0,PHP7.1,Mysql5.7\ php

> 不懂的能够评论或联系我邮箱:owen@owenzhang.com\ android

> 著做权归OwenZhang全部。商业转载请联系OwenZhang得到受权,非商业转载请注明出处。ios

jpush/jpush介绍

这是 JPush REST API 的 PHP 版本封装开发包,是由极光推送官方提供的,通常支持最新的 API 功能。git

对应的 REST API 文档: ​​https://docs.jiguang.cn/jpush/server/push/server_overview/​github

支持的 PHP 版本: 5.3.3 ~ 5.6.x, 7.xsql

若须要兼容 PHP 5.3.3 如下版本,可使用 ​​v3 分支的代码​​​。 由于运行 Composer 须要 PHP 5.3.2+ 以上版本,因此其不提供 Composer 支持, 也能够​​点击连接​​下载 v3.4.x 版本源码。json

jpush/jpush下载

使用 Composer 安装

执行 $ php composer.phar install 或 $ composer install 进行安装。

直接下载源码安装

直接下载源代码也是一种安装 SDK 的方法,不过由于有版本更新的维护问题,因此这种安装方式十分不推荐,但因为种种缘由致使没法使用 Composer,因此咱们也提供了这种状况下的备选方案。bootstrap

  • 下载源代码包,解压到项目中
  • 在项目中引入 autoload:
require 'path_to_sdk/autoload.php';

代码实例

推送接口父类

application/common/JPush.php

<?php
/**
* 极光推送
*/
namespace app\common;

use JPush\Client;

class JPush
{
private $key = '';
private $secret = '';

use InstanceTrait;

public function _init()
{
$this->key = '3412f';
$this->secret = '2c23';
}

/**
* 指定注册ID发送
*/
public function push($registrationId, $title, $text, $url, $itemId)
{
$registrationId = array_filter($registrationId);
\Log::info(var_export([$registrationId, $title, $text, $url, $itemId], true));
$this->_init();

$client = new Client($this->key, $this->secret);
$push = $client->push();

$push->setPlatform('all');
$push->addRegistrationId($registrationId);
$push->addAndroidNotification($title, $text);
$push->androidNotification($text, ['title' => $title, 'alert_type' => 2, 'extras' => ['url' => $url, 'id' => $itemId]]);
$push->iosNotification(['title' => $title, 'body' => $text], ['extras' => ['url' => $url, 'id' => $itemId]]);
$push->options(['apns_production' => false]);
$push->send();
}
}

推送服务类

application/lucky/push/service/PushService.php

<?php
/**
* 推送服务
*/

namespace app\lucky\push\service;

use app\common\JPush;
use app\lucky\follow\service\FollowService;
use app\lucky\push\model\UserPushConfigModel;
use app\lucky\subscribe\service\SubscribeService;
use app\sports\match\service\FollowMatchService;
use app\sports\match\service\SportsApiService;

class PushService
{
public function push()
{
try {
$push = JPush::getInstance()->push(['1517badf006e81e'], '我是标题', '我是内容', 'GameDetails:1909991');
var_dump($push);
} catch (\Exception $e) {
var_dump($e->getMessage());
}

}

/**
* 推送设置
*/
public function pushConfig($userId, $sys, $ext)
{
$userPushConfigModel = new UserPushConfigModel();
$result = $userPushConfigModel->updateConfig($userId, $sys, ['ext' => json_encode($ext), 'update_time' => time()]);

if ($result) {
return ['code' => 0, 'msg' => '添加成功'];
}

return ['code' => -1, 'msg' => '添加失败'];
}

/**
* 获取配置
*/
public function getPushConfig($userId, $sys)
{
$userPushConfigModel = new UserPushConfigModel();
$result = $userPushConfigModel->getConfigByUserId($userId, $sys);
$data = isset($result['ext']) ? $result['ext'] : '';
$data = (array)json_decode($data, true);

return ['code' => 0, 'msg' => '获取成功', 'data' => $data];
}


/**
* 发布资讯推送
*/
public function blogPush($authorId, $title, $text, $blogId)
{
//获取做者的粉丝列表ID
$followService = new FollowService();
$followListId = $followService->getAuthorFollowList($authorId, 'sports');

//获取用户ID的配置
$pushModel = new UserPushConfigModel();
$pushConfig = $pushModel->getConfigByUserIdArr($followListId, 'sports');

$identifyArr = [];
foreach ($pushConfig as $value) {
$ext = (array)json_decode($value['ext'], true);
if (in_array('information', $ext)) {
$identifyArr[] = $value['identify'];
}
}

if (!empty($identifyArr)) {
try {
JPush::getInstance()->push($identifyArr, $title, $text, 'InfoDetails', $blogId);
} catch (\Exception $exception) {
\Log::error($exception->getMessage());
}
}
}



/**
* 登陆关联极光ID
*/
public function loginLinkPush($userId, $identify, $sys = '343')
{
$userPushConfigModel = new UserPushConfigModel();
$config = $userPushConfigModel->getConfigByUserId($userId, 'sports');

if (empty($config)) {
$data = [
'user_id' => $userId,
'identify' => $identify,
'update_time' => time(),
'sys' => $sys,
'ext' => json_encode(['start' => true, 'end' => true, 'score' => true, 'news' => true, 'information' => true])
];

$result = $userPushConfigModel->addConfig($data);
if (empty($result)) {
return ['code' => -1, 'msg' => '添加极光推送失败'];
}

return ['code' => 0, 'msg' => '添加极光推送成功'];
}

$data = [
'identify' => $identify,
'update_time' => time(),
];
$result = $userPushConfigModel->updateConfig($userId, $sys, $data);
if (empty($result)) {
return ['code' => -1, 'msg' => '更新极光推送失败'];
}

return ['code' => 0, 'msg' => '更新极光推送成功'];
}

/**
* 退出登陆关联极光ID
*/
public function logoutLinkPush($userId, $sys = '343')
{
$userPushConfigModel = new UserPushConfigModel();
$data = [
'identify' => '',
'update_time' => time(),
];
$result = $userPushConfigModel->updateConfig($userId, $sys, $data);
if (empty($result)) {
return ['code' => -1, 'msg' => '退出登陆,更新极光推送失败'];
}

return ['code' => 0, 'msg' => '退出登陆,更新极光推送成功'];
}
}

推送实例

application/lucky/admin/controller/Blog.php

//调用推送APP PUSH
$data['author_id']=123;
$data['title']='文章标题今天三美好的一天';
$title = '张三发布资讯';
$pushService = new PushService();
$pushService->blogPush($data['author_id'], $title, mb_substr($data['title'], 0, 10) . '...', $result);

初始化

use JPush\Client as JPush;
...
...

$client = new JPush($app_key, $master_secret);

...

ORapi

$client = new \JPush\Client($app_key, $master_secret);

简单推送

$client->push()
->setPlatform('all')
->addAllAudience()
->setNotificationAlert('Hello, JPush')
->send();

异常处理

$pusher = $client->push();
$pusher->setPlatform('all');
$pusher->addAllAudience();
$pusher->setNotificationAlert('Hello, JPush');
try {
$pusher->send();
} catch (\JPush\Exceptions\JPushException $e) {
// try something else here
print $e;
}

推送生产例子

注意: 这只是使用样例, 不该该直接用于实际环境中!!微信

在下载的中的 ​​examples​​ 文件夹有简单示例代码, 开发者能够参考其中的样例快速了解该库的使用方法。

简单使用方法

先填写对应的appKey和masterSecret,能够额外设定Registration_id。

若要运行 push_example.php 中的示例代码:

# 假定当前目录为 JPush 源码所在的根目录
$ php examples/push_example.php

同时也可编辑相关的示例文件,更改参数查看执行效果

测试

# 编辑 tests/bootstrap.php 文件,填入必须的变量值
# OR 设置相应的环境变量

# 运行所有测试用例
$ composer tests

# 运行某一具体测试用例
$ composer tests/JPush/xxTest.php

Buy me a cup of coffee :)

以为对你有帮助,就给我打赏吧,谢谢!

微信赞扬码连接,点击跳转:

​ https://www.owenzhang.com/wechat_reward.png​​​