且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

发送推送通知给所有用户

更新时间:2023-12-03 16:23:10

通常的做法是存储令牌在数据库中,一旦你需要向他们发送 - 只是通过他们选择的DB和循环令牌

The usual approach is to store tokens in the database and once you need to send them - just select the tokens from the DB and loop through them.

在code可能看起来像

the code might look like that

$pdo = new PDO(
    "mysql:host=$db_host;port=$db_port;dbname=$db_name",
    $db_user,
    $db_pass
);  
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);      
$select_tokens_sql = 'SELECT * FROM tokens';
$select_tokens_statement = $pdo->prepare($select_tokens_sql);

// Open a connection to the APNS server
$fp = stream_socket_client(
    'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp)
  exit("Failed to connect: $err $errstr" . PHP_EOL);

echo 'Connected to APNS' . PHP_EOL;

// Create the payload body
$body['aps'] = array(
  'alert' => $message,
  'sound' => 'default'
);

// Encode the payload as JSON
$payload = json_encode($body);

$select_tokens_statement->execute();
$tokens = $select_tokens_statement->fetchAll();
//loop through the tokens
foreach($tokens as $token) {     

   // Build the binary notification
   $msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) .  $payload;

   // Send it to the server
   $result = fwrite($fp, $msg, strlen($msg));

   if (!$result)
      echo 'Message to the device ' . $token . ' not delivered' . PHP_EOL;
   else
       echo 'Message to the device ' . $token . ' successfully delivered' . PHP_EOL;
}
// Close the connection to the server
fclose($fp);

这也可能是一个好主意,你已经完成发送推送通知后立即听取反馈意见的苹果服务。它会告诉你,如果在某些设备上的应用无法present了,所以你可以放心地从数据库中删除相应的标记。

It might also be a good idea to listen to apple feedback service just after you have finished sending push notifications. It will tell you if on some devices your app is not present anymore so you can safely remove corresponding tokens from the database.