消息推送一般会使用极光推送,相较于其他平台速度还可以。看极光的sdk也挺简单,记录一下,以备后用。
<?php
namespace services\push;
use models\notification\NotificationPush;
use yii\helpers\Json;
use yii\JPush\Client;
use yii\JPush\Exceptions\APIConnectionException;
use yii\JPush\Exceptions\APIRequestException;
use Yii;
use linslin\yii2\curl;
class JPush extends \services\Service
{
private $_API_KEY = '4*********************3';
private $_SECRET_KEY = '7**********************5';
private $_apnsProduction = false;
private $_client;
public function init()
{
$this->_API_KEY = Yii::$app->params['jPush']['appKey'];
$this->_SECRET_KEY = Yii::$app->params['jPush']['secret'];
$this->_apnsProduction = Yii::$app->params['jPush']['production'];
parent::init();
}
private function getClient()
{
if(!$this->_client){
$this->_client = new Client($this->_API_KEY, $this->_SECRET_KEY);
}
return $this->_client;
}
public function pushMessage($data)
{
if(empty($data['platform'])){
$this->addError('请设置推送平台("all", "android", "ios", "winphone")');
return false;
}
/*if(empty($data['alias'])){
$this->addError('请设置别名!');
return false;
}*/
if(empty($data['message'])){
$this->addError('请设置推送消息!');
return false;
}
$pushPayload = $this->getClient()
->push() // PushPayload实例
->setPlatform($data['platform']) // 设置平台
->options(["apns_production"=>$this->_apnsProduction])
->setNotificationAlert($data['message']); // 设置推送通知内容
//别名推送
if($data['alias']){
$pushPayload->addAlias($data['alias']);
}
//别名推送
if($data['registration_id']){
$pushPayload->addRegistrationId($data['registration_id']);
}
//推送所有设备
if($data['all_audience']){
$pushPayload->addAllAudience();
}
try {
$response = $pushPayload->send(); // 执行推送
if(!$response || $response['http_code'] != 200){
$this->addError('推送消息失败!');
\models\setting\Log::error($response,'jPush');
return false;
}else{
\models\setting\Log::info($response,'jPush');
return $response;
}
}catch (APIConnectionException $e) { // 请求异常
$returnData = ['http_code' => $e->getCode(),'http_message' => $e->getMessage()];
$this->addError($e->getMessage());
\models\setting\Log::error($returnData,'jPush');
return $returnData;
} catch (APIRequestException $e) { // 回复异常
$returnData = ['http_code' => $e->getCode(),'http_message' => $e->getMessage()];
$this->addError($e->getMessage());
\models\setting\Log::error($returnData,'jPush');
return $returnData;
}
}
public function syncPush()
{
$models = NotificationPush::find()
->where(['status'=>1])
->andWhere(['>=','created_at',strtotime(date('Y-m-d'))])
->limit(20)
->all();
$report = [
'success'=>[],
'fail'=>[]
];
foreach ($models as $model){
$this->clearErrors();
$this->pushMessage([
'platform'=>["android", "ios"],
'alias'=>$model->alias,
'message'=>$model->content
]);
if($this->hasErrors()){
$model->error = Json::encode($this->getErrors());
$report['fail'][] = $model->notification_sms_id;
}else{
$model->status = 2;
$model->error = '';
$report['success'][] = $model->notification_sms_id;
}
$model->provider = 'jPush';
$model->save();
}
return $report;
}
}