在 php yii2.0 中集成 android Firebase 通知



我知道这是一个非常愚蠢的问题,我正在yii2后端集成android Firebase通知。我知道了很多yii2扩展,但这不起作用,我发现这个很简单,所以尝试使用它。 但是我不知道如何使用它,我必须为此发送HTTP请求。 这是代码。

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=Your_Authorization_Key
{
"registration_ids": ["registration_token"],
"data": {
"message": "This is a Firebase Message!",
}
}

我有auth_key和注册令牌,只需要知道如何执行。

是的,我做到了!!这是任何尝试这样做的人的方法。

假设您有一个后端,您可以在其中提交推送通知的"标题"和"正文"。 现在,当我提交表单时,它有一个操作,我正在读取提交数据。喜欢这个。

use backendhelpersFirebaseNotifications; 

在顶部定义

if ($model->load(Yii::$app->request->post())) {
$model->save(false);
$title = $model->title;
$body = $model->content;
$service = new FirebaseNotifications(['authKey' => 
'YOUR_AUTH_KEY']);
$all_users = User::find()->where(['!=','device_id','Null'])->andwhere(['!=','device_id',' '])->all();
$tokens = [];    
foreach ($all_users as $users) { 
$tokens[] = $users['device_id'];
} 
$message = array('title' => $title, 'body' => $body);
$service->sendNotification($tokens, $message);
return $this->redirect(['index']);
}

我正在打电话

$service->发送通知($tokens, $message);

在帮助程序类的单独文件中定义。 在 Firebase通知.php 等帮助程序文件夹下。它的内容看起来像这样。

<?php
namespace backendhelpers;
use yiibaseObject;
use Yii;
use yiihelpersArrayHelper;
class FirebaseNotifications extends Object
{ 
public $authKey;
public $timeout = 50;
public $sslVerifyHost = false;
public $sslVerifyPeer = false;
public $apiUrl = 'https://fcm.googleapis.com/fcm/send';
public function init()
{
if (!$this->authKey) throw new Exception("Empty authKey");
}
public function send($body)
{
$headers = [
"Authorization:key={$this->authKey}",
'Content-Type: application/json',
'Expect: ',
];
$ch = curl_init($this->apiUrl);
curl_setopt_array($ch, [
CURLOPT_POST           => true,
CURLOPT_SSL_VERIFYHOST => $this->sslVerifyHost,
CURLOPT_SSL_VERIFYPEER => $this->sslVerifyPeer,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_BINARYTRANSFER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER         => false,
CURLOPT_FRESH_CONNECT  => false,
CURLOPT_FORBID_REUSE   => false,
CURLOPT_HTTPHEADER     => $headers,
CURLOPT_TIMEOUT        => $this->timeout,
CURLOPT_POSTFIELDS     => json_encode($body),
]);
$result = curl_exec($ch);
if ($result === false) {
Yii::error('Curl failed: '.curl_error($ch).", with result=$result");
throw new Exception("Could not send notification..");
}
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code<200 || $code>=300) {
Yii::error("got unexpected response code $code with result=$result");
throw new Exception("Could not send notification");
}
curl_close($ch);
$result = json_decode($result , true);
return $result;
}
public function sendNotification($tokens = [], $notification, $options = [])
{   
$body = array(
'registration_ids' => $tokens,
'notification' => $notification,
//array('title' => 'Time of Sports', 'body' => 'Salman Notification'),
//'data' => array('message' => $notification)
);
$body = ArrayHelper::merge($body, $options);
return $this->send($body);
}
}

最新更新