Commit f445057f authored by wwccw0591's avatar wwccw0591

ordi

parent 782590ea
...@@ -52,6 +52,10 @@ class IndexController extends \Our\Controller_Abstract { ...@@ -52,6 +52,10 @@ class IndexController extends \Our\Controller_Abstract {
} }
public function indexAction() { public function indexAction() {
$clientPush=\JPush\ClientPush::getInstance();
$clientPush->pushAll();
echo 'success';
exit;
\Our\Log::getInstance()->write('testLog|||||testLog'); \Our\Log::getInstance()->write('testLog|||||testLog');
var_dump($_SERVER);exit; var_dump($_SERVER);exit;
// echo $_SERVER['USER']);exit; // echo $_SERVER['USER']);exit;
......
<?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 (!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];
}
}
}
<?php
namespace JPush;
use InvalidArgumentException;
use Our\SecretKeys;
class ClientPush
{
private $client;
public function __construct()
{
$app_key = SecretKeys::pushKey;
$master_secret = SecretKeys::pushSecret;
//$registration_id = getenv('registration_id');
$this->client = new Client($app_key, $master_secret);
}
public function pushAll(){
$push_payload = $this->client->push()
->setPlatform('all')
->addAllAudience()
->setNotificationAlert('Hi, JPush');
try {
$response = $push_payload->send();
print_r($response);
} catch (\JPush\Exceptions\APIConnectionException $e) {
// try something here
print $e;
} catch (\JPush\Exceptions\APIRequestException $e) {
// try something here
print $e;
}
return true;
}
public function push($pushData)
{
try {
$response = $this->client->push()
->setPlatform(array('ios', 'android'))
// 一般情况下,关于 audience 的设置只需要调用 addAlias、addTag、addTagAnd 或 addRegistrationId
// 这四个方法中的某一个即可,这里仅作为示例,当然全部调用也可以,多项 audience 调用表示其结果的交集
// 即是说一般情况下,下面三个方法和没有列出的 addTagAnd 一共四个,只适用一个便可满足大多数的场景需求
// ->addAlias('alias')
->addTag(array('tag1', 'tag2'))
// ->addRegistrationId($registration_id)
->setNotificationAlert('Hi, JPush')
->iosNotification('Hello IOS', array(
'sound' => 'sound.caf',
// 'badge' => '+1',
// 'content-available' => true,
// 'mutable-content' => true,
'category' => 'jiguang',
'extras' => array(
'key' => 'value',
'jiguang'
),
))
->androidNotification('Hello Android', array(
'title' => 'hello jpush',
// 'builder_id' => 2,
'extras' => array(
'key' => 'value',
'jiguang'
),
))
->message('message content', array(
'title' => 'hello jpush',
// 'content_type' => 'text',
'extras' => array(
'key' => 'value',
'jiguang'
),
))
->options(array(
// sendno: 表示推送序号,纯粹用来作为 API 调用标识,
// API 返回时被原样返回,以方便 API 调用方匹配请求与返回
// 这里设置为 100 仅作为示例
// 'sendno' => 100,
// time_to_live: 表示离线消息保留时长(秒),
// 推送当前用户不在线时,为该用户保留多长时间的离线消息,以便其上线时再次推送。
// 默认 86400 (1 天),最长 10 天。设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到
// 这里设置为 1 仅作为示例
// 'time_to_live' => 1,
// apns_production: 表示APNs是否生产环境,
// True 表示推送生产环境,False 表示要推送开发环境;如果不指定则默认为推送生产环境
'apns_production' => false,
// big_push_duration: 表示定速推送时长(分钟),又名缓慢推送,把原本尽可能快的推送速度,降低下来,
// 给定的 n 分钟内,均匀地向这次推送的目标用户推送。最大值为1400.未设置则不是定速推送
// 这里设置为 1 仅作为示例
// 'big_push_duration' => 1
))
->send();
print_r($response);
} catch (\JPush\Exceptions\APIConnectionException $e) {
// try something here
print $e;
} catch (\JPush\Exceptions\APIRequestException $e) {
// try something here
print $e;
}
}
/**
* 类实例
*
* @var \DAO\UserModel
*/
private static $_instance = null;
/**
* 获取类实例
*
* @ccw push
*/
public static function getInstance()
{
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
}
<?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 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 {
throw new APIRequestException($response);
}
}
public static function log($client, $content) {
if (!is_null($client->getLogFile())) {
error_log($content . "\r\n", 3, $client->getLogFile());
}
}
}
This diff is collapsed.
<?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);
}
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);
}
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);
}
}
<?php
// 这只是使用样例,不应该直接用于实际生产环境中 !!
require 'config.php';
use JPush\AdminClient as Admin;
$admin = new Admin($dev_key, $dev_secret);
$response = $admin->createApp('aaa', 'cn.jpush.app');
print_r($response);
$appKey = $response['body']['app_key'];
$response = $admin->deleteApp($appKey);
print_r($response);
<?php
require 'config.php';
$response = $client->push()->getCid();
print_r($response);
<?php
require __DIR__ . '/../autoload.php';
use JPush\Client as JPush;
$app_key = getenv('app_key');
$master_secret = getenv('master_secret');
$registration_id = getenv('registration_id');
$client = new JPush($app_key, $master_secret);
<?php
require __DIR__ . '/../config.php';
$response = $client->device()->deleteAlias('alias');
print_r($response);
<?php
require __DIR__ . '/../config.php';
$response = $client->device()->deleteTag('tag');
print_r($response);
<?php
require __DIR__ . '/../config.php';
// 更新 Alias
$response = $client->device()->getAliasDevices('alias');
print_r($response);
<?php
require __DIR__ . '/../config.php';
// 获取指定设备的 Mobile,Alias,Tags 等信息
$response = $client->device()->getDevices($registration_id);
print_r($response);
\ No newline at end of file
<?php
require __DIR__ . '/../config.php';
// 获取用户在线状态(VIP专属接口)
try {
$response = $client->device()->getDevicesStatus($registration_id);
} catch(\JPush\Exceptions\APIRequestException $e) {
print $e;
print $e->getHttpCode();
print $e->getHeaders();
}
print_r($response);
<?php
require __DIR__ . '/../config.php';
// 获取Tag列表
$response = $client->device()->getDevices($registration_id);
print_r($response);
\ No newline at end of file
<?php
require __DIR__ . '/../config.php';
// 更新 Alias
$result = $client->device()->getDevices($registration_id);
print "before update alias = " . $result['body']['alias'] . "\n";
print 'updating alias ... response = ';
$response = $client->device()->updateAlias($registration_id, 'jpush_alias');
print_r($response);
$result = $client->device()->getDevices($registration_id);
print "after update alias = " . $result['body']['alias'] . "\n\n";
// 添加 tag
$result = $client->device()->getDevices($registration_id);
print "before add tags = [" . implode(',', $result['body']['tags']) . "]\n";
print 'add tag1 tag2 ... response = ';
$response = $client->device()->addTags($registration_id, 'tag0');
print_r($response);
$response = $client->device()->addTags($registration_id, ['tag1', 'tag2']);
print_r($response);
$result = $client->device()->getDevices($registration_id);
print "after add tags = [" . implode(',', $result['body']['tags']) . "]\n\n";
// 移除 tag
$result = $client->device()->getDevices($registration_id);
print "before remove tags = [" . implode(',', $result['body']['tags']) . "]\n";
print 'removing tag1 tag2 ... response = ';
$response = $client->device()->removeTags($registration_id, 'tag0');
print_r($response);
$response = $client->device()->removeTags($registration_id, ['tag1', 'tag2']);
print_r($response);
$result = $client->device()->getDevices($registration_id);
print "after remove tags = [" . implode(',', $result['body']['tags']) . "]\n\n";
// 更新 mobile
$result = $client->device()->getDevices($registration_id);
print "before update mobile = " . $result['body']['mobile'] . "\n";
print 'updating mobile ... response = ';
$response = $client->device()->updateMoblie($registration_id, '13800138000');
print_r($response);
$result = $client->device()->getDevices($registration_id);
print "after update mobile = " . $result['body']['mobile'] . "\n\n";
\ No newline at end of file
<?php
require __DIR__ . '/../config.php';
// 为一个标签添加设备
$result = $client->device()->isDeviceInTag($registration_id, 'tag');
$r = $result['body']['result'] ? 'true' : 'false';
print "before add device = " . $r . "\n";
print 'adding device ... response = ';
$response = $client->device()->addDevicesToTag('tag', $registration_id);
print_r($response);
$result = $client->device()->isDeviceInTag($registration_id, 'tag');
$r = $result['body']['result'] ? 'true' : 'false';
print "after add tags = " . $r . "\n\n";
// 为一个标签删除设备
$result = $client->device()->isDeviceInTag($registration_id, 'tag');
$r = $result['body']['result'] ? 'true' : 'false';
print "before remove device = " . $r . "\n";
print 'removing device ... response = ';
$response = $client->device()->removeDevicesFromTag('tag', $registration_id);
print_r($response);
$result = $client->device()->isDeviceInTag($registration_id, 'tag');
$r = $result['body']['result'] ? 'true' : 'false';
print "after remove device = " . $r . "\n\n";
<?php
require __DIR__ . '/../autoload.php';
use JPush\Client as JPush;
$group_key = 'xxxx';
$group_master_secret = 'xxxx';
$client = new JPush('group-' . $group_key, $group_master_secret, null);
$push_payload = $client->push()
->setPlatform('all')
->addAllAudience()
->setNotificationAlert('Hi, JPush');
try {
$response = $push_payload->send();
print_r($response);
} catch (\JPush\Exceptions\APIConnectionException $e) {
// try something here
print $e;
} catch (\JPush\Exceptions\APIRequestException $e) {
// try something here
print $e;
}
<?php
// 这只是使用样例,不应该直接用于实际生产环境中 !!
require 'config.php';
try {
$payload = $client->push()
->setPlatform(array('ios', 'android'))
// ->addAlias('alias')
->addTag(array('tag1', 'tag2'))
// ->addRegistrationId($registration_id)
->setNotificationAlert('Hi, JPush')
->androidNotification('Hello HUAWEI', array(
'title' => 'huawei demo',
// ---------------------------------------------------
// `uri_activity` 字段用于指定想要打开的 activity.
// 值为 activity 节点的 “android:name” 属性值。
'uri_activity' => 'cn.jpush.android.ui.OpenClickActivity',
// ---------------------------------------------------
'extras' => array(
'key' => 'value',
'jiguang'
),
));
// ->send();
print_r($payload->build());
} catch (\JPush\Exceptions\APIConnectionException $e) {
// try something here
print $e;
} catch (\JPush\Exceptions\APIRequestException $e) {
// try something here
print $e;
}
<?php
// 这只是使用样例,不应该直接用于实际生产环境中 !!
require 'config.php';
// 简单推送示例
// 这只是使用样例,不应该直接用于实际生产环境中 !!
$push_payload = $client->push()
->setPlatform('all')
->addAllAudience()
->setNotificationAlert('Hi, JPush');
try {
$response = $push_payload->send();
print_r($response);
} catch (\JPush\Exceptions\APIConnectionException $e) {
// try something here
print $e;
} catch (\JPush\Exceptions\APIRequestException $e) {
// try something here
print $e;
}
// 完整的推送示例
// 这只是使用样例,不应该直接用于实际生产环境中 !!
try {
$response = $client->push()
->setPlatform(array('ios', 'android'))
// 一般情况下,关于 audience 的设置只需要调用 addAlias、addTag、addTagAnd 或 addRegistrationId
// 这四个方法中的某一个即可,这里仅作为示例,当然全部调用也可以,多项 audience 调用表示其结果的交集
// 即是说一般情况下,下面三个方法和没有列出的 addTagAnd 一共四个,只适用一个便可满足大多数的场景需求
// ->addAlias('alias')
->addTag(array('tag1', 'tag2'))
// ->addRegistrationId($registration_id)
->setNotificationAlert('Hi, JPush')
->iosNotification('Hello IOS', array(
'sound' => 'sound.caf',
// 'badge' => '+1',
// 'content-available' => true,
// 'mutable-content' => true,
'category' => 'jiguang',
'extras' => array(
'key' => 'value',
'jiguang'
),
))
->androidNotification('Hello Android', array(
'title' => 'hello jpush',
// 'builder_id' => 2,
'extras' => array(
'key' => 'value',
'jiguang'
),
))
->message('message content', array(
'title' => 'hello jpush',
// 'content_type' => 'text',
'extras' => array(
'key' => 'value',
'jiguang'
),
))
->options(array(
// sendno: 表示推送序号,纯粹用来作为 API 调用标识,
// API 返回时被原样返回,以方便 API 调用方匹配请求与返回
// 这里设置为 100 仅作为示例
// 'sendno' => 100,
// time_to_live: 表示离线消息保留时长(秒),
// 推送当前用户不在线时,为该用户保留多长时间的离线消息,以便其上线时再次推送。
// 默认 86400 (1 天),最长 10 天。设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到
// 这里设置为 1 仅作为示例
// 'time_to_live' => 1,
// apns_production: 表示APNs是否生产环境,
// True 表示推送生产环境,False 表示要推送开发环境;如果不指定则默认为推送生产环境
'apns_production' => false,
// big_push_duration: 表示定速推送时长(分钟),又名缓慢推送,把原本尽可能快的推送速度,降低下来,
// 给定的 n 分钟内,均匀地向这次推送的目标用户推送。最大值为1400.未设置则不是定速推送
// 这里设置为 1 仅作为示例
// 'big_push_duration' => 1
))
->send();
print_r($response);
} catch (\JPush\Exceptions\APIConnectionException $e) {
// try something here
print $e;
} catch (\JPush\Exceptions\APIRequestException $e) {
// try something here
print $e;
}
<?php
// 这只是使用样例不应该直接用于实际生产环境中 !!
require 'config.php';
$payload = $client->push()
->setPlatform("all")
->addAllAudience()
->setNotificationAlert("Hi, 这是一条定时发送的消息")
->build();
// 创建一个2016-12-22 13:45:00触发的定时任务
$response = $client->schedule()->createSingleSchedule("每天14点发送的定时任务", $payload, array("time"=>"2016-12-22 13:45:00"));
print_r($response);
// 创建一个每天14点发送的定时任务
$response = $client->schedule()->createPeriodicalSchedule("每天14点发送的定时任务", $payload,
array(
"start"=>"2016-12-22 13:45:00",
"end"=>"2016-12-25 13:45:00",
"time"=>"14:00:00",
"time_unit"=>"DAY",
"frequency"=>1
));
print_r($response);
<?php
// 这只是使用样例,不应该直接用于实际生产环境中 !!
require 'config.php';
use JPush\Client as JPush;
// 简单推送示例
// 这只是使用样例,不应该直接用于实际生产环境中 !!
$client = new JPush($app_key, $master_secret, null, null, 'BJ');
$push_payload = $client->push()
->setPlatform('all')
->addAllAudience()
->setNotificationAlert('Hi, JPush');
try {
$response = $push_payload->send();
print_r($response);
} catch (\JPush\Exceptions\APIConnectionException $e) {
// try something here
print $e;
} catch (\JPush\Exceptions\APIRequestException $e) {
// try something here
print $e;
}
\ No newline at end of file
<?php
namespace JPush;
const VERSION = '3.6.1';
...@@ -434,18 +434,34 @@ class Common ...@@ -434,18 +434,34 @@ class Common
public static function intergrateOneToMany($list1,$list2,$mergekey1,$mergekey2,$listName='orderGoods'){ public static function intergrateOneToMany($list1,$list2,$mergekey1,$mergekey2,$listName='orderGoods'){
$mergeArray=array(); $mergeArray=array();
$list2key=array(); $list2key=array();
foreach($list2 as $value){ foreach($list1 as $value){
$list2key[$value[$mergekey2]]=$value; $list2key[$value[$mergekey1]]=$value;
} }
$value[$listName]=array(); $value[$listName]=array();
foreach($list1 as &$value){ foreach($list2 as &$value){
if(isset($list2key[$value[$mergekey1]])&&!empty($list2key[$value[$mergekey1]])){ if(isset($list2key[$value[$mergekey2]])&&!empty($list2key[$value[$mergekey2]])){
$value[$listName][]=$list2key[$value[$mergekey1]]; $list2key[$value[$mergekey2]][$listName][]=$value;
} }
array_push($mergeArray,$value);
} }
return $mergeArray; $orders=array_values($list2key);
return $orders;
} }
// //合并一对多列表
// public static function intergrateOneToMany($list1,$list2,$mergekey1,$mergekey2,$listName='orderGoods'){
// $mergeArray=array();
// $list2key=array();
// foreach($list2 as $value){
// $list2key[$value[$mergekey2]]=$value;
// }
// $value[$listName]=array();
// foreach($list1 as &$value){
// if(isset($list2key[$value[$mergekey1]])&&!empty($list2key[$value[$mergekey1]])){
// $value[$listName][]=$list2key[$value[$mergekey1]];
// }
// array_push($mergeArray,$value);
// }
// return $mergeArray;
// }
//合并一对一数组 //合并一对一数组
//合并一对多列表 //合并一对多列表
public static function intergrateOneToOne($list1,$list2,$mergekey1,$mergekey2){ public static function intergrateOneToOne($list1,$list2,$mergekey1,$mergekey2){
......
...@@ -46,6 +46,9 @@ class SecretKeys { ...@@ -46,6 +46,9 @@ class SecretKeys {
const expressUrl='https://kdwlcxf.market.alicloudapi.com'; const expressUrl='https://kdwlcxf.market.alicloudapi.com';
const expressPath='/kdwlcx'; const expressPath='/kdwlcx';
const pushKey='37e9a38cf2983bcdf885e5fd';
const pushSecret='c59868c235bc7ccbe865f9d9';
} }
......
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