PHP实现极光推送
?消息推送一般會使用極光推送,相較于其他平臺速度還可以。看極光的sdk也挺簡單,記錄一下,以備后用。
<?phpnamespace 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;} }?
總結
- 上一篇: UX美即好用效应 Aesthetic U
- 下一篇: 2-2.数据解析篇