首页 > 解决方案 > 从 PHP 发送时未收到 APNS 推送通知。我该如何调试这个问题?

问题描述

您好我正在使用以下代码使用 PHP 发送 APNS 推送通知,但设备上未收到通知。

我使用这个工具来验证我是否有错误的令牌或者我的 .pem 文件是否有问题 - 但如果我在这里测试它:https ://www.pushtry.com/一切正常。

function sendAPNS($message, $id)
{



        
        /* We are using the sandbox version of the APNS for development. For production
        environments, change this to ssl://gateway.push.apple.com:2195 */
        $apnsServer = 'ssl://gateway.sandbox.push.apple.com:2195';
        /* Make sure this is set to the password that you set for your private key
        when you exported it to the .pem file using openssl on your OS X */
        $privateKeyPassword = '';



        $deviceToken = $id;

        /* Replace this with the name of the file that you have placed by your PHP
        script file, containing your private key and certificate that you generated
        earlier */

        $pushCertAndKeyPemFile = 'push.pem';



        $stream = stream_context_create();
        stream_context_set_option($stream,
        'ssl',
        'passphrase',
        $privateKeyPassword);
        stream_context_set_option($stream,
        'ssl',
        'local_cert',
        $pushCertAndKeyPemFile);

        $connectionTimeout = 20;
        $connectionType = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
        $connection = stream_socket_client($apnsServer,
        $errorNumber,
        $errorString,
        $connectionTimeout,
        $connectionType,
        $stream);

        if (!$connection){
                echo "Failed to connect to the APNS server. Error no = $errorNumber<br/>";
        } 
        else 
        {
                echo "Successfully connected to the APNS. Processing...</br>";
        }

        $messageBody['aps'] = array('alert' => $message,
        'sound' => 'default',
        'badge' => 2,
        );

        $payload = json_encode($messageBody);
        $notification = chr(0) .
        pack('n', 32) .
        pack('H*', $deviceToken) .
        pack('n', strlen($payload)) .
        $payload;

        $wroteSuccessfully = fwrite($connection, $notification, strlen($notification));
        var_dump($wroteSuccessfully); 

        if (!$wroteSuccessfully){
                echo "Could not send the message<br/>";
        }
        else {
                echo "Successfully sent the message<br/>";
        }

        fclose($connection);


}

PHP的输出是:

成功连接到 APNS。处理中... int(140) 成功发送消息

我该如何调试这个问题?

标签: phpapple-push-notifications

解决方案


推荐阅读