2013-04-11 2 views
2

У меня есть база данных со всеми devicetokens. Я перебираю маркеры из базы данных, но мой скрипт больше не работает (толкает не посылает).Отправить Push-уведомление нескольким маркерам с PHP (iOS)

Это мой сценарий:

<?PHP 

$db_user = "xxx"; // Gebruiker voor MySQL 
$db_pass = "xxx"; // Wachtwoord voor MySQL 
$db_host = "localhost"; // Host voor MySQL; standaard localhost 
$db_db = "xxx"; // Database 

// Als je al ergens anders een database connectie hebt gemaakt, 
// maak dan van de volgende twee regels commentaar (# of // ervoor zetten) 
mysql_connect($db_host,$db_user,$db_pass); 
mysql_select_db($db_db); 

$query = mysql_query("SELECT * FROM iospush"); 

           while ($row = mysql_fetch_array($query)) { 
            $deviceToken = $row["devicetoken"]; 
            } 

if($_POST['message']){ 

// $deviceToken = 'xxx'; 

    $message = stripslashes($_POST['message']); 

    $payload = '{ 
        "aps" : 

         { "alert" : "'.$message.'", 
"badge" : 1 
         } 
       }'; 


    $ssl='xx.pem'; 

    $ctx = stream_context_create(); 
    stream_context_set_option($ctx, 'ssl', 'local_cert', $ssl); 
    stream_context_set_option($ctx, 'ssl', 'passphrase', 'xxx'); 
    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); 
    if(!$fp){ 
     print "Failed to connect $err $errstrn"; 
     return; 
    } else { 
     print "Notifications sent!"; 
    } 

    $devArray = array(); 
    $devArray[] = $deviceToken; 

    foreach($devArray as $deviceToken){ 
     $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack  ("n",strlen($payload)) . $payload; 
     print "sending message :" . $payload . "n"; 

     fwrite($fp, $msg); 
    } 
    fclose($fp); 
} 

?> 
<form action="pushios.php" method="post"> 
    <input type="text" name="message" maxlength="100"> 
    <input type="submit" value="Send Notification"> 
</form> 

Пожалуйста, помогите мне сделать эту работу!

спасибо что!

+0

Mo требуемая информация. Что именно вы подразумеваете под «Это больше не работает»? Выводит сообщение об ошибке? Где это происходит в сценарии? –

+0

Push Notifications больше не отправляют. –

+0

Вы перезаписываете $ deviceToken весь день - вы никогда не проверяете $ deviceToken ... знаете ли вы что-нибудь о PHP? – djot

ответ

7
$deviceToken = ARRAY(); 
while ($row = mysql_fetch_array($query)) { 
    $deviceToken[] = $row["devicetoken"]; 
} 

...

// or use ($devArray = $deviceToken;) 

foreach($deviceToken as $token){ 
    $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $token)) . pack  ("n",strlen($payload)) . $payload; 
+0

Спасибо! Он отлично работает –

+0

отправляет только одному токену, а не другим .. можете ли вы отправить полный ответ? (Я новичок в PHP, поэтому я неправильно размещаю код ..) – Darpan

+0

обновление: я переместил 'fwrite ($ fp, $ msg);' в 'foreach'. теперь он отправляет 2 пользователям, которых я отправлял, но в прошлый раз, когда я попробовал 'fwrite' в' foreach', он не пошел ко всем пользователям, когда я попытался отправить его 100 пользователям – Darpan

-1

@djot спасибо за ваш ответ, но вы пропустили, чтобы добавить точку перед =

$deviceToken = ARRAY(); 

$deviceToken = explode(',' , @$_POST['devicesToken']); 

........

foreach($deviceToken as $token){ 
$msg.= chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $token)) . pack  ("n",strlen($payload)) . $payload; 
0
function addStoryData() { 

    header("Content-Type:application/json"); 

    $notification = $this->input->post('message'); 

    $device_id = $this->db->select('device_id') 
           ->from('tbl_device') 
           ->where('device_type','iPhone') 
           ->get() 
           ->result_array(); 

    //$this->sendApplePushNotification($device_id,$notification,1); 

    foreach ($device_id as $d_id) {       

     $device_id = $d_id['device_id']; 
     $this->sendApplePushNotification($device_id,$notification,1); 
    } 


} 

