Search code examples
phpiosapple-push-notificationssiebelapn

How and What to send to APN from server so that APN send the notification to device?


I am an iOS developer and i was asked to what type(whole i.e header as well as body) of request to hit APN to get notification to device.

I read many tutorial for setup of server for APN but I am unable to understand as i have no knowledge about PhP and Node Js. After reading apple document , I came to know that it uses http/2 and other various tag and value. But i am unable to construct full request. Any help is highly appreciated.


Solution

  • To send an APNs request using PHP, you need these requirements:

    1. A .pem certificate which should exist in the same path of your php script.
    2. The Device Token, which is needed to send the notification to a specific device.

    Then you can try the following code:

    <?php
        $apnsServer = 'ssl://gateway.push.apple.com:2195';
        $privateKeyPassword = '1234'; // your .pem private key password
    
        $message = 'Hello world!';
    
        $deviceToken = 'YOUR_DEVICE_TOKEN_HERE';
    
        $pushCertAndKeyPemFile = 'PushCertificateAndKey.pem'; // Your .pem certificate
        $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/>";
        exit;
        } else {
        echo "Successfully connected to the APNS...";
        }
        $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));
        if (!$wroteSuccessfully){
        echo "Could not send the message.";
        }
        else {
        echo "Successfully sent the message.";
        }
        fclose($connection);
    
    ?>
    

    Refer to this link for more details.