А еще: я удаляю свой ключ сервера в консоли Firebase (устаревшая версия).
Услуги:
`
Код: Выделить всё
namespace App\Services;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Firebase\JWT\JWT;
class FcmService
{
protected $client;
protected $url;
protected $credentialsFilePath;
public function __construct()
{
$this->client = new Client();
$this->credentialsFilePath = public_path('xxxxxx.json');
$this->url = 'https://fcm.googleapis.com/v1/projects/xxxx/messages:send';
}
public function sendMultiNotification(array $tokens, string $title, string $body)
{
$responses = [];
$batchSize = 500; // Maximum allowed tokens per request
// Split tokens into batches
foreach (array_chunk($tokens, $batchSize) as $tokenBatch) {
$message = [
'message' => [
'tokens' => $tokenBatch, // Use 'tokens' for multiple device tokens
'notification' => [
'title' => $title,
'body' => $body,
],
],
];
try {
$response = $this->client->post($this->url, [
'headers' => [
'Authorization' => 'Bearer ' . $this->generateAccessToken(),
'Content-Type' => 'application/json',
],
'json' => $message,
]);
// Log the response status and body
\Log::info('FCM Response Status: ' . $response->getStatusCode());
\Log::info('FCM Response Body: ' . $response->getBody());
$responses[] = json_decode($response->getBody(), true);
} catch (RequestException $e) {
\Log::error('FCM Error: ' . $e->getMessage());
$responses[] = ['error' => $e->getMessage()];
}
}
return $responses; // Return all responses for each batch
}
protected function generateAccessToken()
{
$credentials = json_decode(file_get_contents($this->credentialsFilePath), true);
$now = time();
$payload = [
'iss' => $credentials['client_email'],
'sub' => $credentials['client_email'],
'iat' => $now,
'exp' => $now + 3600,
'aud' => 'https://fcm.googleapis.com/',
];
return JWT::encode($payload, $credentials['private_key'], 'RS256');
}
}
Контроллер:
Код: Выделить всё
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Services\FcmService;
use Illuminate\Http\Request;
class FcmController1 extends Controller
{
protected $fcmService;
public function __construct(FcmService $fcmService)
{
$this->fcmService = $fcmService; // Assign the injected service to the class property
}
public function send(Request $request)
{
$tokens =['xxxxx',xxx2'];
$title = 'Your Notification Title';
$body = 'Your Notification Body';
$responses = $this->fcmService->sendMultiNotification($tokens, $title, $body);
return response()->json($response);
}
}
"error": "Ошибка клиента: POST https://fcm.googleapis.com/ v1/projects/newbonuscard/messages:send привел к ответу 400 Bad Request:\n{\n "error": {\n "code": 400,\n "message": " Получены недопустимые полезные данные JSON. Неизвестное имя «токены» в «сообщении»: Prot (усечено...)\n"
Подробнее здесь: https://stackoverflow.com/questions/790 ... e-cloud-me
Мобильная версия