手机APP消息推送极光推送jpush-php实例

简介: 手机APP消息推送极光推送jpush-php实例


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

不懂的可以评论或联系我邮箱:owen@owenzhang.com

著作权归OwenZhang所有。商业转载请联系OwenZhang获得授权,非商业转载请注明出处。

jpush/jpush介绍

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

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

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

若需要兼容 PHP 5.3.3 以下版本,可以使用 v3 分支的代码。 因为运行 Composer 需要 PHP 5.3.2+ 以上版本,所以其不提供 Composer 支持, 也可以点击链接下载 v3.4.x 版本源码。

jpush/jpush下载

使用 Composer 安装

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

直接下载源码安装

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

  • 下载源代码包,解压到项目中
  • 在项目中引入 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);
...

OR

$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

目录
相关文章
|
6月前
|
Java
照片一键生成眨眼视频app,手机照片一键生成眨眼动图,通过JAR代码实现效果
这是一个自动生成眨眼GIF动画的Java程序,包含主程序处理、图像变形和GIF生成三个模块。输入照片路径,自动识别人脸眼睛位置,生成闭眼、半闭眼等多帧图像,并合成为眨眼动效GIF文件。
|
3月前
|
存储 开发者 容器
鸿蒙 HarmonyOS NEXT星河版APP应用开发-ArkTS面向对象及组件化UI开发使用实例
本文介绍了ArkTS语言中的Class类、泛型、接口、模块化、自定义组件及状态管理等核心概念,并结合代码示例讲解了对象属性、构造方法、继承、静态成员、访问修饰符等内容,同时涵盖了路由管理、生命周期和Stage模型等应用开发关键知识点。
325 1
鸿蒙 HarmonyOS NEXT星河版APP应用开发-ArkTS面向对象及组件化UI开发使用实例
|
3月前
|
网络协议 Java Linux
【App Service】在Azure环境中如何查看App Service实例当前的网络连接情况呢?
在 Azure App Service(Windows 和 Linux)中部署应用时,分析网络连接状态是排查异常、验证端口监听及确认后端连接的关键。本文介绍如何在 Linux 环境中使用 `netstat` 命令查看特定端口(如 443、3306、6380)的连接情况,并解析输出结果。同时说明在 Windows App Service 中 `netstat` 被禁用的情况下,如何通过门户抓包等替代方法进行网络诊断。内容涵盖命令示例、操作步骤及附录说明,帮助开发者快速掌握云环境中的网络分析技巧。
113 11
|
4月前
|
编解码 数据安全/隐私保护
手机录制脚本自动执行, 免root屏幕录制脚本,自动脚本精灵app【autojs】
自动创建保存目录确保路径存在 动态生成带时间戳的文件名避免重复
|
10月前
|
机器学习/深度学习 存储 人工智能
MNN-LLM App:在手机上离线运行大模型,阿里巴巴开源基于 MNN-LLM 框架开发的手机 AI 助手应用
MNN-LLM App 是阿里巴巴基于 MNN-LLM 框架开发的 Android 应用,支持多模态交互、多种主流模型选择、离线运行及性能优化。
7579 80
MNN-LLM App:在手机上离线运行大模型,阿里巴巴开源基于 MNN-LLM 框架开发的手机 AI 助手应用
|
6月前
|
安全 测试技术 开发者
银行转账模拟器手机版app, 银行转账凭证生成器app,用autojs实现效果【逼真效果】
本内容展示了一套基于Auto.js的银行APP自动化测试脚本和框架,用于学习和研究移动应用测试技术。脚本涵盖登录、转账等功能测试
|
11月前
|
缓存 前端开发 IDE
【06】flutter完成注册页面-密码登录-手机短信验证-找回密码相关页面-并且实现静态跳转打包demo做演示-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草央千澈
【06】flutter完成注册页面-密码登录-手机短信验证-找回密码相关页面-并且实现静态跳转打包demo做演示-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草央千澈
292 0
【06】flutter完成注册页面-密码登录-手机短信验证-找回密码相关页面-并且实现静态跳转打包demo做演示-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草央千澈
|
PHP
PHP的pcntl多进程用法实例
PHP使用PCNTL系列的函数也能做到多进程处理一个事务。
120 12
|
小程序 JavaScript API
微信小程序开发之:保存图片到手机,使用uni-app 开发小程序;还有微信原生保存图片到手机
这篇文章介绍了如何在uni-app和微信小程序中实现将图片保存到用户手机相册的功能。
3333 0
微信小程序开发之:保存图片到手机,使用uni-app 开发小程序;还有微信原生保存图片到手机
|
设计模式 SQL 安全
PHP中的设计模式:单例模式的深入探索与实践在PHP开发领域,设计模式是解决常见问题的高效方案集合。它们不是具体的代码,而是一种编码和设计经验的总结。单例模式作为设计模式中的一种,确保了一个类仅有一个实例,并提供一个全局访问点。本文将深入探讨单例模式的基本概念、实现方式及其在PHP中的应用。
单例模式在PHP中的应用广泛,尤其在处理数据库连接、日志记录等场景时,能显著提高资源利用率和执行效率。本文从单例模式的定义出发,详细解释了其在PHP中的不同实现方法,并探讨了使用单例模式的优势与注意事项。通过对示例代码的分析,读者将能够理解如何在PHP项目中有效应用单例模式。

热门文章

最新文章