網頁

2013年8月19日 星期一

php push_apns iphone

siriusdely push_apns.php 改良資料庫與多線程
 
      $passphrase = 'XXX'; 

      // Put your alert message here:
      $message = 'A push notification has been sent!';

    $timeout = 1; //1sec

    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'smap_pt_pn_key.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

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


      $dbh = new PDO("mysql:host=" . db('hostname') . ";dbname=" . db('dbname'), db('username'), db('password'), 
      array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") ); //POD處理中文的顯示的問題

      $sql_pn_device = "SELECT * FROM yourtablename WHERE user_id = '$user_id' ";

      $stmt = $dbh->prepare($sql_pn_device);
      $stmt->execute();
            
           if($stmt->fetchColumn() > 0) {

              foreach ($dbh->query($sql_pn_device) as $row) {
                        $deviceToken= $row['token'];
                         echo   $deviceToken."---send---".$message."|";
                     
                         push_apns($fp,$passphrase,$deviceToken,$message);
                   }
            } else {
                         echo  $user_id."---fail---";
            }
            
          // Close the connection to the server
          fclose($fp);

 

function push_apns($fp,$passphrase,$deviceToken,$message){


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

    echo 'Connected to APNS' . PHP_EOL;

    // Create the payload body
    $body['aps'] = array(
      'alert' => array(
            'body' => $message,
        'action-loc-key' => 'Bango App',
        ),
        'badge' => 2,
      'sound' => 'oven.caf',
      );

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

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

    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));
    echo "//".$result."//";
    if (!$result)
      echo 'Message not delivered' . PHP_EOL;
    else{
      echo 'Message successfully delivered' . PHP_EOL;
      //echo $message;
    }

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。