Commit fc5b7e05 authored by 蔡闯's avatar 蔡闯

更新推送代码

parent 1844e0cc
......@@ -114,13 +114,14 @@ class Index extends Base
public function getVacancyInfo() {
$vacancy_id = Request::param('vacancy_id');
$data = Db::name('house_vacancy')->alias('hv')
->Join('house_village hvi','hvi.village_id = hv.village_id')
->Join('house_user_bind hub','hub.vacancy_id = hv.vacancy_id')
->leftJoin('house_village hvi','hvi.village_id = hv.village_id')
->leftJoin('house_user_bind hub','hub.vacancy_id = hv.vacancy_id')
->where(['hv.vacancy_id'=>$vacancy_id])
->field('hv.vacancy_code,hv.village_id,hv.parent_id,layout_id,hvi.village_name,hvi.village_address,hvi.province_name,hvi.city_name,hvi.area_name')
->find();
$data['vacancy_address'] = Common::getVacancyAddress($data['vacancy_code'],$data['layout_id']);
$data['vacancyOwnerInfo'] = Common::getOwnerInfo($vacancy_id); //物业信息
$data['vacancyOwnerInfo'] = Common::getOwnerInfo($vacancy_id); //业主信息
$data['isHasOwner'] = empty($data['vacancyOwnerInfo']) ? 0 : 1;
$data['getUserBindType'] = Common::getUserBindType();
$data['getFamilyBindType'] = Common::getFamilyBindType();
return $this->returnJson($data);
......
......@@ -71,4 +71,6 @@ class News extends Base{
}
\ No newline at end of file
......@@ -86,6 +86,7 @@ class User extends Base
//用户绑定房间
public function userBindVacancy(){
//判断参数是否为空
$data['type'] = Request::param('type');
$village_id = Request::param('village_id');
$vacancy_id = Request::param('vacancy_id');
......
......@@ -4,6 +4,7 @@
namespace app\api\controller;
use app\common\controller\Common;
use app\common\controller\Jpush;
use think\facade\Db;
use think\facade\Request;
......@@ -11,13 +12,10 @@ class Village extends Base
{
//搜索小区
public function test() {
$float_1 = 1.11111111111111111111111111111111111111111111111111111;
$float_2 = 1.11111111111111111111111111111111111111111111111111112;
var_dump($float_1==$float_2);
$phone = "135883180489";
$content = "新版本推送";
Jpush::push_oppo($phone,$content);
}
}
\ No newline at end of file
......@@ -78,7 +78,6 @@ class Common extends BaseController
return $data;
}
//对数组中的图片字段进行日期转换
public static function changeImg($data,$field="pic"){
if(empty($data)){
......@@ -133,7 +132,6 @@ class Common extends BaseController
}
/**
* @param $url_ids string 1,2,3
* @param $navAl array
......@@ -873,6 +871,7 @@ class Common extends BaseController
public static function getUserBindType() {
return ['0'=>'业主','1'=>'家人','2'=>'租客','3'=>'替换业主'];
}
//获取需要绑定人员设备
public static function getFamilyBindType() {
return ['1'=>'配偶','2'=>'父母','3'=>'子女','4'=>'亲戚','5'=>'好友'];
......@@ -893,7 +892,7 @@ class Common extends BaseController
//图片上传
public static function uploadImg($file,$path) {
$ext = $file->getOriginalExtension();
if(!in_array($ext,['pjpeg','jpeg','jpg','gif','bmp','png'])) {
if(!in_array($ext,['jpeg','jpg','gif','bmp','png'])) {
return false;
}
......
<?php
namespace app\common\controller;
use \HwPush\push_admin\Application;
use \app\BaseController;
use think\facade\Db;
$file = dirname(dirname(dirname(__DIR__)))."/extend/jpush/autoload.php";
require_once $file;
class Jpush extends BaseController
{
public static $title = "微控云享智慧社区";
//推送所有的
public static function push($phone,$content){
self::push_mi($phone,$content);
self::push_huwei($phone,$content);
self::push_oppo($phone,$content);
self::push_meizu($phone,$content);
self::push_vivo($phone,$content);
self::push_jiguang($phone,$content);
}
/**
* mi推送代码测试,已通过
*/
public static function push_mi($phone,$content){
$alias = $phone;
$title = self::$title;
$desc = $content;
$sender = new \MiPush\xmpush\Sender();
$message1 = new \MiPush\xmpush\Builder();
$message1->title($title); // 通知栏的title
$message1->description($desc); // 通知栏的descption
$message1->passThrough(0); // 这是一条通知栏消息,如果需要透传,把这个参数设置成1,同时去掉title和descption两个参数
$message1->extra( \MiPush\xmpush\Builder::notifyForeground, 1); // 应用在前台是否展示通知,如果不希望应用在前台时候弹出通知,则设置这个参数为0
$message1->notifyId(2); // 通知类型。最多支持0-4 5个取值范围,同样的类型的通知会互相覆盖,不同类型可以在通知栏并存
$message1->build();
$sender->broadcast($message1, $alias)->getRaw();
}
/**
* huawei推送
*/
public static function push_huwei($phone,$content){
$application = Application::getInstance();
//设备token
$device = Db::name('push_device')->where(['phone'=>$phone,'type'=>1])->value('device_id',true);
$device_token = json_encode($device);
$title = self::$title;
$body = $content;
$res = $application->pushMsg($title,$body,$device_token);
}
/**
* oppo 推送
*/
public static function push_oppo($phone,$content){
$application = new \OPush\Application();
$title = self::$title;
$device = Db::name('push_device')->where(['phone'=>$phone,'type'=>2])->column('device_id');
foreach($device as $v){
$res = $application->pushTag($title,$content,$v);
}
}
/**
* meizu 推送
*/
public static function push_meizu($phone,$content){
$application = new \MzPush\Application();
$title = self::$title;
$res = $application->pushTag($title,$content,$phone);
}
/**
* 极光推送iso测试通过
*/
public static function push_jiguang($phone,$content){
$client = new \JPush\Client();
$alias = $phone;
//iso是通了的
$result = $client->push()
->setPlatform(array('all'))// 推送的all
->addAlias($alias)//
->setNotificationAlert($content)
->send();
}
/**
* vivo推送
*/
public static function push_vivo($phone,$content){
$application = new \ViPush\Application();
//别名推送
// $alias = $phone;
// $message = new \ViPush\Message();
// $message->setTitle(self::$title);
// $message->setContent($content);
// $message->setNotifyType(4);
// $message->setAlias($alias);
// $message->setSkipType();
// $message->setSkipType();
// $body = $message->build();
// $res = $application->pushAlias($body);
//tag推送,测试成功
$title = self::$title;
$tag[] = $phone;
return $res = $application->pushTag($title,$content,$tag);
}
}
{
"name": "topthink/think",
"description": "the new thinkphp framework",
"type": "project",
"keywords": [
"framework",
"thinkphp",
"ORM"
],
"homepage": "http://thinkphp.cn/",
"license": "Apache-2.0",
"authors": [
{
"name": "liu21st",
"email": "liu21st@gmail.com"
},
{
"name": "yunwuxin",
"email": "448901948@qq.com"
}
],
"require": {
"php": ">=7.1.0",
"topthink/framework": "^6.0.0",
"topthink/think-orm": "^2.0",
"topthink/think-multi-app": "^1.0",
"firebase/php-jwt": "^5.2",
"phpoffice/phpexcel": "^1.8"
},
"require-dev": {
"symfony/var-dumper": "^4.2",
"topthink/think-trace":"^1.0"
},
"autoload": {
"psr-4": {
"app\\": "app"
},
"psr-0": {
"": "extend/"
}
},
"config": {
"preferred-install": "dist"
},
"scripts": {
"post-autoload-dump": [
"@php think service:discover",
"@php think vendor:publish"
]
}
}
{
"name": "topthink/think",
"description": "the new thinkphp framework",
"type": "project",
"keywords": [
"framework",
"thinkphp",
"ORM"
],
"homepage": "http://thinkphp.cn/",
"license": "Apache-2.0",
"authors": [
{
"name": "liu21st",
"email": "liu21st@gmail.com"
},
{
"name": "yunwuxin",
"email": "448901948@qq.com"
}
],
"require": {
"php": ">=7.1.0",
"topthink/framework": "^6.0.0",
"topthink/think-orm": "^2.0",
"topthink/think-multi-app": "^1.0",
"firebase/php-jwt": "^5.2",
"phpoffice/phpexcel": "^1.8"
},
"require-dev": {
"symfony/var-dumper": "^4.2",
"topthink/think-trace":"^1.0"
},
"autoload": {
"psr-4": {
"app\\": "app"
},
"psr-0": {
"": ["extend/","extend/jpush/"]
}
},
"config": {
"preferred-install": "dist"
},
"scripts": {
"post-autoload-dump": [
"@php think service:discover",
"@php think vendor:publish"
]
}
}
___ ___ __ __ __________ ____ ___ _________ ___ ___ __________ ___ _____________
/ | \/ \ / \ \______ \ | \/ _____// | \ \______ \/ | \______ \
/ ~ \ \/\/ / | ___/ | /\_____ \/ ~ \ | ___/ ~ \ ___/
\ Y /\ / | | | | / / \ Y / | | \ Y / |
\___|_ / \__/\ / |____| |______/ /_______ /\___|_ / |____| \___|_ /|____|
\/ \/ \/ \/ \/
********************************************************************************************
********** instruction: 1)two part:private personal data and public url **********
********** 2)don't change split character such as =/" **********
********** 3)don't new line for HW_PUSH_TOKEN_ARR **********
********** 4)Space will be removed, cannot be a variable **********
********************************************************************************************
********************************************************************************************
********** here is private variable personal data,you must change it! **********
********************************************************************************************
HW_APPID="102526607"
HW_APPSECRET="xxxxx"
### Business Push Token,For common push msg ####
HW_PUSH_TOKEN_ARR="xxxxx"
### Business Push Token,For IOS apn ####
APN_PUSH_TOKEN_ARR="xxxxx"
### Business Push Token,For webpush ####
WEBPUSH_PUSH_TOKEN_ARR="xxxxx"
### FAST APP INFO : different from ordinal app####
HW_FAST_APPID="xxxxx"
HW_FAST_APPSECRET="xxxxx"
HW_FAST_PUSH_TOKEN="xxxxx"
********************************************************************************************
********** below is public url entry,please don't modify if not necessary **********
********************************************************************************************
### Token Server for push msg and top subscribe/unsubscribe ####
HW_TOKEN_SERVER="https://oauth-login.cloud.huawei.com/oauth2/v2/token"
### Push Server address ####
HW_PUSH_SERVER="https://push-api.cloud.huawei.com/v1/{appid}/messages:send"
### Topic Server address ####
HW_TOPIC_SUBSCRIBE_SERVER="https://push-api.cloud.huawei.com/v1/{appid}/topic:subscribe"
HW_TOPIC_UNSUBSCRIBE_SERVER="https://push-api.cloud.huawei.com/v1/{appid}/topic:unsubscribe"
HW_TOPIC_QUERY_SUBSCRIBER_SERVER="https://push-api.cloud.huawei.com/v1/{appid}/topic:list"
### LogLevel:ERROR(1),WARN(2),INFO(3),DEBUG(4) ####
HW_DEFAULT_LOG_LEVEL=3
a:2:{s:12:"access_token";s:88:"CgB6e3x9DjmYP/VKIURJlMrbQYzgvbJ5jcQvQA4i6Ep3t6OcuafHoeuico454a///E3mnDQ5YITryXcTWvUz+ynR";s:11:"expire_time";i:1611370987;}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
include_once (dirname(__FILE__) . '/../../push_admin/Application.php');
include_once (dirname(__FILE__) . '/../../push_admin/Constants.php');
include_once (dirname(__FILE__) . '/../../push_admin/PushLogConfig.php');
include_once (dirname(__FILE__) . '/../../push_admin/PushConfig.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/PushMessage.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/android/AndroidConfig.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/apns/ApnsConfig.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/notification/Notification.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/webpush/WebPushConfig.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/apns/Alert.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/apns/ApnsHmsOptions.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/apns/ApnsHeaders.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/apns/Aps.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/instanceapp/InstanceAppConfig.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/instanceapp/InstanceAppPushbody.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/instanceapp/InstanceAppRingtone.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/android/AndroidNotification.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/webpush/WebPushHeaders.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/webpush/WebPushHmsOptions.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/webpush/WebPushNotification.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/android/Badge.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/android/ClickAction.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/android/LightSetting.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/webpush/WebPushNotificationAction.php');
include_once (dirname(__FILE__) . '/../../push_admin/push_msg/android/LightSettingColor.php');
use push_admin\AndroidConfigDeliveryPriority;
use push_admin\ApnConstant;
use push_admin\Application;
use push_admin\Constants;
use push_admin\NotificationPriority;
use push_admin\push_msg\android\AndroidConfig;
use push_admin\push_msg\android\AndroidNotification;
use push_admin\push_msg\android\Badge;
use push_admin\push_msg\android\ClickAction;
use push_admin\push_msg\android\LightSetting;
use push_admin\push_msg\android\LightSettingColor;
use push_admin\push_msg\apns\Alert;
use push_admin\push_msg\apns\ApnsConfig;
use push_admin\push_msg\apns\ApnsHeaders;
use push_admin\push_msg\apns\ApnsHmsOptions;
use push_admin\push_msg\apns\Aps;
use push_admin\push_msg\instanceapp\InstanceAppConfig;
use push_admin\push_msg\instanceapp\InstanceAppPushbody;
use push_admin\push_msg\instanceapp\InstanceAppRingtone;
use push_admin\push_msg\notification\Notification;
use push_admin\push_msg\PushMessage;
use push_admin\push_msg\webpush\WebPushConfig;
use push_admin\push_msg\webpush\WebPushHeaders;
use push_admin\push_msg\webpush\WebPushHmsOptions;
use push_admin\push_msg\webpush\WebPushNotification;
use push_admin\push_msg\webpush\WebPushNotificationAction;
use push_admin\PushConfig;
use push_admin\PushLogConfig;
class TestPushMsgCommon
{
// ordinal app
private $appid;
private $appsecret;
// FOR PUSH MSG NOTIFICATION,PASSTHROUGH TOPIC/TOKEN/CONDITION
public $hw_push_token_key;
// FOR APN
public $apn_push_token_key;
// FOR WEBPUSH
public $webpush_push_token_key;
// fast app
private $fast_appid;
private $fast_appsecret;
// fast app token
public $fast_push_token;
private $hw_token_server;
private $hw_push_server;
private $log_suffix_show_start = ".............................";
private $log_suffix_show_end = "-----------------------------";
private $push_msg_type;
private $default_topic = 'defaultTopic';
private $str_len = 35;
public function __construct()
{
$pushConfig = PushConfig::getSingleInstance();
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_APPID", $this->str_len, '=') . ">" . $pushConfig->HW_APPID);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_APPSECRET", $this->str_len, '=') . ">" . $pushConfig->HW_APPSECRET);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_TOKEN_SERVER", $this->str_len, '=') . ">" . $pushConfig->HW_TOKEN_SERVER);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_PUSH_TOKEN_ARR", $this->str_len, '=') . ">" . $pushConfig->HW_PUSH_TOKEN_ARR);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("WEBPUSH_PUSH_TOKEN_ARR", $this->str_len, '=') . ">" . $pushConfig->WEBPUSH_PUSH_TOKEN_ARR);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("APN_PUSH_TOKEN_ARR", $this->str_len, '=') . ">" . $pushConfig->APN_PUSH_TOKEN_ARR);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_TOPIC_SUBSCRIBE_SERVER", $this->str_len, '=') . ">" . $pushConfig->HW_TOPIC_SUBSCRIBE_SERVER);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_TOPIC_UNSUBSCRIBE_SERVER", $this->str_len, '=') . ">" . $pushConfig->HW_TOPIC_UNSUBSCRIBE_SERVER);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_TOPIC_QUERY_SUBSCRIBER_SERVER", $this->str_len, '=') . ">" . $pushConfig->HW_TOPIC_QUERY_SUBSCRIBER_SERVER);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_FAST_APPID", $this->str_len, '=') . ">" . $pushConfig->HW_FAST_APPID);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_FAST_APPSECRET", $this->str_len, '=') . ">" . $pushConfig->HW_FAST_APPSECRET);
PushLogConfig::getSingleInstance()->LogMessage(str_pad("HW_FAST_PUSH_TOKEN", $this->str_len, '=') . ">" . $pushConfig->HW_FAST_PUSH_TOKEN);
$this->appsecret = $pushConfig->HW_APPSECRET;
$this->appid = $pushConfig->HW_APPID;
$this->hw_token_server = $pushConfig->HW_TOKEN_SERVER;
$this->hw_push_server = $pushConfig->HW_PUSH_SERVER;
$this->hw_push_token_key = $pushConfig->HW_PUSH_TOKEN_ARR;
$this->apn_push_token_key = $pushConfig->APN_PUSH_TOKEN_ARR;
$this->webpush_push_token_key = $pushConfig->WEBPUSH_PUSH_TOKEN_ARR;
$this->fast_appsecret = $pushConfig->HW_FAST_APPSECRET;
$this->fast_appid = $pushConfig->HW_FAST_APPID;
$this->fast_push_token = $pushConfig->HW_FAST_PUSH_TOKEN;
}
function sendPushMsgMessageByMsgType($msg_type, $topic = "")
{
$application_server = $this->hw_push_server;
$this->printLogMethodOperate("push msg start" . $this->log_suffix_show_start, __FUNCTION__ . ':' . __LINE__);
$this->push_msg_type = $msg_type;
$message = $this->getMessageByMsgType($msg_type);
$this->printLogMethodOperate("msg body:" . json_encode($message->getFields()), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
$application = $this->createApplication($application_server);
$this->printLogMethodOperate("application server:" . json_encode($application->getApplicationFields()), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
$application->push_send_msg($message->getFields());
$this->printLogMethodOperate("push msg end" . $this->log_suffix_show_end, __FUNCTION__ . ':' . __LINE__);
}
function sendPushMsgRealMessage($message,$push_msg_type="")
{
$this->printLogMethodOperate("sendPushMsgRealMessage start push_msg_type:" .$push_msg_type, __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (!empty($push_msg_type)) {
$this->push_msg_type = $push_msg_type;
}
$this->printLogMethodOperate("sendPushMsgRealMessage start push_msg_type:" .$this->push_msg_type, __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
$application_server = $this->hw_push_server;
$application = $this->createApplication($application_server);
$this->printLogMethodOperate("application server:" . json_encode($application->getApplicationFields()), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
$application->push_send_msg($message);
$this->printLogMethodOperate("push msg end" . $this->log_suffix_show_end, __FUNCTION__ . ':' . __LINE__);
}
function sendPushTopicMsgMessage($topic = "")
{
if (empty($topic)) {
$topic = $this->default_topic;
}
$testTopicCommonSample = new TestTopicCommonSample($topic);
$this->printLogMethodOperate("start subscribe topic:" . $topic, __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_INFO_LEVEL);
// subscribe msg
$testTopicCommonSample->sendTopicMessage(Constants::TOPIC_SUBSCRIBE_MSG_TYPE);
// query subscribe msg
$testTopicCommonSample->sendTopicMessage(Constants::TOPIC_SUBSCRIBE_QUERY_MSG_TYPE);
}
/**
* $result==>{"msg":"success","code":"80000000","requestId":"157561883923402813000201",
* "topics":[{"name":"defaultTopic","addDate":"2019-12-06"},
* {"name":"push-test","addDate":"2019-12-06"},
* {"name":"targetTopic","addDate":"2019-12-06"},
* {"name":"weather","addDate":"2019-12-06"}]}
*/
private function isTopicInTopicList($result, $topic)
{
$this->printLogMethodOperate("isTopicInTopicList topic[" . $topic . "],result:" . json_encode($result) . "", __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_INFO_LEVEL);
if (empty($result)) {
return FALSE;
}
$arrResult = json_decode(json_encode($result), true);
$this->printLogMethodOperate("isTopicInTopicList arrResult:" . json_encode($arrResult) . "][code:" . $arrResult["code"], __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (empty($arrResult["code"])) {
return FALSE;
}
$this->printLogMethodOperate("isTopicInTopicList code:" . $arrResult["code"], __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (! in_array($arrResult["code"], array(
"80000000",
80000000
))) {
return FALSE;
}
if (empty($arrResult["topics"])) {
return FALSE;
}
$topicArr = $arrResult["topics"];
$this->printLogMethodOperate("isTopicInTopicList topicArr:" . json_encode($topicArr), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (empty($topicArr)) {
return FALSE;
}
foreach ($topicArr as $topicObject) {
if ($topicObject["name"] == $topic) {
return TRUE;
}
}
$this->printLogMethodOperate("isTopicInTopicList False,topic is not subscribe", __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
return FALSE;
}
private function getDefaultAndroidNotificationContent($titel)
{
$prefixTitleData = '';
switch ($this->push_msg_type) {
case Constants::PUSHMSG_NOTIFICATION_MSG_TYPE:
{
$prefixTitleData = ' notification ';
break;
}
case Constants::PUSHMSG_PASS_THROUGHT_MSG_TYPE:
{
$prefixTitleData = ' passthrough ';
break;
}
case Constants::PUSHMSG_FASTAPP_MSG_TYPE:
{
$prefixTitleData = ' fastapp ';
break;
}
case Constants::PUSHMSG_TOPIC_MSG_TYPE:
{
$prefixTitleData = ' topic ';
break;
}
case Constants::PUSHMSG_CONDITION_MSG_TYPE:
{
$prefixTitleData = ' condition ';
break;
}
case Constants::APN_MSG_TYPE:
{
$prefixTitleData = ' apn ';
break;
}
case Constants::WEB_PUSH_MSG_TYPE:
{
$prefixTitleData = ' webpush ';
break;
}
}
return $prefixTitleData . $titel . $prefixTitleData;
}
private function createAndroidNotification()
{
// generate click_action msg body for android notification-3-click_action
$click_action = new ClickAction();
$click_action->type(2);
$click_action->type(1);
$click_action->intent("#Intent;compo=com.rvr/.Activity;S.W=U;end");
$click_action->action("test add");
$click_action->url("https://www.baidu.com");
$click_action->rich_resource("test rich resource");
$click_action->buildFields();
// generate Badge for android notification-3-badge
$badge = new Badge();
$badge->add_num(99);
$badge->setclass("Classic");
$badge->set_num(99);
$badge->buildFields();
// generate Light Settings for android notification-3-badge
$lightSetting = new LightSetting();
$lightSetting->light_on_duration("3.5");
$lightSetting->light_off_duration("5S");
// set light setting color
$LightSettingColor = new LightSettingColor();
$LightSettingColor->setgenFullcolor(0, 0, 1, 1);
$LightSettingColor->buildFields();
$lightSetting->color($LightSettingColor->getFields());
$lightSetting->buildFields();
// 构建android notification消息体-2 for android config
$android_notification = new AndroidNotification();
$android_notification->title($this->getDefaultAndroidNotificationContent("default hw title "));
$android_notification->body($this->getDefaultAndroidNotificationContent("default hw body"));
$android_notification->icon("https://res.vmallres.com/pimages//common/config/logo/SXppnESYv4K11DBxDFc2.png");
$android_notification->color("#AACCDD");
$android_notification->sound("https://att.chinauui.com/day_120606/20120606_7fcf2235b44f1eab0b4dadtAkAGMTBHK.mp3");
$android_notification->tag("tagBoom");
$android_notification->body_loc_key("M.String.body");
$android_notification->body_loc_args(array(
"Boy",
"Dog"
));
$android_notification->title_loc_key("M.String.title");
$android_notification->title_loc_args(array(
"Girl",
"Cat"
));
$android_notification->channel_id("RingRing");
$android_notification->notify_summary("Some Summary");
$android_notification->image("https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png");
$android_notification->style(0);
$android_notification->big_title("Big Boom Title");
$android_notification->big_body("Big Boom Body");
$android_notification->auto_clear(86400000);
$android_notification->notify_id(486);
$android_notification->group("Espace");
$android_notification->importance(NotificationPriority::NOTIFICATION_PRIORITY_NORMAL);
$android_notification->ticker("i am a ticker");
$android_notification->auto_cancel(false);
$android_notification->when("2019-11-05");
$android_notification->use_default_vibrate(true);
$android_notification->use_default_light(false);
$android_notification->visibility("PUBLIC");
$android_notification->foreground_show(true);
$android_notification->vibrate_config(array(
"1.5",
"2.000000001",
"3"
));
$android_notification->click_action($click_action->getFields());
$android_notification->badge($badge->getFields());
$android_notification->light_settings($lightSetting->getFields());
$android_notification->buildFields();
return $android_notification;
}
private function createAndroidConfig()
{
$android_notification = $this->createAndroidNotification();
$android_config = new AndroidConfig();
$android_config->collapse_key(- 1);
$android_config->urgency(AndroidConfigDeliveryPriority::PRIORITY_HIGH);
$android_config->ttl("1448s");
$android_config->bi_tag("Trump");
if ($this->push_msg_type == Constants::PUSHMSG_FASTAPP_MSG_TYPE) {
$android_config->fast_app_target(1);
}
else{
$android_config->notification($android_notification->getFields());
}
$android_config->buildFields();
return $android_config;
}
private function createNotification()
{
$notification = new Notification("Big News", "This is a Big News!", "https://res.vmallres.com/pimages//common/config/logo/SXppnESYv4K11DBxDFc2_0.png");
$notification->buildFields();
return $notification;
}
private function createApnsConfig()
{
// ApnsHeaders
$apnsHeaders = new ApnsHeaders();
$apnsHeaders->apns_topic("hmspush");
$apnsHeaders->apns_priority(ApnConstant::ANP_PRIORITY_SEND_IMMEDIATELY);
$apnsHeaders->buildFields();
// ApnHmsOptions
$apnsHmsOptions = new ApnsHmsOptions();
$apnsHmsOptions->target_user_type(ApnConstant::APN_TARGET_USER_TEST_USER);
$apnsHmsOptions->buildFields();
// Aps
// Alert
$alert = new Alert();
$alert->title("hw default ios message title");
$alert->body("hw default ios message body");
$alert->action_loc_key("PLAY");
$alert->buildFields();
$aps = new Aps();
$aps->alert($alert->getFields());
$aps->badge(5);
$aps->buildFields();
$apnsConfig = new ApnsConfig();
$apnsConfig->headers($apnsHeaders->getFields());
$apnsConfig->hms_options($apnsHmsOptions->getFields());
$apn_payload["aps"] = $aps->getFields();
$apn_payload["acme1"] = "bar";
$apn_payload["acme2"] = array(
"bang",
"whiz"
);
$apnsConfig->payload($apn_payload);
$apnsConfig->buildFields();
return $apnsConfig;
}
private function createWebPush()
{
$webPushConfig = new WebPushConfig();
$webPushConfig->data("test webpush data");
$webPushHeaders = new WebPushHeaders();
$webPushHeaders->topic("12313ceshi");
$webPushHeaders->ttl("990");
$webPushHeaders->urgency(Constants::WEBPUSH_URGENCY_VERY_LOW);
$webPushHeaders->buildFields();
$webPushConfig->headers($webPushHeaders->getFields());
$webPushHmsOptions = new WebPushHmsOptions();
$webPushHmsOptions->link("https://www.huawei.com/");
$webPushHmsOptions->buildFields();
$webPushConfig->hmsOptions($webPushHmsOptions->getFields());
$webPUshNotionfication = new WebPushNotification();
$webPUshNotionfication->title("notication string");
$webPUshNotionfication->body("web push body");
$webPUshNotionfication->icon("https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png");
$webPUshNotionfication->image("https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png");
$webPUshNotionfication->lang("string");
$webPUshNotionfication->tag("string");
$webPUshNotionfication->badge("string");
$webPUshNotionfication->dir("auto");
$webPUshNotionfication->vibrate(array(
1,
2,
3
));
$webPUshNotionfication->renotify(false);
$webPUshNotionfication->require_interaction(false);
$webPUshNotionfication->silent(false);
$webPUshNotionfication->timestamp(1545201266);
$webPushNotificationAction = new WebPushNotificationAction();
$webPushNotificationAction->title("string");
$webPushNotificationAction->action("123");
$webPushNotificationAction->icon("https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png");
$webPushNotificationAction->buildFields();
$webPUshNotionfication->actions(array(
$webPushNotificationAction->getFields()
));
$webPUshNotionfication->buildFields();
$webPushConfig->notification($webPUshNotionfication->getFields());
$webPushConfig->buildFields();
return $webPushConfig;
}
private function printLogMethodOperate($dataFlow, $functionName = "", $logLevel = "")
{
$logModule = Constants::HW_PUSH_LOG_PUSH_MSG_MODULE;
if (empty($logLevel)) {
$logLevel = Constants::HW_PUSH_LOG_INFO_LEVEL;
}
if (empty($functionName)) {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . $dataFlow, $logLevel, $logModule);
} else {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . '[' . $functionName . ']' . $dataFlow, $logLevel, $logModule);
}
}
private function createApplication($application_server)
{
$this->printLogMethodOperate("createApplication push_msg_type:".$this->push_msg_type, __FUNCTION__ . ':' . __LINE__,Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if ($this->push_msg_type == Constants::PUSHMSG_FASTAPP_MSG_TYPE){
$this->printLogMethodOperate("createApplication PUSHMSG_FASTAPP_MSG_TYPE", __FUNCTION__ . ':' . __LINE__,Constants::HW_PUSH_LOG_DEBUG_LEVEL);
$application = new Application($this->fast_appid, $this->fast_appsecret, $this->hw_token_server, $application_server);
return $application;
}
$application = new Application($this->appid, $this->appsecret, $this->hw_token_server, $application_server);
return $application;
}
private function getMessageByMsgType($msg_type)
{
switch ($msg_type) {
case Constants::PUSHMSG_NOTIFICATION_MSG_TYPE:
{
return $this->createNotificationMsg();
}
case Constants::PUSHMSG_PASS_THROUGHT_MSG_TYPE:
{
return $this->createPassThroughMsg();
}
case Constants::PUSHMSG_FASTAPP_MSG_TYPE:
{
return $this->createFastAppMsg();
}
case Constants::PUSHMSG_TOPIC_MSG_TYPE:
{
return $this->createTopicMsg();
}
case Constants::PUSHMSG_CONDITION_MSG_TYPE:
{
return $this->createConditionMsg();
}
case Constants::APN_MSG_TYPE:
{
return $this->createApnsMsg();
}
case Constants::WEB_PUSH_MSG_TYPE:
{
return $this->createWebPushMsg();
}
}
}
private function createFastAppConfigNotificationData(){
$instanceAppConfig = new InstanceAppConfig();
$instanceAppConfig->pushtype(0);
$instanceAppPushbody = new InstanceAppPushbody();
$instanceAppPushbody->title("test fast app");
$instanceAppPushbody->description("test fast app description");
$instanceAppPushbody->page("/");
$instanceAppPushbody->params(array(
"key1"=>"test1",
"key2"=>"test2"
));
$instanceAppRingtone = new InstanceAppRingtone();
$instanceAppRingtone->breathLight(true);
$instanceAppRingtone->vibration(true);
$instanceAppRingtone->buildFields();
$instanceAppPushbody->ringtone($instanceAppRingtone->getFields());
$instanceAppPushbody->buildFields();
$instanceAppConfig->pushbody($instanceAppPushbody->getFields());
$instanceAppConfig->buildFields();
return $instanceAppConfig;
}
private function createFastAppConfigPassThroughData(){
$instanceAppConfig = new InstanceAppConfig();
$instanceAppConfig->pushtype(1);
$instanceAppPushbody = new InstanceAppPushbody();
$instanceAppPushbody->messageId("111110001");
$instanceAppPushbody->data("hw default passthroug test");
$instanceAppPushbody->buildFields();
$instanceAppConfig->pushbody($instanceAppPushbody->getFields());
$instanceAppConfig->buildFields();
return $instanceAppConfig;
}
private function createFastAppMsg()
{
$this->printLogMethodOperate("push msg notification start", __FUNCTION__ . ':' . __LINE__);
$message = new PushMessage();
$message->data($this->createFastAppConfigNotificationData()->getFields());
$message->android($this->createAndroidConfig()
->getFields());
$message->token(array(
$this->fast_push_token
));
$message->buildFields();
$this->printLogMethodOperate("push msg notification end", __FUNCTION__ . ':' . __LINE__);
return $message;
}
private function createNotificationMsg()
{
$this->printLogMethodOperate("push msg notification start", __FUNCTION__ . ':' . __LINE__);
$message = new PushMessage();
$message->android($this->createAndroidConfig()
->getFields());
$message->notification($this->createNotification()
->getFields());
$message->token(array(
$this->hw_push_token_key
));
$message->buildFields();
$this->printLogMethodOperate("push msg notification end", __FUNCTION__ . ':' . __LINE__);
return $message;
}
private function createTopicMsg()
{
$this->printLogMethodOperate("push msg createTopicMsg start", __FUNCTION__ . ':' . __LINE__);
$message = new PushMessage();
$message->android($this->createAndroidConfig()
->getFields());
// $message->notification($this->createNotification()->buildFields());
$message->topic($this->default_topic);
$message->buildFields();
$this->printLogMethodOperate("push msg createTopicMsg end", __FUNCTION__ . ':' . __LINE__);
return $message;
}
private function createConditionMsg()
{
$this->printLogMethodOperate("push msg createTopicMsg start", __FUNCTION__ . ':' . __LINE__);
$message = new PushMessage();
$message->android($this->createAndroidConfig()
->getFields());
// $message->notification($this->createNotification()->buildFields());
$message->condition("'defaultTopic' in topics");
// $message->condition("'weather' in topics || ('TopicB' in topics && 'TopicC' in topics)");
$message->buildFields();
$this->printLogMethodOperate("push msg createTopicMsg end", __FUNCTION__ . ':' . __LINE__);
return $message;
}
private function createPassThroughMsg()
{
$this->printLogMethodOperate("push msg passthrough start", __FUNCTION__ . ':' . __LINE__);
$message = new PushMessage();
$message->data("1111");
$message->token(array(
$this->hw_push_token_key
));
$message->buildFields();
$this->printLogMethodOperate("push msg passthrough end", __FUNCTION__ . ':' . __LINE__);
return $message;
}
private function createApnsMsg()
{
$this->printLogMethodOperate("push msg apns start", __FUNCTION__ . ':' . __LINE__);
$message = new PushMessage();
$apnsConfig = $this->createApnsConfig();
$message->apns($apnsConfig->getFields());
$message->token(array(
$this->apn_push_token_key
));
$message->buildFields();
$this->printLogMethodOperate("push msg apns end", __FUNCTION__ . ':' . __LINE__);
return $message;
}
private function createWebPushMsg()
{
$this->printLogMethodOperate("push msg webpush start", __FUNCTION__ . ':' . __LINE__);
$message = new PushMessage();
$message->webpush($this->createWebPush()
->getFields());
$message->token(array(
$this->webpush_push_token_key
));
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . '[web-token:' . json_encode($message->get_token()) . ']', Constants::HW_PUSH_LOG_DEBUG_LEVEL);
$message->buildFields();
$this->printLogMethodOperate("push msg webpush end", __FUNCTION__ . ':' . __LINE__);
return $message;
}
}
class TestTopicCommonSample
{
private $topic = "defaultTopic";
private $topic_msg_create_type = 1;
private $appsecret;
private $appid;
private $hw_token_server;
private $hw_topic_subscriber_server;
private $hw_topic_unsubscriber_server;
private $hw_topic_query_subscriber_server;
private $tokenServerKey;
private $log_suffix_show = ".............................";
public function __construct($topic_value = "", $default_msg_create_type = "")
{
if (! empty($topic_value)) {
$this->topic = $topic_value;
}
if (! empty($default_msg_create_type)) {
$this->topic_msg_create_type = $default_msg_create_type;
}
$pushConfig = PushConfig::getSingleInstance();
$this->appsecret = $pushConfig->HW_APPSECRET;
$this->appid = $pushConfig->HW_APPID;
$this->hw_token_server = $pushConfig->HW_TOKEN_SERVER;
$this->tokenServerKey = $pushConfig->HW_PUSH_TOKEN_ARR;
$this->hw_topic_subscriber_server = $pushConfig->HW_TOPIC_SUBSCRIBE_SERVER;
$this->hw_topic_unsubscriber_server = $pushConfig->HW_TOPIC_UNSUBSCRIBE_SERVER;
$this->hw_topic_query_subscriber_server = $pushConfig->HW_TOPIC_QUERY_SUBSCRIBER_SERVER;
}
private function createTopicData()
{
$topicMsg = new TopicMsg();
$topicMsg->topic($this->topic);
$topicMsg->tokenArray(array(
$this->tokenServerKey
));
$topicMsg->buildFields();
return $topicMsg;
}
private function createApplication($application_server)
{
$application = new Application($this->appid, $this->appsecret, $this->hw_token_server, $application_server);
return $application;
}
private function printLogMethodOperate($msg_type, $dataFlow, $functionName = "", $logLevel = "")
{
$dataFlow = 'subscribe topic ' . $dataFlow;
$logModule = Constants::HW_PUSH_LOG_TOPIC_SUBSCRIBE_MODULE;
switch ($msg_type) {
case Constants::TOPIC_UNSUBSCRIBE_MSG_TYPE:
{
$dataFlow = 'unsubscribe topic' . $dataFlow;
$logModule = Constants::HW_PUSH_LOG_TOPIC_UNSUBSCRIBE_MODULE;
}
break;
}
if (empty($logLevel)) {
$logLevel = Constants::HW_PUSH_LOG_INFO_LEVEL;
}
if (empty($functionName)) {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . $dataFlow . $this->log_suffix_show, $logLevel, $logModule);
} else {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . '[' . $functionName . ']' . $dataFlow . $this->log_suffix_show, $logLevel, $logModule);
}
}
private function printLogMsgOperate($msg_type, $dataFlow, $functionName = "", $logLevel = "")
{
$logModule = Constants::HW_PUSH_LOG_TOPIC_SUBSCRIBE_MODULE;
switch ($msg_type) {
case Constants::TOPIC_UNSUBSCRIBE_MSG_TYPE:
{
$logModule = Constants::HW_PUSH_LOG_TOPIC_UNSUBSCRIBE_MODULE;
}
break;
}
if (empty($logLevel)) {
$logLevel = Constants::HW_PUSH_LOG_INFO_LEVEL;
}
if (empty($functionName)) {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . $dataFlow . $this->log_suffix_show, $logLevel, $logModule);
} else {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . '[' . $functionName . ']' . $dataFlow . $this->log_suffix_show, $logLevel, $logModule);
}
}
/**
* topic subscribe/unsubscribe
*/
function sendTopicMessage($msg_type)
{
$this->printLogMethodOperate($msg_type, "start", __FUNCTION__ . ':' . __LINE__);
$topicMsg = $this->createTopicData();
if ($this->topic_msg_create_type == 1) {
$this->printLogMsgOperate($msg_type, "topicMsg:" . json_encode($topicMsg->getFields()), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
$application_server = $this->hw_topic_subscriber_server;
if ($msg_type == Constants::TOPIC_UNSUBSCRIBE_MSG_TYPE) {
$application_server = $this->hw_topic_unsubscriber_server;
} else if ($msg_type == Constants::TOPIC_SUBSCRIBE_QUERY_MSG_TYPE) {
$application_server = $this->hw_topic_query_subscriber_server;
$topicMsg = array(
'token' => $this->tokenServerKey
);
}
$application = $this->createApplication($application_server);
$this->printLogMsgOperate($msg_type, "application server:" . json_encode($application->getApplicationFields()), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
$topicResult = "";
if ($msg_type == Constants::TOPIC_SUBSCRIBE_QUERY_MSG_TYPE) {
$topicResult = $application->common_send_msg($topicMsg);
} else {
$topicResult = $application->common_send_msg($topicMsg->getFields());
}
$this->printLogMethodOperate($msg_type, "end", __FUNCTION__ . ':' . __LINE__);
return $topicResult;
}
}
class TopicMsg
{
// madatory
private $topic;
// madatory
private $tokenArray;
private $fields;
public function __construct()
{
$this->fields = array();
}
public function topic($value)
{
$this->topic = $value;
}
public function tokenArray($value)
{
$this->tokenArray = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
$keys = array(
'topic',
'tokenArray'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: two kinds of method to send apn msg:
* 1) sendPushMsgMessageByMsgType(code class object);
* 2) sendPushMsgRealMessage(text msg)
* 3) ios format may change,sometimes push msg depends of ios msg format
*/
include_once (dirname(__FILE__) . '/push_common/test_sample_push_msg_common.php');
include_once (dirname(__FILE__) . '/../push_admin/Constants.php');
use push_admin\Constants;
$testPushMsgSample = new TestPushMsgCommon();
$testPushMsgSample->sendPushMsgMessageByMsgType(Constants::APN_MSG_TYPE);
$message_arr = array(
'{
"token": [*push_token*],
"apns": {
"hms_options": {
"target_user_type": 1
},
"payload": {
"aps": {
"alert": {
"title": "hw1 message title",
"body": "hw message body",
"action-loc-key": "PLAY"
},
"badge": 5
},
"acme1": "bar",
"acme2": ["bang",
"whiz"]
}
}
}',
'{
"token": [*push_token*],
"apns": {
"hms_options": {
"target_user_type": 1
},
"payload": {
"aps": {
"alert": {
"title": "hw2 message title",
"body": "hw3 message body",
"action-loc-key": "PLAY"
},
"badge": 5
},
"acme1": "bar",
"acme2": ["bang",
"whiz"],
"sound": "default",
"launch-image": "https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png"
}
}
}',
'{
"token": [*push_token*],
"apns": {
"hms_options": {
"target_user_type": 1
},
"payload":{
"aps" : {
"alert" : {
"title" : "Game3 Request",
"body" : "Bob3 wants to play poker",
"action-loc-key" : "PLAY"
},
"badge" : 5
},
"acme1" : "bar",
"acme2" : [ "bang", "whiz" ]
}
}
}'
);
foreach ($message_arr as $message) {
$message=str_ireplace("*push_token*", '"'.$testPushMsgSample->apn_push_token_key.'"',$message);
$testPushMsgSample->sendPushMsgRealMessage(json_decode($message));
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: two kinds of method to send condition msg: sendPushTopicMsgMessage fro subscribe topic
* 1) sendPushMsgMessageByMsgType(code class object);
* 2) sendPushMsgRealMessage(text msg)
* 3) topic and condition not real time, maybe delay
*/
include_once (dirname(__FILE__) . '/push_common/test_sample_push_msg_common.php');
include_once (dirname(__FILE__) . '/../push_admin/Constants.php');
use push_admin\Constants;
$testPushMsgSample = new TestPushMsgCommon();
$testPushMsgSample->sendPushMsgMessageByMsgType(Constants::PUSHMSG_CONDITION_MSG_TYPE);
$message = '{
"android": {
"collapse_key": -1,
"urgency": "HIGH",
"ttl": "1448s",
"bi_tag": "Trump",
"notification": {
"title": " condition1 default hw title condition ",
"body": " condition1 default hw body condition ",
"color": "#AACCDD",
"tag": "tagBoom",
"click_action": {
"type": 1,
"intent": "#Intent;compo=com.rvr\/.Activity;S.W=U;end",
"rich_resource": "test rich resource",
"action": "test add"
},
"body_loc_key": "M.String.body",
"body_loc_args": ["Boy",
"Dog"],
"title_loc_key": "M.String.title",
"title_loc_args": ["Girl",
"Cat"],
"channel_id": "RingRing",
"notify_summary": "Some Summary",
"style": 0,
"big_title": "Big Boom Title",
"big_body": "Big Boom Body",
"auto_clear": 86400000,
"notify_id": 486,
"group": "Espace",
"badge": {
"add_num": 99,
"class": "Classic",
"set_num": 99
},
"ticker": "i am a ticker",
"auto_cancel": false,
"when": "2019-11-05",
"importance": "NORMAL",
"use_default_vibrate": true,
"use_default_light": false,
"vibrate_config": ["1.5",
"2.000000001",
"3"],
"visibility": "PUBLIC",
"light_settings": {
"color": {
"alpha": 0,
"red": 0,
"green": 1,
"blue": 1
},
"light_on_duration": "3.5",
"light_off_duration": "5S"
},
"foreground_show": true
}
},
"condition": *condition*
}';
$topic = '111';
$message=str_ireplace("*condition*", '"\''.$topic.'\' in topics"',$message);
$testPushMsgSample->sendPushMsgRealMessage(json_decode($message));
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: fast app,two kinds of method to send instance app msg:
* 1) sendPushMsgMessageByMsgType(code class object);
* 2) sendPushMsgRealMessage(text msg)
*/
include_once (dirname(__FILE__) . '/push_common/test_sample_push_msg_common.php');
include_once (dirname(__FILE__) . '/../push_admin/Constants.php');
use push_admin\Constants;
$testPushMsgSample = new TestPushMsgCommon();
$testPushMsgSample->sendPushMsgMessageByMsgType(Constants::PUSHMSG_FASTAPP_MSG_TYPE);
$message = '{
"data": "{\"pushtype\":1,\"pushbody\":{\"messageId\":\"111110001\",\"data\":\"test pass-through msg\"}}",
"ssss":"{k1:v1}",
"android": {
"collapse_key": -1,
"urgency": "HIGH",
"ttl": "1448s",
"bi_tag": "Trump",
"fast_app_target": 1
},
"token": [
*push_token*
]
}';
$message=str_ireplace("*push_token*", '"'.$testPushMsgSample->fast_push_token.'"',$message);
$testPushMsgSample->sendPushMsgRealMessage(json_decode($message),Constants::PUSHMSG_FASTAPP_MSG_TYPE);
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: two kinds of method to send notification msg:
* 1) sendPushMsgMessageByMsgType(code class object);
* 2) sendPushMsgRealMessage(text msg)
*/
include_once (dirname(__FILE__) . '/push_common/test_sample_push_msg_common.php');
include_once (dirname(__FILE__) . '/../push_admin/Constants.php');
use push_admin\Constants;
$testPushMsgSample = new TestPushMsgCommon();
$testPushMsgSample->sendPushMsgMessageByMsgType(Constants::PUSHMSG_NOTIFICATION_MSG_TYPE);
$message_arr = array(
'{
"notification": {
"title": "Big News1",
"body": "This is a Big News!",
"image": "https://res.vmallres.com/pimages//common/config/logo/SXppnESYv4K11DBxDFc2_0.png"
},
"android": {
"notification": {
"click_action": {
"type": 1,
"intent": "#Intent;compo=com.rvr/.Activity;S.W=U;end"
}
}
},
"token": [*push_token*]
}',
'{
"notification": {
"title": "Big News",
"body": "This is a Big News!",
"image": "https://res.vmallres.com/pimages//common/config/logo/SXppnESYv4K11DBxDFc2_0.png"
},
"android": {
"notification": {
"title": " real notification default hw title notification2 ",
"body": " real notification default hw body notification ",
"color": "#AACCDD",
"click_action": {
"type": 1,
"intent": "#Intent;compo=com.rvr/.Activity;S.W=U;end"
}
}
},
"token": [*push_token*]
}'
);
foreach ($message_arr as $message) {
$message=str_ireplace("*push_token*", '"'.$testPushMsgSample->hw_push_token_key.'"',$message);
$testPushMsgSample->sendPushMsgRealMessage(json_decode($message));
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: two kinds of method to send passthrough msg:
* 1) sendPushMsgMessageByMsgType(code class object);
* 2) sendPushMsgRealMessage(text msg)
*/
include_once (dirname(__FILE__) . '/push_common/test_sample_push_msg_common.php');
include_once (dirname(__FILE__) . '/../push_admin/Constants.php');
use push_admin\Constants;
$testPushMsgSample = new TestPushMsgCommon();
$testPushMsgSample->sendPushMsgMessageByMsgType(Constants::PUSHMSG_PASS_THROUGHT_MSG_TYPE);
$message_arr = array(
'{
"data": "hw test default data1",
"token": [*push_token*]
}',
'{
"data": "k=v,k=v2",
"android": {
"collapse_key": -1,
"ttl": "10000s",
"bi_tag": "the_sample_bi_tag_for_receipt_service"
},
"token": [*push_token*]
}',
'{
"data": "k=v,k=v",
"android": {
"data": "pass through real data3",
"collapse_key": -1,
"ttl": "10000s",
"bi_tag": "the_sample_bi_tag_for_receipt_service"
},
"token": [*push_token*]
}'
);
foreach ($message_arr as $message) {
$message=str_ireplace("*push_token*", '"'.$testPushMsgSample->hw_push_token_key.'"',$message);
$testPushMsgSample->sendPushMsgRealMessage(json_decode($message));
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: two kinds of method to send topic msg: sendPushTopicMsgMessage for subscribe topic
* 1) sendPushMsgMessageByMsgType(code class object);
* 2) sendPushMsgRealMessage(text msg)
* 3) topic and condition not real time, maybe delay
*/
include_once (dirname(__FILE__) . '/push_common/test_sample_push_msg_common.php');
include_once (dirname(__FILE__) . '/../push_admin/Constants.php');
use push_admin\Constants;
$testPushMsgSample = new TestPushMsgCommon();
$topicSubscribeFlag = true;
$topic = '111';
//first time,must subscribe then could receive push msg;
if ($topicSubscribeFlag == false){
$testPushMsgSample->sendPushTopicMsgMessage($topic);
}
$testPushMsgSample->sendPushMsgMessageByMsgType(Constants::PUSHMSG_TOPIC_MSG_TYPE,$topic);
$message_arr = array('{
"data": "1111",
"android": {
"notification": {
"title": " topic1 default hw title topic ",
"body": " topic1 default hw body topic ",
"color": "#AACCDD",
"tag": "tagBoom",
"click_action": {
"type": 1,
"intent": "#Intent;compo=com.rvr\/.Activity;S.W=U;end",
"rich_resource": "test rich resource",
"action": "test add"
}
}
},
"topic": *topic*
}','{
"data": "1111",
"android": {
"notification": {
"title": " topic2 default hw title topic ",
"body": " topic2 default hw body topic ",
"click_action": {
"type": 1,
"intent": "#Intent;compo=com.rvr\/.Activity;S.W=U;end"
}
}
},
"topic": *topic*
}');
foreach ($message_arr as $message) {
$message=str_ireplace("*topic*", '"'.$topic.'"',$message);
$testPushMsgSample->sendPushMsgRealMessage(json_decode($message));
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: two kinds of method to send webpush msg:
* 1) sendPushMsgMessageByMsgType(code class object);
* 2) sendPushMsgRealMessage(text msg)
*/
include_once (dirname(__FILE__) . '/push_common/test_sample_push_msg_common.php');
include_once (dirname(__FILE__) . '/../push_admin/Constants.php');
use push_admin\Constants;
$testPushMsgSample = new TestPushMsgCommon();
$testPushMsgSample->sendPushMsgMessageByMsgType(Constants::WEB_PUSH_MSG_TYPE);
$message_arr = array('{
"token": [*push_token*],
"webpush": {
"headers": {
"ttl": "990",
"topic": "12313ceshi",
"urgency": "very-low"
},
"data": "test webpush data",
"notification": {
"title": "web2 push title test",
"body": "web2 push body",
"icon": "https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png",
"image": "https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png",
"lang": "string",
"tag": "string",
"badge": "string",
"dir": "auto",
"vibrate": [1,
2,
3],
"renotify": false,
"require_interaction": false,
"silent": false,
"timestamp": 1545201266,
"actions": [{
"title": "string",
"icon": "https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png",
"action": "123"
}]
},
"hms_options": {
"link": "https://www.cctv.com/"
}
}
}',
'{
"token": [*push_token*],
"webpush": {
"headers": {
"ttl": "11990",
"topic": "test",
"urgency": "low"
},
"data": "test webpush data",
"notification": {
"title": "hw default web push title test",
"body": "hw default web push body",
"require_interaction": false,
"silent": false,
"timestamp": 1545201266,
"actions": [{
"title": "string",
"icon": "https://developer-portalres-drcn.dbankcdn.com/system/modules/org.opencms.portal.template.core/resources/images/icon_Promotion.png",
"action": "123"
}]
},
"hms_options": {
"link": "https://www.huawei.com/"
}
}
}'
);
foreach ($message_arr as $message) {
$message=str_ireplace("*push_token*", '"'.$testPushMsgSample->webpush_push_token_key.'"',$message);
$testPushMsgSample->sendPushMsgRealMessage(json_decode($message));
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
include_once (dirname(__FILE__) . '/push_common/test_sample_push_msg_common.php');
include_once (dirname(__FILE__) . '/../push_admin/Constants.php');
use push_admin\Constants;
$testPushMsgSample = new TestPushMsgCommon();
$testPushMsgSample->sendPushMsgMessageByMsgType(Constants::PUSHMSG_NOTIFICATION_MSG_TYPE);
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: Application support ability of push msg:
* push_send_msg => push msg
* common_send_msg => topic msg
*/
namespace HwPush\push_admin;
include_once (dirname(__FILE__) . '/Constants.php');
include_once (dirname(__FILE__) . '/PushLogConfig.php');
class Application
{
private static $instance = null;
private $appid;
private $appsecret;
public $token_expiredtime;
private $access_token;
private $validate_only;
private $hw_token_server;
private $hw_push_server;
private $fields;
private function __clone(){}
public function __construct($appid='', $appsecret='', $hw_token_server='', $hw_push_server='')
{
if(empty($appid) || empty($appsecret || empty($hw_token_server) || empty($hw_push_server))){
$appid = \pushConfig::HW_APP_ID;
$appsecret = \pushConfig::HW_APP_SECRET;
$hw_token_server = \pushConfig::HW_APP_TOKEN_SERVER;
$hw_push_server = \pushConfig::HW_APP_OPEN_URL;
}
$this->appid = $appid;
$this->appsecret = $appsecret;
$this->hw_token_server = $hw_token_server;
$this->hw_push_server = $hw_push_server;
$this->token_expiredtime = null;
$this->accesstoken = null;
$this->validate_only = false; //是否是测试消息,如果是,则只会验证格式是否正确,如果false,则会推送
}
public static function getInstance()
{
//检测当前类属性$instance是否已经保存了当前类的实例
if (self::$instance == null) {
//如果没有,则创建当前类的实例
self::$instance = new self();
}
//如果已经有了当前类实例,就直接返回,不要重复创建类实例
return self::$instance;
}
public function appid($value)
{
$this->appid = $value;
}
public function appsecret($value)
{
$this->appsecret = $value;
}
public function validate_only($value)
{
$this->validate_only = $value;
}
public function getApplicationFields()
{
$keys = array(
'appid',
'appsecret',
'hw_token_server',
'hw_push_server',
'validate_only',
'accesstoken',
'token_expiredtime'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
return $this->fields;
}
private function printLogMethodOperate($dataFlow, $functionName = "", $logLevel = \HwPush\push_admin\Constants::HW_PUSH_LOG_INFO_LEVEL)
{
if (empty($functionName)) {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . $dataFlow, $logLevel);
} else {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . ']' . '[' . $functionName . ']' . $dataFlow, $logLevel);
}
}
private function is_token_expired()
{
if (empty($this->accesstoken)) {
return true;
}
if (time() > $this->token_expiredtime) {
return true;
}
return false;
}
/**
* @return 获取access_token;
*/
public function get_access_token(){
$data = unserialize(file_get_contents(dirname(dirname(__FILE__)).'/config.txt'));
if($data['expire_time']<time() || empty($data)){
return $this->refresh_token();
} else {
return $data['access_token'];
}
}
private function refresh_token()
{
$result = json_decode($this->curl_https_post($this->hw_token_server, http_build_query(array(
"grant_type" => "client_credentials",
"client_secret" => $this->appsecret,
"client_id" => $this->appid
)), array(
"Content-Type: application/x-www-form-urlencoded;charset=utf-8"
)));
// $this->printLogMethodOperate('refresh_token result:' . json_encode($result), __FUNCTION__ . ':' . __LINE__);
if ($result == null || ! array_key_exists("access_token", $result)) {
$this->printLogMethodOperate('refresh_token result error!', __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_ERROR_LEVEL);
return null;
}
//$this->printLogMethodOperate('refresh_token result:' . json_encode($result), __FUNCTION__ . ':' . __LINE__);
$this->access_token = $result->access_token;
$this->token_expiredtime = time() + $result->expires_in;
//文件存储
$data['access_token'] = $result->access_token;
$data['expire_time'] = time() + $result->expires_in;
file_put_contents(dirname(dirname(__FILE__)).'/config.txt', serialize($data));
return $this->access_token;
}
private function curl_https_post($url, $data = array(), $header = array())
{
// $this->printLogMethodOperate('curl_https_post enter url:' . $url, __FUNCTION__ . ':' . __LINE__);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$this->printLogMethodOperate('curl_https_post curl send headers:' . json_encode($header), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
// resolve SSL: no alternative certificate subject name matches target host name
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // check verify
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1); // regular post request
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post submit data
$this->printLogMethodOperate('curl_https_post curl send body:' . $data, __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
$ret = @curl_exec($ch);
if ($ret === false) {
return null;
}
$info = curl_getinfo($ch);
$this->printLogMethodOperate('curl_https_post curl send info:' . json_encode($info), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
curl_close($ch);
return $ret;
}
/**
* push_send_msg for push msg
*/
public function push_send_msg($msg)
{
$this->printLogMethodOperate('push_send_msg enter msg:' . json_encode($msg), __FUNCTION__ . ':' . __LINE__);
$body = array(
"validate_only" => $this->validate_only,
"message" => $msg
);
$this->printLogMethodOperate('push_send_msg new body:' . json_encode($body), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if ($this->is_token_expired()) {
$this->refresh_token();
}
if (empty($this->accesstoken)){
$this->printLogMethodOperate("accesstoken is empty!",
__FUNCTION__ . ':' . __LINE__,Constants::HW_PUSH_LOG_ERROR_LEVEL);
return null;
}
$result = json_decode($this->curl_https_post(str_replace('{appid}', $this->appid, $this->hw_push_server), json_encode($body), array(
"Content-Type: application/json",
"Authorization: Bearer {$this->accesstoken}"
) // Use bearer auth
));
$this->printLogMethodOperate("push_send_msg leave,result:" . json_encode($result), __FUNCTION__ . ':' . __LINE__);
// $result ==> eg: {"code":"80000000","msg":"Success","requestId":"157278422841836431010901"}
if (! empty($result)) {
$arrResult = json_decode(json_encode($result), true);
if (!empty($arrResult["code"]) && !in_array($arrResult["code"], array( "80000000",80000000))) {
$this->printLogMethodOperate("push_send_msg leave,result:" . json_encode($result), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_WARN_LEVEL);
}
}
return $result;
}
/**
* common_send_msg for topic msg/other
*/
public function common_send_msg($msg)
{
$this->printLogMethodOperate('common_send_msg enter msg:' . json_encode($msg), __FUNCTION__ . ':' . __LINE__);
if ($this->is_token_expired()) {
$this->refresh_token();
}
if (empty($this->accesstoken)){
$this->printLogMethodOperate("accesstoken is empty!",
__FUNCTION__ . ':' . __LINE__,Constants::HW_PUSH_LOG_ERROR_LEVEL);
return null;
}
$result = json_decode($this->curl_https_post(str_replace('{appid}', $this->appid, $this->hw_push_server), json_encode($msg), array(
"Content-Type: application/json",
"Authorization: Bearer {$this->accesstoken}"
) // Use bearer auth
));
// $result ==> eg: {"code":"80000000","msg":"Success","requestId":"157278422841836431010901"}
$this->printLogMethodOperate('common_send_msg leave result:' . json_encode($result), __FUNCTION__ . ':' . __LINE__);
if (! empty($result)) {
$arrResult = json_decode(json_encode($result), true);
if (isset($arrResult["code"]) && $arrResult["code"] != "80000000") {
$this->printLogMethodOperate("push_send_msg leave,result:" . json_encode($result), __FUNCTION__ . ':' . __LINE__, Constants::HW_PUSH_LOG_WARN_LEVEL);
}
}
return $result;
}
public function getUrl(){
return $url= "https://push-api.cloud.huawei.com/v1/".$this->appid."/messages:send";
}
public function pushMsg($title,$body,$device_token){
$url = $this->getUrl();
//$headerArray = array("Authorization:Bearer ".$this->get_access_token());
$headerArray = array("Authorization:Bearer ".$this->refresh_token());//正式的时候需要用缓存的access_token;
$data ='{
"validate_only": false,
"message": {
"notification": {
"title": "'.$title.'",
"body": "'.$body.'",
"image": "https://001.ruer.coboriel.com/notice.png"
},
"android": {
"notification": {
"click_action": {
"type": 3
},
"vibrate_config": [
"1",
"3"
]
}
},
"token":
'.$device_token.'
}
}';
return $res = $this->curl_https_post($url,$data,$headerArray);
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: const variables
*/
namespace HwPush\push_admin;
class Constants
{
/**
* push_msg
*/
const WEBPUSH_URGENCY_VERY_LOW = "very-low";
const WEBPUSH_URGENCY_LOW = "low";
const WEBPUSH_URGENCY_NORMAL = "normal";
const WEBPUSH_URGENCY_HIGH = "high";
/*
* Notification Type
*/
const PUSHMSG_NOTIFICATION_MSG_TYPE = 1;
const PUSHMSG_PASS_THROUGHT_MSG_TYPE = 2;
const PUSHMSG_TOPIC_MSG_TYPE = 3;
const PUSHMSG_CONDITION_MSG_TYPE = 4;
const PUSHMSG_FASTAPP_MSG_TYPE = 5;
const APN_MSG_TYPE = 6;
const WEB_PUSH_MSG_TYPE = 7;
const TOPIC_SUBSCRIBE_MSG_TYPE = 8;
const TOPIC_UNSUBSCRIBE_MSG_TYPE = 9;
const TOPIC_SUBSCRIBE_QUERY_MSG_TYPE = 10;
/**
* log
*/
const HW_PUSH_LOG_PUSH_MSG_MODULE = "PushMsg";
const HW_PUSH_LOG_TOPIC_SUBSCRIBE_MODULE = "TopicSubsScribe";
const HW_PUSH_LOG_TOPIC_UNSUBSCRIBE_MODULE = "TopicUnSubsScribe";
const HW_PUSH_LOG_DEBUG_LEVEL = 4;
const HW_PUSH_LOG_INFO_LEVEL = 3;
const HW_PUSH_LOG_WARN_LEVEL = 2;
const HW_PUSH_LOG_ERROR_LEVEL = 1;
const HW_PUSH_LOG_FILE_NAME = 'push.log';
const URL_PATTERN = "/^https.*/";
const VIBRATE_PATTERN = "/[0-9]+|[0-9]+[sS]|[0-9]+[.][0-9]{1,9}|[0-9]+[.][0-9]{1,9}[sS]/";
const COLOR_PATTERN = "/^#[0-9a-fA-F]{6}$/";
const TTL_PATTERN = "/\\d+|\\d+[sS]|\\d+.\\d{1,9}|\\d+.\\d{1,9}[sS]/";
const APN_AUTHORIZATION_PATTERN = "/^bearer*/";
const APN_ID_PATTERN = "/[0-9a-z]{8}(-[0-9a-z]{4}){3}-[0-9a-z]{12}/";
}
class Visibility {
const VISIBILITY_UNSPECIFIED= "VISIBILITY_UNSPECIFIED";
const PRIVATE_STR="PRIVATE";
const PUBLIC_STR="PUBLIC";
const SECRET_STR="SECRET";
}
class NotificationPriority {
const NOTIFICATION_PRIORITY_LOW = 'LOW';
const NOTIFICATION_PRIORITY_NORMAL = 'NORMAL';
const NOTIFICATION_PRIORITY_HIGH = 'HIGH';
}
class AndroidConfigDeliveryPriority{
const PRIORITY_HIGH = 'HIGH';
const PRIORITY_NORMAL = 'NORMAL';
}
class ApnConstant{
//APN PRIORITY
const ANP_PRIORITY_SEND_IMMEDIATELY = "10";
const ANP_PRIORITY_SEND_BY_GROUP = "5";
//APN TARGET USER
const APN_TARGET_USER_TEST_USER = 1;
const APN_TARGET_USER_FORMAL_USER = 2;
const APN_TARGET_USER_VOIP_USER = 3;
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: read config file and make it applicaitonable
*/
namespace HwPush\push_admin;
class PushConfig
{
// ORDINAL APP
public $HW_APPID;
public $HW_APPSECRET;
public $HW_PUSH_TOKEN_ARR;
public $APN_PUSH_TOKEN_ARR;
public $WEBPUSH_PUSH_TOKEN_ARR;
// FAST APP
public $HW_FAST_APPID;
public $HW_FAST_APPSECRET;
public $HW_FAST_PUSH_TOKEN;
public $HW_TOKEN_SERVER;
public $HW_PUSH_SERVER;
public $HW_TOPIC_SUBSCRIBE_SERVER;
public $HW_TOPIC_UNSUBSCRIBE_SERVER;
public $HW_TOPIC_QUERY_SUBSCRIBER_SERVER;
public $HW_DEFAULT_LOG_LEVEL = 3;
private $log_read_flag = true; //false,是否记入日志
private function __construct()
{
if ($this->log_read_flag == false) {
$file_path = "../config.ini";
if (file_exists($file_path)) {
$file_contents = file($file_path);
// read line
for ($i = 0; $i < count($file_contents); $i ++) {
$this->processConfigData($file_contents[$i]);
}
$this->log_read_flag = true;
} else {
echo $file_path . " not exist,please config first!!!<br>";
}
}
}
public static function getSingleInstance()
{
static $obj;
if (! isset($obj)) {
$obj = new PushConfig();
}
return $obj;
}
private function processConfigData($lineData)
{
if (empty($lineData)) {
return;
}
if (strncmp($lineData, "#", 1) == 0) {
return;
}
$lineData = str_replace("\"", "", $lineData);
$lineData = str_replace("\'", "", $lineData);
$lineData = str_replace(" ", "", $lineData);
$lineData = str_replace(";", "", $lineData);
$order=array("\r\n","\n","\r");
$lineData=str_replace($order,"",$lineData);
$lineData = str_replace(PHP_EOL, '', $lineData);
$resultPos = stripos($lineData, "=");
if (FALSE == $resultPos) {
return;
}
$key = substr($lineData, 0, $resultPos);
if (FALSE == $key) {
return;
}
$value = $this->processConfigValueData(substr($lineData, $resultPos + 1));
switch ($key) {
case "HW_APPID":
{
$this->HW_APPID = $value;
}
break;
case "HW_APPSECRET":
{
$this->HW_APPSECRET = $value;
}
break;
case "HW_TOKEN_SERVER":
{
$this->HW_TOKEN_SERVER = $value;
}
break;
case "HW_PUSH_SERVER":
{
$this->HW_PUSH_SERVER = $value;
}
break;
case "HW_TOPIC_SUBSCRIBE_SERVER":
{
$this->HW_TOPIC_SUBSCRIBE_SERVER = $value;
}
break;
case "HW_TOPIC_UNSUBSCRIBE_SERVER":
{
$this->HW_TOPIC_UNSUBSCRIBE_SERVER = $value;
}
break;
case "HW_TOPIC_QUERY_SUBSCRIBER_SERVER":
{
$this->HW_TOPIC_QUERY_SUBSCRIBER_SERVER = $value;
}
break;
case "HW_PUSH_TOKEN_ARR":
{
$this->HW_PUSH_TOKEN_ARR = $value;
}
break;
case "APN_PUSH_TOKEN_ARR":
{
$this->APN_PUSH_TOKEN_ARR = $value;
}
break;
case "WEBPUSH_PUSH_TOKEN_ARR":
{
$this->WEBPUSH_PUSH_TOKEN_ARR = $value;
}
break;
case "HW_DEFAULT_LOG_LEVEL":
{
$this->HW_DEFAULT_LOG_LEVEL = $value;
}
break;
case "HW_FAST_APPID":
{
$this->HW_FAST_APPID = $value;
}
break;
case "HW_FAST_APPSECRET":
{
$this->HW_FAST_APPSECRET = $value;
}
break;
case "HW_FAST_PUSH_TOKEN":
{
$this->HW_FAST_PUSH_TOKEN = $value;
}
break;
}
}
private function processConfigValueData($lineDataMapValue)
{
$key = stripos($lineDataMapValue, "\"");
if (FALSE == $key) {
return $lineDataMapValue;
}
if ($key > 0) {
return str_replace("\"", "", substr($lineDataMapValue, $key));
}
return $lineDataMapValue;
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace HwPush\push_admin;
include_once (dirname(__FILE__) . '/Constants.php');
include_once (dirname(__FILE__) . '/PushConfig.php');
use Exception;
class PushLogConfig
{
private $LogFile;
private $logBanner = "
___ ___ __ __ __________ ____ ___ _________ ___ ___ __________ ___ _____________
/ | \/ \ / \ \______ \ | \/ _____// | \ \______ \/ | \______ \
/ ~ \ \/\/ / | ___/ | /\_____ \/ ~ \ | ___/ ~ \ ___/
\ Y /\ / | | | | / / \ Y / | | \ Y / |
\___|_ / \__/\ / |____| |______/ /_______ /\___|_ / |____| \___|_ /|____|
\/ \/ \/ \/ \/
";
private $LOG_MODULE_FIXED_LEN = 20;
private $default_log_level = Constants::HW_PUSH_LOG_INFO_LEVEL;
private function __construct()
{
$this->LogFile = @fopen(Constants::HW_PUSH_LOG_FILE_NAME, 'a+');
if (! is_resource($this->LogFile)) {
throw new Exception(Constants::HW_PUSH_LOG_FILE_NAME . 'invalid file Stream');
}
fwrite($this->LogFile, $this->logBanner);
$pushConfig = PushConfig::getSingleInstance();
$this->default_log_level = $pushConfig->HW_DEFAULT_LOG_LEVEL;
if (empty($this->default_log_level)){
$this->default_log_level = Constants::HW_PUSH_LOG_INFO_LEVEL;
}
}
/**
* single instance
*/
public static function getSingleInstance()
{
static $obj;
if (! isset($obj)) {
$obj = new PushLogConfig();
}
return $obj;
}
/**
* core log process
*/
public function LogMessage($msg, $logLevel = Constants::HW_PUSH_LOG_INFO_LEVEL, $module = null, $timeZone = 'Asia/shanghai', $timeFormat = "%Y-%m-%d %H:%M:%S")
{
if (empty($logLevel)) {
$logLevel = Constants::HW_PUSH_LOG_INFO_LEVEL;
}
if ($logLevel > $this->default_log_level) {
return;
}
date_default_timezone_set($timeZone);
$time = strftime($timeFormat, time());
$msg = str_replace("\t", '', $msg);
$msg = str_replace("\n", '', $msg);
$strLogLevel = $this->levelToString($logLevel);
if (isset($module)) {
$module = '[' . str_pad(str_replace(array(
"\n",
"\t"
), array(
"",
""
), $module), $this->LOG_MODULE_FIXED_LEN) . ']';
$logLine = "$time\t$strLogLevel\t$module\t$msg\r\n";
} else {
$logLine = "$time\t$strLogLevel\t$msg\r\n";
}
print_r($logLine . '<br>');
fwrite($this->LogFile, $logLine);
}
private function levelToString($logLevel)
{
$ret = 'LOG::UNKNOWN';
switch ($logLevel) {
case Constants::HW_PUSH_LOG_DEBUG_LEVEL:
$ret = 'LOG::DEBUG';
break;
case Constants::HW_PUSH_LOG_INFO_LEVEL:
$ret = 'LOG::INFO';
break;
case Constants::HW_PUSH_LOG_WARN_LEVEL:
$ret = 'LOG::WARNING';
break;
case Constants::HW_PUSH_LOG_ERROR_LEVEL:
$ret = 'LOG::ERROR';
break;
}
return $ret;
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: push message push control parameter:
* 5 kinds of msg payload:$data,$notification,$android,$apns,$webpush
* 3 kinds of Message sending object:$token,$topic,$condition
*/
namespace push_admin\push_msg;
class PushMessage
{
private $data;
private $notification;
private $android;
private $apns;
private $webpush;
private $token;
private $topic;
private $condition;
private $fields;
public function __construct()
{
$this->fields = array();
$this->token = null;
$this->condition = null;
$this->topic = null;
$this->notification = null;
}
public function data($value)
{
$this->data = $value;
}
public function notification($value)
{
$this->notification = $value;
}
public function android($value)
{
$this->android = $value;
}
public function token($value)
{
$this->token = $value;
}
public function get_token(){
return $this->token;
}
public function topic($value)
{
$this->topic = $value;
}
public function condition($value)
{
$this->condition = $value;
}
public function apns($value)
{
$this->apns = $value;
}
public function webpush($value)
{
$this->webpush = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
$keys = array(
'data',
'notification',
'android',
'token',
'topic',
'condition',
'apns',
'webpush'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace push_admin;
class ValidatorUtil{
function validatePattern($pattern,$value){
$result = preg_match($pattern, $value);
if (1 == $result){
return TRUE;
}
return FALSE;
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace push_admin\push_msg\android;
include_once (dirname(__FILE__) . '/../../Constants.php');
include_once (dirname(__FILE__) . '/../ValidatorUtil.php');
use push_admin\ValidatorUtil;
use push_admin\Constants;
use push_admin\AndroidConfigDeliveryPriority;
use Exception;
use push_admin\PushLogConfig;
class AndroidConfig
{
private $collapse_key;
private $category;
private $urgency;
private $ttl;
private $bi_tag;
private $fast_app_target;
private $notification;
private $fields;
private $data;
public function __construct()
{
$this->urgency = null;
$this->notification = null;
$this->fields = array();
}
public function getFields()
{
return $this->fields;
}
public function collapse_key($value)
{
$this->collapse_key = $value;
}
public function category($value)
{
$this->category = $value;
}
public function urgency($value)
{
$this->urgency = $value;
}
public function ttl($value)
{
$this->ttl = $value;
}
public function bi_tag($value)
{
$this->bi_tag = $value;
}
public function fast_app_target($value)
{
$this->fast_app_target = $value;
}
public function notification($value)
{
$this->notification = $value;
}
public function data($value)
{
$this->data = $value;
}
public function buildFields()
{
try {
$this->check_parameter();
} catch (Exception $e) {
// echo $e;
PushLogConfig::getSingleInstance()->LogMessage($e,Constants::HW_PUSH_LOG_ERROR_LEVEL);
return;
}
$keys = array(
'collapse_key',
'category',
'urgency',
'ttl',
'bi_tag',
'fast_app_target',
'notification',
'data'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter()
{
if (! empty($this->collapse_key) && ($this->collapse_key < - 1 || $this->collapse_key > 100)) {
throw new Exception("Collapse Key should be [-1, 100]");
}
if (! empty($this->fast_app_target) && ! in_array($this->fast_app_target, array(
1,
2
))) {
throw new Exception("Invalid fast app target type[one of 1 or 2]");
}
if (! empty($this->urgency) && ! in_array($this->urgency, array(
AndroidConfigDeliveryPriority::PRIORITY_HIGH,
AndroidConfigDeliveryPriority::PRIORITY_NORMAL
))) {
throw new Exception("delivery priority shouid be [HIGH, NOMAL]");
}
if (! empty($this->ttl)) {
if (FALSE == ValidatorUtil::validatePattern(Constants::TTL_PATTERN, $this->ttl)) {
throw new Exception("The TTL's format is wrong");
}
}
}
public function get_all_vars()
{
var_dump(get_object_vars($this));
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace push_admin\push_msg\android;
include_once (dirname(__FILE__) . '/../../Constants.php');
include_once (dirname(__FILE__) . '/../ValidatorUtil.php');
use push_admin\ValidatorUtil;
use push_admin\Constants;
use push_admin\NotificationPriority;
use push_admin\Visibility;
use Exception;
use push_admin\PushLogConfig;
/**
* optional for android config
*/
class AndroidNotification
{
private $title;
private $body;
private $icon;
private $color;
private $sound;
private $tag;
private $click_action;
private $body_loc_key;
private $body_loc_args;
private $title_loc_key;
private $title_loc_args;
private $channel_id;
private $notify_summary;
private $image;
private $notify_icon;
/**
* notification style:
* 0:default
* 1:big text
* 2:big photo
*/
private $style;
private $big_title;
private $big_body;
private $auto_clear;
private $notify_id;
private $group;
private $badge;
private $ticker;
private $auto_cancel;
private $when;
private $importance;
private $use_default_vibrate;
private $use_default_light;
private $vibrate_config;
private $visibility;
private $light_settings;
private $foreground_show;
private $fields;
public function __construct()
{
$this->click_action = array();
$this->body_loc_args = array();
$this->title_loc_args = array();
$this->badge = array();
$this->light_settings = array();
$this->foreground_show = true;
$this->fields = array();
}
public function title($value)
{
$this->title = $value;
}
public function body($value)
{
$this->body = $value;
}
public function icon($value)
{
$this->icon = $value;
}
public function color($value)
{
$this->color = $value;
}
public function sound($value)
{
$this->sound = $value;
}
public function tag($value)
{
$this->tag = $value;
}
public function click_action($value)
{
$this->click_action = $value;
}
public function body_loc_key($value)
{
$this->body_loc_key = $value;
}
public function body_loc_args($value)
{
$this->body_loc_args = $value;
}
public function title_loc_key($value)
{
$this->title_loc_key = $value;
}
public function title_loc_args($value)
{
$this->title_loc_args = $value;
}
public function channel_id($value)
{
$this->channel_id = $value;
}
public function notify_summary($value)
{
$this->notify_summary = $value;
}
// added
public function image($value)
{
$this->image = $value;
}
public function notify_icon($value)
{
$this->notify_icon = $value;
}
public function style($value)
{
$this->style = $value;
}
public function big_title($value)
{
$this->big_title = $value;
}
public function big_body($value)
{
$this->big_body = $value;
}
public function auto_clear($value)
{
$this->auto_clear = $value;
}
public function notify_id($value)
{
$this->notify_id = $value;
}
public function group($value)
{
$this->group = $value;
}
public function badge($value)
{
$this->badge = $value;
}
public function ticker($value)
{
$this->ticker = $value;
}
public function auto_cancel($value)
{
$this->auto_cancel = $value;
}
public function when($value)
{
$this->when = $value;
}
public function importance($value)
{
$this->importance = $value;
}
public function use_default_vibrate($value)
{
$this->use_default_vibrate = $value;
}
public function use_default_light($value)
{
$this->use_default_light = $value;
}
public function vibrate_config($value)
{
$this->vibrate_config = $value;
}
public function visibility($value)
{
$this->visibility = $value;
}
public function light_settings($value)
{
$this->light_settings = $value;
}
public function foreground_show($value)
{
$this->foreground_show = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
try {
$this->check_parameter();
} catch (Exception $e) {
PushLogConfig::getSingleInstance()->LogMessage($e,Constants::HW_PUSH_LOG_ERROR_LEVEL);
return;
}
$keys = array(
'title',
'body',
'image',
'icon',
'color',
'sound',
'tag',
'click_action',
'body_loc_key',
'body_loc_args',
'title_loc_key',
'title_loc_args',
'channel_id',
'notify_summary',
'notify_icon',
'style',
'big_title',
'big_body',
'auto_clear',
'notify_id',
'group',
'badge',
'ticker',
'auto_cancel',
'when',
'importance',
'use_default_vibrate',
'use_default_light',
'vibrate_config',
'visibility',
'light_settings',
'foreground_show'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter()
{
if (empty($this->title))
{
throw new Exception("title should be set");
}
if (empty($this->body))
{
throw new Exception("body should be set");
}
if (! empty($this->color)) {
if (FALSE == ValidatorUtil::validatePattern(Constants::COLOR_PATTERN, $this->color)) {
throw new Exception("Wrong color format, color must be in the form #RRGGBB");
}
}
if (! empty($this->body_loc_args) && empty($this->body_loc_key)) {
throw new Exception("bodyLocKey is required when specifying bodyLocArgs");
}
if (! empty($this->title_loc_args) && empty($this->title_loc_key)) {
throw new Exception("titleLocKey is required when specifying titleLocArgs");
}
if (! empty($this->image)) {
if (FALSE == ValidatorUtil::validatePattern(Constants::URL_PATTERN, $this->image)) {
throw new Exception("notifyIcon must start with https");
}
}
if (($this->style) && (gettype($this->style) != "integer")) {
throw new Exception("type of style is wrong.");
}
if (! in_array($this->style, array(
0,
1
))) {
throw new Exception("style should be one of 0:default, 1: big text");
}
// importance
if (! empty($this->importance) && ! in_array($this->importance, array(
NotificationPriority::NOTIFICATION_PRIORITY_LOW,
NotificationPriority::NOTIFICATION_PRIORITY_NORMAL,
NotificationPriority::NOTIFICATION_PRIORITY_HIGH,
))) {
throw new Exception("notification priority shouid be [LOW,NORMAL,HIGH]");
}
// vibrate_config
if (! empty($this->vibrate_config)) {
foreach ($this->vibrate_config as $key) {
if (FALSE == ValidatorUtil::validatePattern(Constants::VIBRATE_PATTERN, $key)) {
throw new Exception("Wrong vibrate timing format");
}
}
}
// visibility
if (! empty($this->visibility) && ! in_array($this->visibility, array(
Visibility::VISIBILITY_UNSPECIFIED,
Visibility::PRIVATE_STR,
Visibility::PUBLIC_STR,
Visibility::SECRET_STR
))) {
throw new Exception("visibility shouid be [VISIBILITY_UNSPECIFIED, PRIVATE, PUBLIC, SECRET]");
}
// auto_clear
if (($this->auto_clear) && (gettype($this->auto_clear) != "integer")) {
throw new Exception("type of auto_clear is wrong.");
}
// notify_id
if (($this->notify_id) && (gettype($this->notify_id) != "integer")) {
throw new Exception("type of notify_id is wrong.");
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: Badge class =>AndroidNotification(badge)
* =>AndroidConfig(notification)
* =>PushMessage(android)
*/
namespace push_admin\push_msg\android;
use Exception;
class Badge
{
private $add_num;
private $class;
private $set_num;
private $fields;
public function __construct()
{
$this->fields = array();
}
public function add_num($value)
{
$this->add_num = $value;
}
public function setclass($value)
{
$this->class = $value;
}
public function set_num($value)
{
$this->set_num = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
try {
$this->check_parameter();
} catch (Exception $e) {
echo $e;
}
$keys = array(
'add_num',
'class',
'set_num'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter()
{
if (($this->add_num) && (gettype($this->add_num) != "integer")) {
throw new Exception("type of add_num is wrong.");
}
if (is_int($this->add_num) && ($this->add_num < 1 || $this->add_num > 100)) {
throw new Exception("add_num should locate between 0 and 100");
}
if (($this->set_num) && (gettype($this->set_num) != "integer")) {
throw new Exception("type of set_num is wrong.");
}
if (is_int($this->set_num) && ($this->set_num < 1 || $this->set_num > 100)) {
throw new Exception("set_num should locate between 0 and 100");
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: ClickAction class =>AndroidNotification(clickaction)
* =>AndroidConfig(notification)
* =>PushMessage(android)
*/
namespace push_admin\push_msg\android;
include_once (dirname(__FILE__) . '/../ValidatorUtil.php');
use push_admin\ValidatorUtil;
use Exception;
class ClickAction
{
private $type;
private $intent;
private $url;
private $rich_resource;
// added
private $action;
private $fields;
public function __construct()
{
$this->rich_resource = null;
$this->url = null;
}
public function type($value)
{
$this->type = $value;
}
public function intent($value)
{
$this->intent = $value;
}
public function url($value)
{
$this->url = $value;
}
public function rich_resource($value)
{
$this->rich_resource = $value;
}
// added
public function action($value)
{
$this->action = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
try {
$this->check_parameter();
} catch (Exception $e) {
echo $e;
}
$keys = array(
'type',
'intent',
'url',
'rich_resource',
// add
'action'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter()
{
if (($this->type) && (gettype($this->type) != "integer")) {
throw new Exception("type of type is wrong.");
}
if (!in_array($this->type, array(1,2,3,4))){
throw new Exception("click type should be one of 1: customize action, 2: open url, 3: open app, 4: open rich media");
}
$PATTERN = "/^https.*/";
switch($this->type){
case 1:{
if (is_null($this->intent) && is_null($this->action)) {
throw new Exception("when type=1,intent/action at least one is valid");
}
}
break;
case 2:{
if (is_null($this->url)){
throw new Exception("url is required when click type=2");
}
if (FALSE == ValidatorUtil::validatePattern($PATTERN,$this->url)){
throw new Exception("url must start with https");
}
}
break;
case 4:{
if (is_null($this->richResource)){
throw new Exception("richResource is required when click type=4");
}
if (FALSE == ValidatorUtil::validatePattern($PATTERN,$this->richResource)){
throw new Exception("richResource must start with https");
}
}
break;
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: LightSetting class =>AndroidNotification(light_setting)
* =>AndroidConfig(notification)
* =>PushMessage(android)
*/
namespace push_admin\push_msg\android;
include_once (dirname(__FILE__) . '/../ValidatorUtil.php');
use push_admin\ValidatorUtil;
use Exception;
class LightSetting
{
private $color;
private $light_on_duration;
private $light_off_duration;
private $fields;
public function __construct()
{
$this->color = array();
$this->fields = array();
}
public function color($value)
{
$this->color = $value;
}
public function light_on_duration($value)
{
$this->light_on_duration = $value;
}
public function light_off_duration($value)
{
$this->light_off_duration = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
try {
$this->check_parameter();
} catch (Exception $e) {
echo $e;
}
$keys = array(
'color',
'light_on_duration',
'light_off_duration'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter()
{
if (empty($this->color)){
throw new Exception("color must be selected when light_settings is set");
}
if (empty($this->light_on_duration)){
throw new Exception("light_on_duration must be selected when light_settings is set");
}
if (empty($this->light_off_duration)){
throw new Exception("light_off_duration must be selected when light_settings is set");
}
$LIGTH_DURATION_PATTERN = "/\\d+|\\d+[sS]|\\d+.\\d{1,9}|\\d+.\\d{1,9}[sS]/";
if ( FALSE == ValidatorUtil::validatePattern($LIGTH_DURATION_PATTERN,$this->light_on_duration)) {
throw new Exception("light_on_duration format is wrong");
}
if (FALSE == ValidatorUtil::validatePattern($LIGTH_DURATION_PATTERN,$this->light_off_duration) ) {
throw new Exception("light_off_duration format is wrong");
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: LightSettingColor =>LightSetting(color)
* =>AndroidNotification(light_setting)
* =>AndroidConfig(notification)
* =>PushMessage(android)
*/
namespace push_admin\push_msg\android;
use Exception;
class LightSettingColor
{
private $alpha;
private $red;
private $green;
private $blue;
private $fields;
public function __construct()
{
$this->alpha = 1;
$this->red = 0;
$this->green = 0;
$this->blue = 0;
$this->fields = array();
}
public function setgenFullcolor($alpha, $red, $green, $blue)
{
$this->alpha = $alpha;
$this->red = $red;
$this->green = $green;
$this->blue = $blue;
}
public function alpha($value)
{
$this->alpha = $value;
}
public function red($value)
{
$this->red = $value;
}
public function green($value)
{
$this->green = $value;
}
public function blue($value)
{
$this->blue = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
try {
$this->check_parameter();
} catch (Exception $e) {
echo $e;
}
$keys = array(
'alpha',
'red',
'green',
'blue'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter()
{
if (empty($this->alpha) && (gettype($this->alpha) != "integer")) {
throw new Exception("type of alpha is wrong.");
}
if (empty($this->red) && (gettype($this->red) != "integer")) {
throw new Exception("type of red is wrong.");
}
if (empty($this->green) && (gettype($this->green) != "integer")) {
throw new Exception("type of green is wrong.");
}
if (empty($this->blue) && (gettype($this->blue) != "integer")) {
throw new Exception("type of blue is wrong.");
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: Alert => =>PushMessage(apns) for ios channel
*/
namespace push_admin\push_msg\apns;
include_once (dirname(__FILE__) . '/../../../push_admin/PushLogConfig.php');
use push_admin\PushLogConfig;
use push_admin\Constants;
class Alert {
private $title;
private $body;
private $title_loc_key;
private $title_loc_args;
private $action_loc_key;
private $loc_key;
private $loc_args;
private $launch_image;
private $fields;
public function title($value) {
$this->title = $value;
}
public function body($value) {
$this->body = $value;
}
public function title_loc_key($value) {
$this->title_loc_key = $value;
}
public function title_loc_args($value) {
$this->title_loc_args = $value;
}
public function action_loc_key($value) {
$this->action_loc_key = $value;
}
public function loc_key($value) {
$this->loc_key = $value;
}
public function loc_args($value) {
$this->loc_args = $value;
}
public function launch_image($value) {
$this->launch_image = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
$keys = array(
'title',
'body',
'title-loc-key',
'title-loc-args',
'action-loc-key',
'loc-key',
'loc-args',
'launch-image'
);
foreach ($keys as $key) {
$value = str_replace('-', '_', $key);
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][before key:' . $key . '][after key:' . $value . ']', Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (isset($this->$value)) {
$this->fields[$key] = $this->$value;
}
}
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][buildFields result:' . json_encode($this->fields), Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: ApnsConfig => =>PushMessage(apns) for ios channel
*/
namespace push_admin\push_msg\apns;
include_once (dirname(__FILE__) . '/../../../push_admin/PushLogConfig.php');
use push_admin\PushLogConfig;
use push_admin\Constants;
class ApnsConfig
{
private $payload;
private $headers;
private $hms_options;
private $fields;
public function __construct()
{
$this->fields = array();
}
public function payload($value)
{
$this->payload = $value;
}
public function headers($value)
{
$this->headers = $value;
}
public function hms_options($value)
{
$this->hms_options = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
$keys = array(
'headers',
'hms_options',
'payload'
);
foreach ($keys as $key) {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][key:' . $key . '][value:' . json_encode($this->$key) . ']', Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][buildFields result:' . json_encode($this->fields), Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace push_admin\push_msg\apns;
include_once (dirname(__FILE__) . '/../ValidatorUtil.php');
include_once (dirname(__FILE__) . '/../../../push_admin/PushLogConfig.php');
use Exception;
use push_admin\ValidatorUtil;
use push_admin\Constants;
use push_admin\ApnConstant;
use push_admin\PushLogConfig;
class ApnsHeaders
{
private $authorization;
private $apns_id;
private $apns_expiration;
private $apns_priority;
private $apns_topic;
private $apns_collapse_id;
private $fields;
public function authorization($value)
{
$this->authorization = $value;
}
public function apns_id($value)
{
$this->apns_id = $value;
}
public function apns_expiration($value)
{
$this->apns_expiration = $value;
}
public function apns_priority($value)
{
$this->apns_priority = $value;
}
public function apns_topic($value)
{
$this->apns_topic = $value;
}
public function apns_collapse_id($value)
{
$this->apns_collapse_id = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
try {
$this->check_parameter();
} catch (Exception $e) {
echo $e;
}
$keys = array(
'authorization',
'apns-id',
'apns-expiration',
'apns-priority',
'apns-topic',
'apns-collapse-id'
);
foreach ($keys as $key) {
$value = str_replace('-', '_', $key);
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][before key:' . $key . '][after key:' . $value . ']', Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (isset($this->$value)) {
$this->fields[$key] = $this->$value;
}
}
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][buildFields result:' . json_encode($this->fields), Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
private function check_parameter()
{
if (! empty($this->authorization)) {
if (FALSE == ValidatorUtil::validatePattern(Constants::APN_AUTHORIZATION_PATTERN, $this->authorization)) {
throw new Exception("authorization must start with bearer");
}
}
if (! empty($this->apns_id)) {
if (FALSE == ValidatorUtil::validatePattern(Constants::APN_ID_PATTERN, $this->apns_id)) {
throw new Exception("apns-id format error");
}
}
if (! empty($this->apns_priority)) {
if (! in_array($this->apns_priority, array(
ApnConstant::ANP_PRIORITY_SEND_BY_GROUP,
ApnConstant::ANP_PRIORITY_SEND_IMMEDIATELY
))) {
throw new Exception("apns-priority should be SEND_BY_GROUP:5 or SEND_IMMEDIATELY:10");
}
}
if (! empty($this->apns_collapse_id)) {
if (strlen($this->apns_priority) >= 64) {
throw new Exception("Number of apnsCollapseId bytes should be less than 64");
}
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace push_admin\push_msg\apns;
use Exception;
class ApnsHmsOptions {
private $target_user_type;
public function getFields()
{
return $this->fields;
}
public function target_user_type($value)
{
$this->target_user_type = $value;
}
public function buildFields()
{
try {
$this->check_parameter();
} catch (Exception $e) {
echo $e;
}
$keys = array(
'target_user_type'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter()
{
if (!empty($this->target_user_type)
&& !in_array($this->target_user_type,array(1,2,3))) {
throw new Exception("target_user_type range TEST_USER:1,FORMAL_USER:2,VOIP_USER:3");
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
namespace push_admin\push_msg\apns;
include_once (dirname(__FILE__) . '/../../../push_admin/PushLogConfig.php');
use push_admin\PushLogConfig;
use push_admin\Constants;
class Aps {
private $alert;
private $badge;
private $sound;
private $content_available;
private $category;
private $thread_id;
private $fields;
public function alert($value) {
$this->alert = $value;
}
public function badge($value) {
$this->badge = $value;
}
public function sound($value) {
$this->sound = $value;
}
public function content_available($value) {
$this->content_available = $value;
}
public function category($value) {
$this->category = $value;
}
public function thread_id($value) {
$this->thread_id = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
$keys = array(
'alert',
'badge',
'sound',
'content-available',
'category',
'thread-id'
);
foreach ($keys as $key) {
$value = str_replace('-', '_', $key);
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][before key:' . $key . '][after key:' . $value . ']', Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (isset($this->$value)) {
$this->fields[$key] = $this->$value;
}
}
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][buildFields result:' . json_encode($this->fields), Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: ApnsConfig => =>PushMessage(apns) for ios channel
*/
namespace push_admin\push_msg\instanceapp;
include_once (dirname(__FILE__) . '/../../../push_admin/PushLogConfig.php');
use push_admin\PushLogConfig;
use push_admin\Constants;
class InstanceAppConfig
{
//push_type 0:notification;1,pass-through
private $pushtype;
private $pushbody;
private $fields;
public function __construct()
{
}
public function pushtype($value)
{
$this->pushtype = $value;
}
public function pushbody($value)
{
$this->pushbody = $value;
}
public function getFields()
{
$result = "{";
foreach ($this->fields as $key=>$value) {
$result = $result .$key.":".json_encode($value).",";
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][result:' .$result, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
if (strlen($result) > 1){
$result = rtrim($result, ",");
}
$result = $result."}";
return $result;
}
public function buildFields()
{
$keys = array(
'pushtype',
'pushbody'
);
foreach ($keys as $key) {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][key:' . $key . '][value:' . json_encode($this->$key) . ']', Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][buildFields result:' . json_encode($this->fields), Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: ApnsConfig => =>PushMessage(apns) for ios channel
*/
namespace push_admin\push_msg\instanceapp;
include_once (dirname(__FILE__) . '/../../../push_admin/PushLogConfig.php');
use push_admin\PushLogConfig;
use push_admin\Constants;
class InstanceAppPushbody
{
// for pass-through
private $messageId;
private $data;
// for notification
private $title;
private $description;
private $page;
private $params;
private $ringtone;
private $fields;
public function __construct()
{
}
public function messageId($value)
{
$this->messageId = $value;
}
public function data($value)
{
$this->data = $value;
}
public function title($value)
{
$this->title = $value;
}
public function description($value)
{
$this->description = $value;
}
public function page($value)
{
$this->page = $value;
}
public function params($value)
{
$this->params = $value;
}
public function ringtone($value)
{
$this->ringtone = $value;
}
public function getFields()
{
$result = "{";
foreach ($this->fields as $key=>$value) {
$result = $result .$key.":".json_encode($value).",";
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][result:' .$result, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
if (strlen($result) > 1){
$result = rtrim($result, ",");
}
$result = $result."}";
return $result;
}
public function buildFields()
{
$keys = array(
'messageId',
'data',
'title',
'description',
'page',
'params',
'ringtone'
);
foreach ($keys as $key) {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][key:' . $key . '][value:' . json_encode($this->$key) . ']', Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][buildFields result:' . json_encode($this->fields), Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: ApnsConfig => =>PushMessage(apns) for ios channel
*/
namespace push_admin\push_msg\instanceapp;
include_once (dirname(__FILE__) . '/../../../push_admin/PushLogConfig.php');
use push_admin\PushLogConfig;
use push_admin\Constants;
class InstanceAppRingtone
{
private $vibration;
private $breathLight;
private $fields;
public function __construct()
{
$this->fields = array();
}
public function vibration($value)
{
$this->vibration = $value;
}
public function breathLight($value)
{
$this->breathLight = $value;
}
public function getFields()
{
$result = "{";
foreach ($this->fields as $key=>$value) {
$result = $result .$key.":".json_encode($value).",";
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][result:' .$result, Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
if (strlen($result) > 1){
$result = rtrim($result, ",");
}
$result = $result."}";
return $result;
}
public function buildFields()
{
$keys = array(
'vibration',
'breathLight'
);
foreach ($keys as $key) {
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][key:' . $key . '][value:' . json_encode($this->$key) . ']', Constants::HW_PUSH_LOG_DEBUG_LEVEL);
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
PushLogConfig::getSingleInstance()->LogMessage('[' . __CLASS__ . '][buildFields result:' . json_encode($this->fields), Constants::HW_PUSH_LOG_DEBUG_LEVEL);
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: Notification message push control parameter =>PushMessage(notification) for ios channel
*/
namespace push_admin\push_msg\notification;
/**
* optional for message
*/
use Exception;
class Notification
{
/**
* optional
*/
private $title;
/**
* optional
*/
private $body;
/**
* optional
*/
private $image;
private $fields;
public function __construct($title, $body, $image)
{
$this->title = $title;
$this->body = $body;
$this->image = $image;
$this->fields = array();
}
public function title($value)
{
$this->title = $value;
}
public function body($value)
{
$this->body = $value;
}
public function image($value)
{
$this->image = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{ try {
$this->check_parameter();
} catch (Exception $e) {
echo $e;
}
$keys = array(
'title',
'body',
'image'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter()
{
if (empty($this->title))
{
throw new Exception("title should be set");
}
if (empty($this->body))
{
throw new Exception("body should be set");
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: webpush message push control parameter, which is required for webpush msg=>PushMessage(webpush)
*/
namespace push_admin\push_msg\webpush;
class WebPushConfig
{
private $headers;
private $data;
private $notification;
private $hms_options;
private $fields;
public function __construct()
{
$this->headers = array();
$this->notification = array();
$this->hmsOptions = array();
$this->fields = array();
}
public function headers($value)
{
$this->headers = $value;
}
public function data($value)
{
$this->data = $value;
}
public function notification($value)
{
$this->notification = $value;
}
public function hmsOptions($value)
{
$this->hms_options = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
$keys = array(
'headers',
'data',
'notification',
'hms_options'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
}
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: WebPush Headers class =>WebPushConfig(headers)
* =>PushMessage(webpush)
*/
namespace push_admin\push_msg\webpush;
class WebPushHeaders
{
private $ttl;
private $topic;
private $urgency;
private $fields;
public function __construct()
{
$this->fields = array();
}
public function ttl($value)
{
$this->ttl = $value;
}
public function topic($value)
{
$this->topic = $value;
}
public function urgency($value)
{
$this->urgency = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
$keys = array(
'ttl',
'topic',
'urgency'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: WebPushHmsOptions class =>WebPushConfig(hms_options)
* =>PushMessage(webpush)
*/
namespace push_admin\push_msg\webpush;
class WebPushHmsOptions
{
private $link;
private $fields;
public function __construct()
{
$this->fields = array();
}
public function link($value) {
$this->link = $value;
}
public function getFields() {
return $this->fields;
}
public function buildFields() {
$keys = array(
'link'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: WebPushNotification class =>WebPushConfig(notification)
* =>PushMessage(webpush)
*/
namespace push_admin\push_msg\webpush;
use Exception;
class WebPushNotification
{
private $title;
private $body;
private $icon;
private $image;
private $lang;
private $tag;
private $badge;
private $dir;
private $vibrate;
private $renotify;
private $require_interaction;
private $silent;
private $timestamp;
private $actions;
private $fields;
public function __construct()
{
$this->actions = array();
$this->fields = array();
}
public function title($value) {
$this->title = $value;
}
public function body($value) {
$this->body = $value;
}
public function icon($value) {
$this->icon = $value;
}
public function image($value) {
$this->image = $value;
}
public function lang($value) {
$this->lang = $value;
}
public function tag($value) {
$this->tag = $value;
}
public function badge($value) {
$this->badge = $value;
}
public function dir($value) {
$this->dir = $value;
}
public function vibrate($value) {
$this->vibrate = $value;
}
public function renotify($value) {
$this->renotify = $value;
}
public function require_interaction($value) {
$this->require_interaction = $value;
}
public function silent($value) {
$this->silent = $value;
}
public function timestamp($value) {
$this->timestamp = $value;
}
public function actions($value) {
$this->actions = $value;
}
public function getFields() {
return $this->fields;
}
public function buildFields() {
try{
$this->check_parameter();
}catch (Exception $e) {
echo $e;
}
$keys = array(
'title',
'body',
'icon',
'image',
'lang',
'tag',
'badge',
'dir',
'vibrate',
'renotify',
'require_interaction',
'silent',
'timestamp',
'actions'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
private function check_parameter() {
if (($this->renotify) && (gettype($this->renotify) != "boolean")) {
throw new Exception("type of renotify is wrong.");
}
if (($this->require_interaction) && (gettype($this->require_interaction) != "boolean")) {
throw new Exception("type of requireInteraction is wrong.");
}
if (($this->silent) && (gettype($this->silent) != "boolean")) {
throw new Exception("type of silent is wrong.");
}
}
}
\ No newline at end of file
<?php
/**
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* function: WebPushNotificationAction =>WebPushNotification(action)
* =>WebPushConfig(notification)
* =>PushMessage(webpush)
*/
namespace push_admin\push_msg\webpush;
class WebPushNotificationAction
{
private $title;
private $icon;
private $action;
private $fields;
public function __construct()
{
$this->fields = array();
}
public function title($value)
{
$this->title = $value;
}
public function action($value)
{
$this->action = $value;
}
public function icon($value)
{
$this->icon = $value;
}
public function getFields()
{
return $this->fields;
}
public function buildFields()
{
$keys = array(
'title',
'icon',
'action'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
}
}
}
}
\ No newline at end of file
<?php
namespace JPush;
class AdminClient {
const ADMIN_URL = 'https://admin.jpush.cn/v1/app/';
private $devKey;
private $devSecret;
private $retryTimes;
private $logFile;
function __construct($devKey, $devSecret) {
if (!is_string($devKey) || !is_string($devSecret)) {
throw new InvalidArgumentException("Invalid devKey or devSecret");
}
$this->devKey = $devKey;
$this->devSecret = $devSecret;
$this->retryTimes = 1;
$this->logFile = null;
}
public function getAuthStr() { return $this->devKey . ":" . $this->devSecret; }
public function getRetryTimes() { return $this->retryTimes; }
public function getLogFile() { return $this->logFile; }
public function createApp($appName, $androidPackage, $groupName=null) {
$url = AdminClient::ADMIN_URL;
$body = [
'app_name' => $appName,
'android_package'=> $androidPackage,
'group_name' => $groupName
];
return Http::post($this, $url, $body);
}
public function deleteApp($appKey) {
$url = AdminClient::ADMIN_URL . $appKey . '/delete';
return Http::post($this, $url, []);
}
}
<?php
namespace JPush;
use InvalidArgumentException;
class Client {
private $appKey;
private $masterSecret;
private $retryTimes;
private $logFile;
private $zone;
private static $zones = [
'DEFAULT' => [
'push' => 'https://api.jpush.cn/v3/',
'report' => 'https://report.jpush.cn/v3/',
'device' => 'https://device.jpush.cn/v3/devices/',
'alias' => 'https://device.jpush.cn/v3/aliases/',
'tag' => 'https://device.jpush.cn/v3/tags/',
'schedule' => 'https://api.jpush.cn/v3/schedules'
],
'BJ' => [
'push' => 'https://bjapi.push.jiguang.cn/v3/',
'report' => 'https://bjapi.push.jiguang.cn/v3/report/',
'device' => 'https://bjapi.push.jiguang.cn/v3/device/',
'alias' => 'https://bjapi.push.jiguang.cn/v3/device/aliases/',
'tag' => 'https://bjapi.push.jiguang.cn/v3/device/tags/',
'schedules' => 'https://bjapi.push.jiguang.cn/v3/push/schedules'
]
];
public function __construct($appKey='', $masterSecret='', $logFile=Config::DEFAULT_LOG_FILE, $retryTimes=Config::DEFAULT_MAX_RETRY_TIMES, $zone = null) {
if (empty($appKey) || empty($masterSecret)) {
//载入配置文件然后获取
$appKey = \pushConfig::JPUSH_APP_KEY;
$masterSecret = \pushConfig::JPUSH_MASTER_SECRET;
if(!is_string($appKey) || !is_string($masterSecret)){
throw new InvalidArgumentException("Invalid appKey or masterSecret");
}
}
$this->appKey = $appKey;
$this->masterSecret = $masterSecret;
if (!is_null($retryTimes)) {
$this->retryTimes = $retryTimes;
} else {
$this->retryTimes = 1;
}
$this->logFile = $logFile;
if (!is_null($zone) && in_array(strtoupper($zone), array_keys(self::$zones))) {
$this->zone = strtoupper($zone);
} else {
$this->zone = null;
}
}
public function push() { return new PushPayload($this); }
public function report() { return new ReportPayload($this); }
public function device() { return new DevicePayload($this); }
public function schedule() { return new SchedulePayload($this);}
public function getAuthStr() { return $this->appKey . ":" . $this->masterSecret; }
public function getRetryTimes() { return $this->retryTimes; }
public function getLogFile() { return $this->logFile; }
public function is_group() {
$str = substr($this->appKey, 0, 6);
return $str === 'group-';
}
public function makeURL($key) {
if (is_null($this->zone)) {
return self::$zones['DEFAULT'][$key];
} else {
return self::$zones[$this->zone][$key];
}
}
// public function cc(){
// return "cc";
// }
}
<?php
namespace JPush;
class Config {
const DISABLE_SOUND = "_disable_Sound";
const DISABLE_BADGE = 0x10000;
const USER_AGENT = 'JPush-API-PHP-Client';
const CONNECT_TIMEOUT = 20;
const READ_TIMEOUT = 120;
const DEFAULT_MAX_RETRY_TIMES = 3;
const DEFAULT_LOG_FILE = "./jpush.log";
const HTTP_GET = 'GET';
const HTTP_POST = 'POST';
const HTTP_DELETE = 'DELETE';
const HTTP_PUT = 'PUT';
}
<?php
namespace JPush;
use InvalidArgumentException;
class DevicePayload {
private $client;
/**
* DevicePayload constructor.
* @param $client JPush
*/
public function __construct($client)
{
$this->client = $client;
}
public function getDevices($registrationId) {
$url = $this->client->makeURL('device') . $registrationId;
return Http::get($this->client, $url);
}
public function updateAlias($registration_id, $alias) {
return $this->updateDevice($registration_id, $alias);
}
public function addTags($registration_id, $tags) {
$tags = is_array($tags) ? $tags : array($tags);
return $this->updateDevice($registration_id, null, null, $tags);
}
public function removeTags($registration_id, $tags) {
$tags = is_array($tags) ? $tags : array($tags);
return $this->updateDevice($registration_id, null, null, null, $tags);
}
public function updateMoblie($registration_id, $mobile) {
return $this->updateDevice($registration_id, null, $mobile);
}
public function clearMobile($registrationId) {
$url = $this->client->makeURL('device') . $registrationId;
return Http::post($this->client, $url, ['mobile' => '']);
}
public function clearTags($registrationId) {
$url = $this->client->makeURL('device') . $registrationId;
return Http::post($this->client, $url, ['tags' => '']);
}
public function updateDevice($registrationId, $alias = null, $mobile = null, $addTags = null, $removeTags = null) {
$payload = array();
if (!is_string($registrationId)) {
throw new InvalidArgumentException('Invalid registration_id');
}
$aliasIsNull = is_null($alias);
$mobileIsNull = is_null($mobile);
$addTagsIsNull = is_null($addTags);
$removeTagsIsNull = is_null($removeTags);
if ($aliasIsNull && $addTagsIsNull && $removeTagsIsNull && $mobileIsNull) {
throw new InvalidArgumentException("alias, addTags, removeTags not all null");
}
if (!$aliasIsNull) {
if (is_string($alias)) {
$payload['alias'] = $alias;
} else {
throw new InvalidArgumentException("Invalid alias string");
}
}
if (!$mobileIsNull) {
if (is_string($mobile)) {
$payload['mobile'] = $mobile;
} else {
throw new InvalidArgumentException("Invalid mobile string");
}
}
$tags = array();
if (!$addTagsIsNull) {
if (is_array($addTags)) {
$tags['add'] = $addTags;
} else {
throw new InvalidArgumentException("Invalid addTags array");
}
}
if (!$removeTagsIsNull) {
if (is_array($removeTags)) {
$tags['remove'] = $removeTags;
} else {
throw new InvalidArgumentException("Invalid removeTags array");
}
}
if (count($tags) > 0) {
$payload['tags'] = $tags;
}
$url = $this->client->makeURL('device') . $registrationId;
return Http::post($this->client, $url, $payload);
}
public function getTags() {
$url = $this->client->makeURL('tag');
return Http::get($this->client, $url);
}
public function isDeviceInTag($registrationId, $tag) {
if (!is_string($registrationId)) {
throw new InvalidArgumentException("Invalid registration_id");
}
if (!is_string($tag)) {
throw new InvalidArgumentException("Invalid tag");
}
$url = $this->client->makeURL('tag') . $tag . '/registration_ids/' . $registrationId;
return Http::get($this->client, $url);
}
public function addDevicesToTag($tag, $addDevices) {
$device = is_array($addDevices) ? $addDevices : array($addDevices);
return $this->updateTag($tag, $device, null);
}
public function removeDevicesFromTag($tag, $removeDevices) {
$device = is_array($removeDevices) ? $removeDevices : array($removeDevices);
return $this->updateTag($tag, null, $device);
}
public function updateTag($tag, $addDevices = null, $removeDevices = null) {
if (!is_string($tag)) {
throw new InvalidArgumentException("Invalid tag");
}
$addDevicesIsNull = is_null($addDevices);
$removeDevicesIsNull = is_null($removeDevices);
if ($addDevicesIsNull && $removeDevicesIsNull) {
throw new InvalidArgumentException("Either or both addDevices and removeDevices must be set.");
}
$registrationId = array();
if (!$addDevicesIsNull) {
if (is_array($addDevices)) {
$registrationId['add'] = $addDevices;
} else {
throw new InvalidArgumentException("Invalid addDevices");
}
}
if (!$removeDevicesIsNull) {
if (is_array($removeDevices)) {
$registrationId['remove'] = $removeDevices;
} else {
throw new InvalidArgumentException("Invalid removeDevices");
}
}
$url = $this->client->makeURL('tag') . $tag;
$payload = array('registration_ids'=>$registrationId);
return Http::post($this->client, $url, $payload);
}
public function deleteTag($tag) {
if (!is_string($tag)) {
throw new InvalidArgumentException("Invalid tag");
}
$url = $this->client->makeURL('tag') . $tag;
return Http::delete($this->client, $url);
}
public function getAliasDevices($alias, $platform = null) {
if (!is_string($alias)) {
throw new InvalidArgumentException("Invalid alias");
}
$url = $this->client->makeURL('alias') . $alias;
if (!is_null($platform)) {
if (is_array($platform)) {
$isFirst = true;
foreach($platform as $item) {
if ($isFirst) {
$url = $url . '?platform=' . $item;
$isFirst = false;
} else {
$url = $url . ',' . $item;
}
}
} else if (is_string($platform)) {
$url = $url . '?platform=' . $platform;
} else {
throw new InvalidArgumentException("Invalid platform");
}
}
return Http::get($this->client, $url);
}
public function deleteAlias($alias) {
if (!is_string($alias)) {
throw new InvalidArgumentException("Invalid alias");
}
$url = $this->client->makeURL('alias') . $alias;
return Http::delete($this->client, $url);
}
public function getDevicesStatus($registrationId) {
if (!is_array($registrationId) && !is_string($registrationId)) {
throw new InvalidArgumentException('Invalid registration_id');
}
if (is_string($registrationId)) {
$registrationId = explode(',', $registrationId);
}
$payload = array();
if (count($registrationId) <= 0) {
throw new InvalidArgumentException('Invalid registration_id');
}
$payload['registration_ids'] = $registrationId;
$url = $this->client->makeURL('device') . 'status';
return Http::post($this->client, $url, $payload);
}
}
<?php
namespace JPush\Exceptions;
class APIConnectionException extends JPushException {
function __toString() {
return "\n" . __CLASS__ . " -- {$this->message} \n";
}
}
<?php
namespace JPush\Exceptions;
class APIRequestException extends JPushException {
private $http_code;
private $headers;
private static $expected_keys = array('code', 'message');
function __construct($response){
$this->http_code = $response['http_code'];
$this->headers = $response['headers'];
$body = json_decode($response['body'], true);
if (key_exists('error', $body)) {
$this->code = $body['error']['code'];
$this->message = $body['error']['message'];
} else {
$this->code = $body['code'];
$this->message = $body['message'];
}
}
public function __toString() {
return "\n" . __CLASS__ . " -- [{$this->code}]: {$this->message} \n";
}
public function getHttpCode() {
return $this->http_code;
}
public function getHeaders() {
return $this->headers;
}
}
<?php
namespace JPush\Exceptions;
class JPushException extends \Exception {
function __construct($message) {
parent::__construct($message);
}
}
<?php
namespace JPush\Exceptions;
class ServiceNotAvaliable extends JPushException {
private $http_code;
private $headers;
function __construct($response){
$this->http_code = $response['http_code'];
$this->headers = $response['headers'];
$this->message = $response['body'];
}
function __toString() {
return "\n" . __CLASS__ . " -- [{$this->http_code}]: {$this->message} \n";
}
public function getHttpCode() {
return $this->http_code;
}
public function getHeaders() {
return $this->headers;
}
}
<?php
namespace JPush;
use JPush\Exceptions\APIConnectionException;
use JPush\Exceptions\APIRequestException;
use JPush\Exceptions\ServiceNotAvaliable;
final class Http {
public static function get($client, $url) {
$response = self::sendRequest($client, $url, Config::HTTP_GET, $body=null);
return self::processResp($response);
}
public static function post($client, $url, $body) {
$response = self::sendRequest($client, $url, Config::HTTP_POST, $body);
return self::processResp($response);
}
public static function put($client, $url, $body) {
$response = self::sendRequest($client, $url, Config::HTTP_PUT, $body);
return self::processResp($response);
}
public static function delete($client, $url) {
$response = self::sendRequest($client, $url, Config::HTTP_DELETE, $body=null);
return self::processResp($response);
}
private static function sendRequest($client, $url, $method, $body=null, $times=1) {
self::log($client, "Send " . $method . " " . $url . ", body:" . json_encode($body) . ", times:" . $times);
if (!defined('CURL_HTTP_VERSION_2_0')) {
define('CURL_HTTP_VERSION_2_0', 3);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, Config::USER_AGENT);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, Config::CONNECT_TIMEOUT); // 连接建立最长耗时
curl_setopt($ch, CURLOPT_TIMEOUT, Config::READ_TIMEOUT); // 请求最长耗时
// 设置SSL版本 1=CURL_SSLVERSION_TLSv1, 不指定使用默认值,curl会自动获取需要使用的CURL版本
// curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 如果报证书相关失败,可以考虑取消注释掉该行,强制指定证书版本
//curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'TLSv1');
// 设置Basic认证
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $client->getAuthStr());
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
// 设置Post参数
if ($method === Config::HTTP_POST) {
curl_setopt($ch, CURLOPT_POST, true);
} else if ($method === Config::HTTP_DELETE || $method === Config::HTTP_PUT) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}
if (!is_null($body)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Connection: Keep-Alive'
));
$output = curl_exec($ch);
$response = array();
$errorCode = curl_errno($ch);
// $msg = '';
// $data = json_decode($body, true);
// if (isset($data['options']['sendno'])) {
// $sendno = $data['options']['sendno'];
// $msg = 'sendno: ' . $sendno;
// }
$msg = '';
if (isset($body['options']['sendno'])) {
$sendno = $body['options']['sendno'];
$msg = 'sendno: ' . $sendno;
}
if ($errorCode) {
$retries = $client->getRetryTimes();
if ($times < $retries) {
return self::sendRequest($client, $url, $method, $body, ++$times);
} else {
if ($errorCode === 28) {
throw new APIConnectionException($msg . "Response timeout. Your request has probably be received by JPush Server,please check that whether need to be pushed again." );
} elseif ($errorCode === 56) {
// resolve error[56 Problem (2) in the Chunked-Encoded data]
throw new APIConnectionException($msg . "Response timeout, maybe cause by old CURL version. Your request has probably be received by JPush Server, please check that whether need to be pushed again.");
} else {
throw new APIConnectionException("$msg . Connect timeout. Please retry later. Error:" . $errorCode . " " . curl_error($ch));
}
}
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header_text = substr($output, 0, $header_size);
$body = substr($output, $header_size);
$headers = array();
foreach (explode("\r\n", $header_text) as $i => $line) {
if (!empty($line)) {
if ($i === 0) {
$headers[0] = $line;
} else if (strpos($line, ": ")) {
list ($key, $value) = explode(': ', $line);
$headers[$key] = $value;
}
}
}
$response['headers'] = $headers;
$response['body'] = $body;
$response['http_code'] = $httpCode;
}
curl_close($ch);
return $response;
}
public static function processResp($response) {
$data = json_decode($response['body'], true);
if ($response['http_code'] === 200) {
$result = array();
$result['body'] = $data;
$result['http_code'] = $response['http_code'];
$result['headers'] = $response['headers'];
return $result;
} elseif (is_null($data)) {
throw new ServiceNotAvaliable($response);
} else {
var_dump($response);exit;
throw new APIRequestException($response);
}
}
public static function log($client, $content) {
if (!is_null($client->getLogFile())) {
error_log($content . "\r\n", 3, $client->getLogFile());
}
}
}
<?php
namespace JPush;
use InvalidArgumentException;
class PushPayload {
private static $EFFECTIVE_DEVICE_TYPES = array('ios', 'android', 'winphone');
private $client;
private $url;
private $cid;
private $platform;
private $audience;
private $tags;
private $tagAnds;
private $tagNots;
private $alias;
private $registrationIds;
private $segmentIds;
private $abtests;
private $notificationAlert;
private $iosNotification;
private $androidNotification;
private $winPhoneNotification;
private $smsMessage;
private $message;
private $options;
/**
* PushPayload constructor.
* @param $client JPush
*/
function __construct($client) {
$this->client = $client;
$url = $this->client->is_group() ? 'grouppush' : 'push';
$this->url = $this->client->makeURL('push') . $url;
}
public function getCid($count = 1, $type = 'push') {
$url = $this->client->makeURL('push') . 'push/cid?count=' . $count . '&type=' . $type;
return Http::get($this->client, $url);
}
public function setCid($cid) {
$this->cid = trim($cid);
return $this;
}
public function setPlatform($platform) {
# $required_keys = array('all', 'android', 'ios', 'winphone');
if (is_string($platform)) {
$ptf = strtolower($platform);
if ('all' === $ptf) {
$this->platform = 'all';
} elseif (in_array($ptf, self::$EFFECTIVE_DEVICE_TYPES)) {
$this->platform = array($ptf);
}
} elseif (is_array($platform)) {
$ptf = array_map('strtolower', $platform);
$this->platform = array_intersect($ptf, self::$EFFECTIVE_DEVICE_TYPES);
}
return $this;
}
public function setAudience($all) {
if (strtolower($all) === 'all') {
$this->addAllAudience();
return $this;
} else {
throw new InvalidArgumentException('Invalid audience value');
}
}
public function addAllAudience() {
$this->audience = "all";
return $this;
}
public function addTag($tag) {
return $this->updateAudience('tags', $tag, 'tag');
}
public function addTagAnd($tag) {
return $this->updateAudience('tagAnds', $tag, 'tag_and');
}
public function addTagNot($tag) {
return $this->updateAudience('tagNots', $tag, 'tag_not');
}
public function addAlias($alias) {
return $this->updateAudience('alias', $alias, 'alias');
}
public function addRegistrationId($registrationId) {
return $this->updateAudience('registrationIds', $registrationId, 'registration_id');
}
public function addSegmentId($segmentId) {
return $this->updateAudience('segmentIds', $segmentId, 'segment');
}
public function addAbtest($abtest) {
return $this->updateAudience('abtests', $abtest, 'abtest');
}
private function updateAudience($key, $value, $name) {
if (is_null($this->$key)) {
$this->$key = array();
}
if (is_array($value)) {
foreach($value as $v) {
if (!is_string($v)) {
throw new InvalidArgumentException("Invalid $name value");
}
if (!in_array($v, $this->$key)) {
array_push($this->$key, $v);
}
}
} else if (is_string($value)) {
if (!in_array($value, $this->$key)) {
array_push($this->$key, $value);
}
} else {
throw new InvalidArgumentException("Invalid $name value");
}
return $this;
}
public function setNotificationAlert($alert) {
if (!is_string($alert)) {
throw new InvalidArgumentException("Invalid alert value");
}
$this->notificationAlert = $alert;
return $this;
}
public function addWinPhoneNotification($alert=null, $title=null, $_open_page=null, $extras=null) {
$winPhone = array();
if (!is_null($alert)) {
if (!is_string($alert)) {
throw new InvalidArgumentException("Invalid winphone notification");
}
$winPhone['alert'] = $alert;
}
if (!is_null($title)) {
if (!is_string($title)) {
throw new InvalidArgumentException("Invalid winphone title notification");
}
if(strlen($title) > 0) {
$winPhone['title'] = $title;
}
}
if (!is_null($_open_page)) {
if (!is_string($_open_page)) {
throw new InvalidArgumentException("Invalid winphone _open_page notification");
}
if (strlen($_open_page) > 0) {
$winPhone['_open_page'] = $_open_page;
}
}
if (!is_null($extras)) {
if (!is_array($extras)) {
throw new InvalidArgumentException("Invalid winphone extras notification");
}
if (count($extras) > 0) {
$winPhone['extras'] = $extras;
}
}
if (count($winPhone) <= 0) {
throw new InvalidArgumentException("Invalid winphone notification");
}
$this->winPhoneNotification = $winPhone;
return $this;
}
public function setSms($delay_time, $temp_id, array $temp_para = []) {
$sms = array();
$sms['temp_id'] = $temp_id;
$sms['delay_time'] = ($delay_time === 0 || (is_int($delay_time) && $delay_time > 0 && $delay_time <= 86400)) ? $delay_time : 0;
if (!empty($temp_para)) {
$sms['temp_para'] = $temp_para;
}
$this->smsMessage = $sms;
return $this;
}
public function build() {
$payload = array();
// validate platform
if (is_null($this->platform)) {
throw new InvalidArgumentException("platform must be set");
}
$payload["platform"] = $this->platform;
if (!is_null($this->cid)) {
$payload['cid'] = $this->cid;
}
// validate audience
$audience = array();
if (!is_null($this->tags)) {
$audience["tag"] = $this->tags;
}
if (!is_null($this->tagAnds)) {
$audience["tag_and"] = $this->tagAnds;
}
if (!is_null($this->tagNots)) {
$audience["tag_not"] = $this->tagNots;
}
if (!is_null($this->alias)) {
$audience["alias"] = $this->alias;
}
if (!is_null($this->registrationIds)) {
$audience["registration_id"] = $this->registrationIds;
}
if (!is_null($this->segmentIds)) {
$audience["segment"] = $this->segmentIds;
}
if (!is_null($this->abtests)) {
$audience["abtest"] = $this->abtests;
}
if (is_null($this->audience) && count($audience) <= 0) {
throw new InvalidArgumentException("audience must be set");
} else if (!is_null($this->audience) && count($audience) > 0) {
throw new InvalidArgumentException("you can't add tags/alias/registration_id/tag_and when audience='all'");
} else if (is_null($this->audience)) {
$payload["audience"] = $audience;
} else {
$payload["audience"] = $this->audience;
}
// validate notification
$notification = array();
if (!is_null($this->notificationAlert)) {
$notification['alert'] = $this->notificationAlert;
}
if (!is_null($this->androidNotification)) {
$notification['android'] = $this->androidNotification;
if (is_null($this->androidNotification['alert'])) {
if (is_null($this->notificationAlert)) {
throw new InvalidArgumentException("Android alert can not be null");
} else {
$notification['android']['alert'] = $this->notificationAlert;
}
}
}
if (!is_null($this->iosNotification)) {
$notification['ios'] = $this->iosNotification;
if (is_null($this->iosNotification['alert'])) {
if (is_null($this->notificationAlert)) {
throw new InvalidArgumentException("iOS alert can not be null");
} else {
$notification['ios']['alert'] = $this->notificationAlert;
}
}
}
if (!is_null($this->winPhoneNotification)) {
$notification['winphone'] = $this->winPhoneNotification;
if (is_null($this->winPhoneNotification['alert'])) {
if (is_null($this->winPhoneNotification)) {
throw new InvalidArgumentException("WinPhone alert can not be null");
} else {
$notification['winphone']['alert'] = $this->notificationAlert;
}
}
}
if (count($notification) > 0) {
$payload['notification'] = $notification;
}
if (!is_null($this->message)) {
$payload['message'] = $this->message;
}
if (!array_key_exists('notification', $payload) && !array_key_exists('message', $payload)) {
throw new InvalidArgumentException('notification and message can not all be null');
}
if (!is_null($this->smsMessage)) {
$payload['sms_message'] = $this->smsMessage;
}
if (is_null($this->options)) {
$this->options();
}
$payload['options'] = $this->options;
return $payload;
}
public function toJSON() {
$payload = $this->build();
return json_encode($payload);
}
public function printJSON() {
echo $this->toJSON();
return $this;
}
public function send() {
return Http::post($this->client, $this->url, $this->build());
}
public function validate() {
$url = $this->client->makeURL('push') . '/push/validate';
return Http::post($this->client, $url, $this->build());
}
private function generateSendno() {
return rand(100000, getrandmax());
}
# new methods
public function iosNotification($alert = '', array $notification = array()) {
$ios = array();
$ios['alert'] = (is_string($alert) || is_array($alert)) ? $alert : '';
if (!empty($notification)) {
if (isset($notification['sound'])) {
if (is_string($notification['sound']) || is_array($notification['sound'])) {
$ios['sound'] = $notification['sound'];
} else {
unset($notification['sound']);
}
}
if (isset($notification['content-available'])) {
if (is_bool($notification['content-available'])) {
$ios['content-available'] = $notification['content-available'];
} else {
unset($notification['content-available']);
}
}
if (isset($notification['mutable-content'])) {
if (is_bool($notification['mutable-content'])) {
$ios['mutable-content'] = $notification['mutable-content'];
} else {
unset($notification['mutable-content']);
}
}
if (isset($notification['extras'])) {
if (is_array($notification['extras']) && !empty($notification['extras'])) {
$ios['extras'] = $notification['extras'];
} else {
unset($notification['extras']);
}
}
$ios = array_merge($notification, $ios);
}
if (!isset($ios['sound'])) {
$ios['sound'] = '';
}
if (!isset($ios['badge'])) {
$ios['badge'] = '+1';
}
$this->iosNotification = $ios;
return $this;
}
public function androidNotification($alert = '', array $notification = array()) {
$android = array();
$android['alert'] = is_string($alert) ? $alert : '';
if (!empty($notification)) {
if (isset($notification['builder_id'])) {
if (is_int($notification['builder_id'])) {
$android['builder_id'] = $notification['builder_id'];
} else {
unset($notification['builder_id']);
}
}
if (isset($notification['priority'])) {
if (is_int($notification['priority'])) {
$android['priority'] = $notification['priority'];
} else {
unset($notification['priority']);
}
}
if (isset($notification['style'])) {
if (is_int($notification['style'])) {
$android['style'] = $notification['style'];
} else {
unset($notification['style']);
}
}
if (isset($notification['alert_type'])) {
if (is_int($notification['alert_type'])) {
$android['alert_type'] = $notification['alert_type'];
} else {
unset($notification['alert_type']);
}
}
if (isset($notification['inbox'])) {
if (is_array($notification['inbox']) && !empty($notification['inbox'])) {
$android['inbox'] = $notification['inbox'];
} else {
unset($notification['inbox']);
}
}
if (isset($notification['intent'])) {
if (is_array($notification['intent']) && !empty($notification['intent'])) {
$android['intent'] = $notification['intent'];
} else {
unset($notification['intent']);
}
}
if (isset($notification['extras'])) {
if (is_array($notification['extras']) && !empty($notification['extras'])) {
$android['extras'] = $notification['extras'];
} else {
unset($notification['extras']);
}
}
$android = array_merge($notification, $android);
}
$this->androidNotification = $android;
return $this;
}
public function message($msg_content, array $msg = array()) {
# $required_keys = array('title', 'content_type', 'extras');
if (is_string($msg_content)) {
$message = array();
$message['msg_content'] = $msg_content;
if (!empty($msg)) {
if (isset($msg['title']) && is_string($msg['title'])) {
$message['title'] = $msg['title'];
}
if (isset($msg['content_type']) && is_string($msg['content_type'])) {
$message['content_type'] = $msg['content_type'];
}
if (isset($msg['extras']) && is_array($msg['extras']) && !empty($msg['extras'])) {
$message['extras'] = $msg['extras'];
}
}
$this->message = $message;
}
return $this;
}
public function options(array $opts = array()) {
# $required_keys = array('sendno', 'time_to_live', 'override_msg_id', 'apns_production', 'apns_collapse_id', 'big_push_duration');
$options = array();
if (isset($opts['sendno'])) {
$options['sendno'] = $opts['sendno'];
} else {
$options['sendno'] = $this->generateSendno();
}
if (isset($opts['time_to_live']) && $opts['time_to_live'] <= 864000 && $opts['time_to_live'] >= 0) {
$options['time_to_live'] = $opts['time_to_live'];
}
if (isset($opts['override_msg_id'])) {
$options['override_msg_id'] = $opts['override_msg_id'];
}
if (isset($opts['apns_production'])) {
$options['apns_production'] = (bool)$opts['apns_production'];
} else {
$options['apns_production'] = false;
}
if (isset($opts['apns_collapse_id'])) {
$options['apns_collapse_id'] = $opts['apns_collapse_id'];
}
if (isset($opts['big_push_duration']) && $opts['big_push_duration'] <= 1400 && $opts['big_push_duration'] >= 0) {
$options['big_push_duration'] = $opts['big_push_duration'];
}
$options = array_merge($opts, $options);
$this->options = $options;
return $this;
}
###############################################################################
############# 以下函数已过期,不推荐使用,仅作为兼容接口存在 #########################
###############################################################################
public function addIosNotification($alert=null, $sound=null, $badge=null, $content_available=null, $category=null, $extras=null) {
$ios = array();
if (!is_null($alert)) {
if (!is_string($alert) && !is_array($alert)) {
throw new InvalidArgumentException("Invalid ios alert value");
}
$ios['alert'] = $alert;
}
if (!is_null($sound)) {
if (!is_string($sound)) {
throw new InvalidArgumentException("Invalid ios sound value");
}
if ($sound !== Config::DISABLE_SOUND) {
$ios['sound'] = $sound;
}
} else {
// 默认sound为''
$ios['sound'] = '';
}
if (!is_null($badge)) {
if (is_string($badge) && !preg_match("/^[+-]{1}[0-9]{1,3}$/", $badge)) {
if (!is_int($badge)) {
throw new InvalidArgumentException("Invalid ios badge value");
}
}
if ($badge != Config::DISABLE_BADGE) {
$ios['badge'] = $badge;
}
} else {
// 默认badge为'+1'
$ios['badge'] = '+1';
}
if (!is_null($content_available)) {
if (!is_bool($content_available)) {
throw new InvalidArgumentException("Invalid ios content-available value");
}
$ios['content-available'] = $content_available;
}
if (!is_null($category)) {
if (!is_string($category)) {
throw new InvalidArgumentException("Invalid ios category value");
}
if (strlen($category)) {
$ios['category'] = $category;
}
}
if (!is_null($extras)) {
if (!is_array($extras)) {
throw new InvalidArgumentException("Invalid ios extras value");
}
if (count($extras) > 0) {
$ios['extras'] = $extras;
}
}
if (count($ios) <= 0) {
throw new InvalidArgumentException("Invalid iOS notification");
}
$this->iosNotification = $ios;
return $this;
}
public function addAndroidNotification($alert=null, $title=null, $builderId=null, $extras=null) {
$android = array();
if (!is_null($alert)) {
if (!is_string($alert)) {
throw new InvalidArgumentException("Invalid android alert value");
}
$android['alert'] = $alert;
}
if (!is_null($title)) {
if(!is_string($title)) {
throw new InvalidArgumentException("Invalid android title value");
}
if(strlen($title) > 0) {
$android['title'] = $title;
}
}
if (!is_null($builderId)) {
if (!is_int($builderId)) {
throw new InvalidArgumentException("Invalid android builder_id value");
}
$android['builder_id'] = $builderId;
}
if (!is_null($extras)) {
if (!is_array($extras)) {
throw new InvalidArgumentException("Invalid android extras value");
}
if (count($extras) > 0) {
$android['extras'] = $extras;
}
}
if (count($android) <= 0) {
throw new InvalidArgumentException("Invalid android notification");
}
$this->androidNotification = $android;
return $this;
}
public function setMessage($msg_content, $title=null, $content_type=null, $extras=null) {
$message = array();
if (is_null($msg_content) || !is_string($msg_content)) {
throw new InvalidArgumentException("Invalid message content");
} else {
$message['msg_content'] = $msg_content;
}
if (!is_null($title)) {
if (!is_string($title)) {
throw new InvalidArgumentException("Invalid message title");
}
$message['title'] = $title;
}
if (!is_null($content_type)) {
if (!is_string($content_type)) {
throw new InvalidArgumentException("Invalid message content type");
}
$message["content_type"] = $content_type;
}
if (!is_null($extras)) {
if (!is_array($extras)) {
throw new InvalidArgumentException("Invalid message extras");
}
if (count($extras) > 0) {
$message['extras'] = $extras;
}
}
$this->message = $message;
return $this;
}
public function setSmsMessage($smsMessage) {
$this->smsMessage = $smsMessage;
return $this;
}
public function setOptions($sendno=null, $time_to_live=null, $override_msg_id=null, $apns_production=null, $big_push_duration=null) {
$options = array();
if (!is_null($sendno)) {
if (!is_int($sendno)) {
throw new InvalidArgumentException('Invalid option sendno');
}
$options['sendno'] = $sendno;
} else {
$options['sendno'] = $this->generateSendno();
}
if (!is_null($time_to_live)) {
if (!is_int($time_to_live) || $time_to_live < 0 || $time_to_live > 864000) {
throw new InvalidArgumentException('Invalid option time to live, it must be a int and in [0, 864000]');
}
$options['time_to_live'] = $time_to_live;
}
if (!is_null($override_msg_id)) {
if (!is_long($override_msg_id)) {
throw new InvalidArgumentException('Invalid option override msg id');
}
$options['override_msg_id'] = $override_msg_id;
}
if (!is_null($apns_production)) {
if (!is_bool($apns_production)) {
throw new InvalidArgumentException('Invalid option apns production');
}
$options['apns_production'] = $apns_production;
} else {
$options['apns_production'] = false;
}
if (!is_null($big_push_duration)) {
if (!is_int($big_push_duration) || $big_push_duration < 0 || $big_push_duration > 1440) {
throw new InvalidArgumentException('Invalid option big push duration, it must be a int and in [0, 1440]');
}
$options['big_push_duration'] = $big_push_duration;
}
$this->options = $options;
return $this;
}
/*
针对RegID方式批量单推
https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#vip
*/
public function batchPushByRegid(array $singlePayloads) {
$body = array(
"pushlist"=>array()
);
$response = $this -> getCid(count($singlePayloads), 'push');
$cidlist = $response['body']['cidlist'];
foreach ($cidlist as $i => $cid) {
$body["pushlist"][$cid] = $singlePayloads[$i];
}
$url = $this->client->makeURL('push') . 'push/batch/regid/single';
return Http::post($this->client, $url, $body);
}
/*
针对Alias方式批量单推
https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#vip
*/
public function batchPushByAlias(array $singlePayloads) {
$body = array(
"pushlist"=>array()
);
$response = $this -> getCid(count($singlePayloads), 'push');
$cidlist = $response['body']['cidlist'];
foreach ($cidlist as $i => $cid) {
$body["pushlist"][$cid] = $singlePayloads[$i];
}
$url = $this->client->makeURL('push') . 'push/batch/alias/single';
return Http::post($this->client, $url, $body);
}
}
<?php
namespace JPush;
use InvalidArgumentException;
class ReportPayload {
private static $EFFECTIVE_TIME_UNIT = array('HOUR', 'DAY', 'MONTH');
private $client;
/**
* ReportPayload constructor.
* @param $client JPush
*/
public function __construct($client)
{
$this->client = $client;
}
public function getReceived($msgIds) {
$queryParams = '?msg_ids=';
if (is_array($msgIds) && !empty($msgIds)) {
$msgIdsStr = implode(',', $msgIds);
$queryParams .= $msgIdsStr;
} elseif (is_string($msgIds)) {
$queryParams .= $msgIds;
} else {
throw new InvalidArgumentException("Invalid msg_ids");
}
$url = $this->client->makeURL('report') . 'received' . $queryParams;
return Http::get($this->client, $url);
}
/*
送达统计详情(新)
https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/#_7
*/
public function getReceivedDetail($msgIds) {
$queryParams = '?msg_ids=';
if (is_array($msgIds) && !empty($msgIds)) {
$msgIdsStr = implode(',', $msgIds);
$queryParams .= $msgIdsStr;
} elseif (is_string($msgIds)) {
$queryParams .= $msgIds;
} else {
throw new InvalidArgumentException("Invalid msg_ids");
}
$url = $this->client->makeURL('report') . 'received/detail' . $queryParams;
return Http::get($this->client, $url);
}
public function getMessageStatus($msgId, $rids, $data = null) {
$url = $this->client->makeURL('report') . 'status/message';
$registrationIds = is_array($rids) ? $rids : array($rids);
$body = [
'msg_id' => $msgId,
'registration_ids' => $registrationIds
];
if (!is_null($data)) {
$body['data'] = $data;
}
return Http::post($this->client, $url, $body);
}
public function getMessages($msgIds) {
$queryParams = '?msg_ids=';
if (is_array($msgIds) && !empty($msgIds)) {
$msgIdsStr = implode(',', $msgIds);
$queryParams .= $msgIdsStr;
} elseif (is_string($msgIds)) {
$queryParams .= $msgIds;
} else {
throw new InvalidArgumentException("Invalid msg_ids");
}
$url = $this->client->makeURL('report') . 'messages/' .$queryParams;
return Http::get($this->client, $url);
}
/*
消息统计详情(VIP 专属接口,新)
https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/#vip_1
*/
public function getMessagesDetail($msgIds) {
$queryParams = '?msg_ids=';
if (is_array($msgIds) && !empty($msgIds)) {
$msgIdsStr = implode(',', $msgIds);
$queryParams .= $msgIdsStr;
} elseif (is_string($msgIds)) {
$queryParams .= $msgIds;
} else {
throw new InvalidArgumentException("Invalid msg_ids");
}
$url = $this->client->makeURL('report') . 'messages/detail' .$queryParams;
return Http::get($this->client, $url);
}
public function getUsers($time_unit, $start, $duration) {
$time_unit = strtoupper($time_unit);
if (!in_array($time_unit, self::$EFFECTIVE_TIME_UNIT)) {
throw new InvalidArgumentException('Invalid time unit');
}
$url = $this->client->makeURL('report') . 'users/?time_unit=' . $time_unit . '&start=' . $start . '&duration=' . $duration;
return Http::get($this->client, $url);
}
}
<?php
namespace JPush;
use InvalidArgumentException;
class SchedulePayload {
private $client;
/**
* SchedulePayload constructor.
* @param $client JPush
*/
public function __construct($client) {
$this->client = $client;
}
public function createSingleSchedule($name, $push_payload, $trigger) {
if (!is_string($name)) {
throw new InvalidArgumentException('Invalid schedule name');
}
if (!is_array($push_payload)) {
throw new InvalidArgumentException('Invalid schedule push payload');
}
if (!is_array($trigger)) {
throw new InvalidArgumentException('Invalid schedule trigger');
}
$payload = array();
$payload['name'] = $name;
$payload['enabled'] = true;
$payload['trigger'] = array("single"=>$trigger);
$payload['push'] = $push_payload;
$url = $this->client->makeURL('schedule');
return Http::post($this->client, $url, $payload);
}
public function createPeriodicalSchedule($name, $push_payload, $trigger) {
if (!is_string($name)) {
throw new InvalidArgumentException('Invalid schedule name');
}
if (!is_array($push_payload)) {
throw new InvalidArgumentException('Invalid schedule push payload');
}
if (!is_array($trigger)) {
throw new InvalidArgumentException('Invalid schedule trigger');
}
$payload = array();
$payload['name'] = $name;
$payload['enabled'] = true;
$payload['trigger'] = array("periodical"=>$trigger);
$payload['push'] = $push_payload;
$url = $this->client->makeURL('schedule');
return Http::post($this->client, $url, $payload);
}
public function updateSingleSchedule($schedule_id, $name=null, $enabled=null, $push_payload=null, $trigger=null) {
if (!is_string($schedule_id)) {
throw new InvalidArgumentException('Invalid schedule id');
}
$payload = array();
if (!is_null($name)) {
if (!is_string($name)) {
throw new InvalidArgumentException('Invalid schedule name');
} else {
$payload['name'] = $name;
}
}
if (!is_null($enabled)) {
if (!is_bool($enabled)) {
throw new InvalidArgumentException('Invalid schedule enable');
} else {
$payload['enabled'] = $enabled;
}
}
if (!is_null($push_payload)) {
if (!is_array($push_payload)) {
throw new InvalidArgumentException('Invalid schedule push payload');
} else {
$payload['push'] = $push_payload;
}
}
if (!is_null($trigger)) {
if (!is_array($trigger)) {
throw new InvalidArgumentException('Invalid schedule trigger');
} else {
$payload['trigger'] = array("single"=>$trigger);
}
}
if (count($payload) <= 0) {
throw new InvalidArgumentException('Invalid schedule, name, enabled, trigger, push can not all be null');
}
$url = $this->client->makeURL('schedule') . "/" . $schedule_id;
return Http::put($this->client, $url, $payload);
}
public function updatePeriodicalSchedule($schedule_id, $name=null, $enabled=null, $push_payload=null, $trigger=null) {
if (!is_string($schedule_id)) {
throw new InvalidArgumentException('Invalid schedule id');
}
$payload = array();
if (!is_null($name)) {
if (!is_string($name)) {
throw new InvalidArgumentException('Invalid schedule name');
} else {
$payload['name'] = $name;
}
}
if (!is_null($enabled)) {
if (!is_bool($enabled)) {
throw new InvalidArgumentException('Invalid schedule enable');
} else {
$payload['enabled'] = $enabled;
}
}
if (!is_null($push_payload)) {
if (!is_array($push_payload)) {
throw new InvalidArgumentException('Invalid schedule push payload');
} else {
$payload['push'] = $push_payload;
}
}
if (!is_null($trigger)) {
if (!is_array($trigger)) {
throw new InvalidArgumentException('Invalid schedule trigger');
} else {
$payload['trigger'] = array("periodical"=>$trigger);
}
}
if (count($payload) <= 0) {
throw new InvalidArgumentException('Invalid schedule, name, enabled, trigger, push can not all be null');
}
$url = $this->client->makeURL('schedule') . "/" . $schedule_id;
return Http::put($this->client, $url, $payload);
}
public function getSchedules($page = 1) {
if (!is_int($page)) {
$page = 1;
}
$url = $this->client->makeURL('schedule') . "?page=" . $page;
return Http::get($this->client, $url);
}
public function getSchedule($schedule_id) {
if (!is_string($schedule_id)) {
throw new InvalidArgumentException('Invalid schedule id');
}
$url = $this->client->makeURL('schedule') . "/" . $schedule_id;
return Http::get($this->client, $url);
}
public function deleteSchedule($schedule_id) {
if (!is_string($schedule_id)) {
throw new InvalidArgumentException('Invalid schedule id');
}
$url = $this->client->makeURL('schedule') . "/" . $schedule_id;
return Http::delete($this->client, $url);
}
public function getMsgIds($schedule_id) {
if (!is_string($schedule_id)) {
throw new InvalidArgumentException('Invalid schedule id');
}
$url = $this->client->makeURL('schedule') . '/' . $schedule_id . '/msg_ids';
return Http::get($this->client, $url);
}
}
<?php
class test
{
public function __construct()
{
}
public function push(){
return "就这样吧";
}
}
\ No newline at end of file
<?php
namespace JPush;
const VERSION = '3.6.6';
<?php
use xmpush\Builder;
use xmpush\HttpBase;
use xmpush\Sender;
use xmpush\Constants;
use xmpush\Stats;
use xmpush\Tracer;
use xmpush\Feedback;
use xmpush\DevTools;
use xmpush\Subscription;
use xmpush\TargetedMessage;
use xmpush\Region;
include_once(dirname(__FILE__) . '/autoload.php');
$secret = 'your app secret';
$package = 'your app packagename';
// 常量设置必须在new Sender()方法之前调用
Constants::setPackage($package);
Constants::setSecret($secret);
$aliasList = array('alias1', 'alias2');
$title = '你好';
$desc = '这是一条mipush推送消息';
$payload = '{"test":1,"ok":"It\'s a string"}';
$sender = new Sender();
// $sender->setRegion(Region::China);// 支持海外
// message1 演示自定义的点击行为
$message1 = new Builder();
$message1->title($title); // 通知栏的title
$message1->description($desc); // 通知栏的descption
$message1->passThrough(0); // 这是一条通知栏消息,如果需要透传,把这个参数设置成1,同时去掉title和descption两个参数
$message1->payload($payload); // 携带的数据,点击后将会通过客户端的receiver中的onReceiveMessage方法传入。
$message1->extra(Builder::notifyForeground, 1); // 应用在前台是否展示通知,如果不希望应用在前台时候弹出通知,则设置这个参数为0
$message1->notifyId(2); // 通知类型。最多支持0-4 5个取值范围,同样的类型的通知会互相覆盖,不同类型可以在通知栏并存
$message1->build();
$targetMessage = new TargetedMessage();
$targetMessage->setTarget('alias1', TargetedMessage::TARGET_TYPE_ALIAS); // 设置发送目标。可通过regID,alias和topic三种方式发送
$targetMessage->setMessage($message1);
// message2 演示预定义点击行为中的点击直接打开app行为
$message2 = new Builder();
$message2->title($title);
$message2->description($desc);
$message2->passThrough(0);
$message2->payload($payload); // 对于预定义点击行为,payload会通过点击进入的界面的intent中的extra字段获取,而不会调用到onReceiveMessage方法。
$message2->extra(Builder::notifyEffect, 1); // 此处设置预定义点击行为,1为打开app
$message2->extra(Builder::notifyForeground, 1);
$message2->notifyId(0);
$message2->build();
$targetMessage2 = new TargetedMessage();
$targetMessage2->setTarget('alias2', TargetedMessage::TARGET_TYPE_ALIAS);
$targetMessage2->setMessage($message2);
$targetMessageList = array($targetMessage, $targetMessage2);
//print_r($sender->multiSend($targetMessageList,TargetedMessage::TARGET_TYPE_ALIAS)->getRaw());
print_r($sender->sendToAliases($message1, $aliasList)->getRaw());
//$stats = new Stats();
//$startDate = '20140301';
//$endDate = '20140312';
//print_r($stats->getStats($startDate,$endDate)->getData());
//$tracer = new Tracer();
//print_r($tracer->getMessageStatusById('t1000270409640393266xW')->getRaw());
?>
<?php
define('MiPush_Root', dirname(__FILE__) . '/');
function mipushAutoload($classname) {
$parts = explode('\\', $classname);
$path = MiPush_Root . implode('/', $parts) . '.php';
if (file_exists($path)) {
include($path);
}
}
spl_autoload_register('mipushAutoload');
<?php
use xmpush\IOSBuilder;
use xmpush\Sender;
use xmpush\Constants;
use xmpush\Stats;
use xmpush\Tracer;
use xmpush\Region;
include_once(dirname(__FILE__) . '/autoload.php');
$secret = 'your app secret';
$bundleId = 'your app bundleId';
Constants::setBundleId($bundleId);
Constants::setSecret($secret);
$aliasList = array('2', 'alias2');
$desc = '这是一条mipush推送消息';
$payload = '{"test":1,"ok":"It\'s a string"}';
$message = new IOSBuilder();
$message->description($desc);
$message->soundUrl('default');
$message->badge('4');
$message->extra('payload', $payload);
$message->build();
$sender = new Sender();
// $sender->setRegion(Region::China);// 支持海外
print_r($sender->sendToAliases($message, $aliasList)->getRaw());
?>
<?php
/**
* (android)消息体.
* @author wangkuiwei
* @name Builder
* @desc 构建发送给Android设备的Message对象。
*
*/
namespace MiPush\xmpush;
class Builder extends Message {
const soundUri = 'sound_uri';
const notifyForeground = 'notify_foreground';
const notifyEffect = 'notify_effect';
const intentUri = 'intent_uri';
const webUri = 'web_uri';
const flowControl = 'flow_control';
const callback = 'callback';
const instantNotify = 'instant_notify';
public function __construct() {
$this->notify_id = 0;
$this->notify_type = -1;
$this->payload = '';
$this->restricted_package_name = Constants::$packageName;
parent::__construct();
}
public function payload($payload) {
$this->payload = $payload;
}
public function title($title) {
$this->title = $title;
}
public function description($description) {
$this->description = $description;
}
public function passThrough($passThrough) {
$this->pass_through = $passThrough;
}
public function notifyType($type) {
$this->notify_type = $type;
}
public function restrictedPackageNames($packageNameList) {
$jointPackageNames = '';
foreach ($packageNameList as $packageName) {
if (isset($packageName)) {
$jointPackageNames .= $packageName . Constants::$comma;
}
}
$this->restricted_package_name = $jointPackageNames;
}
public function timeToLive($ttl) {
$this->time_to_live = $ttl;
}
public function timeToSend($timeToSend) {
$this->time_to_send = $timeToSend;
}
public function instantNotify($isInstantNotify) {
if ($isInstantNotify) {
$this->extra(self::instantNotify, "1");
} else {
unset($this->extra[self::instantNotify]);
}
}
public function notifyId($notifyId) {
$this->notify_id = $notifyId;
}
public function hybridPath($value) {
$this->extra[self::HYBRID_PATH] = $value;
}
public function extra($key, $value) {
$this->extra[$key] = $value;
}
public function build() {
$keys = array(
'payload', 'title', 'description', 'pass_through', 'notify_type',
'restricted_package_name', 'time_to_live', 'time_to_send', 'notify_id'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
$this->json_infos[$key] = $this->$key;
}
}
//单独处理extra
$JsonExtra = array();
if (count($this->extra) > 0) {
foreach ($this->extra as $extraKey => $extraValue) {
$this->fields[Message::EXTRA_PREFIX . $extraKey] = $extraValue;
$JsonExtra[$extraKey] = $extraValue;
}
}
$this->json_infos['extra'] = $JsonExtra;
}
}
?>
<?php
/**
* 常量定义.
* @author wangkuiwei
* @name Constants
* @desc 常量定义
*
*/
namespace MiPush\xmpush;
class Constants {
public static $comma = ',';
public static $multi_topic_split = ';$;';
public static $packageName = '';
public static $bundle_id = '';
public static $secret = '';
/**
* 是否在网络访问问题时,自动切换访问的域名
*/
public static $autoSwitchHost = true;
/**
* 网络访问的超时时间,当超过该时间时,则认为可用性较低,会优先选择其他域名
*/
public static $accessTimeOut = 5000;
public static $HTTP_PROTOCOL = "https";
public static $USE_HTTPS = true;
/**
* 是否测试环境
*/
public static $sandbox = false;
/**
* 如果设置了IP、域名,则使用手动设置的值,只用于内部测试,不对外开放
*/
/**
* @return string
*/
public static $host = null;
const reg_url = '/v3/message/regid';
const alias_url = '/v3/message/alias';
const user_account_url = '/v2/message/user_account';
const topic_url = '/v3/message/topic';
const multi_topic_url = '/v3/message/multi_topic';
const all_url = '/v3/message/all';
const multi_messages_regids_url = '/v2/multi_messages/regids';
const multi_messages_aliases_url = '/v2/multi_messages/aliases';
const multi_messages_user_accounts_url = '/v2/multi_messages/user_accounts';
const stats_url = '/v1/stats/message/counters';
const message_trace_url = '/v1/trace/message/status';
const messages_trace_url = '/v1/trace/messages/status';
const validation_regids_url = '/v1/validation/regids';
const subscribe_url = '/v2/topic/subscribe';
const unsubscribe_url = '/v2/topic/unsubscribe';
const subscribe_alias_url = '/v2/topic/subscribe/alias';
const unsubscribe_alias_url = '/v2/topic/unsubscribe/alias';
const fetch_invalid_regids_url = 'https://feedback.xmpush.xiaomi.com/v1/feedback/fetch_invalid_regids';
const delete_schedule_job = '/v2/schedule_job/delete';
const check_schedule_job_exist = '/v2/schedule_job/exist';
const get_all_aliases = '/v1/alias/all';
const get_all_topics = '/v1/topic/all';
const UNION = 'UNION';
const INTERSECTION = 'INTERSECTION';
const EXCEPT = 'EXCEPT';
/**
* 相关域名定义
*/
const HOST_EMQ = "emq.xmpush.xiaomi.com";
const HOST_SANDBOX = "sandbox.xmpush.xiaomi.com";
/**
* 国内机房相关域名
*/
const HOST_PRODUCTION = "api.xmpush.xiaomi.com";
const HOST_PRODUCTION_FEEDBACK = "feedback.xmpush.xiaomi.com";
/**
* 海外机房相关域名
*/
const HOST_GLOBAL_PRODUCTION = "api.xmpush.global.xiaomi.com";
const HOST_GLOBAL_PRODUCTION_FEEDBACK = "feedback.xmpush.global.xiaomi.com";
/**
* VIP域名
*/
const HOST_VIP = "vip.api.xmpush.xiaomi.com";
const X_PUSH_HOST_LIST = "X-PUSH-HOST-LIST";
const HOST_RESPONSE_EXPECT_TIME = 5; // 响应时间低于这个值,host降权
const X_PUSH_SDK_VERSION = "X-PUSH-SDK-VERSION";
const SDK_VERSION = "PHP_SDK_V2.2.21";
const EXTRA_PARAM_NOTIFY_EFFECT = "notify_effect";
const NOTIFY_LAUNCHER_ACTIVITY = "1";
const NOTIFY_ACTIVITY = "2";
const NOTIFY_WEB = "3";
const EXTRA_PARAM_INTENT_URI = "intent_uri";
const EXTRA_PARAM_WEB_URI = "web_uri";
public static function setPackage($package) {
self::$packageName = $package;
}
public static function setSecret($secret) {
self::$secret = $secret;
}
public static function setBundleId($bundleId) {
self::$bundle_id = $bundleId;
}
public static function useOfficial() {
self::$sandbox = false;
self::$host = null;
}
public static function useSandbox() {
self::$sandbox = true;
self::$host = null;
}
/**
* 仅限内部使用,用户测试专门的IP
*/
public static function useInternalHost($hostOrIP) {
self::$host = $hostOrIP;
}
public static function useHttp() {
self::$HTTP_PROTOCOL = "http";
}
}
?>
<?php
/**
* 设备查询工具集.
* @author wangkuiwei
* @name DevTools
*
*/
namespace MiPush\xmpush;
class DevTools extends HttpBase {
public function __construct() {
parent::__construct();
}
public function getAliasesOf($packageName, $regId, $retries = 1) {
$fields = array('registration_id' => $regId, 'restricted_package_name' => $packageName);
$result = $this->getResult(PushRequestPath::V1_GET_ALL_ALIAS(), $fields, $retries);
return $result;
}
public function getTopicsOf($packageName, $regId, $retries = 1) {
$fields = array('registration_id' => $regId, 'restricted_package_name' => $packageName);
$result = $this->getResult(PushRequestPath::V1_GET_ALL_TOPIC(), $fields, $retries);
return $result;
}
}
?>
<?php
/**
* 错误码定义.
* @author wangkuiwei
* @name ErrorCode
* @desc 错误码
*
*/
namespace MiPush\xmpush;
class ErrorCode {
const Success = 0;
const NETWORK_ERROR_TIMEOUT = -1;
}
?>
<?php
/**
* 获取失效的regId列表.
* @author wangkuiwei
* @name Feedback
* @desc 获取失效的regId列表。
*
*/
namespace MiPush\xmpush;
class Feedback extends HttpBase {
public function __construct() {
parent::__construct();
}
public function getInvalidRegIds($retries = 1) {
$result = $this->getResult(PushRequestPath::V1_FEEDBACK_INVALID_REGID(), array(), $retries);
return $result;
}
}
?>
<?php
/**
* @author wangkuiwei
* @name HttpBase
*
*/
namespace MiPush\xmpush;
class HttpBase {
private $appSecret;
private $region;
private $isVip;
/**
* @param string $appSecret
*/
public function setAppSecret($appSecret) {
$this->appSecret = $appSecret;
}
/**
* @param int $region
*/
public function setRegion($region) {
$this->region = $region;
}
/**
* @param bool $isVip
*/
public function setIsVip($isVip) {
$this->isVip = $isVip;
}
public function __construct() {
$this->appSecret = Constants::$secret;
$this->region = Region::China;
$this->isVip = false;
}
//发送请求,获取result,带重试
public function getResult($requestPath, $fields, $retries) {
$result = new Result($this->getReq($requestPath, $fields));
if ($result->getErrorCode() == ErrorCode::Success) {
return $result;
}
//重试
for ($i = 0; $i < $retries; $i++) {
$result = new Result($this->getReq($requestPath, $fields));
if ($result->getErrorCode() == ErrorCode::Success) {
break;
}
}
return $result;
}
//get方式发送请求
public function getReq($requestPath, $fields, $timeout = 3) {
return $this->httpRequest($requestPath, $fields, "Get", $timeout);
}
//发送请求,获取result,带重试
public function postResult($requestPath, $fields, $retries) {
$result = new Result($this->postReq($requestPath, $fields));
if ($result->getErrorCode() == ErrorCode::Success) {
return $result;
}
//重试
for ($i = 0; $i < $retries; $i++) {
$result = new Result($this->postReq($requestPath, $fields));
if ($result->getErrorCode() == ErrorCode::Success) {
break;
}
}
return $result;
}
//post方式发送请求
public function postReq($requestPath, $fields, $timeout = 10) {
return $this->httpRequest($requestPath, $fields, "Post", $timeout);
}
private function buildFullRequestURL(Server $server, PushRequestPath $requestPath) {
return Constants::$HTTP_PROTOCOL . "://" . $server->getHost() . $requestPath->getPath();
}
private function httpRequest($requestPath, $fields, $method, $timeout = 10) {
$server = ServerSwitch::getInstance()->selectServer($requestPath, $this->region, $this->isVip);
$url = $this->buildFullRequestURL($server, $requestPath);
$headers = array('Authorization: key=' . $this->appSecret,
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
Constants::X_PUSH_SDK_VERSION . ': ' . Constants::SDK_VERSION);
if (Constants::$autoSwitchHost && ServerSwitch::getInstance()->needRefreshHostList()) {
array_push($headers, Constants::X_PUSH_HOST_LIST . ': true');
}
array_push($headers, "Expect:");
// Open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
if ($method == "Post") {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
} else {
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($fields));
curl_setopt($ch, CURLOPT_POST, false);
}
$content = curl_exec($ch);
$result = "";
if ($content !== false) {
$info = curl_getinfo($ch);
$total_time = $info['total_time'];
if ($total_time > Constants::HOST_RESPONSE_EXPECT_TIME) {
$server->decrPriority();
} else {
$server->incrPriority();
}
list($responseHeaderStr, $result) = explode("\r\n\r\n", $content, 2);
$responseHeaders = $this->convertHeaders($responseHeaderStr);
if (array_key_exists(Constants::X_PUSH_HOST_LIST, $responseHeaders)) {
$serverListStr = $responseHeaders[Constants::X_PUSH_HOST_LIST];
ServerSwitch::getInstance()->initialize($serverListStr);
}
} else {
$server->decrPriority();
$result = json_encode(array(
"code" => ErrorCode::NETWORK_ERROR_TIMEOUT,
"reason" => "network error or timeout"
));
}
// Close connection
curl_close($ch);
return $result;
}
/**
* @param $responseHeaderStr
* @return array
*/
private function convertHeaders($responseHeaderStr) {
$responseHeaderArr = explode("\r\n", $responseHeaderStr);
$responseHeaders = array();
foreach ($responseHeaderArr as $responseHeader) {
$items = explode(":", $responseHeader, 2);
if ($items !== false) {
if (count($items) == 2) {
$responseHeaders[trim($items[0])] = trim($items[1]);
} else {
$responseHeaders["Header_" . count($responseHeaders)] = trim($responseHeader);
}
}
}
return $responseHeaders;
}
}
?>
<?php
/**
* IOS设备的消息体.
* @author wangkuiwei
* @name IOSBuilder
* @desc 构建发送给IOS设备的Message对象。
*
*/
namespace MiPush\xmpush;
class IOSBuilder extends Message {
const soundUrl = 'sound_url';
const badge = 'badge';
protected $apsProperFields; // 用于存储aps的属性,为的是支持新的扩展属性
public function __construct() {
parent::__construct();
$this->apsProperFields = array();
}
public function description($description) {
$this->description = $description;
}
public function timeToLive($ttl) {
$this->time_to_live = $ttl;
}
public function timeToSend($timeToSend) {
$this->time_to_send = $timeToSend;
}
public function soundUrl($url) {
$this->extra(IOSBuilder::soundUrl, $url);
}
public function badge($badge) {
$this->extra(IOSBuilder::badge, $badge);
}
public function contentAvailable($value) {
$this->extra("content-available", $value);
}
public function showContent() {
$this->extra("show-content", "1");
}
public function extra($key, $value) {
$this->extra[$key] = $value;
}
public function title($title) {
$this->apsProperFields["title"] = $title;
}
public function subtitle($subtitle) {
$this->apsProperFields["subtitle"] = $subtitle;
}
public function body($body) {
$this->apsProperFields["body"] = $body;
}
public function mutableContent($mutableContent) {
$this->apsProperFields["mutable-content"] = $mutableContent;
}
public function apsProperFields($key, $value) {
$this->apsProperFields[$key] = $value;
}
public function build() {
$keys = array(
'description', 'time_to_live', 'time_to_send'
);
foreach ($keys as $key) {
if (isset($this->$key)) {
$this->fields[$key] = $this->$key;
$this->json_infos[$key] = $this->$key;
}
}
//单独处理extra
$JsonExtra = array();
if (count($this->extra) > 0) {
foreach ($this->extra as $extraKey => $extraValue) {
$this->fields[Message::EXTRA_PREFIX . $extraKey] = $extraValue;
$JsonExtra[$extraKey] = $extraValue;
}
}
$this->json_infos['extra'] = $JsonExtra;
// 单独处理apsProperFields
if (count($this->apsProperFields) > 0) {
foreach ($this->apsProperFields as $key => $value) {
$this->fields[Message::APS_PROPER_FIELDS_PREFIX . $key] = $value;
}
}
}
}
?>
<?php
/**
* 消息体.
* @author wangkuiwei
* @name Message
* @desc 构建要发送的消息内容。
*
*/
namespace MiPush\xmpush;
class Message {
const EXTRA_PREFIX = 'extra.';
const APS_PROPER_FIELDS_PREFIX = 'aps_proper_fields.';
const HYBRID_PUSH_ACTION = "push_server_action";
const HYBRID_ACTION_MESSAGE = "hybrid_message";
const HYBRID_DEBUG = "hybrid_debug";
const HYBRID_PATH = "hybrid_pn";
protected $payload; //消息内容
protected $restricted_package_name; //支持多包名
protected $pass_through; //是否透传给app(1 透传 0 通知栏信息)
protected $notify_type; //通知类型 可组合 (-1 Default_all,1 Default_sound,2 Default_vibrate(震动),4 Default_lights)
protected $notify_id; //0-4同一个notifyId在通知栏只会保留一条
protected $extra; //可选项,额外定义一些key value(字符不能超过1024,key不能超过10个)
protected $description; //在通知栏的描述,长度小于128
protected $title; //在通知栏的标题,长度小于16
protected $time_to_live; //可选项,当用户离线是,消息保留时间,默认两周,单位ms
protected $time_to_send; //可选项,定时发送消息,用自1970年1月1日以来00:00:00.0 UTC时间表示(以毫秒为单位的时间)。
protected $fields; //含有本条消息所有属性的数组
protected $json_infos;
/* IOS 使用 */
protected $sound_url; //可选,消息铃声
protected $badge; //可选,自定义通知数字角标
public function __construct() {
$this->extra = array();
$this->fields = array();
}
public function getFields() {
return $this->fields;
}
public function getJSONInfos() {
return $this->json_infos;
}
}
?>
<?php
/**
* Created by PhpStorm.
* User: zhangdali
* Date: 2016/12/7
* Time: 下午6:30
*/
namespace MiPush\xmpush;
class PushRequestPath {
// regid message
static function V2_SEND() {
return new static("/v2/send", PushRequestType::MESSAGE);
}
static function V2_REGID_MESSAGE() {
return new static("/v2/message/regid", PushRequestType::MESSAGE);
}
static function V3_REGID_MESSAGE() {
return new static("/v3/message/regid", PushRequestType::MESSAGE);
}
// subscribe topic
static function V2_SUBSCRIBE_TOPIC() {
return new static("/v2/topic/subscribe", PushRequestType::MESSAGE);
}
static function V2_UNSUBSCRIBE_TOPIC() {
return new static("/v2/topic/unsubscribe", PushRequestType::MESSAGE);
}
static function V2_SUBSCRIBE_TOPIC_BY_ALIAS() {
return new static("/v2/topic/subscribe/alias", PushRequestType::MESSAGE);
}
static function V2_UNSUBSCRIBE_TOPIC_BY_ALIAS() {
return new static("/v2/topic/unsubscribe/alias", PushRequestType::MESSAGE);
}
// alias message
static function V2_ALIAS_MESSAGE() {
return new static("/v2/message/alias", PushRequestType::MESSAGE);
}
static function V3_ALIAS_MESSAGE() {
return new static("/v3/message/alias", PushRequestType::MESSAGE);
}
// broadcast message
static function V2_BROADCAST_TO_ALL() {
return new static("/v2/message/all", PushRequestType::MESSAGE);
}
static function V3_BROADCAST_TO_ALL() {
return new static("/v3/message/all", PushRequestType::MESSAGE);
}
static function V2_BROADCAST() {
return new static("/v2/message/topic", PushRequestType::MESSAGE);
}
static function V3_BROADCAST() {
return new static("/v3/message/topic", PushRequestType::MESSAGE);
}
static function V2_MULTI_TOPIC_BROADCAST() {
return new static("/v2/message/multi_topic", PushRequestType::MESSAGE);
}
static function V3_MILTI_TOPIC_BROADCAST() {
return new static("/v3/message/multi_topic", PushRequestType::MESSAGE);
}
static function V2_DELETE_BROADCAST_MESSAGE() {
return new static("/v2/message/delete", PushRequestType::MESSAGE);
}
// user account message
static function V2_USER_ACCOUNT_MESSAGE() {
return new static("/v2/message/user_account", PushRequestType::MESSAGE);
}
// miid message
static function V2_MIID_MESSAGE() {
return new static("/v2/message/miid", PushRequestType::MESSAGE);
}
// multi message
static function V2_SEND_MULTI_MESSAGE_WITH_REGID() {
return new self("/v2/multi_messages/regids", PushRequestType::MESSAGE);
}
static function V2_SEND_MULTI_MESSAGE_WITH_ALIAS() {
return new self("/v2/multi_messages/aliases", PushRequestType::MESSAGE);
}
static function V2_SEND_MULTI_MESSAGE_WITH_ACCOUNT() {
return new self("/v2/multi_messages/user_accounts", PushRequestType::MESSAGE);
}
// validate
static function V1_VALIDATE_REGID() {
return new static("/v1/validation/regids", PushRequestType::MESSAGE);
}
static function V1_GET_ALL_ACCOUNT() {
return new static("/v1/account/all", PushRequestType::MESSAGE);
}
static function V1_GET_ALL_TOPIC() {
return new static("/v1/topic/all", PushRequestType::MESSAGE);
}
static function V1_GET_ALL_ALIAS() {
return new static("/v1/alias/all", PushRequestType::MESSAGE);
}
static function V1_GET_ALL_MIID() {
return new static("/v1/miid/all", PushRequestType::MESSAGE);
}
// trace
static function V1_MESSAGES_STATUS() {
return new static("/v1/trace/messages/status", PushRequestType::MESSAGE);
}
static function V1_MESSAGE_STATUS() {
return new static("/v1/trace/message/status", PushRequestType::MESSAGE);
}
static function V1_GET_MESSAGE_COUNTERS() {
return new static("/v1/stats/message/counters", PushRequestType::MESSAGE);
}
// presence
static function V1_REGID_PRESENCE() {
return new static("/v1/regid/presence", PushRequestType::MESSAGE);
}
static function V2_REGID_PRESENCE() {
return new static("/v1/regid/presence", PushRequestType::MESSAGE);
}
// schedule job
static function V2_DELETE_SCHEDULE_JOB() {
return new static("/v2/schedule_job/delete", PushRequestType::MESSAGE);
}
static function V3_DELETE_SCHEDULE_JOB() {
return new static("/v3/schedule_job/delete", PushRequestType::MESSAGE);
}
static function V2_CHECK_SCHEDULE_JOB_EXIST() {
return new static("/v2/schedule_job/exist", PushRequestType::MESSAGE);
}
static function V2_QUERY_SCHEDULE_JOB() {
return new static("/v2/schedule_job/query", PushRequestType::MESSAGE);
}
// feedback
static function V1_FEEDBACK_INVALID_ALIAS() {
return new static("/v1/feedback/fetch_invalid_aliases", PushRequestType::FEEDBACK);
}
static function V1_FEEDBACK_INVALID_REGID() {
return new static("/v1/feedback/fetch_invalid_regids", PushRequestType::FEEDBACK);
}
static function V1_FEEDBACK_INVALID_MIID() {
return new static("/v1/feedback/fetch_invalid_miid", PushRequestType::FEEDBACK);
}
// emq job
static function V1_EMQ_ACK_INFO() {
return new static("/msg/ack/info", PushRequestType::EMQ);
}
static function V1_EMQ_CLICK_INFO() {
return new static("/msg/click/info", PushRequestType::EMQ);
}
static function V1_EMQ_INVALID_REGID() {
return new static("/app/invalid/regid", PushRequestType::EMQ);
}
/**
* PushRequestPath constructor.
* @param string $path
* @param int $requestType
*/
public function __construct($path, $requestType) {
$this->path = $path;
$this->requestType = $requestType;
}
/**
* @return int
*/
public function getRequestType() {
return $this->requestType;
}
/**
* @return string
*/
public function getPath() {
return $this->path;
}
/**
* @var string
*/
private $path;
/**
* @var int
*/
private $requestType;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: zhangdali
* Date: 2016/12/13
* Time: 下午5:26
*/
namespace MiPush\xmpush;
class PushRequestType {
const MESSAGE = 0;
const FEEDBACK = 1;
const EMQ = 2;
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: zhangdali
* Date: 2018/3/12
* Time: 下午5:44
*/
namespace MiPush\xmpush;
class Region {
const China = 0; // 国内
const Other = 1; // 国外其他地方,比如新加坡
public static function getFeedbackHostList() {
return array(
Region::China => Constants::HOST_PRODUCTION_FEEDBACK,
Region::Other => Constants::HOST_GLOBAL_PRODUCTION_FEEDBACK
);
}
public static function getApiHostList() {
return array(
Region::China => Constants::HOST_PRODUCTION,
Region::Other => Constants::HOST_GLOBAL_PRODUCTION
);
}
}
\ No newline at end of file
<?php
/**
* 服务器返回的结果.
* @author wangkuiwei
* @name Result
* @desc Sender发送消息后,服务器返回的结果。
*
*/
namespace MiPush\xmpush;
class Result {
private $errorCode;
private $raw;
public function __construct($jsonStr) {
$data = json_decode($jsonStr, true);
$this->raw = $data;
$this->errorCode = $data['code'];
}
public function getErrorCode() {
return $this->errorCode;
}
public function getRaw() {
return $this->raw;
}
}
?>
<?php
/**
* MiPush消息发送类.
* @author wangkuiwei
* @name Sender
* @desc MiPush消息发送
*
*/
namespace MiPush\xmpush;
class Sender extends HttpBase {
public function __construct() {
parent::__construct();
}
//指定regId单发消息
public function send(Message $message, $regId, $retries = 1) {
$fields = $message->getFields();
$fields['registration_id'] = $regId;
return $this->postResult(PushRequestPath::V3_REGID_MESSAGE(), $fields, $retries);
}
//指定regId列表群发
public function sendToIds(Message $message, $regIdList, $retries = 1) {
$fields = $message->getFields();
$jointRegIds = '';
foreach ($regIdList as $regId) {
if (isset($regId)) {
$jointRegIds .= $regId . Constants::$comma;
}
}
$fields['registration_id'] = $jointRegIds;
return $this->postResult(PushRequestPath::V3_REGID_MESSAGE(), $fields, $retries);
}
//多条发送
public function multiSend($targetMessages, $type, $retries = 1) {
$requestPath = $this->multiSendRequestPath($type);
$data = array();
foreach ($targetMessages as $targetMsg) {
array_push($data, $targetMsg->getFields());
}
$fields = array('messages' => json_encode($data));
return $this->postResult($requestPath, $fields, $retries);
}
//多条发送
public function multiSendAtTime($targetMessages, $type, $timeToSend, $retries = 1) {
$requestPath = $this->multiSendRequestPath($type);
$data = array();
foreach ($targetMessages as $targetMsg) {
array_push($data, $targetMsg->getFields());
}
$fields = array('messages' => json_encode($data), 'time_to_send' => $timeToSend);
return $this->postResult($requestPath, $fields, $retries);
}
//指定别名单发
public function sendToAlias(Message $message, $alias, $retries = 1) {
$fields = $message->getFields();
$fields['alias'] = $alias;
return $this->postResult(PushRequestPath::V3_ALIAS_MESSAGE(), $fields, $retries);
}
//指定别名列表群发
public function sendToAliases(Message $message, $aliasList, $retries = 1) {
$fields = $message->getFields();
$jointAliases = '';
foreach ($aliasList as $alias) {
if (strlen($jointAliases) > 0) {
$jointAliases = $jointAliases . Constants::$comma;
}
$jointAliases = $jointAliases . $alias;
}
$fields['alias'] = $jointAliases;
return $this->postResult(PushRequestPath::V3_ALIAS_MESSAGE(), $fields, $retries);
}
//指定userAccount群发
public function sendToUserAccount(Message $message, $userAccount, $retries = 1) {
$fields = $message->getFields();
$fields['user_account'] = $userAccount;
return $this->postResult(PushRequestPath::V2_USER_ACCOUNT_MESSAGE(), $fields, $retries);
}
//指定userAccount列表群发
public function sendToUserAccounts(Message $message, $userAccountList, $retries = 1) {
$fields = $message->getFields();
$jointUserAccounts = '';
foreach ($userAccountList as $userAccount) {
if (strlen($jointUserAccounts) > 0) {
$jointUserAccounts = $jointUserAccounts . Constants::$comma;
}
$jointUserAccounts = $jointUserAccounts . $userAccount;
}
$fields['user_account'] = $jointUserAccounts;
return $this->postResult(PushRequestPath::V2_USER_ACCOUNT_MESSAGE(), $fields, $retries);
}
//指定topic群发,指定标签推送
public function broadcast(Message $message, $topic, $retries = 1) {
$fields = $message->getFields();
$fields['topic'] = $topic;
return $this->postResult(PushRequestPath::V3_BROADCAST(), $fields, $retries);
}
//向所有设备发送消息
public function broadcastAll(Message $message, $retries = 1) {
$fields = $message->getFields();
return $this->postResult(PushRequestPath::V3_BROADCAST_TO_ALL(), $fields, $retries);
}
//广播消息,多个topic,支持topic间的交集、并集或差集
public function multiTopicBroadcast(Message $message, $topicList, $topicOp, $retries = 1) {
if (count($topicList) == 1) {
return $this->broadcast($message, $topicList[0], $retries);
}
$fields = $message->getFields();
$jointTopics = '';
foreach ($topicList as $topic) {
if (strlen($jointTopics) > 0) {
$jointTopics = $jointTopics . Constants::$multi_topic_split;
}
$jointTopics = $jointTopics . $topic;
}
$fields['topics'] = $jointTopics;
$fields['topic_op'] = $topicOp;
return $this->postResult(PushRequestPath::V3_MILTI_TOPIC_BROADCAST(), $fields, $retries);
}
// 检测定时任务是否存在
public function checkScheduleJobExist($msgId, $retries = 1) {
$fields = array('job_id' => $msgId);
return $this->postResult(PushRequestPath::V2_CHECK_SCHEDULE_JOB_EXIST(), $fields, $retries);
}
// 删除定时任务
public function deleteScheduleJob($msgId, $retries = 1) {
$fields = array('job_id' => $msgId);
return $this->postResult(PushRequestPath::V2_DELETE_SCHEDULE_JOB(), $fields, $retries);
}
// Hybrid
public function sendHybridMessageByRegId(Message $message, $regIdList, $isDebug = false, $retries = 1) {
$fields = $message->getFields();
$this->hybridHandle($isDebug, $fields);
$jointRegIds = '';
foreach ($regIdList as $regId) {
if (isset($regId)) {
$jointRegIds .= $regId . Constants::$comma;
}
}
$fields['registration_id'] = $jointRegIds;
return $this->postResult(PushRequestPath::V2_REGID_MESSAGE(), $fields, $retries);
}
public function broadcastHybridAll(Message $message, $isDebug = false, $retries = 1) {
$fields = $message->getFields();
$this->hybridHandle($isDebug, $fields);
return $this->postResult(PushRequestPath::V2_BROADCAST_TO_ALL(), $fields, $retries);
}
/**
* @param $type
* @return PushRequestPath
*/
private function multiSendRequestPath($type) {
if ($type == TargetedMessage::TARGET_TYPE_ALIAS) {
$requestPath = PushRequestPath::V2_SEND_MULTI_MESSAGE_WITH_ALIAS();
return $requestPath;
} else if ($type == TargetedMessage::TARGET_TYPE_USER_ACCOUNT) {
$requestPath = PushRequestPath::V2_SEND_MULTI_MESSAGE_WITH_ACCOUNT();
return $requestPath;
} else {
$requestPath = PushRequestPath::V2_SEND_MULTI_MESSAGE_WITH_REGID();
return $requestPath;
}
}
/**
* @param $isDebug
* @param $fields
* @return mixed
*/
private function hybridHandle($isDebug, &$fields) {
$fields[Message::EXTRA_PREFIX . Message::HYBRID_PUSH_ACTION] = Message::HYBRID_ACTION_MESSAGE;
if ($isDebug) {
$fields[Message::EXTRA_PREFIX . Message::HYBRID_DEBUG] = "1";
}
return $fields;
}
}
?>
<?php
/**
* Created by PhpStorm.
* User: zhangdali
* Date: 2016/12/5
* Time: 下午4:36
*/
namespace MiPush\xmpush;
class Server {
/**
* @var string
*/
private $host;
/**
* @var int
*/
private $priority;
private $minPriority;
private $maxPriority;
private $decrStep;
private $incrStep;
/**
* Server constructor.
* @param string $host
* @param int $minPriority
* @param int $maxPriority
* @param int $decrStep
* @param int $incrStep
*/
public function __construct($host, $minPriority, $maxPriority, $decrStep, $incrStep) {
$this->host = $host;
$this->priority = $maxPriority;
$this->minPriority = $minPriority;
$this->maxPriority = $maxPriority;
$this->decrStep = $decrStep;
$this->incrStep = $incrStep;
}
function __destruct() {
}
/**
* @return string
*/
public function getHost() {
return $this->host;
}
/**
* @param $host
*/
public function setHost($host) {
$this->host = $host;
}
/**
* @return int
*/
public function getPriority() {
return $this->priority;
}
/**
* @param int $priority
*/
public function setPriority($priority) {
$this->priority = $priority;
}
public function incrPriority() {
$this->changePriority(true, $this->incrStep);
}
public function decrPriority() {
$this->changePriority(false, $this->incrStep);
}
/**
* @param bool $incr
* @param int $step
*/
private function changePriority($incr, $step) {
$newPriority = $incr ? $this->priority + $step : $this->priority - $step;
if ($newPriority < $this->minPriority) {
$newPriority = $this->minPriority;
}
if ($newPriority > $this->maxPriority) {
$newPriority = $this->maxPriority;
}
$this->priority = $newPriority;
}
}
\ No newline at end of file
<?php
/**
* 用于多个域名之间的切换逻辑
* Created by PhpStorm.
* User: zhangdali
* Date: 2016/12/5
* Time: 下午4:29
*/
namespace MiPush\xmpush;
class ServerSwitch {
/**
* 存储message的server
* @var array Server
*/
private $servers;
private $apiRegionList;
private $feedbackRegionList;
private $sandbox;
private $specified;
private $emq;
private $messageVip;
private $defaultServer;
private $inited = false;
private $lastRefreshTime;
static $REFRESH_SERVER_HOST_INTERVAL = 300000; // 5 * 60 * 1000
/**
* @var ServerSwitch reference to singleton instance
*/
private static $instance;
/**
* 通过延迟加载(用到时才加载)获取实例
*
* @return self
*/
public static function getInstance() {
if (!isset(self::$instance)) {
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}
/**
* 是否需要刷新host列表
* @return bool
*/
public function needRefreshHostList() {
return !$this->inited ||
$this->currentTimeMillis() - $this->lastRefreshTime >= self::$REFRESH_SERVER_HOST_INTERVAL;
}
/**
* @param String $serverListStr : host:min:max:step,host:min:max:step,...
*/
public function initialize($serverListStr) {
if (!$this->needRefreshHostList()) {
return;
}
$serverStrArr = explode(',', $serverListStr);
$servers = array();
$i = 0;
foreach ($serverStrArr as $serverStr) {
$sp = explode(":", $serverStr);
if (count($sp) < 5) {
$servers[$i] = $this->defaultServer;
continue;
}
$servers[$i] = new Server($sp[0], intval($sp[1]), intval($sp[2]), intval($sp[3]), intval($sp[4]));
if (!empty($this->servers)) {
foreach ($this->servers as $server) {
if (strcmp($server->getHost(), $servers[$i]->getHost())) {
$servers[$i]->setPriority($server->getPriority());
}
}
}
$i++;
}
$this->inited = true;
$this->lastRefreshTime = $this->currentTimeMillis();
$this->servers = $servers;
}
/**
* @param PushRequestPath $requestPath
*/
/**
* @param PushRequestPath $requestPath
* @return Server
*/
public function &selectServer($requestPath, $region, $isVip) {
if (isset(Constants::$host)) {
$this->specified->setHost(Constants::$host);
return $this->specified;
}
if (Constants::$sandbox) {
return $this->sandbox;
}
switch ($requestPath->getRequestType()) {
case PushRequestType::FEEDBACK:
switch ($region) {
case Region::Other:
return $this->feedbackRegionList[$region];
default:
return $this->feedbackRegionList[Region::China];
}
case PushRequestType::EMQ:
return $this->emq;
default:
switch ($region) {
case Region::Other:
return $this->apiRegionList[$region];
default:
if ($isVip) {
return $this->messageVip;
}
return $this->selectMsgServer();
}
}
}
/**
* @return mixed|Server
*/
private function &selectMsgServer() {
if (!Constants::$autoSwitchHost || !$this->inited) {
return $this->defaultServer;
}
$allPriority = 0;
$priorities = array();
foreach ($this->servers as $server) {
$priorities[] = $server->getPriority();
$allPriority += $server->getPriority();
}
$randomPoint = mt_rand(0, $allPriority);
$sum = 0;
for ($i = 0; $i < count($priorities); $i++) {
$sum += $priorities[$i];
if ($randomPoint <= $sum) {
return $this->servers[$i];
}
}
return $this->defaultServer;
}
/**
* 构造函数私有,不允许在外部实例化
*/
private function __construct() {
$this->sandbox = new Server(Constants::HOST_SANDBOX, 100, 100, 0, 0);
$this->specified = new Server(Constants::$host, 100, 100, 0, 0);
$this->emq = new Server(Constants::HOST_EMQ, 100, 100, 0, 0);
$this->defaultServer = new Server(Constants::HOST_PRODUCTION, 1, 90, 10, 5);
$this->lastRefreshTime = $this->currentTimeMillis();
$hostList = Region::getFeedbackHostList();
$this->feedbackRegionList = array();
foreach ($hostList as $region => $host) {
$this->feedbackRegionList[$region] = new Server($host, 100, 100, 0, 0);
}
$hostList = Region::getApiHostList();
$this->apiRegionList = array();
foreach ($hostList as $region => $host) {
$this->apiRegionList[$region] = new Server($host, 100, 100, 0, 0);
}
$this->messageVip = new Server(Constants::HOST_VIP, 100, 100, 0, 0);
}
/**
* 防止对象实例被克隆
*
* @return void
*/
private function __clone() {
}
/**
* 防止被反序列化
*
* @return void
*/
private function __wakeup() {
}
/**
* 获取当前时间(毫秒)
* @return int
*/
private function currentTimeMillis() {
return ceil(microtime(true) * 1000);
}
}
\ No newline at end of file
<?php
/**
* 获取发送的消息统计数据.
* @author wangkuiwei
* @name Stats
* @desc 获取发送的消息统计数据。
*
*/
namespace MiPush\xmpush;
class Stats extends HttpBase {
private $package; //android用
private $bundle; //ios用
public function __construct() {
parent::__construct();
$this->package = Constants::$packageName;
$this->bundle = Constants::$bundle_id;
}
public function getStats($startDate, $endDate, $type = 'android', $retries = 1) {
if ($type == 'ios') {
$fields = array(
'start_date' => $startDate,
'end_date' => $endDate,
'restricted_package_name' => $this->bundle
);
} else {
$fields = array(
'start_date' => $startDate,
'end_date' => $endDate,
'restricted_package_name' => $this->package
);
}
$result = $this->getResult(PushRequestPath::V1_GET_MESSAGE_COUNTERS(), $fields, $retries);
return $result;
}
}
?>
<?php
/**
* 订阅/取消订阅标签.
* @author wangkuiwei
* @name Subscription
*
*/
namespace MiPush\xmpush;
class Subscription extends HttpBase {
public function __construct() {
parent::__construct();
}
public function subscribe($regId, $topic, $retries = 1) {
$fields = array('registration_id' => $regId, 'topic' => $topic);
return $this->postResult(PushRequestPath::V2_SUBSCRIBE_TOPIC(), $fields, $retries);
}
public function subscribeForRegids($regIdList, $topic, $retries = 1) {
$jointRegIds = '';
foreach ($regIdList as $regId) {
if (isset($regId)) {
$jointRegIds .= $regId . Constants::$comma;
}
}
$fields = array('registration_id' => $jointRegIds, 'topic' => $topic);
return $this->postResult(PushRequestPath::V2_SUBSCRIBE_TOPIC(), $fields, $retries);
}
public function unsubscribe($regId, $topic, $retries = 1) {
$fields = array('registration_id' => $regId, 'topic' => $topic);
return $this->postResult(PushRequestPath::V2_UNSUBSCRIBE_TOPIC(), $fields, $retries);
}
public function unsubscribeForRegids($regIdList, $topic, $retries = 1) {
$jointRegIds = '';
foreach ($regIdList as $regId) {
if (isset($regId)) {
$jointRegIds .= $regId . Constants::$comma;
}
}
$fields = array('registration_id' => $jointRegIds, 'topic' => $topic);
return $this->postResult(PushRequestPath::V2_UNSUBSCRIBE_TOPIC(), $fields, $retries);
}
public function subscribeTopicByAlias($aliasList, $topic, $retries = 1) {
$jointAliases = '';
foreach ($aliasList as $alias) {
if (isset($alias)) {
$jointAliases .= $alias . Constants::$comma;
}
}
$fields = array('aliases' => $jointAliases, 'topic' => $topic);
return $this->postResult(PushRequestPath::V2_SUBSCRIBE_TOPIC_BY_ALIAS(), $fields, $retries);
}
public function unsubscribeTopicByAlias($aliasList, $topic, $retries = 1) {
$jointAliases = '';
foreach ($aliasList as $alias) {
if (isset($alias)) {
$jointAliases .= $alias . Constants::$comma;
}
}
$fields = array('aliases' => $jointAliases, 'topic' => $topic);
return $this->postResult(PushRequestPath::V2_UNSUBSCRIBE_TOPIC_BY_ALIAS(), $fields, $retries);
}
public function subscribeByPackageName($regId, $topic, $packageName, $retries = 1) {
$fields = array('registration_id' => $regId, 'topic' => $topic, 'restricted_package_name' => $packageName);
return $this->postResult(PushRequestPath::V2_SUBSCRIBE_TOPIC(), $fields, $retries);
}
public function subscribeForRegidsByPackageName($regIdList, $topic, $packageName, $retries = 1) {
$jointRegIds = '';
foreach ($regIdList as $regId) {
if (isset($regId)) {
$jointRegIds .= $regId . Constants::$comma;
}
}
$fields = array('registration_id' => $jointRegIds, 'topic' => $topic, 'restricted_package_name' => $packageName);
return $this->postResult(PushRequestPath::V2_SUBSCRIBE_TOPIC(), $fields, $retries);
}
public function unsubscribeByPackageName($regId, $topic, $packageName, $retries = 1) {
$fields = array('registration_id' => $regId, 'topic' => $topic, 'restricted_package_name' => $packageName);
return $this->postResult(PushRequestPath::V2_UNSUBSCRIBE_TOPIC(), $fields, $retries);
}
public function unsubscribeForRegidsByPackageName($regIdList, $topic, $packageName, $retries = 1) {
$jointRegIds = '';
foreach ($regIdList as $regId) {
if (isset($regId)) {
$jointRegIds .= $regId . Constants::$comma;
}
}
$fields = array('registration_id' => $jointRegIds, 'topic' => $topic, 'restricted_package_name' => $packageName);
return $this->postResult(PushRequestPath::V2_UNSUBSCRIBE_TOPIC(), $fields, $retries);
}
public function subscribeTopicByPackageNameAlias($aliasList, $topic, $packageName, $retries = 1) {
$jointAliases = '';
foreach ($aliasList as $alias) {
if (isset($alias)) {
$jointAliases .= $alias . Constants::$comma;
}
}
$fields = array('aliases' => $jointAliases, 'topic' => $topic, 'restricted_package_name' => $packageName);
return $this->postResult(PushRequestPath::V2_SUBSCRIBE_TOPIC_BY_ALIAS(), $fields, $retries);
}
public function unsubscribeTopicByPackageNameAlias($aliasList, $topic, $packageName, $retries = 1) {
$jointAliases = '';
foreach ($aliasList as $alias) {
if (isset($alias)) {
$jointAliases .= $alias . Constants::$comma;
}
}
$fields = array('aliases' => $jointAliases, 'topic' => $topic, 'restricted_package_name' => $packageName);
return $this->postResult(PushRequestPath::V2_UNSUBSCRIBE_TOPIC_BY_ALIAS(), $fields, $retries);
}
}
?>
<?php
/**
* 要发送的消息内容和消息的发送目标.
* @author wangkuiwei
* @name TargetedMessage
* @desc 构建要发送的消息内容和消息的发送目标。
*
*/
namespace MiPush\xmpush;
class TargetedMessage {
const TARGET_TYPE_REGID = 1;
const TARGET_TYPE_ALIAS = 2;
const TARGET_TYPE_USER_ACCOUNT = 3;
private $targetType;
private $target;
/**
* @var Message
*/
private $message;
public function __construct() {
}
public function setTarget($target, $targetType) {
$this->targetType = $targetType;
$this->target = $target;
}
public function setMessage(Message $message) {
$this->message = $message;
}
public function getFields() {
return array(
'target' => $this->target,
'message' => $this->message->getJSONInfos()
);
}
}
?>
<?php
/**
* 消息状态追踪API.
* @author wangkuiwei
* @name Tracer
* @desc 消息状态追踪API。
*
*/
namespace MiPush\xmpush;
class Tracer extends HttpBase {
public function __construct() {
parent::__construct();
}
public function getMessageStatusById($msgId, $retries = 1) {
$fields = array(
'msg_id' => $msgId
);
$result = $this->getResult(PushRequestPath::V1_MESSAGE_STATUS(), $fields, $retries);
return $result;
}
public function getMessageStatusByJobKey($jobKey, $retries = 1) {
$fields = array(
'job_key' => $jobKey
);
$result = $this->getResult(PushRequestPath::V1_MESSAGE_STATUS(), $fields, $retries);
return $result;
}
public function getMessagesStatusByTimeArea($beginTime, $endTime, $retries = 1) {
$fields = array(
'begin_time' => $beginTime,
'end_time' => $endTime
);
$result = $this->getResult(PushRequestPath::V1_MESSAGES_STATUS(), $fields, $retries);
return $result;
}
}
?>
<?php
namespace MzPush;
class Application
{
private $appid;
private $appkey;
private $appsecret;
public function __construct()
{
$this->appid = \pushConfig::MZ_APP_ID;
$this->appkey = \pushConfig::MZ_APP_KEY;
$this->appsecret = \pushConfig::MZ_APP_SECRET;
}
public function pushTag($title,$content,$tag){
$url = "http://server-api-push.meizu.com/garcia/api/server/push/pushTask/pushToTag";
$header[] = "Content-Type:application/x-www-form-urlencoded;charset=UTF-8";
$data['appId'] = $this->appid;
//$data['pushIds'] = "18606715209";
$data['pushType'] = 0;
$data['tagNames'] = $tag;
$data['scope'] = 0;
$data['messageJson'] = json_encode([
'noticeBarInfo' =>[
'title' => $title,
'content' =>$content,
],
'pushTimeInfo' =>[
'offLine' =>1,
'validTime' =>24
]
]);
$data['sign'] = $this->getSign($data);
return $res = $this->curl_https_post($url,http_build_query($data),$header);
}
private function curl_https_post($url, $data = array(), $header = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // check verify
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1); // regular post request
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post submit data
$ret = @curl_exec($ch);
if ($ret === false) {
return null;
}
curl_close($ch);
return $ret;
}
//生成签名
public function getSign($data){
ksort($data); //字典序排序
$sign = '';
foreach($data as $k =>$v){
$sign.=$k."=".$v;
}
return md5($sign.$this->appsecret);
}
}
\ No newline at end of file
<?php
namespace OPush;
class Application
{
private $appid;
private $appkey;
private $appsecret;
private $appserversecret;
private $url = "https://api.push.oppomobile.com/";
public function __construct()
{
$this->appid = \pushConfig::OP_APP_ID;
$this->appkey = \pushConfig::OP_APP_KEY;
$this->appsecret = \pushConfig::OP_APP_SECRET;
$this->appserversecret = \pushConfig::OP_APP_SERVER_SECRET;
}
public function get_access_token(){
$cacheauth = unserialize(file_get_contents( (dirname(__FILE__)).'/config.txt'));
if(empty($cacheauth) || ( time() >$cacheauth['expire_time'] )){
//重新拉取
$url = $this->url."server/v1/auth";
$headerArray=array('Content-Type : application/x-www-form-urlencoded');
$data['app_key'] = $this->appkey;
$data['timestamp'] = $this->msectime();
$data['sign'] = hash("sha256",$this->appkey.$data['timestamp'].$this->appserversecret);
$res = $this->curl_https_post($url,$data,$headerArray);
$resarr =json_decode($res,true);
if($resarr['code'] ==0){
$in['auth_token'] = $resarr['data']['auth_token'];
$in['expire_time'] = time()+86400;
file_put_contents(dirname(__FILE__).'/config.txt', serialize($in));
return $resarr['data']['auth_token'];
}else {
return false;
}
} else {
return $cacheauth['auth_token'];
}
}
//获取毫秒时间戳
function msectime(){
list($msec, $sec) = explode(' ', microtime());
$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
return $msectime;
}
private function curl_https_post($url, $data = array(), $header = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // check verify
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//使返回的字符串不输出到页面中,而是直接返回
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//尝试连接时等待的秒数
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1); // regular post request;这时候Content-type : application/x-www-form-urlencoded;所以header不用设置
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post submit data,$data其实是string类型的,所以不同的Content-type 要把参数利用json_encode转化或者是http_build_query转化
$ret = @curl_exec($ch);
if ($ret === false) {
return null;
}
curl_close($ch);
return $ret;
}
function curl_https__get($url,$headerArray){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
$output = curl_exec($ch);
curl_close($ch);
return $output = json_decode($output, true);
}
/**
* 别名推送,单推
*/
public function pushAlias($content,$title,$alias){
$url = $this->url."server/v1/message/notification/unicast";
$header[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
$header[] = "auth_token: ".$this->get_access_token();
$data['message'] = json_encode([
'target_type' =>5,
'target_value' =>$alias,
'notification' =>[
'title' =>$title,
'content' =>$content
]
]);
return $res = $this->curl_https_post($url,http_build_query($data),$header);
}
/**
* 标签推送
* @param $title
* @param $content
* @param $tag
* @return bool|string|null
*/
public function pushTag($title,$content,$tag){
$url = $this->url."server/v1/message/notification/unicast";
$header[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
$header[] = "auth_token: ".$this->get_access_token();
$data['message'] = json_encode([
'target_type' =>2,
'target_value' => $tag,
'notification' =>[
'title' =>$title,
'content'=>$content
]
]);
return $res = $this->curl_https_post($url,http_build_query($data),$header);
}
//查询当天的app发送量
public function getSendNum(){
$url = "https://feedback.push.oppomobile.com/server/v1/feedback/fetch_push_permit";
$header[] = "Content-type : application/x-www-form-urlencoded;charset=UFT-8";
$header[] = "auth_token: ".$this->get_access_token();
return $res = $this->curl_https__get($url,$header);
}
}
\ No newline at end of file
<?php
namespace OPush;
class Message
{
public function __construct()
{
}
}
\ No newline at end of file
<?php
namespace ViPush;
class Application{
private $appid;
private $appkey;
private $appsecret;
private $url ="https://api-push.vivo.com.cn";
public function __construct()
{
$this->appid = \pushConfig::VO_APP_ID;
$this->appkey = \pushConfig::VO_APP_KEY;
$this->appsecret = \pushConfig::VO_APP_SECRET;
}
//推送
/**
* @param Array $tag
*/
public function pushTag($title,$content,$tag){
$url = $this->url."/message/tagPush";
$header[] = "Content-Type:application/json;charset=UTF-8";
$header[] = "authToken:".$this->get_auth_token();
$data['tagExpression'] = [
'andTags' => $tag
];
$data['notifyType'] = 4; //1:无,2:响铃,3:振动,4:响铃和振动
$data['title'] = $title;
$data['content'] = $content;
$data['skipType'] = 1; //点击跳转类型 1:打开APP首页 2:打开链接 3:自定义 4:打开app内指定页面
$data['requestId'] = $this->appsecret;
return $res = $this->curl_https_post($url,json_encode($data),$header);
}
//利用别名推送
public function pushAlias($body){
$header[] = "Content-Type:application/json";
$url = $this->url."/message/send";
$res = $this->curl_https_post($url,$body,$header);
return $res;
}
//获取auth_token
public function get_auth_token(){
$cacheauth = unserialize(file_get_contents(dirname(__FILE__).'/config.txt'));
if(empty($cacheauth) || ( time()>$cacheauth['expire_time'] )){
$url = $this->url."/message/auth";
$header[] = "Content-Type:application/json;charset=UTF-8";
$data['appId'] = $this->appid;
$data['appKey'] = $this->appkey;
$data['timestamp'] = $this->msectime();
$data['sign'] = md5($data['appId'].$data['appKey'].$data['timestamp'].$this->appsecret);
$res = $this->curl_https_post($url, json_encode($data),$header);
$resArr = json_decode($res,true);
if($resArr['result'] ==0){
//写入文件
$in['auth_token'] = $resArr['authToken'];
$in['expire_time'] = time() + 86000;
file_put_contents(dirname(__FILE__).'/config.txt', serialize($in));
return $resArr['authToken'];
} else {
return false;
}
} else {
return $cacheauth['auth_token'];
}
}
private function curl_https_post($url, $data = array(), $header = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // check verify
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_POST, 1); // regular post request
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Post submit data
$ret = @curl_exec($ch);
if ($ret === false) {
return null;
}
curl_close($ch);
return $ret;
}
//获取毫秒时间戳
function msectime(){
list($msec, $sec) = explode(' ', microtime());
$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
return $msectime;
}
public function getConfig(){
return ['appid'=>$this->appid,'appsecret'=>$this->appkey,'appsecret'=>$this->appsecret];
}
}
\ No newline at end of file
<?php
namespace ViPush;
//创建请求体
class Message{
private $body;
public function __construct($appsecret='')
{
if($appsecret){
$this->body['requestId'] = $appsecret;
} else {
$this->body['requestId'] = \Config::VO_APP_SECRET;
}
}
/**
* 必须
* 设置title
* @param $title
*/
public function setTitle($title){
$this->body['title'] = trim($title);
}
/**
* 必须
* 设置content
* @param $content
*
*/
public function setContent($content){
$this->body['content'] = trim($content);
}
/**
* 设置提醒级别
* @param $notifyType 1:无,2:响铃,3:振动,4:响铃和振动
*/
public function setNotifyType($notifyType=1){
$this->body['notifyType'] = $notifyType;
}
/**
* @param Array $tag
*/
public function setTag($tag){
$this->body['tagExpression']['andTags'] = $tag;
}
/**
* 必须
* 设置点击通知的动作 1:打开APP首页 2:打开链接 3:自定义 4:打开app内指定页面
* @return false|string
*/
public function setSkipType($skipType=1){
$this->body['skipType'] = $skipType;
}
/**
* 非必要设置
* 跳转方式,当SkipType为2的时候需要设置
* @param int $skipContent
*/
public function setSkipContent($skipContent=1){
if($this->body['skipType'] == 2 || $this->body['skipType']==3 ){
$this->body['skipContent'] = $skipContent;
}
}
/**
* alias 与 regId 两个必须设置一个
* 设置别名
* @param $alias
*/
public function setAlias($alias){
$this->body['alias'] = $alias;
}
/**
* 设置设备id
* @param $regId
*/
public function setRegId($regId){
$this->body['regId'] = $regId;
}
/**
* 非必要设置
* 设置消息停留的时间,默认是一天,最长可以7天,单位是秒
* @param int $s
*/
public function setTimeToLive($s=86400){
$this->body['timeToLive'] = $s;
}
/**
* 非必要设置
* 网络方式 -1:不限,1:wifi下发送,不填默认为-1
* @param int $networkType
*/
public function setNetworkType($networkType=1){
$this->body['networkType'] = $networkType;
}
//检查并生成请求参数
public function build(){
if(empty($this->body['title'])){
return "title未设置!";
}
if(empty($this->body['content'])){
return "content未设置!";
}
return json_encode(($this->body));
}
}
\ No newline at end of file
a:2:{s:10:"auth_token";s:36:"9183de8a-dc7a-4f75-a43f-dd4c3b3b9ef4";s:11:"expire_time";i:1611452822;}
\ No newline at end of file
<?php
function classLoader($class)
{
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
$file = __DIR__ . '/' . $path . '.php';
if (file_exists($file)) {
require_once $file;
} else {
echo $file;
}
}
spl_autoload_register('classLoader');
//初始化相对于的配置文件
//引入配置文件
//小米相关的配置初始化,其他的可以在初始化的时候注入配置参数,小米必须先设置
\MiPush\xmpush\Constants::setPackage(pushConfig::MI_APP_PACKAGE);
\MiPush\xmpush\Constants::setSecret(pushConfig::MI_APP_SECRET);
<?php
class pushConfig{
//极光推送霞凝光
const JPUSH_APP_KEY = '5f70ec544d6771d4c26231b7';
const JPUSH_MASTER_SECRET = 'ef559e4cc4f1e98e6243e2ed';
//小米推送
const MI_APP_KEY = '5551846788324';
const MI_APP_ID = '2882303761518467324';
const MI_APP_SECRET = '4R2ymmOoGWfNVxr1aCaJqg==';
const MI_APP_PACKAGE = 'com.rz.family';
//华为推送
const HW_APP_ID = '102526607';
const HW_APP_SECRET = '197d874086b8456e90607f5f43a708a813205d53c9d14be75f727a1d2926fe59';
const HW_APP_TOKEN_SERVER ='https://oauth-login.cloud.huawei.com/oauth2/v2/token';
const HW_APP_OPEN_URL = 'https://push-api.cloud.huawei.com';
//OPPO
const OP_APP_ID = '30307272';
const OP_APP_KEY = 'db61deb0ea7d4629814a11cdbc25e497';
const OP_APP_SECRET = '149ad6551dbc4ec7b0e42d61a9f4ae0d';
const OP_APP_SERVER_SECRET = '6c2a66c966f24d248df801aab4e77b27';
//魅族
const MZ_APP_ID = '132648';
const MZ_APP_KEY = 'f54d1893b15847148f80d52362be7ae3';
const MZ_APP_SECRET = '04957a324d994cca92eaacc1f43cdee3';
//vivo
const VO_APP_ID = '103992290';
const VO_APP_KEY = 'c1b5fb21e72dd7a753c8c38a72e5b25c';
const VO_APP_SECRET = '4ae55bfa-f124-4274-8363-82f3854d9677';
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment