2010-01-20 183 views

回答

0

我有同樣的問題,但通過編輯這一行,我現在忽視解決...

$output = json_encode($payload);

$payload = json_encode($payload);

第一個將給予strlen的錯誤,但我的服務器上的錯誤呢不生成。在真實服務器上嘗試失敗後,在本地主機上運行時出現strlen錯誤。

我還爲local_cert添加了ssl passpharse,因爲我的pem文件有密碼。

以下是最終的代碼...請用您自己的信息替換your_token_hex_string和your_passphrase。

$device = 'your_token_hex_string'; 
$payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default'); 
$payload = json_encode($payload); 

$options = array('ssl' => array(
    'local_cert' => 'apns_dev.pem', 
    'passphrase' => 'your_passphrase' 
)); 

$streamContext = stream_context_create(); 
stream_context_set_option($streamContext, $options); 
$apns = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext); 

$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device)) . chr(0) . chr(strlen($payload)) . $payload; 
fwrite($apns, $apnsMessage); 
fclose($apns);
7

創建常用的功能推送通知傳遞的功能devicetoken,以下消息PARAMS和額外參數,按您的應用需求。 如果您使用的是開發者pem文件,那麼您必須使用「gateway.sandbox.push.apple.com:2195」,如果您使用的是distributer panm文件,則必須使用「gateway.push.apple.com:2195」

public function pushtoios($devicetoken, $message, $params = array()) { 
    $passphrase = 'apple'; 
    $ctx = stream_context_create(); 
/*Development pam file*/ 
    //stream_context_set_option($ctx, 'ssl', 'local_cert', your path.'apns-dev.pem'); 
/*Distributer pam file*/ 
    stream_context_set_option($ctx, 'ssl', 'local_cert', your path.'apns-distr.pem'); 
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); 

/*For Development pam file*/ 
    //$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); 

/*For Distributer pam file*/ 
    $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); 
    if (!$fp) 
     exit("Failed to connect amarnew: $err $errstr" . PHP_EOL); 

    $body['aps'] = array(
     'alert' => $message, 
     'sound' => 'default' 
    ); 
    $body['type'] = $params['type']; 
    $body['params'] = $params; 
    $payload = json_encode($body); 
    $msg = chr(0) . pack('n', 32) . pack('H*', $devicetoken) . pack('n', strlen($payload)) . $payload; 

    $result = fwrite($fp, $msg, strlen($msg)); 
    if (!$result) { 
     return false; 
    } else { 
     return true; 
    } 
    fclose($fp); 
} 
+0

太棒了,確實是對的! –