function sendApplePushNotification($tToken,$tAlert,$notification) 
{ 

    /* 
     print_r($tToken); 
     echo '----------------------------'; 
     print_r($tAlert); 
     echo '----------------------------'; 
     print_r($detail); 
     echo '----------------------------'; 
     print_r($notification); 
     echo '----------------------------'; 
     print_r($tToken); 
     die; 
    */  
     $tPayload="test"; 
     //$tHost = 'gateway.sandbox.push.apple.com'; 
     $tHost = 'gateway.push.apple.com'; 

     $tPort = 2195; 

     // Provide the Certificate and Key Data. 
     // home/ibliocrq/public_html/shopostreet.com/shopostreet/application/ckShopostreet_development.pem 
     //echo $this->config->item('pushcertDevelopment.pem');die; 

     //echo base_url('RestAPI/pushcertDevelopment.pem'); 
     //die; 
     $tCert = '/home/chatstor/public_html/readify/pushcertDistribution.pem'; 
     //$tCert = '/home/chatstor/public_html/readify/pushcertDevelopment.pem'; 


     //$tCert = 'ckUnionMallProdution.pem'; 

     // Provide the Private Key Passphrase (alternatively you can keep this secrete 

     // and enter the key manually on the terminal -> remove relevant line from code). 

     // Replace XXXXX with your Passphrase 

     $tPassphrase = '[email protected]'; 

     // Provide the Device Identifier (Ensure that the Identifier does not have spaces in it). 

     // Replace this token with the token of the iOS device that is to receive the notification. 

     //==================== 
     // $tToken = 'da38439e7b2bf83bfae2011eb680debdfeeded66602f685033fd4b25101d31a2'; 

     //==================== 

     // The message that is to appear on the dialog. 

     //==================== 
     // $tAlert = 'Test Heartfelt Push Notification'; 
     //==================== 

     // The Badge Number for the Application Icon (integer >=0). 

     // $tBadge = 1; 
     $tBadge = intval($notification); 

     // Audible Notification Option. 

     $tSound = 'default'; 

     // The content that is returned by the LiveCode "pushNotificationReceived" message. 

     //==================== 
     // $tPayload = 'You get a New Bubble'; 
     //==================== 

     // Create the message content that is to be sent to the device. 

     $tBody['aps'] = array (
     'alert' => $tAlert, 
     'badge' => $tBadge, 
     'sound' => $tSound, 

     //'detail' => $detail, 
     ); 

     //print_r($tBody); 

     $tBody ['payload'] = $tPayload; 
     //$tBody ['bubble_id'] = "101"; 

     // Encode the body to JSON. 

     $tBody = json_encode ($tBody); 

     // Create the Socket Stream. 

     $tContext = stream_context_create(); 

     stream_context_set_option ($tContext, 'ssl', 'local_cert', $tCert); 

     // Remove this line if you would like to enter the Private Key Passphrase manually. 

     stream_context_set_option ($tContext, 'ssl', 'passphrase', $tPassphrase); 

     // Open the Connection to the APNS Server. 

     $tSocket = stream_socket_client ('ssl://'.$tHost.':'.$tPort, $error, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $tContext); 


     // Check if we were able to open a socket. 

     if (!$tSocket) 
     { 
       echo json_encode(array("ResponseCode"=>"2","Result"=>"false","ResponseMsg"=> "APNS Connection Failed.")); 
       exit ("APNS Connection Failed: $error $errstr" . PHP_EOL); 
     } 

     // Build the Binary Notification. 


     /*foreach($tToken as $deviceToken){ 

      echo $tToken['device_id']; 

      $tMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $tToken['device_id']) . pack ('n', strlen ($tBody)) . $tBody; 

      // Send the Notification to the Server. 

      $tResult = fwrite ($tSocket, $tMsg, strlen ($tMsg)); 



      if ($tResult){ 
        echo json_encode(array("ResponseCode"=>"1","Result"=>"true","ResponseMsg"=> "Notification has been sent.")); 
      }else{ 
        echo json_encode(array("ResponseCode"=>"2","Result"=>"false","ResponseMsg"=> "Notification could not sent.")); 
      } 
     } 
     fclose ($tSocket);*/ 
     //fclose($fp); 


     $tMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $tToken) . pack ('n', strlen ($tBody)) . $tBody; 

     // Send the Notification to the Server. 

     $tResult = fwrite ($tSocket, $tMsg, strlen ($tMsg)); 



     if ($tResult){ 
       echo json_encode(array("ResponseCode"=>"1","Result"=>"true","ResponseMsg"=> "Notification has been sent.")); 
     }else{ 
       echo json_encode(array("ResponseCode"=>"2","Result"=>"false","ResponseMsg"=> "Notification could not sent.")); 
     } 

     // Close the Connection to the Server. 

     fclose ($tSocket); 
} 
} 
Смежные вопросы