Allow sending message to topics using FCM v1 API

This commit is contained in:
Kijin Sung 2024-04-23 23:58:15 +09:00
parent ac16d2e7f5
commit c7f96ad75b
2 changed files with 64 additions and 8 deletions

View file

@ -145,7 +145,7 @@ class Push
}
/**
* Get the list of recipients without country codes.
* Get the list of recipients.
*
* @return array
*/
@ -154,6 +154,28 @@ class Push
return $this->to;
}
/**
* Add a topic.
*
* @param string $topic
* @return bool
*/
public function addTopic(string $topic): bool
{
$this->topics[] = $topic;
return true;
}
/**
* Get the list of topics.
*
* @return array
*/
public function getTopics(): array
{
return $this->topics;
}
/**
* Set the subject.
*
@ -376,7 +398,7 @@ class Push
$output = null;
// FCM HTTP v1 or Legacy API
if(count($tokens->fcm))
if(count($tokens->fcm) || count($this->topics))
{
$fcm_driver_name = array_key_exists('fcmv1', config('push.types') ?: []) ? 'fcmv1' : 'fcm';
$fcm_driver = $this->getDriver($fcm_driver_name);
@ -442,7 +464,7 @@ class Push
{
$args->device_token_type[] = 'apns';
}
if(!count($args->device_token_type))
if(!count($args->device_token_type) || !count($args->member_srl))
{
return $result;
}

View file

@ -123,8 +123,8 @@ class FCMv1 extends Base implements PushInterface
}
// Send a notification to each token, grouped into chunks to speed up the process.
$chunked_tokens = array_chunk($tokens, self::CHUNK_SIZE);
foreach($chunked_tokens as $tokens)
$chunked_tokens = $tokens ? array_chunk($tokens, self::CHUNK_SIZE) : [[]];
foreach ($chunked_tokens as $tokens)
{
$requests = [];
foreach ($tokens as $i => $token)
@ -132,9 +132,6 @@ class FCMv1 extends Base implements PushInterface
$requests[$i] = [
'url' => $api_url,
'method' => 'POST',
'data' => null,
'headers' => [],
'cookies' => [],
'settings' => [
'auth' => 'google_auth',
'base_uri' => self::BASE_URL,
@ -170,6 +167,43 @@ class FCMv1 extends Base implements PushInterface
}
}
// Send a notification to each topic.
$topics = $message->getTopics();
if (count($topics))
{
$requests = [];
foreach ($topics as $i => $topic)
{
$requests[$i] = [
'url' => $api_url,
'method' => 'POST',
'settings' => [
'auth' => 'google_auth',
'base_uri' => self::BASE_URL,
'handler' => $stack,
'json' => $payload,
],
];
$requests[$i]['settings']['json']['message']['topic'] = $topic;
}
$responses = HTTP::multiple($requests);
foreach ($responses as $response)
{
$status_code = $response->getStatusCode();
$result = @json_decode($response->getBody()->getContents());
if ($status_code === 200)
{
$output->success[$topics[$i]] = $result->name ?? '';
}
else
{
$error_message = $result->error->message ?? ($result->error->status ?? $response->getReasonPhrase());
$message->addError('FCM error: HTTP ' . $status_code . ' ' . $error_message);
}
}
}
return $output;
}
}